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

<!--
  ~ 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.
  -->

<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="org.activiti.engine.impl.persistence.entity.TaskEntity">

  <!-- TASK INSERT -->

  <insert id="insertTask" parameterType="org.activiti.engine.impl.persistence.entity.TaskEntity">
    insert into ${prefix}ACT_RU_TASK (ID_, REV_, NAME_, PARENT_TASK_ID_, DESCRIPTION_, PRIORITY_, CREATE_TIME_, OWNER_,
                      ASSIGNEE_, DELEGATION_, EXECUTION_ID_, PROC_INST_ID_, PROC_DEF_ID_, TASK_DEF_KEY_, DUE_DATE_, CATEGORY_, SUSPENSION_STATE_, TENANT_ID_, FORM_KEY_)
    values (#{id, jdbcType=VARCHAR},
            1,
            #{name, jdbcType=VARCHAR},
            #{parentTaskId, jdbcType=VARCHAR},
            #{description, jdbcType=VARCHAR},
            #{priority, jdbcType=INTEGER},
            #{createTime, jdbcType=TIMESTAMP},
            #{owner, jdbcType=VARCHAR},
            #{assignee, jdbcType=VARCHAR},
            #{delegationStateString, jdbcType=VARCHAR},
            #{executionId, jdbcType=VARCHAR},
            #{processInstanceId, jdbcType=VARCHAR},
            #{processDefinitionId, jdbcType=VARCHAR},
            #{taskDefinitionKey, jdbcType=VARCHAR},
            #{dueDate, jdbcType=TIMESTAMP},
            #{category, jdbcType=VARCHAR},
            #{suspensionState, jdbcType=INTEGER},
            #{tenantId, jdbcType=VARCHAR},
            #{formKey, jdbcType=VARCHAR}
           )
  </insert>

  <!-- TASK UPDATE -->

  <update id="updateTask" parameterType="org.activiti.engine.impl.persistence.entity.TaskEntity">
    update ${prefix}ACT_RU_TASK
    <set>
      REV_ = #{revisionNext, jdbcType=INTEGER},
      NAME_ = #{name, jdbcType=VARCHAR},
      PARENT_TASK_ID_ = #{parentTaskId, jdbcType=VARCHAR},
      PRIORITY_ = #{priority, jdbcType=INTEGER},
      CREATE_TIME_ = #{createTime, jdbcType=TIMESTAMP},
      OWNER_ = #{owner, jdbcType=VARCHAR},
      ASSIGNEE_ = #{assignee, jdbcType=VARCHAR},
      DELEGATION_ = #{delegationStateString, jdbcType=VARCHAR},
      EXECUTION_ID_ = #{executionId, jdbcType=VARCHAR},
      PROC_DEF_ID_ = #{processDefinitionId, jdbcType=VARCHAR},
      DESCRIPTION_ = #{description, jdbcType=VARCHAR},
      DUE_DATE_ = #{dueDate, jdbcType=TIMESTAMP},
      CATEGORY_ = #{category, jdbcType=VARCHAR},
      SUSPENSION_STATE_ = #{suspensionState, jdbcType=INTEGER},
      FORM_KEY_ = #{formKey, jdbcType=INTEGER}
    </set>
    where ID_= #{id, jdbcType=VARCHAR}
      and REV_ = #{revision, jdbcType=INTEGER}
  </update>

  <update id="updateTaskTenantIdForDeployment" parameterType="java.util.Map">
    update ${prefix}ACT_RU_TASK set
      TENANT_ID_ = #{tenantId, jdbcType=VARCHAR}
    where
      ID_ in (
        SELECT T.ID_ from ${prefix}ACT_RU_TASK T
        inner join ${prefix}ACT_RE_PROCDEF P on T.PROC_DEF_ID_  = P.ID_
        inner join ${prefix}ACT_RE_DEPLOYMENT D on P.DEPLOYMENT_ID_ = D.ID_
        where D.ID_ = #{deploymentId, jdbcType=VARCHAR}
      )
  </update>

    <!-- See http://stackoverflow.com/questions/4429319/you-cant-specify-target-table-for-update-in-from-clause
       Tested this on MySQL 5.6: does NOT use a temporary table (so good, performance0 -->
  <update id="updateTaskTenantIdForDeployment_mysql" parameterType="java.util.Map">
    update ${prefix}ACT_RU_TASK set
      TENANT_ID_ = #{tenantId, jdbcType=VARCHAR}
    where
      ID_ in (

          SELECT tempTask.tempId
          FROM (
                SELECT T.ID_ as tempId
                FROM  ${prefix}ACT_RU_TASK T
                inner join ${prefix}ACT_RE_PROCDEF P on T.PROC_DEF_ID_  = P.ID_
                inner join ${prefix}ACT_RE_DEPLOYMENT D on P.DEPLOYMENT_ID_ = D.ID_
                where D.ID_ = #{deploymentId, jdbcType=VARCHAR}

        ) AS tempTask

    )
  </update>

  <!-- TASK DELETE -->
  <delete id="deleteTask" parameterType="org.activiti.engine.impl.persistence.entity.TaskEntity">
    delete from ${prefix}ACT_RU_TASK where ID_ = #{id} and REV_ = #{revision}
  </delete>

  <delete id="bulkDeleteTask" parameterType="java.util.Collection">
    delete from ${prefix}ACT_RU_TASK where
    <foreach item="task" collection="list" index="index" separator=" or ">
        ID_ = #{task.id, jdbcType=VARCHAR}
    </foreach>
  </delete>

  <!-- TASK RESULTMAP -->

  <resultMap id="taskResultMap" type="org.activiti.engine.impl.persistence.entity.TaskEntity">
    <id property="id" column="ID_" jdbcType="VARCHAR"/>
    <result property="revision" column="REV_" jdbcType="INTEGER"/>
    <result property="nameWithoutCascade" column="NAME_" jdbcType="VARCHAR"/>
    <result property="parentTaskIdWithoutCascade" column="PARENT_TASK_ID_" jdbcType="VARCHAR"/>
    <result property="descriptionWithoutCascade" column="DESCRIPTION_" jdbcType="VARCHAR"/>
    <result property="priorityWithoutCascade" column="PRIORITY_" jdbcType="INTEGER"/>
    <result property="createTime" column="CREATE_TIME_" jdbcType="TIMESTAMP" />
    <result property="ownerWithoutCascade" column="OWNER_" jdbcType="VARCHAR"/>
    <result property="assigneeWithoutCascade" column="ASSIGNEE_" jdbcType="VARCHAR"/>
    <result property="delegationStateString" column="DELEGATION_" jdbcType="VARCHAR"/>
    <result property="executionId" column="EXECUTION_ID_" jdbcType="VARCHAR" />
    <result property="processInstanceId" column="PROC_INST_ID_" jdbcType="VARCHAR" />
    <result property="processDefinitionId" column="PROC_DEF_ID_" jdbcType="VARCHAR"/>
    <result property="taskDefinitionKeyWithoutCascade" column="TASK_DEF_KEY_" jdbcType="VARCHAR"/>
    <result property="dueDateWithoutCascade" column="DUE_DATE_" jdbcType="TIMESTAMP"/>
    <result property="categoryWithoutCascade" column="CATEGORY_" jdbcType="VARCHAR" />
    <result property="suspensionState" column="SUSPENSION_STATE_" jdbcType="INTEGER" />
    <result property="tenantId" column="TENANT_ID_" jdbcType="VARCHAR" />
    <result property="formKey" column="FORM_KEY_" jdbcType="VARCHAR" />
  </resultMap>

  <resultMap id="taskAndVariablesResultMap" type="org.activiti.engine.impl.persistence.entity.TaskEntity">
    <id property="id" column="ID_" jdbcType="VARCHAR"/>
    <result property="revision" column="REV_" jdbcType="INTEGER"/>
    <result property="nameWithoutCascade" column="NAME_" jdbcType="VARCHAR"/>
    <result property="parentTaskIdWithoutCascade" column="PARENT_TASK_ID_" jdbcType="VARCHAR"/>
    <result property="descriptionWithoutCascade" column="DESCRIPTION_" jdbcType="VARCHAR"/>
    <result property="priorityWithoutCascade" column="PRIORITY_" jdbcType="INTEGER"/>
    <result property="createTime" column="CREATE_TIME_" jdbcType="TIMESTAMP" />
    <result property="ownerWithoutCascade" column="OWNER_" jdbcType="VARCHAR"/>
    <result property="assigneeWithoutCascade" column="ASSIGNEE_" jdbcType="VARCHAR"/>
    <result property="delegationStateString" column="DELEGATION_" jdbcType="VARCHAR"/>
    <result property="executionId" column="EXECUTION_ID_" jdbcType="VARCHAR" />
    <result property="processInstanceId" column="PROC_INST_ID_" jdbcType="VARCHAR" />
    <result property="processDefinitionId" column="PROC_DEF_ID_" jdbcType="VARCHAR"/>
    <result property="taskDefinitionKeyWithoutCascade" column="TASK_DEF_KEY_" jdbcType="VARCHAR"/>
    <result property="dueDateWithoutCascade" column="DUE_DATE_" jdbcType="TIMESTAMP"/>
    <result property="categoryWithoutCascade" column="CATEGORY_" jdbcType="VARCHAR" />
    <result property="suspensionState" column="SUSPENSION_STATE_" jdbcType="INTEGER" />
    <result property="tenantId" column="TENANT_ID_" jdbcType="VARCHAR" />
    <result property="formKey" column="FORM_KEY_" jdbcType="VARCHAR" />
    <collection property="queryVariables" column="TASK_ID_" javaType="ArrayList" ofType="org.activiti.engine.impl.persistence.entity.VariableInstanceEntity">
      <id property="id" column="VAR_ID_"/>
      <result property="name" column="VAR_NAME_" javaType="String" jdbcType="VARCHAR" />
      <result property="type" column="VAR_TYPE_" javaType="org.activiti.engine.impl.variable.VariableType" jdbcType="VARCHAR" />
      <result property="revision" column="VAR_REV_" jdbcType="INTEGER" />
      <result property="processInstanceId" column="VAR_PROC_INST_ID_" jdbcType="VARCHAR" />
      <result property="executionId" column="VAR_EXECUTION_ID_" jdbcType="VARCHAR" />
      <result property="taskId" column="VAR_TASK_ID_" jdbcType="VARCHAR" />
      <result property="byteArrayRef" column="VAR_BYTEARRAY_ID_" typeHandler="ByteArrayRefTypeHandler"/>
      <result property="doubleValue" column="VAR_DOUBLE_" jdbcType="DOUBLE" />
      <result property="textValue" column="VAR_TEXT_" jdbcType="VARCHAR" />
      <result property="textValue2" column="VAR_TEXT2_" jdbcType="VARCHAR" />
      <result property="longValue" column="VAR_LONG_" jdbcType="BIGINT" />
    </collection>
  </resultMap>

  <!-- TASK SELECT -->

  <select id="selectTask" parameterType="string" resultMap="taskResultMap">
   select * from ${prefix}ACT_RU_TASK where ID_ = #{id}
  </select>

  <select id="selectTasksByParentTaskId" parameterType="org.activiti.engine.impl.db.ListQueryParameterObject" resultMap="taskResultMap">
    select * from ${prefix}ACT_RU_TASK where PARENT_TASK_ID_ = #{parameter}
  </select>

  <select id="selectTasksByExecutionId" parameterType="org.activiti.engine.impl.db.ListQueryParameterObject" resultMap="taskResultMap">
    select distinct T.*
    from ${prefix}ACT_RU_TASK T
    where T.EXECUTION_ID_ = #{parameter}
  </select>

  <select id="selectTasksByProcessInstanceId" parameterType="org.activiti.engine.impl.db.ListQueryParameterObject" resultMap="taskResultMap">
    select T.*
    from ${prefix}ACT_RU_TASK T
    where T.PROC_INST_ID_ = #{parameter}
  </select>

  <!-- Using distinct here because a task can appear multiple times in a resultset when -->
  <select id="selectTaskByQueryCriteria" parameterType="org.activiti.engine.impl.TaskQueryImpl" resultMap="taskResultMap">
    ${limitBefore}
    select distinct RES.* ${limitBetween}
    <include refid="selectTaskByQueryCriteriaSql"/>
    ${orderBy}
    ${limitAfter}
  </select>

  <select id="selectTaskCountByQueryCriteria" parameterType="org.activiti.engine.impl.TaskQueryImpl" resultType="long">
    select count(distinct RES.ID_)
    <include refid="selectTaskByQueryCriteriaSql"/>
  </select>

  <sql id="selectTaskByQueryCriteriaSql">
    from ${prefix}ACT_RU_TASK RES
    <include refid="commonSelectTaskByQueryCriteriaSql"/>
  </sql>

  <select id="selectTaskWithVariablesByQueryCriteria" parameterType="org.activiti.engine.impl.TaskQueryImpl" resultMap="taskAndVariablesResultMap">
    ${limitBefore}
    select RES.*,
    VAR.ID_ as VAR_ID_, VAR.NAME_ as VAR_NAME_, VAR.TYPE_ as VAR_TYPE_, VAR.REV_ as VAR_REV_,
    VAR.PROC_INST_ID_ as VAR_PROC_INST_ID_, VAR.EXECUTION_ID_ as VAR_EXECUTION_ID_, VAR.TASK_ID_ as VAR_TASK_ID_,
    VAR.BYTEARRAY_ID_ as VAR_BYTEARRAY_ID_, VAR.DOUBLE_ as VAR_DOUBLE_,
    VAR.TEXT_ as VAR_TEXT_, VAR.TEXT2_ as VAR_TEXT2_, VAR.LONG_ as VAR_LONG_
    ${limitBetween}
    <include refid="selectTaskWithVariablesByQueryCriteriaSql"/>
    ${orderBy}
    ${limitAfter}
  </select>

  <select id="selectTaskWithVariablesByQueryCriteria_mssql_or_db2" parameterType="org.activiti.engine.impl.TaskQueryImpl" resultMap="taskAndVariablesResultMap">
    ${limitBefore}
    select distinct TEMPRES_ID_ as ID_, TEMPRES_REV_ as REV_, TEMPRES_NAME_ as NAME_,
    TEMPRES_PARENT_TASK_ID_ as PARENT_TASK_ID_, TEMPRES_DESCRIPTION_ as DESCRIPTION_,
    TEMPRES_PRIORITY_ as PRIORITY_, TEMPRES_CREATE_TIME_ as CREATE_TIME_,
    TEMPRES_OWNER_ as OWNER_, TEMPRES_ASSIGNEE_ as ASSIGNEE_, TEMPRES_DELEGATION_ as DELEGATION_,
    TEMPRES_EXECUTION_ID_ as EXECUTION_ID_, TEMPRES_PROC_INST_ID_ as PROC_INST_ID_,
    TEMPRES_PROC_DEF_ID_ as PROC_DEF_ID_, TEMPRES_TASK_DEF_KEY_ as TASK_DEF_KEY_,
    TEMPRES_DUE_DATE_ as DUE_DATE_, TEMPRES_SUSPENSION_STATE_ as SUSPENSION_STATE_,
    TEMPVAR_ID_ as VAR_ID_, TEMPVAR_NAME_ as VAR_NAME_, TEMPVAR_TYPE_ as VAR_TYPE_, TEMPVAR_REV_ as VAR_REV_,
    TEMPVAR_PROC_INST_ID_ as VAR_PROC_INST_ID_, TEMPVAR_EXECUTION_ID_ as VAR_EXECUTION_ID_, TEMPVAR_TASK_ID_ as VAR_TASK_ID_,
    TEMPVAR_BYTEARRAY_ID_ as VAR_BYTEARRAY_ID_, TEMPVAR_DOUBLE_ as VAR_DOUBLE_,
    TEMPVAR_TEXT_ as VAR_TEXT_, TEMPVAR_TEXT2_ as VAR_TEXT2_, TEMPVAR_LONG_ as VAR_LONG_
    ${limitOuterJoinBetween}
    RES.ID_ as TEMPRES_ID_, RES.REV_ as TEMPRES_REV_, RES.NAME_ as TEMPRES_NAME_,
    RES.PARENT_TASK_ID_ as TEMPRES_PARENT_TASK_ID_, RES.DESCRIPTION_ as TEMPRES_DESCRIPTION_,
    RES.PRIORITY_ as TEMPRES_PRIORITY_, RES.CREATE_TIME_ as TEMPRES_CREATE_TIME_,
    RES.OWNER_ as TEMPRES_OWNER_, RES.ASSIGNEE_ as TEMPRES_ASSIGNEE_, RES.DELEGATION_ as TEMPRES_DELEGATION_,
    RES.EXECUTION_ID_ as TEMPRES_EXECUTION_ID_, RES.PROC_INST_ID_ as TEMPRES_PROC_INST_ID_,
    RES.PROC_DEF_ID_ as TEMPRES_PROC_DEF_ID_, RES.TASK_DEF_KEY_ as TEMPRES_TASK_DEF_KEY_,
    RES.DUE_DATE_ as TEMPRES_DUE_DATE_, RES.SUSPENSION_STATE_ as TEMPRES_SUSPENSION_STATE_,
    VAR.ID_ as TEMPVAR_ID_, VAR.NAME_ as TEMPVAR_NAME_, VAR.TYPE_ as TEMPVAR_TYPE_, VAR.REV_ as TEMPVAR_REV_,
    VAR.PROC_INST_ID_ as TEMPVAR_PROC_INST_ID_, VAR.EXECUTION_ID_ as TEMPVAR_EXECUTION_ID_, VAR.TASK_ID_ as TEMPVAR_TASK_ID_,
    VAR.BYTEARRAY_ID_ as TEMPVAR_BYTEARRAY_ID_, VAR.DOUBLE_ as TEMPVAR_DOUBLE_,
    VAR.TEXT_ as TEMPVAR_TEXT_, VAR.TEXT2_ as TEMPVAR_TEXT2_, VAR.LONG_ as TEMPVAR_LONG_
    <include refid="selectTaskWithVariablesByQueryCriteriaSql"/>
    ${orderBy}
    ${limitAfter}
  </select>

  <sql id="selectTaskWithVariablesByQueryCriteriaSql">
    from ${prefix}ACT_RU_TASK RES
    <choose>
      <when test="includeTaskLocalVariables && includeProcessVariables">
        left outer join ${prefix}ACT_RU_VARIABLE VAR ON RES.ID_ = VAR.TASK_ID_ or RES.PROC_INST_ID_ = VAR.EXECUTION_ID_
      </when>
      <otherwise>
        <if test="includeTaskLocalVariables">
          left outer join ${prefix}ACT_RU_VARIABLE VAR ON RES.ID_ = VAR.TASK_ID_
        </if>
        <if test="includeProcessVariables">
          left outer join ${prefix}ACT_RU_VARIABLE VAR ON RES.PROC_INST_ID_ = VAR.EXECUTION_ID_ and VAR.TASK_ID_ is null
        </if>
      </otherwise>
    </choose>
    <include refid="commonSelectTaskByQueryCriteriaSql"/>
  </sql>

  <sql id="commonSelectTaskByQueryCriteriaSql">
    <if test="candidateUser != null || candidateGroups != null || bothCandidateAndAssigned || (orQueryObject != null && (orQueryObject.candidateUser != null || orQueryObject.candidateGroups != null || orQueryObject.bothCandidateAndAssigned))">
      <choose>
        <when test="bothCandidateAndAssigned || (orQueryObject != null && orQueryObject.bothCandidateAndAssigned)">left</when>
        <otherwise>inner</otherwise>
      </choose>
      join ${prefix}ACT_RU_IDENTITYLINK I on I.TASK_ID_ = RES.ID_
    </if>
    <foreach collection="queryVariableValues" index="index" item="var">
      <choose>
        <when test="var.local">
          inner join ${prefix}ACT_RU_VARIABLE A${index} on RES.ID_ = A${index}.TASK_ID_
        </when>
        <otherwise>
          inner join ${prefix}ACT_RU_VARIABLE A${index} on RES.PROC_INST_ID_ = A${index}.PROC_INST_ID_
        </otherwise>
      </choose>
    </foreach>
     <if test="orQueryObject != null">
      <foreach collection="orQueryObject.queryVariableValues" index="index" item="var">
        <choose>
          <when test="var.local">
            left outer join ${prefix}ACT_RU_VARIABLE A_OR${index} on RES.ID_ = A_OR${index}.TASK_ID_
          </when>
          <otherwise>
            left outer join ${prefix}ACT_RU_VARIABLE A_OR${index} on RES.PROC_INST_ID_ = A_OR${index}.PROC_INST_ID_
          </otherwise>
        </choose>
      </foreach>
      </if>

    <if test="processDefinitionKey != null || processDefinitionKeyLike != null ||  processDefinitionKeyLikeIgnoreCase != null || processDefinitionName != null || processDefinitionNameLike != null || (orQueryObject != null && (orQueryObject.processDefinitionKey != null || orQueryObject.processDefinitionKeyLike != null || orQueryObject.processDefinitionKeyLikeIgnoreCase != null || orQueryObject.processDefinitionName != null || orQueryObject.processDefinitionNameLike != null))">
      inner join ${prefix}ACT_RE_PROCDEF D on RES.PROC_DEF_ID_ = D.ID_
    </if>
    <if test="processInstanceBusinessKey != null || processInstanceBusinessKeyLike != null  || processInstanceBusinessKeyLikeIgnoreCase != null || (orQueryObject != null && (orQueryObject.processInstanceBusinessKey != null || orQueryObject.processInstanceBusinessKeyLike != null || orQueryObject.processInstanceBusinessKeyLikeIgnoreCase != null))">
        inner join ${prefix}ACT_RU_EXECUTION E on RES.PROC_INST_ID_ = E.ID_
    </if>
    <if test="deploymentId != null || (deploymentIds != null && deploymentIds.size() > 0) || (orQueryObject != null && (orQueryObject.deploymentId != null || (orQueryObject.deploymentIds != null && orQueryObject.deploymentIds.size() > 0)))">
      left outer join ${prefix}ACT_RE_PROCDEF DEPLOY_P ON RES.PROC_DEF_ID_ = DEPLOY_P.ID_
    </if>
    <where>
      <if test="taskId != null">
        RES.ID_ = #{taskId}
      </if>
      <if test="name != null">
        and RES.NAME_ = #{name}
      </if>
      <if test="nameLike != null">
        and RES.NAME_ like #{nameLike}
      </if>
      <if test="nameLikeIgnoreCase != null">
        and lower(RES.NAME_) like #{nameLikeIgnoreCase}
      </if>
      <if test="nameList != null && nameList.size() > 0">
        and RES.NAME_ IN
        <foreach item="name" index="index" collection="nameList"
                 open="(" separator="," close=")">
          #{name}
        </foreach>
      </if>
      <if test="nameListIgnoreCase != null && nameListIgnoreCase.size() > 0">
        and lower(RES.NAME_) IN
        <foreach item="name" index="index" collection="nameListIgnoreCase"
                 open="(" separator="," close=")">
          #{name}
        </foreach>
      </if>
      <if test="description != null">
        and RES.DESCRIPTION_ = #{description}
      </if>
      <if test="descriptionLike != null">
        and RES.DESCRIPTION_ like #{descriptionLike}
      </if>
      <if test="descriptionLikeIgnoreCase != null">
        and lower(RES.DESCRIPTION_) like #{descriptionLikeIgnoreCase}
      </if>
      <if test="priority != null">
        and RES.PRIORITY_ = #{priority}
      </if>
      <if test="minPriority != null">
        and RES.PRIORITY_ >= #{minPriority}
      </if>
      <if test="maxPriority != null">
        and RES.PRIORITY_ <= #{maxPriority}
      </if>
      <if test="assignee != null">
        and RES.ASSIGNEE_ = #{assignee}
      </if>
      <if test="assigneeLike != null">
        and RES.ASSIGNEE_ like #{assigneeLike}
      </if>
      <if test="assigneeLikeIgnoreCase != null">
        and lower(RES.ASSIGNEE_) like #{assigneeLikeIgnoreCase}
      </if>
      <if test="owner != null">
        and RES.OWNER_ = #{owner}
      </if>
      <if test="ownerLike != null">
        and RES.OWNER_ like #{ownerLike}
      </if>
       <if test="ownerLikeIgnoreCase != null">
        and lower(RES.OWNER_) like #{ownerLikeIgnoreCase}
      </if>
      <if test="unassigned">
        and RES.ASSIGNEE_ IS NULL
      </if>
      <if test="noDelegationState">
        and RES.DELEGATION_ IS NULL
      </if>
      <if test="delegationState != null">
        and RES.DELEGATION_ = #{delegationStateString}
      </if>
      <if test="processInstanceId != null">
        and RES.PROC_INST_ID_ = #{processInstanceId}
      </if>
      <if test="processInstanceBusinessKey != null">
        and E.BUSINESS_KEY_ = #{processInstanceBusinessKey}
      </if>
      <if test="processInstanceBusinessKeyLike != null">
        and E.BUSINESS_KEY_ like #{processInstanceBusinessKeyLike}
      </if>
      <if test="processInstanceBusinessKeyLikeIgnoreCase != null">
        and lower(E.BUSINESS_KEY_) like #{processInstanceBusinessKeyLikeIgnoreCase}
      </if>
      <if test="executionId != null">
        and RES.EXECUTION_ID_ = #{executionId}
      </if>
      <if test="createTime != null">
        and RES.CREATE_TIME_ = #{createTime}
      </if>
      <if test="createTimeBefore != null">
        and RES.CREATE_TIME_ < #{createTimeBefore}
      </if>
      <if test="createTimeAfter != null">
        and RES.CREATE_TIME_ > #{createTimeAfter}
      </if>
      <if test="key != null">
        and RES.TASK_DEF_KEY_ = #{key}
      </if>
      <if test="keyLike != null">
        and RES.TASK_DEF_KEY_ like #{keyLike}
      </if>
      <if test="processDefinitionId != null">
        and RES.PROC_DEF_ID_ = #{processDefinitionId}
      </if>
      <if test="processDefinitionKey != null">
        and D.KEY_ = #{processDefinitionKey}
      </if>
      <if test="processDefinitionKeyLike != null">
        and D.KEY_ like #{processDefinitionKeyLike}
      </if>
      <if test="processDefinitionKeyLikeIgnoreCase != null">
        and lower(D.KEY_) like #{processDefinitionKeyLikeIgnoreCase}
      </if>
      <if test="processDefinitionName != null">
        and D.NAME_ = #{processDefinitionName}
      </if>
      <if test="processDefinitionNameLike != null">
        and D.NAME_ like #{processDefinitionNameLike}
      </if>
      <if test="deploymentId != null">
        and DEPLOY_P.DEPLOYMENT_ID_ = #{deploymentId}
      </if>
      <if test="deploymentIds != null && deploymentIds.size() > 0">
        and DEPLOY_P.DEPLOYMENT_ID_ IN
        <foreach item="deployment" index="index" collection="deploymentIds"
                 open="(" separator="," close=")">
          #{deployment}
        </foreach>
      </if>
      <if test="dueDate != null">
        and RES.DUE_DATE_ = #{dueDate}
      </if>
      <if test="dueBefore != null">
        and RES.DUE_DATE_ < #{dueBefore}
      </if>
      <if test="dueAfter != null">
        and RES.DUE_DATE_ > #{dueAfter}
      </if>
      <if test="withoutDueDate">
        and RES.DUE_DATE_ is null
      </if>
      <if test="dueDate != null || dueBefore != null || dueAfter != null">
        and RES.DUE_DATE_ is not null
      </if>
      <if test="category != null">
        and RES.CATEGORY_ = #{category}
      </if>
      <if test="excludeSubtasks">
        and RES.PARENT_TASK_ID_ IS NULL
      </if>
      <if test="!bothCandidateAndAssigned && (candidateUser != null || candidateGroups != null)">
        and RES.ASSIGNEE_ is null
        and I.TYPE_ = 'candidate'
        and
        (
          <if test="candidateUser != null">
            I.USER_ID_ = #{candidateUser}
          </if>
          <if test="candidateUser != null && candidateGroups != null && candidateGroups.size() > 0">
            or
          </if>
          <if test="candidateGroups != null && candidateGroups.size() > 0">
            I.GROUP_ID_ IN
            <foreach item="group" index="index" collection="candidateGroups"
                     open="(" separator="," close=")">
              #{group}
            </foreach>
          </if>
        )
      </if>
      <if test="involvedUser != null">
        and (
          exists(select LINK.USER_ID_ from ${prefix}ACT_RU_IDENTITYLINK LINK where USER_ID_ = #{involvedUser} and LINK.TASK_ID_ = RES.ID_)
          or RES.ASSIGNEE_ = #{involvedUser}
          or RES.OWNER_ = #{involvedUser}
          )
      </if>
      <foreach item="var" collection="queryVariableValues" index="index">
        <if test="!var.local">
          <!-- When process instance variable is queried for, taskId should be null -->
          and A${index}.TASK_ID_ is null
        </if>
        <if test="var.name != null">
          <!-- Match-all variable-names when name is null -->
          and A${index}.NAME_= #{var.name}
        </if>
        <if test="var.name == null">
          and A${index}.NAME_ is not null
        </if>
        <if test="!var.type.equals('null')">
          and A${index}.TYPE_ = #{var.type}
        </if>

        <!-- Variable value -->
        <if test="var.textValue != null && var.longValue == null && var.doubleValue == null">
          <choose>
            <when test="var.operator.equals('EQUALS_IGNORE_CASE') || var.operator.equals('NOT_EQUALS_IGNORE_CASE')">
              and lower(A${index}.TEXT_)
            </when>
            <otherwise>
              and A${index}.TEXT_
            </otherwise>
          </choose>
          <choose>
              <when test="var.operator.equals('LIKE')">LIKE</when>
              <otherwise><include refid="executionVariableOperator" /></otherwise>
          </choose>
          #{var.textValue}
        </if>
        <if test="var.textValue2 != null">
          and A${index}.TEXT2_
          <choose>
            <when test="var.operator.equals('LIKE')">LIKE</when>
            <otherwise><include refid="executionVariableOperator" /></otherwise>
          </choose>
          #{var.textValue2}
        </if>
        <if test="var.longValue != null">
          and A${index}.LONG_
          <include refid="executionVariableOperator" />
          #{var.longValue}
        </if>
        <if test="var.doubleValue != null">
          and A${index}.DOUBLE_
          <include refid="executionVariableOperator" />
          #{var.doubleValue}
        </if>
        <!-- Null variable type -->
        <if test="var.textValue == null && var.textValue2 == null && var.longValue == null && var.doubleValue == null">
          <choose>
            <when test="var.operator.equals('NOT_EQUALS')">
              and (A${index}.TEXT_ is not null or A${index}.TEXT2_ is not null or A${index}.LONG_ is not null or A${index}.DOUBLE_ is not null or A${index}.BYTEARRAY_ID_ is not null)
            </when>
            <otherwise>
              and A${index}.TEXT_ is null and A${index}.TEXT2_ is null and A${index}.LONG_ is null and A${index}.DOUBLE_ is null and A${index}.BYTEARRAY_ID_ is null
            </otherwise>
          </choose>
        </if>
      </foreach>
      <if test="suspensionState != null">
        <if test="suspensionState.stateCode == 1">
            and RES.SUSPENSION_STATE_ = 1
        </if>
        <if test="suspensionState.stateCode == 2">
            and RES.SUSPENSION_STATE_ = 2
        </if>
      </if>
      <if test="tenantId != null">
        and RES.TENANT_ID_ = #{tenantId}
      </if>
      <if test="tenantIdLike != null">
        and RES.TENANT_ID_ like #{tenantIdLike}
      </if>
      <if test="withoutTenantId">
        and (RES.TENANT_ID_ = '' or RES.TENANT_ID_ is null)
      </if>
      <choose>
        <when test="bothCandidateAndAssigned">
          <!-- if dbIdentityUsed set true in process engine configuration -->
          <if test="userIdForCandidateAndAssignee != null">
            <if test="candidateGroups == null">
              and (RES.ASSIGNEE_ = #{userIdForCandidateAndAssignee} or (RES.ASSIGNEE_ is null and (I.USER_ID_ = #{userIdForCandidateAndAssignee}
              or I.GROUP_ID_ IN (select g.GROUP_ID_ from ACT_ID_MEMBERSHIP g where g.USER_ID_ = #{userIdForCandidateAndAssignee} ) ) ) )
            </if>
          </if>
          <!-- if dbIdentityUsed set false in process engine configuration of using custom session factory of GroupIdentityManager -->
          <if test="candidateGroups != null">
            and (RES.ASSIGNEE_ = #{userIdForCandidateAndAssignee}
            or (RES.ASSIGNEE_ is null
            and I.TYPE_ = 'candidate' and (I.USER_ID_ = #{userIdForCandidateAndAssignee}
            <if test="candidateGroups.size() > 0">
              or I.GROUP_ID_ IN
              <foreach item="group" index="index" collection="candidateGroups"
                       open="(" separator="," close=")">
                #{group}
              </foreach>
            </if>
            )))
          </if>
        </when>
      </choose>
      <if test="orQueryObject != null">
        and
        <trim prefix="(" prefixOverrides="OR" suffix=")">
            <if test="orQueryObject.taskId != null">
              RES.ID_ = #{orQueryObject.taskId}
            </if>
            <if test="orQueryObject.name != null">
              or RES.NAME_ = #{orQueryObject.name}
            </if>
            <if test="orQueryObject.nameLike != null">
              or RES.NAME_ like #{orQueryObject.nameLike}
            </if>
            <if test="orQueryObject.nameLikeIgnoreCase != null">
              or lower(RES.NAME_) like #{orQueryObject.nameLikeIgnoreCase}
            </if>
            <if test="orQueryObject.nameList != null && orQueryObject.nameList.size() > 0">
              or RES.NAME_ IN
              <foreach item="name" index="index" collection="orQueryObject.nameList"
                      open="(" separator="," close=")">
                #{name}
              </foreach>
            </if>
            <if test="orQueryObject.nameListIgnoreCase != null && orQueryObject.nameListIgnoreCase.size() > 0">
              or lower(RES.NAME_) IN
              <foreach item="name" index="index" collection="orQueryObject.nameListIgnoreCase"
                       open="(" separator="," close=")">
                #{name}
              </foreach>
            </if>
            <if test="orQueryObject.description != null">
              or RES.DESCRIPTION_ = #{orQueryObject.description}
            </if>
            <if test="orQueryObject.descriptionLike != null">
              or RES.DESCRIPTION_ like #{orQueryObject.descriptionLike}
            </if>
             <if test="orQueryObject.descriptionLikeIgnoreCase != null">
              or lower(RES.DESCRIPTION_) like #{orQueryObject.descriptionLikeIgnoreCase}
            </if>
            <if test="orQueryObject.priority != null">
              or RES.PRIORITY_ = #{orQueryObject.priority}
            </if>
            <if test="orQueryObject.minPriority != null">
              or RES.PRIORITY_ >= #{orQueryObject.minPriority}
            </if>
            <if test="orQueryObject.maxPriority != null">
              or RES.PRIORITY_ <= #{orQueryObject.maxPriority}
            </if>
            <if test="orQueryObject.assignee != null">
              or RES.ASSIGNEE_ = #{orQueryObject.assignee}
            </if>
            <if test="orQueryObject.assigneeLike != null">
              or RES.ASSIGNEE_ like #{orQueryObject.assigneeLike}
            </if>
            <if test="orQueryObject.assigneeLikeIgnoreCase != null">
              or lower(RES.ASSIGNEE_) like #{orQueryObject.assigneeLikeIgnoreCase}
            </if>
            <if test="orQueryObject.owner != null">
              or RES.OWNER_ = #{orQueryObject.owner}
            </if>
            <if test="orQueryObject.ownerLike != null">
              or RES.OWNER_ like #{orQueryObject.ownerLike}
            </if>
            <if test="orQueryObject.ownerLikeIgnoreCase != null">
              or RES.OWNER_ like #{orQueryObject.ownerLikeIgnoreCase}
            </if>
            <if test="orQueryObject.unassigned">
              or RES.ASSIGNEE_ IS NULL
            </if>
            <if test="orQueryObject.noDelegationState">
              or RES.DELEGATION_ IS NULL
            </if>
            <if test="orQueryObject.delegationState != null">
              or RES.DELEGATION_ = #{orQueryObject.delegationStateString}
            </if>
            <if test="orQueryObject.processInstanceId != null">
              or RES.PROC_INST_ID_ = #{orQueryObject.processInstanceId}
            </if>
            <if test="orQueryObject.processInstanceBusinessKey != null">
              or E.BUSINESS_KEY_ = #{orQueryObject.processInstanceBusinessKey}
            </if>
            <if test="orQueryObject.processInstanceBusinessKeyLike != null">
              or E.BUSINESS_KEY_ like #{orQueryObject.processInstanceBusinessKeyLike}
            </if>
            <if test="orQueryObject.processInstanceBusinessKeyLikeIgnoreCase != null">
              or lower(E.BUSINESS_KEY_) like #{orQueryObject.processInstanceBusinessKeyLikeIgnoreCase}
            </if>
            <if test="orQueryObject.executionId != null">
              or RES.EXECUTION_ID_ = #{orQueryObject.executionId}
            </if>
            <if test="orQueryObject.createTime != null">
              or RES.CREATE_TIME_ = #{orQueryObject.createTime}
            </if>
            <if test="orQueryObject.createTimeBefore != null">
              or RES.CREATE_TIME_ < #{orQueryObject.createTimeBefore}
            </if>
            <if test="orQueryObject.createTimeAfter != null">
              or RES.CREATE_TIME_ > #{orQueryObject.createTimeAfter}
            </if>
            <if test="orQueryObject.key != null">
              or RES.TASK_DEF_KEY_ = #{orQueryObject.key}
            </if>
            <if test="orQueryObject.keyLike != null">
              or RES.TASK_DEF_KEY_ like #{orQueryObject.keyLike}
            </if>
            <if test="orQueryObject.processDefinitionId != null">
              or RES.PROC_DEF_ID_ = #{orQueryObject.processDefinitionId}
            </if>
            <if test="orQueryObject.processDefinitionKey != null">
              or D.KEY_ = #{orQueryObject.processDefinitionKey}
            </if>
            <if test="orQueryObject.processDefinitionKeyLike != null">
              or D.KEY_ like #{orQueryObject.processDefinitionKeyLike}
            </if>
             <if test="orQueryObject.processDefinitionKeyLikeIgnoreCase != null">
              or lower(D.KEY_) like #{orQueryObject.processDefinitionKeyLikeIgnoreCase}
            </if>
            <if test="orQueryObject.processDefinitionName != null">
              or D.NAME_ = #{orQueryObject.processDefinitionName}
            </if>
            <if test="orQueryObject.processDefinitionNameLike != null">
              or D.NAME_ like #{orQueryObject.processDefinitionNameLike}
            </if>
            <if test="orQueryObject.deploymentId != null">
              or DEPLOY_P.DEPLOYMENT_ID_ = #{orQueryObject.deploymentId}
            </if>
            <if test="orQueryObject.deploymentIds != null && orQueryObject.deploymentIds.size() > 0">
              or DEPLOY_P.DEPLOYMENT_ID_ IN
              <foreach item="deployment" index="index" collection="orQueryObject.deploymentIds"
                       open="(" separator="," close=")">
                #{deployment}
              </foreach>
            </if>
            <if test="orQueryObject.dueDate != null">
              or RES.DUE_DATE_ = #{orQueryObject.dueDate}
            </if>
            <if test="orQueryObject.dueBefore != null">
              or (RES.DUE_DATE_ < #{orQueryObject.dueBefore} and RES.DUE_DATE_ is not null)
            </if>
            <if test="orQueryObject.dueAfter != null">
              or (RES.DUE_DATE_ > #{orQueryObject.dueAfter} and RES.DUE_DATE_ is not null)
            </if>
            <if test="orQueryObject.withoutDueDate">
              or RES.DUE_DATE_ is null
            </if>
            <if test="orQueryObject.category != null">
              or RES.CATEGORY_ = #{orQueryObject.category}
            </if>
            <if test="orQueryObject.excludeSubtasks">
              or RES.PARENT_TASK_ID_ IS NULL
            </if>

            <if test="!orQueryObject.bothCandidateAndAssigned && (orQueryObject.candidateUser != null || orQueryObject.candidateGroups != null)">
              or (RES.ASSIGNEE_ is null
              and I.TYPE_ = 'candidate'
              and
              (
                <if test="orQueryObject.candidateUser != null">
                  I.USER_ID_ = #{orQueryObject.candidateUser}
                </if>
                <if test="orQueryObject.candidateUser != null && orQueryObject.candidateGroups != null && orQueryObject.candidateGroups.size() > 0">
                  or
                </if>
                <if test="orQueryObject.candidateGroups != null && orQueryObject.candidateGroups.size() > 0">
                  I.GROUP_ID_ IN
                  <foreach item="group" index="index" collection="orQueryObject.candidateGroups"
                           open="(" separator="," close=")">
                    #{group}
                  </foreach>
                </if>
              ))
            </if>
            <if test="orQueryObject.involvedUser != null">
              or (
                exists(select LINK.USER_ID_ from ${prefix}ACT_RU_IDENTITYLINK LINK where USER_ID_ = #{orQueryObject.involvedUser} and LINK.TASK_ID_ = RES.ID_)
                or RES.ASSIGNEE_ = #{orQueryObject.involvedUser}
                or RES.OWNER_ = #{orQueryObject.involvedUser}
                )
            </if>
            <foreach item="var" collection="orQueryObject.queryVariableValues" index="index">
              or
              <trim prefix="(" prefixOverrides="AND" suffix=")">
              <if test="!var.local">
                <!-- When process instance variable is queried for, taskId should be null -->
                and A_OR${index}.TASK_ID_ is null
              </if>
              <if test="var.name != null">
                <!-- Match-all variable-names when name is null -->
                and A_OR${index}.NAME_= #{var.name}
              </if>
              <if test="var.name == null">
          		and A_OR${index}.NAME_ is not null
        	  </if>
              <if test="!var.type.equals('null')">
                and A_OR${index}.TYPE_ = #{var.type}
              </if>
              <!-- Variable value -->
              <if test="var.textValue != null && var.longValue == null && var.doubleValue == null">
                <choose>
                  <when test="var.operator.equals('EQUALS_IGNORE_CASE') || var.operator.equals('NOT_EQUALS_IGNORE_CASE')">
                    and lower(A_OR${index}.TEXT_)
                  </when>
                  <otherwise>
                    and A_OR${index}.TEXT_
                  </otherwise>
                </choose>
                <choose>
                    <when test="var.operator.equals('LIKE')">LIKE</when>
                    <otherwise><include refid="executionVariableOperator" /></otherwise>
                </choose>
                #{var.textValue}
              </if>
              <if test="var.textValue2 != null">
                and A_OR${index}.TEXT2_
                <choose>
                  <when test="var.operator.equals('LIKE')">LIKE</when>
                  <otherwise><include refid="executionVariableOperator" /></otherwise>
                </choose>
                #{var.textValue2}
              </if>
              <if test="var.longValue != null">
                and A_OR${index}.LONG_
                <include refid="executionVariableOperator" />
                #{var.longValue}
              </if>
              <if test="var.doubleValue != null">
                and A_OR${index}.DOUBLE_
                <include refid="executionVariableOperator" />
                #{var.doubleValue}
              </if>
              <!-- Null variable type -->
              <if test="var.textValue == null && var.textValue2 == null && var.longValue == null && var.doubleValue == null">
                <choose>
                  <when test="var.operator.equals('NOT_EQUALS')">
                    and (A_OR${index}.TEXT_ is not null or A_OR${index}.TEXT2_ is not null or A_OR${index}.LONG_ is not null or A_OR${index}.DOUBLE_ is not null or A_OR${index}.BYTEARRAY_ID_ is not null)
                  </when>
                  <otherwise>
                    and A_OR${index}.TEXT_ is null and A_OR${index}.TEXT2_ is null and A_OR${index}.LONG_ is null and A_OR${index}.DOUBLE_ is null and A_OR${index}.BYTEARRAY_ID_ is null
                  </otherwise>
                </choose>
              </if>
              </trim>
            </foreach>
            <if test="orQueryObject.suspensionState != null">
              <if test="orQueryObject.suspensionState.stateCode == 1">
                  or RES.SUSPENSION_STATE_ = 1
              </if>
              <if test="orQueryObject.suspensionState.stateCode == 2">
                  or RES.SUSPENSION_STATE_ = 2
              </if>
            </if>
            <if test="orQueryObject.tenantId != null">
              or RES.TENANT_ID_ = #{orQueryObject.tenantId}
            </if>
            <if test="orQueryObject.tenantIdLike != null">
              or RES.TENANT_ID_ like #{orQueryObject.tenantIdLike}
            </if>
            <if test="orQueryObject.withoutTenantId">
              or (RES.TENANT_ID_ = '' or RES.TENANT_ID_ is null)
            </if>
            <choose>
              <when test="orQueryObject.bothCandidateAndAssigned">
                <!-- if dbIdentityUsed set true in process engine configuration -->
                <if test="orQueryObject.userIdForCandidateAndAssignee != null">
                  <if test="orQueryObject.candidateGroups == null">
                    or (RES.ASSIGNEE_ = #{orQueryObject.userIdForCandidateAndAssignee} or (RES.ASSIGNEE_ is null and (I.USER_ID_ = #{orQueryObject.userIdForCandidateAndAssignee}
                    or I.GROUP_ID_ IN (select g.GROUP_ID_ from ACT_ID_MEMBERSHIP g where g.USER_ID_ = #{orQueryObject.userIdForCandidateAndAssignee} ) ) ) )
                  </if>
                </if>
                <!-- if dbIdentityUsed set false in process engine configuration of using custom session factory of GroupIdentityManager -->
                <if test="orQueryObject.candidateGroups != null">
                  or (RES.ASSIGNEE_ = #{orQueryObject.userIdForCandidateAndAssignee}
                  or (RES.ASSIGNEE_ is null
                  and I.TYPE_ = 'candidate' and (I.USER_ID_ = #{orQueryObject.userIdForCandidateAndAssignee}
                  <if test="orQueryObject.candidateGroups.size() > 0">
                    or I.GROUP_ID_ IN
                    <foreach item="group" index="index" collection="orQueryObject.candidateGroups"
                             open="(" separator="," close=")">
                      #{group}
                    </foreach>
                  </if>
                  )))
                </if>
              </when>
            </choose>
          </trim>
        </if>
     </where>
  </sql>

  <sql id="executionVariableOperator">
    <choose>
      <when test="var.operator.equals('EQUALS')">=</when>
      <when test="var.operator.equals('EQUALS_IGNORE_CASE')">=</when>
      <when test="var.operator.equals('NOT_EQUALS')"><></when>
      <when test="var.operator.equals('NOT_EQUALS_IGNORE_CASE')"><></when>
      <when test="var.operator.equals('GREATER_THAN')">></when>
      <when test="var.operator.equals('GREATER_THAN_OR_EQUAL')">>=</when>
      <when test="var.operator.equals('LESS_THAN')"><</when>
      <when test="var.operator.equals('LESS_THAN_OR_EQUAL')"><=</when>
   </choose>
  </sql>

  <select id="selectTaskByNativeQuery" parameterType="java.util.Map" resultMap="taskResultMap">
  	<if test="resultType == 'LIST_PAGE'">
  		${limitBefore}
  	</if>
    ${sql}
    <if test="resultType == 'LIST_PAGE'">
  		${limitAfter}
  	</if>
  </select>

  <select id="selectTaskByNativeQuery_mssql_or_db2" parameterType="java.util.Map" resultMap="taskResultMap">
  	<if test="resultType == 'LIST_PAGE'">
  		${limitBeforeNativeQuery}
  	</if>
  	${sql}
    <if test="resultType == 'LIST_PAGE'">
  		${limitAfter}
  	</if>
  </select>

  <select id="selectTaskCountByNativeQuery" parameterType="java.util.Map" resultType="long">
     ${sql}
  </select>

</mapper>


text:
package org.apache.bookkeeper.mledger.offload.jcloud.impl;

import org.apache.bookkeeper.mledger.offload.jcloud.OffloadIndexEntry;

/**
 * The Index Entry in OffloadIndexBlock.
 */
public class OffloadIndexEntryImpl implements OffloadIndexEntry {
    public static OffloadIndexEntryImpl of(long entryId, int partId, long offset, long blockHeaderSize) {
        return new OffloadIndexEntryImpl(entryId, partId, offset, blockHeaderSize);
    }

    private final long entryId;
    private final int partId;
    private final long offset;
    private final long blockHeaderSize;

    @Override
    public long getEntryId() {
        return entryId;
    }

    @Override
    public int getPartId() {
        return partId;
    }

    @Override
    public long getOffset() {
        return offset;
    }

    @Override
    public long getDataOffset() {
        return offset + blockHeaderSize;
    }

    private OffloadIndexEntryImpl(long entryId, int partId, long offset, long blockHeaderSize) {
        this.entryId = entryId;
        this.partId = partId;
        this.offset = offset;
        this.blockHeaderSize = blockHeaderSize;
    }

    @Override
    public String toString() {
        return String.format("[eid:%d, part:%d, offset:%d, doffset:%d]",
                entryId, partId, offset, getDataOffset());
    }
}

redpajama_set_name: RedPajamaGithub


text:
AnimalType = {};
AnimalType_mt = Class(AnimalType, AnimalMod);

InitObjectClass(AnimalType, "AnimalType", ObjectIds.OBJECT_ANIMAL);

addModEventListener(AnimalType);

AnimalMod.AnimalTypes = {};
--
local modItem = ModsUtil.findModItemByModName(g_currentModName);

AnimalType.classId = nil ;
AnimalType.className = "AnimalType";
AnimalType.Filename = "animalt.lua";

local a = AnimalMod;
local husbandries = {};
local tmpHusbandries = {}; -- only to store the husbandry animals during load
tmpHusbandries.cow = {};
tmpHusbandries.sheep = {};
tmpHusbandries.chicken = {};

AnimalMod.NUM_ANIMALTYPES = 4;
local unknown = "unknown";
AnimalMod.ANIMALTYPE_UNKNOWN = 0;
AnimalMod.ANIMALTYPE_COW = 1;
AnimalMod.ANIMALTYPE_SHEEP = 2;
AnimalMod.ANIMALTYPE_CHICKEN = 3;

a.animalTypeIntToName = {};
a.animalTypeNameToInt = {};

a.animalTypeToFillType = {};
a.fillTypeToAnimalType = {};
a.animalTypeIndexToDesc = {};

a.husbandriesIntToName = {};
a.husbandriesNameToInt = {};

a.husbandriesTypeIndexToDesc = {};

local function addGame()
     AnimalMod.NUM_ANIMALTYPES = 0;
     a.AnimalTypes[unknown] = AnimalMod.NUM_ANIMALTYPES;
     husbandries[unknown] = AnimalMod.NUM_ANIMALTYPES;

     a.husbandriesNameToInt[unknown] = AnimalMod.NUM_ANIMALTYPES;
     a.husbandriesIntToName[AnimalMod.NUM_ANIMALTYPES] = unknown;
     a.animalTypeNameToInt[unknown] = AnimalMod.NUM_ANIMALTYPES;
     a.animalTypeIntToName[AnimalMod.NUM_ANIMALTYPES] = unknown;
     local desc = {name = unknown, index = AnimalMod.NUM_ANIMALTYPES};
        desc.litersPerSqmPerSecond = litersPerSqmPerSecond;
        desc.massPerLiter = Utils.getNoNil(massPerLiter, 0.0001);
     local self = {name = unknown, index = AnimalMod.NUM_ANIMALTYPES};
     self.type = unknown;
     self.fillType = Fillable.FILLTYPE_UNKNOWN;
     self.animalType = AnimalMod.ANIMALTYPE_UNKNOWN;
     self.husbandryType = AnimalMod.ANIMALTYPE_UNKNOWN;
     self.fillLevel = 0;
     self.i3dFilename = "";
     self.fileName = "";
     self.litersPerSqmPerSecond = 0.1;
     self.massPerLiter = Utils.getNoNil(massPerLiter, 0.0001);
     AnimalMod.AnimalTypes[unknown] = self;
     AnimalMod.animalTypeIndexToDesc[AnimalMod.NUM_ANIMALTYPES] = self;
     AnimalMod.husbandriesTypeIndexToDesc[AnimalMod.NUM_ANIMALTYPES] = self;
-- adding the game animaltypes --
-- cow
     AnimalMod.NUM_ANIMALTYPES = AnimalMod.NUM_ANIMALTYPES + 1;
     a.husbandriesNameToInt["cow"] = AnimalMod.NUM_ANIMALTYPES;
     a.husbandriesIntToName[AnimalMod.NUM_ANIMALTYPES] = "cow";
     a.animalTypeNameToInt["cow"] = AnimalMod.NUM_ANIMALTYPES;
     a.animalTypeIntToName[AnimalMod.NUM_ANIMALTYPES] = "cow";
     local desc = {name = "cow", index = AnimalMod.NUM_ANIMALTYPES};
        desc.litersPerSqmPerSecond = litersPerSqmPerSecond;
        desc.massPerLiter = Utils.getNoNil(massPerLiter, 0.0001);
     local self = {name = "cow", index = AnimalMod.NUM_ANIMALTYPES};
     self.type = "cow";
     self.fillType = Fillable.FILLTYPE_COW;
     self.animalType = AnimalMod.ANIMALTYPE_COW;
     self.husbandryType = AnimalMod.ANIMALTYPE_COW;
     self.fillLevel = 0;
     self.i3dFilename = "";
     self.fileName = "";
     self.litersPerSqmPerSecond = 0.1;
     self.massPerLiter = Utils.getNoNil(massPerLiter, 0.0001);

     AnimalMod.AnimalTypes["cow"] = self;
     AnimalMod.animalTypeIndexToDesc[AnimalMod.NUM_ANIMALTYPES] = self;
     AnimalMod.husbandriesTypeIndexToDesc[AnimalMod.NUM_ANIMALTYPES] = self;

     local hudOverlayFilename, hudOverlayFilenameSmall = AnimalMod.HUDdir .."cowHud.dds", AnimalMod.HUDdir .."cowHud.dds";
     local fillType = Fillable.registerFillType("cow", "cow", 0.2, true, hudOverlayFilename, hudOverlayFilenameSmall, desc.massPerLiter)
     AnimalMod.animalTypeToFillType[AnimalMod.NUM_ANIMALTYPES] = fillType;
     AnimalMod.fillTypeToAnimalType[fillType] = AnimalMod.NUM_ANIMALTYPES;

     print(tostring(Fillable.fillTypeNameToInt["cow"]));

-- sheep
     AnimalMod.NUM_ANIMALTYPES = AnimalMod.NUM_ANIMALTYPES + 1;
     a.husbandriesNameToInt["sheep"] = AnimalMod.NUM_ANIMALTYPES;
     a.husbandriesIntToName[AnimalMod.NUM_ANIMALTYPES] = "sheep";
     a.animalTypeNameToInt["sheep"] = AnimalMod.NUM_ANIMALTYPES;
     a.animalTypeIntToName[AnimalMod.NUM_ANIMALTYPES] = "sheep";
     local desc = {name = "sheep", index = AnimalMod.NUM_ANIMALTYPES};
           desc.litersPerSqmPerSecond = 0;
           desc.massPerLiter = Utils.getNoNil(massPerLiter, 0.0001);
     local self = {name = "sheep", index = AnimalMod.NUM_ANIMALTYPES};
          self.type = "sheep";
          self.fillType = Fillable.FILLTYPE_SHEEP;
          self.animalType = AnimalMod.ANIMALTYPE_SHEEP;
          self.husbandryType = AnimalMod.ANIMALTYPE_SHEEP;
          self.fillLevel = 0;
          self.i3dFilename = "";
          self.fileName = "";
          self.litersPerSqmPerSecond = 0.1;
          self.massPerLiter = Utils.getNoNil(massPerLiter, 0.0001);

     AnimalMod.AnimalTypes["sheep"] = self;
     AnimalMod.animalTypeIndexToDesc[AnimalMod.NUM_ANIMALTYPES] = self;
     AnimalMod.animalTypeIndexToDesc[AnimalMod.NUM_ANIMALTYPES] = self;

     local hudOverlayFilename, hudOverlayFilenameSmall = AnimalMod.HUDdir .."sheepHud.dds", AnimalMod.HUDdir .."sheepHud.dds";
     local fillType = Fillable.registerFillType("sheep", "sheep", 0.2, true, hudOverlayFilename, hudOverlayFilenameSmall, desc.massPerLiter)
     AnimalMod.animalTypeToFillType[AnimalMod.NUM_ANIMALTYPES] = fillType;
     AnimalMod.fillTypeToAnimalType[fillType] = AnimalMod.NUM_ANIMALTYPES;

     print(tostring(Fillable.fillTypeNameToInt["sheep"]));

     -- chicken
     AnimalMod.NUM_ANIMALTYPES = AnimalMod.NUM_ANIMALTYPES + 1;
     a.husbandriesNameToInt["chicken"] = AnimalMod.NUM_ANIMALTYPES;
     a.husbandriesIntToName[AnimalMod.NUM_ANIMALTYPES] = "chicken";
     a.animalTypeNameToInt["chicken"] = AnimalMod.NUM_ANIMALTYPES;
     a.animalTypeIntToName[AnimalMod.NUM_ANIMALTYPES] = "chicken";
     local desc = {name = "chicken", index = AnimalMod.NUM_ANIMALTYPES};
        desc.litersPerSqmPerSecond = 0;
        desc.massPerLiter = Utils.getNoNil(massPerLiter, 0.0001);
     local self = {name = "chicken", index = AnimalMod.NUM_ANIMALTYPES};
        self.type = "chicken";
        self.fillType = Fillable.FILLTYPE_CHICKEN;
        self.animalType = AnimalMod.ANIMALTYPE_CHICKEN;
        self.husbandryType = AnimalMod.ANIMALTYPE_CHICKEN;
        self.fillLevel = 0;
        self.stomage = {};
        self.i3dFilename = "";
        self.fileName = "";
        self.litersPerSqmPerSecond = 0.1;
        self.massPerLiter = Utils.getNoNil(massPerLiter, 0.0001);

     AnimalMod.AnimalTypes["chicken"] = self;
     AnimalMod.animalTypeIndexToDesc[AnimalMod.NUM_ANIMALTYPES] = self;
     AnimalMod.animalTypeIndexToDesc[AnimalMod.NUM_ANIMALTYPES] = self;

     local hudOverlayFilename, hudOverlayFilenameSmall = AnimalMod.HUDdir .."chickenHud.dds", AnimalMod.HUDdir .."chickenHud.dds";
     local fillType = Fillable.registerFillType("chicken", "chicken", 0.2, true, hudOverlayFilename, hudOverlayFilenameSmall, desc.massPerLiter)
     AnimalMod.animalTypeToFillType[AnimalMod.NUM_ANIMALTYPES] = fillType;
     AnimalMod.fillTypeToAnimalType[fillType] = AnimalMod.NUM_ANIMALTYPES;

     print(tostring(Fillable.fillTypeNameToInt["chicken"]));

     print("default animals setup OK");
end;

addGame();

-- Giants code modified to suit our needs
function AnimalMod.registerAnimalType(name, nameI18N, pricePerLiter, litersPerSqmPerSecond, partOfEconomy, hudOverlayFilename, hudOverlayFilenameSmall, massPerLiter, i3dFilename, xmlFile)
    local key = "ANIMALTYPE_"..string.upper(name);
    local key2 = "FILLTYPE_" ..string.upper(name);
    local key3 = name;
    --(Fillable[key2] == nil and AnimalMod[key] == nil and husbandries[key3] == nil)
    if AnimalMod[key] == nil then
        AnimalMod.NUM_ANIMALTYPES = AnimalMod.NUM_ANIMALTYPES+1;
        AnimalMod[key] = AnimalMod.NUM_ANIMALTYPES;

        local desc = {name = name, index = AnimalMod.NUM_ANIMALTYPES};
        desc.litersPerSqmPerSecond = litersPerSqmPerSecond;
        desc.massPerLiter = Utils.getNoNil(massPerLiter, 0.0001);
        local self = {name = name, index = AnimalMod.NUM_ANIMALTYPES};
          self.customEnvironment, self.baseDirectory = Utils.getModNameAndBaseDirectory(i3dFilename);
          self.type = name;
          self.fillType = "Fillable.FILLTYPE_" ..string.upper(name);
          self.animalType = "AnimalMod.ANIMALTYPE_" ..string.upper(name);
          self.fillLevel = 0;
          self.stomage = {};
          self.i3dFilename = nil or i3dFilename;
          self.fileName = nil or xmlFile;
          self.litersPerSqmPerSecond = litersPerSqmPerSecond;
          self.massPerLiter = Utils.getNoNil(massPerLiter, 0.0001);
          AnimalMod.AnimalTypes[name] = self;

        AnimalMod.animalTypeIndexToDesc[AnimalMod.NUM_ANIMALTYPES] = self;

             if Fillable[key2] == nil then
             local fillType = Fillable.registerFillType(name, nameI18N, pricePerLiter, partOfEconomy, hudOverlayFilename, hudOverlayFilenameSmall, desc.massPerLiter)
             AnimalMod.animalTypeToFillType[AnimalMod.NUM_ANIMALTYPES] = fillType;
             AnimalMod.fillTypeToAnimalType[fillType] = AnimalMod.NUM_ANIMALTYPES;
             end;
             -- need to create a tmp storage and extra fucntion to check on loadmap
             if (tmpHusbandries[key3]) == nil then -- if (g_currentMission.husbandries[key3]) == nil then
              tmpHusbandries[key3] = {}; -- g_currentMission.husbandries[key3] = AnimalMod.NUM_ANIMALTYPES;
              tmpHusbandries[key3].totalNumAnimals = 0;
              setHusTable(name);
              AnimalMod.husbandriesTypeIndexToDesc[AnimalMod.NUM_ANIMALTYPES] = self;
             end;
        print("AnimalMod.registerAnimalType: " ..name);
    end;
end;

function AnimalType:init()
print("init before load");
     for k,v in pairs(tmpHusbandries)do

           if (g_currentMission.husbandries[k]) == nil then

             g_currentMission.husbandries[k] = {};
             g_currentMission.husbandries[k].totalNumAnimals = 0;
             g_currentMission.husbandries[k] = tmpHusbandries[k]; --g_currentMission.husbandries.cow;
             g_currentMission.husbandries[k].tipTriggersFillLevels = g_currentMission.husbandries.cow.tipTriggersFillLevels;
             g_currentMission.husbandries[k].manureHeap = g_currentMission.husbandries.cow.manureHeap;
             g_currentMission.husbandries[k].tipTriggers = g_currentMission.husbandries.cow.tipTriggers;
             g_currentMission.husbandries[k].liquidManureTrigger = g_currentMission.husbandries.cow.liquidManureTrigger;

           end;
           print("test: " ..type(tmpHusbandries[k]) .." vs " ..type(g_currentMission.husbandries[k]));

           --tmpHusbandries[k] = g_currentMission.husbandries[k];
     end;
for k,v in pairs(g_currentMission.husbandries.cow.tipTriggersFillLevels[12][1])do
     print("tipTriggersFillLevels: " ..k .." = " ..tostring(v));
end;
-- for ks,vs in pairs(tmpHusbandries)do
     -- print("tmpHusbandries: " ..ks .." = " ..tostring(vs));
-- end;
for _, location in pairs(g_currentMission.tipTriggers) do
    if (location.isFarmTrigger) then
      for index, _ in pairs(location.acceptedFillTypes) do
        if location.animalHusbandry then
          print("location.animalHusbandry: " ..location.id);

        end;
      end;
    end;
  end;
end;

function AnimalType:loadMap(name)
 husbandries = g_currentMission.husbandries;
 AnimalType:init();
 for animal , index in pairs (AnimalHusbandry) do
 --print(animal, type(index))
     -- for ind,valeu in pairs (index) do
     -- print("AnimalTypes: " ..animal .." : " ..ind .." = " .. type(valeu));
    -- end;
 end;

 for animals , tables in pairs (StoreItemsUtil.storeItemsByXMLFilename.chicken) do --VehicleTypeUtil.vehicleTypes.forwarder - StatisticView
     --for inds,valeus in pairs (tables) do

     if (type(tables) == "string" or type(tables) == "number")then
     print("(StoreItemsUtil: " ..animals .." : " ..tostring(tables));
     elseif(type(tables) == "table") then
          for k,v in pairs(tables)do
               if (type(v) == "string" or type(v) == "number")then
                    print("(StoreItemsUtil: " ..k .." : " ..tostring(v));
               elseif(type(v) == "table") then
                    print("(StoreItemsUtil: " ..k .." : " ..type(v));
               end;
          end;
     end;
    --end;

 end;
 -----
 buyAnimal("test", 2, 4);

end;

print("animal loaded " ..AnimalType.className .. " " ..AnimalType.intToName[1]);

-- function AnimalType:new(baseDirectory, customMt)
    -- local mt = customMt;
    -- if mt == nil then
        -- mt = AnimalType_mt;
    -- end;
    -- AnimalMod.registerAnimalType(name, nameI18N, pricePerLiter, litersPerSqmPerSecond, true, hudOverlayFilename, hudOverlayFilenameSmall, massPerLiter, i3dFilename)
    -- local self = AnimalType:superClass():new(baseDirectory, mt);
	-- self.customEnvironment, self.baseDirectory = Utils.getModNameAndBaseDirectory(AnimalType.Filename);

    -- return self;
-- end;

function AnimalType:load(id)

end;

function AnimalType:mouseEvent(posX, posY, isDown, isUp, button)

end;

function AnimalType:keyEvent(unicode, sym, modifier, isDown)

end;

function AnimalType:updateTick(dt)

end;

function AnimalType:update(dt)

-- this is only for the in game animalTypes
for animaltype, v in pairs (husbandries)do
local key1 = "FILLTYPE_" ..string.upper(animaltype);
local key2 = animaltype;
local animal = g_currentMission:getSiloAmount(Fillable[key1]);
local numanimal = 1;

     if(husbandries[key2].totalNumAnimals > 0)then

          if( husbandries[key2].totalNumAnimals > animal) then

          g_currentMission:setSiloAmount(Fillable[key1], animal + numanimal);
          print("buy true store: " ..key2);
          end;

          if(husbandries[key2].totalNumAnimals < animal) then

          g_currentMission:setSiloAmount(Fillable[key1], animal - numanimal);
          print("sell true store: " ..key2);
          end;

     end;
end;

end;

function buyAnimal(animaltype, amount, position)
if(position == 1 or position == 2 or position == 3)then
print("you can not use this function on the default animalTypes: " ..position);
return;
else
local key = animaltype;
husbandries[key].totalNumAnimals = husbandries[key].totalNumAnimals + amount;
--table.insert(husbandries[key].numAnimals[0], amount);
print("added " ..amount .." of aniamls to " ..animaltype);
for k, v in pairs(husbandries[key].numAnimals)do
print ("numAnimals: " ..k, v);
husbandries[key].numAnimals[k] = amount;
end;
print(ShopScreen.PAGE_VEHICLE_CATEGORY); -- 5
print(ShopScreen.TYPE_VEHICLE);
end;

end;

function AnimalType:draw()

end;
function AnimalType:delete()

end;

function AnimalType:deleteMap(name)

end;

function AnimalType:superClass()
return AnimalType;
end;

function setHusTable(name)

local tmpCattle = tmpHusbandries[name];
tmpCattle.id = 26;
--tmpCattle.tipTriggersFillLevels = g_currentMission.husbandries.cow.tipTriggersFillLevels; --{};
-- AnimalHusbandry.20 = table: 0x1039f6f0
-- AnimalHusbandry.21 = table: 0x103913f8
-- AnimalHusbandry.10 = table: 0x1073a4f0
-- AnimalHusbandry.12 = table: 0x10616e58
tmpCattle.typeName = name;
tmpCattle.updateMinutesInterval = 20;
tmpCattle.totalNumAnimals = 0;
tmpCattle.numObjectsInPalletSpawnerTrigger = 0;
tmpCattle.strawPlaneMaxFillLevel = 18000;
tmpCattle.husbandryId = 116619;
tmpCattle.husbandryDirtyFlag = 1;
tmpCattle.numVisibleAnimals = {[0] = 1, [1] = 0};
-- AnimalHusbandry.0 = 1
-- AnimalHusbandry.1 = 0
tmpCattle.updateMinutes = 0;
tmpCattle.fillLevelMilk = 0;
tmpCattle.numSubTypes = 2;
tmpCattle.nextDirtyFlag = 2;
tmpCattle.productivity = 0;
tmpCattle.strawPlaneMinY = 114.7;
--tmpCattle.manureHeap = g_currentMission.husbandries.cow.manureHeap; --{};
-- tmpCattle.manureHeap.movingId = 124908;
-- tmpCattle.manureHeap.moveMaxY = 0;
-- tmpCattle.manureHeap.fillType = 26;
-- tmpCattle.manureHeap.vehiclesInRange = {};
--return nothing 'nothing inrange'
-- tmpCattle.manureHeap.infoTriggerId = 116650;
-- tmpCattle.manureHeap.moneyChangeId = 99;
-- tmpCattle.manureHeap.nodeId = 124907;
-- tmpCattle.manureHeap.triggerMaxY = 0;
-- tmpCattle.manureHeap.capacity = 400000;
-- tmpCattle.manureHeap.triggerMinY = 0.4;
-- tmpCattle.manureHeap.lastMoneyChange = -1;
-- tmpCattle.manureHeap.fillLevel = 0;
-- tmpCattle.manureHeap.triggerYPower = 0.5;
-- tmpCattle.manureHeap.moveYPower = 0.5;
-- tmpCattle.manureHeap.triggerId = 124909;
-- tmpCattle.manureHeap.moveMinY = -3.9;
-- tmpCattle.manureHeap.fillLevelObject = g_currentMission.husbandries.cow.fillLevelObject; --{} ;
-- holds copy of self
tmpCattle.baseDirectory = "";
--tmpCattle.tipTriggers = g_currentMission.husbandries.cow.tipTriggers; -- {};
-- tmpCattle.tipTriggers[1] = {};
-- tmpCattle.tipTriggers[1].triggerStartId = 124885;
-- tmpCattle.tipTriggers[1].triggerId = 124887;
-- tmpCattle.tipTriggers[1].acceptedFillTypes = {};
-- tmpCattle.tipTriggers[1].lastMoneyChange = -1;
-- tmpCattle.tipTriggers[1].triggerWidth = 1.2000000476837;
-- tmpCattle.tipTriggers[1].moveMinY = 0;
-- tmpCattle.tipTriggers[1].triggerEndId = 124886;
-- tmpCattle.tipTriggers[1].animalPlaces = {};
-- tmpCattle.tipTriggers[1].id = 27;
-- tmpCattle.tipTriggers[1].stationName = Station;
-- tmpCattle.tipTriggers[1].rootNode = 124884;
-- tmpCattle.tipTriggers[1].moneyChangeId = 96;
-- tmpCattle.tipTriggers[1].triggerTipWidth = inf;
-- tmpCattle.tipTriggers[1].nextDirtyFlag = 2;
-- tmpCattle.tipTriggers[1].fillPlane = 124888;
-- tmpCattle.tipTriggers[1].updateEventListeners = {};
-- tmpCattle.tipTriggers[1].tipTriggerDirtyFlag = 1;
-- tmpCattle.tipTriggers[1].animalHusbandry = {};
-- tmpCattle.tipTriggers[1].moveMaxY = 0.5;
-- tmpCattle.tipTriggers[1].moveBackScale = 8.3333333333333e-007;
-- tmpCattle.tipTriggers[1].priceMultipliers = {};
-- tmpCattle.tipTriggers[1].moveScale = 4.0000001899898e-005;
-- tmpCattle.tipTriggers[1].dirtyMask = 0;
-- tmpCattle.tipTriggers[1].shovelCatcherId = 124884;
-- AnimalHusbandry.2 = table: 0x10515000
-- AnimalHusbandry.3 = table: 0x1036e340
	-- 1 trigger
	--
tmpCattle.strawPlaneId = 124924;
tmpCattle.virtualToVisibleAnimals = {};
tmpCattle.virtualToVisibleAnimals[1] = {visible = 6, virtual = 6};
tmpCattle.virtualToVisibleAnimals[2] = {visible = 6, virtual = 6};
-- AnimalHusbandry.1 = table: 0x108b4c70
-- AnimalHusbandry.2 = table: 0x108b4cc0
	-- AnimalHusbandry.visible = 6
	-- AnimalHusbandry.virtual = 6
--tmpCattle.liquidManureTrigger = g_currentMission.husbandries.cow.liquidManureTrigger; -- {};
tmpCattle.numAnimals = {};
tmpCattle.strawPlaneMaxY = 115;
print("structure made");
end;


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Text from List</title>

first item

second item

third item

<button id="showItems">Show</button>


text:
using System;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenProtocolInterpreter.PLCUserData;

namespace MIDTesters.PLCUserData
{
    [TestClass]
    public class TestMid0245 : MidTester
    {
        [TestMethod]
        public void Mid0245Revision1()
        {
            string package = "00460245            022My identifier less than";
            var mid = _midInterpreter.Parse<Mid0245>(package);

            Assert.AreEqual(typeof(Mid0245), mid.GetType());
            Assert.IsNotNull(mid.Offset);
            Assert.IsNotNull(mid.UserData);
            Assert.AreEqual(package, mid.Pack());
        }

        [TestMethod]
        public void Mid0245ByteRevision1()
        {
            string package = "00460245            022My identifier less than";
            byte[] bytes = GetAsciiBytes(package);
            var mid = _midInterpreter.Parse<Mid0245>(bytes);

            Assert.AreEqual(typeof(Mid0245), mid.GetType());
            Assert.IsNotNull(mid.Offset);
            Assert.IsNotNull(mid.UserData);
            Assert.IsTrue(mid.PackBytes().SequenceEqual(bytes));
        }
    }
}


text:
package com.example.exercitiirecapitulative;

import android.app.Activity;
import android.app.SearchManager;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final EditText editText = (EditText) findViewById(R.id.edit_text);

        editText.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				Toast.makeText(getApplicationContext(), start+"", Toast.LENGTH_LONG).show();
				if(start > 3) {
					char[] c = s.toString().toCharArray();
					c[c.length - 1] = '*';
					editText.setText(new String(c));
					editText.setSelection(start+1);
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {

			}
		});

        CheckBox c1 = (CheckBox) findViewById(R.id.chkAndroid);
        c1.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if(isChecked) {
					findViewById(R.id.chkAndroid2).setVisibility(View.VISIBLE);
				} else {
					findViewById(R.id.chkAndroid2).setVisibility(View.GONE);
				}
			}
		});

        Button b1 = (Button) findViewById(R.id.button1);
        b1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				/*Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
				intent.setData(Uri.parse("http://www.google.ro"));
				intent.putExtra(SearchManager.QUERY, "andreea");
				startActivity(intent);*/

				Uri uri = Uri.parse("http://www.google.com/#q=andreea vali");
				Intent intent = new Intent(Intent.ACTION_VIEW, uri);
				startActivity(intent);
			}
		});

        Button b2 = (Button) findViewById(R.id.buton2);
        b2.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(Intent.ACTION_VIEW);
				intent.setData(Uri.parse("http://ocw.cs.pub.ro/pdsd"));
				startActivity(intent);
			}
		});

        Button callVali = (Button) findViewById(R.id.call_vali);
        callVali.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(Intent.ACTION_CALL);
				intent.setData(Uri.parse("tel:0729845326"));
				startActivity(intent);
			}
		});

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}


text:
package org.jclouds.cloudstack.features;

import static org.jclouds.reflect.Reflection2.method;

import java.io.IOException;

import org.jclouds.cloudstack.domain.ResourceLimit;
import org.jclouds.cloudstack.domain.ResourceLimit.ResourceType;
import org.jclouds.cloudstack.internal.BaseCloudStackApiTest;
import org.jclouds.fallbacks.MapHttp4xxCodesToExceptions;
import org.jclouds.http.functions.ParseFirstJsonValueNamed;
import org.jclouds.rest.internal.GeneratedHttpRequest;
import org.testng.annotations.Test;

import com.google.common.collect.ImmutableList;
import com.google.common.reflect.Invokable;
/**
 * Tests behavior of {@code DomainLimitApi}
 */
@Test(groups = "unit", testName = "DomainLimitApiTest")
public class DomainLimitApiTest extends BaseCloudStackApiTest<DomainLimitApi> {

   public void testUpdateResourceLimit() throws SecurityException, NoSuchMethodException, IOException {
      Invokable<?, ?> method = method(DomainLimitApi.class, "updateResourceLimit", ResourceLimit.class);
      GeneratedHttpRequest httpRequest = processor.createRequest(method, ImmutableList.<Object> of(
            ResourceLimit.builder().resourceType(ResourceType.SNAPSHOT).account("foo").domainId("100").max(101).build()));

      assertRequestLineEquals(
            httpRequest,
            "GET http://localhost:8080/client/api?response=json&command=updateResourceLimit&resourcetype=3&account=foo&domainid=100&max=101 HTTP/1.1");
      assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
      assertPayloadEquals(httpRequest, null, null, false);

      assertResponseParserClassEquals(method, httpRequest, ParseFirstJsonValueNamed.class);
      assertSaxResponseParserClassEquals(method, null);
      assertFallbackClassEquals(method, MapHttp4xxCodesToExceptions.class);

      checkFilters(httpRequest);

   }
}


text:
from django.utils.translation import ugettext_lazy as _

from horizon import exceptions
from horizon import tabs
from horizon.utils import memoized

from openstack_dashboard import api
from openstack_dashboard.dashboards.project.networks.ports import tabs \
    as ports_tabs
from openstack_dashboard.dashboards.project.networks.subnets import tabs \
    as subnets_tabs
from openstack_dashboard.dashboards.project.networks \
    import tables as project_tables
from openstack_dashboard.utils import filters

class OverviewTab(tabs.Tab):
    name = _("Overview")
    slug = "overview"
    template_name = ("project/networks/_detail_overview.html")
    preload = False

    @memoized.memoized_method
    def _get_data(self):
        network = {}
        network_id = None
        try:
            network_id = self.tab_group.kwargs['network_id']
            network = api.neutron.network_get(self.request, network_id)
            network.set_id_as_name_if_empty(length=0)

            choices = project_tables.STATUS_DISPLAY_CHOICES
            network.status_label = (
                filters.get_display_label(choices, network.status))
            choices = project_tables.DISPLAY_CHOICES
            network.admin_state_label = (
                filters.get_display_label(choices, network.admin_state))
        except Exception:
            msg = _('Unable to retrieve details for network "%s".') \
                % (network_id)
            exceptions.handle(self.request, msg)
        return network

    def get_context_data(self, request, **kwargs):
        context = super(OverviewTab, self).get_context_data(request, **kwargs)
        network = self._get_data()

        context["network"] = network
        return context

class NetworkDetailsTabs(tabs.TabGroup):
    slug = "network_tabs"
    tabs = (OverviewTab, subnets_tabs.SubnetsTab, ports_tabs.PortsTab, )
    sticky = True


text:
@class NSString, XCTBlockingQueue, XCTestConfiguration;
@protocol XCTTestRunSessionDelegate;

@interface XCTTestRunSession : NSObject <XCTTestWorker>
{
    id <XCTTestRunSessionDelegate> _delegate;
    XCTestConfiguration *_testConfiguration;
    XCTBlockingQueue *_workQueue;
}

+ (void)initialize;
- (void).cxx_destruct;
@property(retain) XCTBlockingQueue *workQueue; // @synthesize workQueue=_workQueue;
@property(retain) XCTestConfiguration *testConfiguration; // @synthesize testConfiguration=_testConfiguration;
@property __weak id <XCTTestRunSessionDelegate> delegate; // @synthesize delegate=_delegate;
- (void)shutdown;
- (void)executeTestIdentifiers:(id)arg1 skippingTestIdentifiers:(id)arg2 completionHandler:(CDUnknownBlockType)arg3 completionQueue:(id)arg4;
- (void)fetchDiscoveredTestClasses:(CDUnknownBlockType)arg1;
- (_Bool)runTestsAndReturnError:(id *)arg1;
- (_Bool)_preTestingInitialization;
- (void)resumeAppSleep:(id)arg1;
- (id)suspendAppSleep;
- (id)initWithTestConfiguration:(id)arg1;

// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;

@end


text:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
using System.Net;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using System.Net.Mail;
using System.Net.Mime;
using System.Data;

using PI.Pimail;
using PI.Pimail.Models;

namespace PI.Pimail.Tests
{

    public partial class TestPimail
    {

        [TestMethod]
        public void Pimail_MailStoreDatabase_List_ShouldReturnAllEmails()
        {
            //Arrange
            var context = new TestPimailContext();
            context.Emails.Add(GetEmail("one"));
            context.Emails.Add(GetEmail("two"));
            context.Emails.Add(GetEmail("three"));

            //Act
            IMailStore ms = new MailStoreDatabase(context);
            var items = ms.List();

            //Assert
            Assert.AreEqual(3, items.Count());

        }

        [TestMethod]
        public void Pimail_MailStoreDatabase_FindByName_ShouldReturnFoundMail()
        {
            //Arrange
            var context = new TestPimailContext();
            context.Emails.Add(GetEmail("one"));
            context.Emails.Add(GetEmail("two"));
            context.Emails.Add(GetEmail("three"));

            //Act
            IMailStore ms = new MailStoreDatabase(context);
            var item = ms.FindByName("one");

            //Assert
            Assert.AreEqual("one", item.Name);

        }

        [TestMethod]
        public void Pimail_MailStoreDatabase_FindByName_ShouldFail_NoMail()
        {
            //Arrange
            var context = new TestPimailContext();
            context.Emails.Add(GetEmail("one"));
            context.Emails.Add(GetEmail("two"));
            context.Emails.Add(GetEmail("three"));

            //Act
            IMailStore ms = new MailStoreDatabase(context);
            var item = ms.FindByName("four");

            //Assert
            Assert.IsNull(item);

        }

        [TestMethod]
        public void Pimail_MailStoreDatabase_Create_ShouldReturnNewMail()
        {
            //Arrange
            var context = new TestPimailContext();
            Email email = GetEmail();

            //Act
            IMailStore ms = new MailStoreDatabase(context);
            var item = ms.Create(email);

            //Assert
            Assert.AreEqual(email.Name, item.Name);
        }

        [TestMethod]
        public async void Pimail_MailStoreDatabase_CreateAsync_ShouldReturnNewMail()
        {
            //Arrange
            var context = new TestPimailContext();
            Email email = GetEmail();

            //Act
            IMailStore ms = new MailStoreDatabase(context);
            var item = await ms.CreateAsync(email);

            //Assert
            Assert.AreEqual(email.Name, item.Name);
        }

        [TestMethod]
        [ExpectedException(typeof(DuplicateNameException))]
        public void Pimail_MailStoreDatabase_Create_ShouldFail_MailExists()
        {
            //Arrange
            var context = new TestPimailContext();
            context.Emails.Add(GetEmail());
            Email email = GetEmail();

            //Act
            IMailStore ms = new MailStoreDatabase(context);
            var item = ms.Create(email);

        }

        [TestMethod]
        public void Pimail_MailStoreDatabase_Update_ShouldReturnSavedMail()
        {
            //Arrange
            var context = new TestPimailContext();
            context.Emails.Add(GetEmail());
            Email email = GetEmail();
            email.To = "hi@test.com";
            email.SetUpdate("Bob");

            //Act
            IMailStore ms = new MailStoreDatabase(context);
            var item = ms.Update(email);

            //Assert
            Assert.AreEqual("hi@test.com", item.To);
            Assert.AreEqual("Bob", item.Updator);
        }

        [TestMethod]
        public async void Pimail_MailStoreDatabase_UpdateAsync_ShouldReturnSavedMail()
        {
            //Arrange
            var context = new TestPimailContext();
            context.Emails.Add(GetEmail());
            Email email = GetEmail();
            email.To = "hi@test.com";
            email.SetUpdate("Bob");

            //Act
            IMailStore ms = new MailStoreDatabase(context);
            var item = await ms.UpdateAsync(email);

            //Assert
            Assert.AreEqual("hi@test.com", item.To);
            Assert.AreEqual("Bob", item.Updator);
        }
    }
}


text:
mac
====

Manageacloud is a flexible orchestration platform. It allows you to create, destroy and organise servers and infrastructures.

Fork me on `GitHub <https://github.com/manageacloud/manageacloud-cli>`_!

Features
--------
- Orchestrate servers
- Orchestrate production ready infrastructure (golden images, autoscaling groups, load balancers, etc)
- Versioning servers and infrastructure
- Empower Continuous Delivery
- View who is the owner of the resources (servers and infrastructure)
- Interact with your servers using a Command Line Interface, REST Api or Web Interface
- Manage access to servers
- Convert your infrastructure into code
- Orchestrate servers using your existing automation codes (eg Docker, Puppet, Chef, SaltStack, etc)
- Test server configurations easily
- Integrate any technology that can be operated from the command line interface or an API
- Keep the history (including logs) of servers and infrastructure
- Trigger events via WebHooks
- Although Manageacloud is technology agnostic, we have created some shortcuts for easier operation with Amazon Web Services, Google Compute Engine, Rackspace and Digital Ocean

Access to the `documentation <https://manageacloud.com/docs>`_ or to the `quickstart guide <https://manageacloud.com/quickstart>`_ to learn more.

Installation
============

Command Line Interface
----------------------

Install vis ``pip3 install``:

.. sourcecode:: bash

    pip3 install mac

Examples
========

Standalone applications
-----------------------

To create a new server and install apache for Ubuntu

.. sourcecode:: bash

    mac instance create -b "apt-get update && apt-get install apache2 -y" -r ubuntu:trusty

To create a new server and install apache for CentOS

.. sourcecode:: bash

    mac instance create -b "apt-get update && apt-get install apache2 -y" -r centos:7

To install Wordpress

.. sourcecode:: bash

    mac instance create -c basic_wordpress_installation

Infrastructures
---------------

You can learn more about how to orchestrate infrastructure using our [quickstart guide](https://manageacloud.com/quickstart)

The following example:
 - Creates an instance and a load balancer in AWS
 - Deploys an application and version *version_2*

This infrastructure has a *name* and a *version*, which makes it ideal for some scenarios such as blue-green deployments.

.. sourcecode:: bash

    mac -s infrastructure macfile https://goo.gl/ezRWx1 -p INF_VERSION=2 APP_BRANCH=version_2


text:
using System.Collections.Generic;
using System.IO;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Moq;
using NUnit.Framework;

namespace Shuttle.Core.MSBuild.Tests
{
    [TestFixture]
    public class SetNugetPackageVersionsTests
    {
        [Test]
        public void Should_be_able_to_set_nuget_dependency_versions_using_custom_values()
        {
            var task = new SetNugetPackageVersions
            {
                BuildEngine = new Mock<IBuildEngine>().Object,
                OpenTag = "%",
                CloseTag = "%",
                PackageFolder = new TaskItem(FilePathExtensions.BasePath(@".\packages")),
                Files = new List<ITaskItem>
                {
                    new TaskItem(FilePathExtensions.BasePath(@".\files\set-nuget-depencency-versions-custom-test.txt"))
                }.ToArray()
            };

            File.Copy(FilePathExtensions.BasePath(@".\files\set-nuget-depencency-versions-custom.txt"),
                FilePathExtensions.BasePath(@".\files\set-nuget-depencency-versions-custom-test.txt"), true);

            Assert.True(task.Execute());

            var contents = File.ReadAllText(FilePathExtensions.BasePath(@".\files\set-nuget-depencency-versions-custom-test.txt"));

            Assert.IsTrue(contents.Contains("<dependency id=\"another.package\" version=\"[3.2.1]\" />"));
            Assert.IsTrue(contents.Contains("<dependency id=\"some-package\" version=\"[1.2.3]\" />"));
            Assert.IsTrue(contents.Contains("<dependency id=\"prerelease-package\" version=\"[4.5.6]\" />"));
            Assert.IsTrue(contents.Contains("<dependency id=\"full-version.package\" version=\"[4.5.6.7000]\" />"));

            File.Delete(FilePathExtensions.BasePath(@".\files\set-nuget-depencency-versions-custom-test.txt"));
        }

        [Test]
        public void Should_be_able_to_set_nuget_dependency_versions_using_defaults()
        {
            var task = new SetNugetPackageVersions
            {
                BuildEngine = new Mock<IBuildEngine>().Object,
                PackageFolder = new TaskItem(FilePathExtensions.BasePath(@".\packages")),
                Files = new List<ITaskItem>
                {
                    new TaskItem(FilePathExtensions.BasePath(@".\files\set-nuget-depencency-versions-default-test.txt"))
                }.ToArray()
            };

            File.Copy(FilePathExtensions.BasePath(@".\files\set-nuget-depencency-versions-default.txt"),
                FilePathExtensions.BasePath(@".\files\set-nuget-depencency-versions-default-test.txt"), true);

            Assert.True(task.Execute());

            var contents = File.ReadAllText(FilePathExtensions.BasePath(@".\files\set-nuget-depencency-versions-default-test.txt"));

            Assert.IsTrue(contents.Contains("<dependency id=\"another.package\" version=\"[3.2.1]\" />"));
            Assert.IsTrue(contents.Contains("<dependency id=\"some-package\" version=\"[1.2.3]\" />"));
            Assert.IsTrue(contents.Contains("<dependency id=\"prerelease-package\" version=\"[4.5.6]\" />"));
            Assert.IsTrue(contents.Contains("<dependency id=\"full-version.package\" version=\"[4.5.6.7000]\" />"));

            File.Delete(FilePathExtensions.BasePath(@".\files\set-nuget-depencency-versions-default-test.txt"));
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>schema_statements.rb</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" href="../../../../../../../../../../../../../../../../../css/reset.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../../../../../../../../../../../../../../../../css/main.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../../../../../../../../../../../../../../../../css/github.css" type="text/css" media="screen" />

            Ruby on Rails 4.2.1

            schema_statements.rb

                ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/connection_adapters/abstract/schema_statements.rb

Last modified: 2015-04-15 16:46:17 +0800

Required Files

active_record/migration/join_table

active_support/core_ext/string/access

digest

Namespace

          MODULE
          ActiveRecord

          MODULE
          ActiveRecord::ConnectionAdapters

          MODULE
          ActiveRecord::ConnectionAdapters::SchemaStatements


text:
import React from "react"
import PropTypes from "prop-types"
import { isEqual } from "lodash"
import cx from "classnames"
import IconClear from "../../icons/IconClear"
import SingleSelector from "./SingleSelector"
import MultiSelector from "./MultiSelector"

const defaultRenderLabel = ({ label, ...rest }) => (
    {label}
)

const defaultRenderInput = props => (

        <input type="text" {...props} />

)

const defaultRenderItem = ({
    item,
    index,
    selectedItem,
    highlightedIndex,
    itemToString,
    ...rest
}) => (
    <div
        className={cx("Select-option", {
            "is-selected": isEqual(item, selectedItem),
            "is-focused": index === highlightedIndex
        })}
        key={`${itemToString(item)}-${index}`}
        {...rest}
    >
        {itemToString(item)}

)

const defaultRenderArrow = props => (

)

const defaultRenderClear = props => (

        <IconClear />

)

const defaultItemToString = item => (item ? item.label : "")

export default class Selector extends React.PureComponent {
    static defaultProps = {
        data: [],
        clearable: true,
        searchable: true,
        renderLabel: defaultRenderLabel,
        renderInput: defaultRenderInput,
        renderItem: defaultRenderItem,
        renderClear: defaultRenderClear,
        renderArrow: defaultRenderArrow,
        itemToString: defaultItemToString
    }

    static propTypes = {
        data: PropTypes.array.isRequired,
        name: PropTypes.string,
        value: PropTypes.oneOfType([
            PropTypes.object,
            PropTypes.string,
            PropTypes.number
        ]),
        onChange: PropTypes.func,
        isLoading: PropTypes.bool,
        multi: PropTypes.bool,
        clearable: PropTypes.bool,
        searchable: PropTypes.bool,
        placeholder: PropTypes.string,
        renderLabel: PropTypes.func,
        renderInput: PropTypes.func,
        renderItem: PropTypes.func,
        renderClear: PropTypes.func,
        renderArrow: PropTypes.func,
        itemToString: PropTypes.func,
        onFocus: PropTypes.func,
        onBlur: PropTypes.func,
        onClick: PropTypes.func
    }

    state = {
        isOpen: false,
        isFocused: false
    }

    handleChange = (value, stateAndHelpers = {}) => {
        const { name, onChange } = this.props
        onChange && onChange(value, { ...stateAndHelpers, name })
    }

    handleClick = e => {
        this.setState(() => ({ isOpen: true, isFocused: true }))
        this.props.onClick && this.props.onClick(e)
    }

    handleFocus = e => {
        this.setState(() => ({ isOpen: true, isFocused: true }))
        this.props.onFocus && this.props.onFocus(e)
    }

    handleBlur = e => {
        this.setState(() => ({ isFocused: false }))
        this.props.onBlur && this.props.onBlur(e)
    }

    handleDownshiftStateChange = changes => {
        if (changes.hasOwnProperty("isOpen")) {
            this.setState(() => ({ isOpen: changes.isOpen }))
        }
    }

    render() {
        const { multi, ...rest } = this.props
        const Component = multi ? MultiSelector : SingleSelector
        return (
            <Component
                {...rest}
                onChange={this.handleChange}
                onFocus={this.handleFocus}
                onBlur={this.handleBlur}
                onClick={this.handleClick}
                onDownshiftStateChange={this.handleDownshiftStateChange}
                isOpen={this.state.isOpen}
                isFocused={this.state.isFocused}
                inputRef={n => (this.input = n)}
            />
        )
    }
}


text:
GH_STATUS_REPO_NAME=${INITIATING_REPO_NAME:-"multipart-frontend"}
CONTEXT_MESSAGE=${CONTEXT_MESSAGE:-"default"}
GH_STATUS_GIT_COMMIT=${INITIATING_GIT_COMMIT:-${GIT_COMMIT}}

function github_status {
  STATUS="$1"
  MESSAGE="$2"
  gh-status "$GH_STATUS_REPO_NAME" "$GH_STATUS_GIT_COMMIT" "$STATUS" -d "Build #${BUILD_NUMBER} ${MESSAGE}" -u "$BUILD_URL" -c "$CONTEXT_MESSAGE" >/dev/null
}

function error_handler {
  trap - ERR # disable error trap to avoid recursion
  local parent_lineno="$1"
  local message="$2"
  local code="${3:-1}"
  if [[ -n "$message" ]] ; then
    echo "Error on or near line ${parent_lineno}: ${message}; exiting with status ${code}"
  else
    echo "Error on or near line ${parent_lineno}; exiting with status ${code}"
  fi
  github_status error "errored on Jenkins"
  exit "${code}"
}

trap 'error_handler ${LINENO}' ERR
github_status pending "is running on Jenkins"

# Cleanup anything left from previous test runs
git clean -fdx

# Try to merge master into the current branch, and abort if it doesn't exit
# cleanly (ie there are conflicts). This will be a noop if the current branch
# is master.
git merge --no-commit origin/master || git merge --abort

export RAILS_ENV=test
bundle install --path "${HOME}/bundles/${JOB_NAME}" --deployment --without development

# Uncomment if this app uses a database
# bundle exec rake db:drop db:create db:schema:load

if bundle exec rake ${TEST_TASK:-"default"}; then
  github_status success "succeeded on Jenkins"
else
  github_status failure "failed on Jenkins"
  exit 1
fi