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

    Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
    under one or more contributor license agreements. See the NOTICE file
    distributed with this work for additional information regarding copyright
    ownership. Camunda licenses this file to you under the Apache License,
    Version 2.0; 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.camunda.bpm.engine.impl.persistence.entity.TaskEntity">

  <!-- TASK INSERT -->

  <insert id="insertTask" parameterType="org.camunda.bpm.engine.impl.persistence.entity.TaskEntity">
    insert into ${prefix}ACT_RU_TASK (
      ID_,
      NAME_,
      PARENT_TASK_ID_,
      DESCRIPTION_,
      PRIORITY_,
      CREATE_TIME_,
      LAST_UPDATED_,
      OWNER_,
      ASSIGNEE_,
      DELEGATION_,
      EXECUTION_ID_,
      PROC_INST_ID_,
      PROC_DEF_ID_,
      CASE_EXECUTION_ID_,
      CASE_INST_ID_,
      CASE_DEF_ID_,
      TASK_DEF_KEY_,
      DUE_DATE_,
      FOLLOW_UP_DATE_,
      SUSPENSION_STATE_,
      TENANT_ID_,
      REV_
    ) values (
      #{id, jdbcType=VARCHAR},
      #{name, jdbcType=VARCHAR},
      #{parentTaskId, jdbcType=VARCHAR},
      #{description, jdbcType=VARCHAR},
      #{priority, jdbcType=INTEGER},
      #{createTime, jdbcType=TIMESTAMP},
      #{lastUpdated, jdbcType=TIMESTAMP},
      #{owner, jdbcType=VARCHAR},
      #{assignee, jdbcType=VARCHAR},
      #{delegationStateString, jdbcType=VARCHAR},
      #{executionId, jdbcType=VARCHAR},
      #{processInstanceId, jdbcType=VARCHAR},
      #{processDefinitionId, jdbcType=VARCHAR},
      #{caseExecutionId, jdbcType=VARCHAR},
      #{caseInstanceId, jdbcType=VARCHAR},
      #{caseDefinitionId, jdbcType=VARCHAR},
      #{taskDefinitionKey, jdbcType=VARCHAR},
      #{dueDate, jdbcType=TIMESTAMP},
      #{followUpDate, jdbcType=TIMESTAMP},
      #{suspensionState, jdbcType=INTEGER},
      #{tenantId, jdbcType=VARCHAR},
      1
    )
  </insert>

  <!-- TASK UPDATE -->

  <update id="updateTask" parameterType="org.camunda.bpm.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},
      LAST_UPDATED_ = #{lastUpdated, 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},
      CASE_EXECUTION_ID_ = #{caseExecutionId, jdbcType=VARCHAR},
      CASE_INST_ID_ = #{caseInstanceId, jdbcType=VARCHAR},
      CASE_DEF_ID_ = #{caseDefinitionId, jdbcType=VARCHAR},
      TASK_DEF_KEY_ = #{taskDefinitionKey, jdbcType=VARCHAR},
      DESCRIPTION_ = #{description, jdbcType=VARCHAR},
      DUE_DATE_ = #{dueDate, jdbcType=TIMESTAMP},
      FOLLOW_UP_DATE_ = #{followUpDate, jdbcType=TIMESTAMP},
      SUSPENSION_STATE_ = #{suspensionState, jdbcType=INTEGER},
      TENANT_ID_ = #{tenantId, jdbcType=VARCHAR}
    </set>
    where ID_= #{id, jdbcType=VARCHAR}
      and REV_ = #{revision, jdbcType=INTEGER}
  </update>

  <update id="updateTaskSuspensionStateByParameters" parameterType="org.camunda.bpm.engine.impl.db.ListQueryParameterObject">
    update ${prefix}ACT_RU_TASK set
      REV_ = 1 + REV_ ,
      SUSPENSION_STATE_ = #{parameter.suspensionState, jdbcType=INTEGER}
    <where>
      <include refid="updateTaskSuspensionStateByParametersSql" />
    </where>
  </update>

  <sql id="updateTaskSuspensionStateByParametersSql">
    <if test="parameter.processInstanceId != null">
      PROC_INST_ID_ = #{parameter.processInstanceId, jdbcType=VARCHAR}
    </if>
    <if test="parameter.processDefinitionId != null">
      PROC_DEF_ID_ = #{parameter.processDefinitionId, jdbcType=VARCHAR}
    </if>
    <if test="parameter.processDefinitionKey != null">
      PROC_DEF_ID_ IN (
      SELECT ID_
      FROM ${prefix}ACT_RE_PROCDEF PD
      WHERE PD.KEY_ = #{parameter.processDefinitionKey, jdbcType=VARCHAR}
      <if test="parameter.isProcessDefinitionTenantIdSet">
        <if test="parameter.processDefinitionTenantId != null">
          and PD.TENANT_ID_ = #{parameter.processDefinitionTenantId, jdbcType=VARCHAR}
        </if>
        <if test="parameter.processDefinitionTenantId == null">
          and PD.TENANT_ID_ is null
        </if>
      </if>
      )
      <bind name="columnPrefix" value="''"/>
      <include refid="org.camunda.bpm.engine.impl.persistence.entity.TenantEntity.queryTenantCheckWithPrefix" />
    </if>
    <if test="parameter.caseExecutionId != null">
      CASE_EXECUTION_ID_ = #{parameter.caseExecutionId, jdbcType=VARCHAR}
    </if>
  </sql>

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

  <!-- TASK RESULTMAP -->

  <resultMap id="taskResultMap" type="org.camunda.bpm.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="lastUpdated" column="LAST_UPDATED_" 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="caseExecutionId" column="CASE_EXECUTION_ID_" jdbcType="VARCHAR" />
    <result property="caseInstanceIdWithoutCascade" column="CASE_INST_ID_" jdbcType="VARCHAR" />
    <result property="caseDefinitionId" column="CASE_DEF_ID_" jdbcType="VARCHAR"/>
    <result property="taskDefinitionKeyWithoutCascade" column="TASK_DEF_KEY_" jdbcType="VARCHAR"/>
    <result property="dueDateWithoutCascade" column="DUE_DATE_" jdbcType="TIMESTAMP"/>
    <result property="followUpDateWithoutCascade" column="FOLLOW_UP_DATE_" jdbcType="TIMESTAMP"/>
    <result property="suspensionState" column="SUSPENSION_STATE_" jdbcType="INTEGER" />
    <result property="tenantId" column="TENANT_ID_" jdbcType="VARCHAR" />
    <!-- note: if you add mappings here, make sure to select the columns in 'columnSelection' -->
  </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.camunda.bpm.engine.impl.db.ListQueryParameterObject" resultMap="taskResultMap">
    select * from ${prefix}ACT_RU_TASK where PARENT_TASK_ID_ = #{parameter}
  </select>

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

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

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

  <select id="selectTaskByQueryCriteria" parameterType="org.camunda.bpm.engine.impl.TaskQueryImpl" resultMap="taskResultMap">
    <include refid="org.camunda.bpm.engine.impl.persistence.entity.Commons.bindOrderBy"/>
    ${limitBefore}
    select ${distinct}
    <include refid="columnSelection"/>
    ${limitBetween}
    <if test="taskNameCaseInsensitive">
      , lower(RES.NAME_) LOWER_NAME_
    </if>
    <include refid="org.camunda.bpm.engine.impl.persistence.entity.Commons.orderBySelection"/>
    <include refid="selectTaskByQueryCriteriaSql"/>
    ${orderBy}
    ${limitAfter}
  </select>

  <select id="selectTaskCountByQueryCriteria" parameterType="org.camunda.bpm.engine.impl.TaskQueryImpl" resultType="long">
    ${countDistinctBeforeStart} RES.ID_ ${countDistinctBeforeEnd}
    <include refid="selectTaskByQueryCriteriaSql"/>
    ${countDistinctAfterEnd}
  </select>

  <sql id="columnSelection">
    RES.REV_, RES.ID_, RES.NAME_, RES.PARENT_TASK_ID_, RES.DESCRIPTION_, RES.PRIORITY_,
    RES.CREATE_TIME_, RES.OWNER_, RES.ASSIGNEE_, RES.DELEGATION_, RES.EXECUTION_ID_,
    RES.PROC_INST_ID_, RES.PROC_DEF_ID_, RES.CASE_EXECUTION_ID_, RES.CASE_INST_ID_,
    RES.CASE_DEF_ID_, RES.TASK_DEF_KEY_, RES.DUE_DATE_, RES.FOLLOW_UP_DATE_,
    RES.SUSPENSION_STATE_, RES.TENANT_ID_, RES.LAST_UPDATED_
  </sql>

  <sql id="selectTaskByQueryCriteriaSql">

    from ${prefix}ACT_RU_TASK RES
    <bind name="I_JOIN" value="false" />
    <bind name="D_JOIN" value="false" />
    <bind name="E_JOIN" value="false" />
    <bind name="CD_JOIN" value="false" />
    <bind name="CE_JOIN" value="false" />
    <bind name="E1_JOIN" value="false" />
    <bind name="JOIN_TYPE" value="'inner join'" />

    <foreach collection="queries" item="query">
      <if test="query.isOrQueryActive">
        <bind name="JOIN_TYPE" value="'left join'" />
      </if>
      <if test="query != null && (query.candidateUser != null || query.candidateGroups != null || query.involvedUser != null || query.withCandidateGroups || query.withCandidateUsers)">
        <bind name="I_JOIN" value="true" />
      </if>
      <!-- the process definition table is joined if
      1. a process-definition-related filter is used
      2. authorization check is enabled (as permissions are defined per process definition) -->
      <if test="query != null &&
        (query.processDefinitionKey != null || query.processDefinitionName != null ||
        query.processDefinitionNameLike != null ||
        (query.processDefinitionKeys != null && query.processDefinitionKeys.length > 0)) ||
        authCheck.shouldPerformAuthorizatioCheck && authCheck.authUserId != null">
        <bind name="D_JOIN" value="true" />
      </if>
      <if test="query != null && (query.processInstanceBusinessKey != null || query.processInstanceBusinessKeyLike != null ||
              (query.processInstanceBusinessKeys != null && query.processInstanceBusinessKeys.length > 0))">
        <bind name="E_JOIN" value="true" />
      </if>
      <if test="query != null && (query.caseDefinitionKey != null || query.caseDefinitionName != null || query.caseDefinitionNameLike != null)">
        <bind name="CD_JOIN" value="true" />
      </if>
      <if test="query != null && (query.caseInstanceBusinessKey != null || query.caseInstanceBusinessKeyLike != null)">
        <bind name="CE_JOIN" value="true" />
      </if>
      <if test="query != null && (query.activityInstanceIdIn != null && query.activityInstanceIdIn.length > 0)">
        <bind name="E1_JOIN" value="true" />
      </if>
    </foreach>

    <if test="I_JOIN">
      <!-- Identity links are always left-joined, because the involvedUser criterion
        either requires an identity link or a not-null assignee or owner field (i.e.
        it can be fulfilled without an identity link) -->
      left join ${prefix}ACT_RU_IDENTITYLINK I on I.TASK_ID_ = RES.ID_
    </if>
    <if test="D_JOIN">
      <choose>
        <!-- if we do not query for cmmn or standalone tasks, then an inner join is
          always correct, regardless if it is an 'and' or 'or' query. Every task
          references a process definition then. -->
        <when test="queryForProcessTasksOnly">inner join</when>
        <!-- If authorizations are enabled and we query for case tasks, it must always be a left join -->
        <when test="authCheck.shouldPerformAuthorizatioCheck && authCheck.authUserId != null">
          left join
        </when>
        <otherwise>
          ${JOIN_TYPE}
        </otherwise>
      </choose>
      ${prefix}ACT_RE_PROCDEF D on RES.PROC_DEF_ID_ = D.ID_
    </if>
    <if test="E_JOIN">
      ${JOIN_TYPE} ${prefix}ACT_RU_EXECUTION E on RES.PROC_INST_ID_ = E.ID_
    </if>
    <if test="CD_JOIN">
      ${JOIN_TYPE} ${prefix}ACT_RE_CASE_DEF CD on RES.CASE_DEF_ID_ = CD.ID_
    </if>
    <if test="CE_JOIN">
      ${JOIN_TYPE} ${prefix}ACT_RU_CASE_EXECUTION CE on RES.CASE_INST_ID_ = CE.ID_
    </if>
    <if test="E1_JOIN">
      left join ${prefix}ACT_RU_EXECUTION E1 on RES.EXECUTION_ID_ = E1.ID_
    </if>

    <if test="authCheck.shouldPerformAuthorizatioCheck && authCheck.authUserId != null">
      <if test="!authCheck.revokeAuthorizationCheckEnabled">
        <include refid="org.camunda.bpm.engine.impl.persistence.entity.AuthorizationEntity.authCheckJoinWithoutOnClause" />
        AUTH ON (AUTH.RESOURCE_ID_ ${authJoinStart} RES.ID_ ${authJoinSeparator} D.KEY_ ${authJoinSeparator} '*' ${authJoinEnd})
      </if>
    </if>

    <foreach collection="orderingProperties" item="orderingProperty" index="i">
      <if test="orderingProperty.relation != null">
        <bind name="tableAlias" value="@org.camunda.bpm.engine.impl.db.sql.MybatisJoinHelper@tableAlias(orderingProperty.relation, i)"/>
        left join
        ${prefix}${@org.camunda.bpm.engine.impl.db.sql.MybatisJoinHelper@tableMapping(orderingProperty.relation)}
        ${tableAlias}
        on
        <include refid="org.camunda.bpm.engine.impl.persistence.entity.Commons.filterOrderByRelations"/>
      </if>
    </foreach>
    <where>
      <foreach collection="queries" item="query" index="i">
        <choose>
          <when test="i == 0">
            <bind name="queryType" value="'and'" />
          </when>
          <otherwise>
            <bind name="queryType" value="'or'" />
          </otherwise>
        </choose>
        and (
        <trim suffixOverrides="and">
          1 = 1 and
          <trim prefixOverrides="or|and">
            <if test="query.taskId != null">
              ${queryType} RES.ID_ = #{query.taskId}
            </if>
            <if test="query.taskIdIn != null && query.taskIdIn.length > 0">
              ${queryType} RES.ID_ in
              <foreach item="item" index="index" collection="query.taskIdIn"
                       open="(" separator="," close=")">
                #{item}
              </foreach>
            </if>
            <if test="query.name != null">
              <!-- based on CAM-6363 compare name case insensitive -->
              ${queryType} UPPER(RES.NAME_) = UPPER(#{query.name})
            </if>
            <if test="query.nameNotEqual != null">
              ${queryType} UPPER(RES.NAME_) != UPPER(#{query.nameNotEqual})
            </if>
            <if test="query.nameLike != null">
              <!-- based on CAM-6165 compare name like case insensitive -->
              ${queryType} UPPER(RES.NAME_) like UPPER(#{query.nameLike}) ESCAPE ${escapeChar}
            </if>
            <if test="query.nameNotLike != null">
              ${queryType} UPPER(RES.NAME_) not like UPPER(#{query.nameNotLike}) ESCAPE ${escapeChar}
            </if>
            <if test="query.description != null">
              <!-- based on CAM-12186 description case insensitive -->
              ${queryType} UPPER(RES.DESCRIPTION_) = UPPER(#{query.description})
            </if>
            <if test="query.descriptionLike != null">
              ${queryType} UPPER(RES.DESCRIPTION_) like UPPER(#{query.descriptionLike}) ESCAPE ${escapeChar}
            </if>
            <if test="query.priority != null">
              ${queryType} RES.PRIORITY_ = #{query.priority}
            </if>
            <if test="query.minPriority != null">
              ${queryType} RES.PRIORITY_ >= #{query.minPriority}
            </if>
            <if test="query.maxPriority != null">
              ${queryType} RES.PRIORITY_ <= #{query.maxPriority}
            </if>
            <if test="query.assignee != null">
              ${queryType} RES.ASSIGNEE_ = #{query.assignee}
            </if>
            <if test="query.assigneeLike != null">
              ${queryType} RES.ASSIGNEE_ like #{query.assigneeLike} ESCAPE ${escapeChar}
            </if>
            <if test="query.assigneeIn != null && query.assigneeIn.size > 0">
              ${queryType} RES.ASSIGNEE_ in
              <foreach item="assignee" index="index" collection="query.assigneeIn"
                       open="(" separator="," close=")">
                #{assignee}
              </foreach>
            </if>
            <if test="query.assigneeNotIn != null && query.assigneeNotIn.size > 0">
              ${queryType} RES.ASSIGNEE_ NOT in
              <foreach item="assignee" index="index" collection="query.assigneeNotIn"
                       open="(" separator="," close=")">
                #{assignee}
              </foreach>
            </if>
            <if test="query.owner != null">
              ${queryType} RES.OWNER_ = #{query.owner}
            </if>
            <if test="query.unassigned">
              ${queryType} RES.ASSIGNEE_ IS NULL
            </if>
            <if test="query.assigned">
              ${queryType} RES.ASSIGNEE_ IS NOT NULL
            </if>
            <if test="query.noDelegationState">
              ${queryType} RES.DELEGATION_ IS NULL
            </if>
            <if test="query.delegationState != null">
              ${queryType} RES.DELEGATION_ = #{query.delegationStateString}
            </if>
            <if test="query.processInstanceId != null">
              ${queryType} RES.PROC_INST_ID_ = #{query.processInstanceId}
            </if>
            <if test="query.processInstanceIdIn != null && query.processInstanceIdIn.length > 0">
              ${queryType} RES.PROC_INST_ID_ in
              <foreach item="item" index="index" collection="query.processInstanceIdIn"
                       open="(" separator="," close=")">
                #{item}
              </foreach>
            </if>
            <if test="query.processInstanceBusinessKey != null">
              ${queryType} E.BUSINESS_KEY_ = #{query.processInstanceBusinessKey}
            </if>
            <if test="query.processInstanceBusinessKeys != null && query.processInstanceBusinessKeys.length > 0">
              ${queryType} E.BUSINESS_KEY_ in
              <foreach item="item" index="index" collection="query.processInstanceBusinessKeys"
                       open="(" separator="," close=")">
                #{item}
              </foreach>
            </if>
            <if test="query.processInstanceBusinessKeyLike != null">
              ${queryType} E.BUSINESS_KEY_ like #{query.processInstanceBusinessKeyLike} ESCAPE ${escapeChar}
            </if>
            <if test="query.executionId != null">
              ${queryType} RES.EXECUTION_ID_ = #{query.executionId}
            </if>
            <if test="query.caseInstanceId != null">
              ${queryType} RES.CASE_INST_ID_ = #{query.caseInstanceId}
            </if>
            <if test="query.caseInstanceBusinessKey != null">
              ${queryType} CE.BUSINESS_KEY_ = #{query.caseInstanceBusinessKey}
            </if>
            <if test="query.caseInstanceBusinessKeyLike != null">
              ${queryType} CE.BUSINESS_KEY_ like #{query.caseInstanceBusinessKeyLike} ESCAPE ${escapeChar}
            </if>
            <if test="query.caseExecutionId != null">
              ${queryType} RES.CASE_EXECUTION_ID_ = #{query.caseExecutionId}
            </if>
            <if test="query.createTime != null">
              ${queryType} RES.CREATE_TIME_ = #{query.createTime}
            </if>
            <if test="query.createTimeBefore != null">
              ${queryType} RES.CREATE_TIME_ < #{query.createTimeBefore}
            </if>
            <if test="query.createTimeAfter != null">
              ${queryType} RES.CREATE_TIME_ > #{query.createTimeAfter}
            </if>
            <if test="query.updatedAfter != null">
              ${queryType} (RES.LAST_UPDATED_ > #{query.updatedAfter}
              OR RES.LAST_UPDATED_ IS NULL AND RES.CREATE_TIME_ > #{query.updatedAfter})
            </if>
            <if test="query.key != null">
              ${queryType} RES.TASK_DEF_KEY_ = #{query.key}
            </if>
            <if test="query.keyLike != null">
              ${queryType} RES.TASK_DEF_KEY_ like #{query.keyLike} ESCAPE ${escapeChar}
            </if>
            <if test="query.parentTaskId != null">
              ${queryType} RES.PARENT_TASK_ID_ = #{query.parentTaskId}
            </if>
            <if test="query.taskDefinitionKeys != null && query.taskDefinitionKeys.length > 0">
              ${queryType} RES.TASK_DEF_KEY_ in
              <foreach item="item" index="index" collection="query.taskDefinitionKeys"
                       open="(" separator="," close=")">
                #{item}
              </foreach>
            </if>
            <if test="query.processDefinitionId != null">
              ${queryType} RES.PROC_DEF_ID_ = #{query.processDefinitionId}
            </if>
            <if test="query.processDefinitionKey != null">
              ${queryType} D.KEY_ = #{query.processDefinitionKey}
            </if>
            <if test="query.processDefinitionKeys != null && query.processDefinitionKeys.length > 0">
              ${queryType} D.KEY_ in
              <foreach item="item" index="index" collection="query.processDefinitionKeys"
                       open="(" separator="," close=")">
                #{item}
              </foreach>
            </if>
            <if test="query.processDefinitionName != null">
              ${queryType} D.NAME_ = #{query.processDefinitionName}
            </if>
            <if test="query.processDefinitionNameLike != null">
              ${queryType} D.NAME_ like #{query.processDefinitionNameLike} ESCAPE ${escapeChar}
            </if>
            <if test="query.caseDefinitionId != null">
              ${queryType} RES.CASE_DEF_ID_ = #{query.caseDefinitionId}
            </if>
            <if test="query.caseDefinitionKey != null">
              ${queryType} CD.KEY_ = #{query.caseDefinitionKey}
            </if>
            <if test="query.caseDefinitionName != null">
              ${queryType} CD.NAME_ = #{query.caseDefinitionName}
            </if>
            <if test="query.caseDefinitionNameLike != null">
              ${queryType} CD.NAME_ like #{query.caseDefinitionNameLike} ESCAPE ${escapeChar}
            </if>
            <if test="query.dueDate != null || query.dueBefore != null || query.dueAfter != null">
              ${queryType}
              <trim prefix="(" suffix=")" prefixOverrides="and|or">
                <if test="query.dueDate != null">
                  ${queryType} RES.DUE_DATE_ = #{query.dueDate}
                </if>
                <if test="query.dueBefore != null">
                  ${queryType} RES.DUE_DATE_ < #{query.dueBefore}
                </if>
                <if test="query.dueAfter != null">
                  ${queryType} RES.DUE_DATE_ > #{query.dueAfter}
                </if>

                and RES.DUE_DATE_ is not null
              </trim>
            </if>
            <if test="query.withoutDueDate">
              ${queryType} RES.DUE_DATE_ is null
            </if>
            <if test="query.followUpDate != null || query.followUpBefore != null || query.followUpAfter != null">
              ${queryType}
              <trim prefix="(" suffix=")" prefixOverrides="and|or">
                <if test="query.followUpDate != null">
                  ${queryType} RES.FOLLOW_UP_DATE_ = #{query.followUpDate}
                </if>
                <if test="query.followUpBefore != null && !query.followUpNullAccepted">
                  ${queryType} RES.FOLLOW_UP_DATE_ < #{query.followUpBefore}
                </if>
                <if test="query.followUpBefore != null && query.followUpNullAccepted">
                  ${queryType} (RES.FOLLOW_UP_DATE_ IS NULL OR RES.FOLLOW_UP_DATE_ < #{query.followUpBefore})
                </if>
                <if test="query.followUpAfter != null">
                  ${queryType} RES.FOLLOW_UP_DATE_ > #{query.followUpAfter}
                </if>

                <if test="!query.followUpNullAccepted">
                  and RES.FOLLOW_UP_DATE_ is not null
                </if>
              </trim>
            </if>
            <if test="query.excludeSubtasks">
              ${queryType} RES.PARENT_TASK_ID_ IS NULL
            </if>
            <if test="query.activityInstanceIdIn != null && query.activityInstanceIdIn.length > 0">
              ${queryType} E1.ACT_INST_ID_ in
              <foreach item="item" index="index" collection="query.activityInstanceIdIn"
                       open="(" separator="," close=")">
                #{item}
              </foreach>
            </if>
            <if test="query.tenantIds != null && query.tenantIds.length > 0">
              ${queryType} RES.TENANT_ID_ in
              <foreach item="tenantId" index="index" collection="query.tenantIds"
                       open="(" separator="," close=")">
                #{tenantId}
              </foreach>
            </if>
            <if test="query.isWithoutTenantId">
              ${queryType} RES.TENANT_ID_ is null
            </if>
            <if test="query.candidateUser != null || query.candidateGroups != null || query.withCandidateGroups || query.withCandidateUsers">
              ${queryType}
              <trim prefixOverrides="and" prefix="(" suffix=")">
                <if test="!query.includeAssignedTasks">
                  and RES.ASSIGNEE_ is null
                </if>
                and I.TYPE_ = 'candidate'
                <if test="query.candidateUser != null || query.candidateGroups != null">
                  and
                  (
                  <if test="query.candidateUser != null">
                    I.USER_ID_ = #{query.candidateUser}
                  </if>
                  <if test="query.candidateUser != null && query.candidateGroups != null && query.candidateGroups.size > 0">
                    or
                  </if>
                  <if test="query.candidateGroups != null && query.candidateGroups.size > 0">
                    I.GROUP_ID_ IN
                    <foreach item="group" index="index" collection="query.candidateGroups"
                             open="(" separator="," close=")">
                      #{group}
                    </foreach>
                  </if>
                  )
                </if>

                <if test="query.withCandidateGroups">
                  and I.GROUP_ID_ is not null
                </if>

                <if test="query.withCandidateUsers">
                  and I.USER_ID_ is not null
                </if>
              </trim>
            </if>

            <if test="query.withoutCandidateGroups || query.withoutCandidateUsers">
              ${queryType}
              <trim prefixOverrides="and" prefix="(" suffix=")">
                <if test="!query.includeAssignedTasks">
                  and RES.ASSIGNEE_ is null
                </if>

                <if test="query.withoutCandidateGroups">
                  and NOT EXISTS (
                  select 1
                  from ${prefix}ACT_RU_IDENTITYLINK I
                  <where>
                    I.TYPE_ = 'candidate'
                    and I.GROUP_ID_ is not null
                    AND I.TASK_ID_ = RES.ID_
                  </where>
                  )
                </if>

                <if test="query.withoutCandidateUsers">
                  and NOT EXISTS (
                  select 1
                  from ${prefix}ACT_RU_IDENTITYLINK I
                  <where>
                    I.TYPE_ = 'candidate'
                    and I.USER_ID_ is not null
                    AND I.TASK_ID_ = RES.ID_
                  </where>
                  )
                </if>
              </trim>
            </if>

            <if test="query.involvedUser != null">
              ${queryType} (I.USER_ID_ = #{query.involvedUser} or RES.ASSIGNEE_ = #{query.involvedUser} or RES.OWNER_ = #{query.involvedUser})
            </if>

            <!-- queryVariables -->
            <!-- PLEASE NOTE: If you change anything have a look into the HistoricVariableInstance & HistoricProcessInstance, the same query object is used there! -->
            <foreach collection="query.variables" index="index" item="queryVariableValue">
              ${queryType} EXISTS (
              select
              ID_
              from
              ${prefix}ACT_RU_VARIABLE
              WHERE
              <bind name="varPrefix" value="''"/>

              <include refid="org.camunda.bpm.engine.impl.persistence.entity.Commons.variableNameEqualsCaseInsensitive" />

              <choose>
                <when test="queryVariableValue.local">
                  and RES.ID_ = TASK_ID_
                </when>
                <otherwise>
                  <!-- When process instance or case instance variable is queried for, taskId should be null -->
                  and TASK_ID_ is null

                  <choose>
                    <when test="queryVariableValue.processInstanceVariable">
                      and RES.PROC_INST_ID_ = PROC_INST_ID_
                    </when>
                    <otherwise>
                      and RES.CASE_INST_ID_ = CASE_INST_ID_
                    </otherwise>
                  </choose>

                </otherwise>
              </choose>
              <bind name="varTypeField" value="'TYPE_'"/>
              <if test="queryVariableValue.valueConditions != null">
                and
                <include refid="org.camunda.bpm.engine.impl.persistence.entity.Commons.variableValueConditions"/>
              </if>
              )
            </foreach>
            <if test="query.suspensionState != null">
              <if test="query.suspensionState.stateCode == 1">
                ${queryType} RES.SUSPENSION_STATE_ = 1
              </if>
              <if test="query.suspensionState.stateCode == 2">
                ${queryType} RES.SUSPENSION_STATE_ = 2
              </if>
            </if>
          </trim>
        </trim>
        )
      </foreach>

      <!-- Task query does not use left join if cmmn is disabled,
        so we don't need to account for case tasks in this case. -->
      <bind name="applyAuthorizationCheckForCaseInstances" value="authCheck.useLeftJoin" />
      <include refid="org.camunda.bpm.engine.impl.persistence.entity.AuthorizationEntity.contextualAuthorizationCheck" />
      <include refid="org.camunda.bpm.engine.impl.persistence.entity.TenantEntity.queryTenantCheck" />

    </where>
  </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>

  <!-- TASK GROUP ASSIGNMENT REPORT RESULT MAP -->

  <resultMap id="taskCountByCandidateGroupReportResultMap" type="org.camunda.bpm.engine.impl.persistence.entity.TaskCountByCandidateGroupResultEntity">
    <result property="taskCount" column="TASK_COUNT_" jdbcType="INTEGER" />
    <result property="groupName" column="GROUP_NAME_" jdbcType="VARCHAR" />
  </resultMap>

  <select id="selectTaskCountByCandidateGroupReportQuery" parameterType="org.camunda.bpm.engine.impl.TaskReportImpl" resultMap="taskCountByCandidateGroupReportResultMap">
    SELECT
        COUNT(T.ID_) AS TASK_COUNT_,
        I.GROUP_ID_ AS GROUP_NAME_
    FROM
        ${prefix}ACT_RU_TASK T
    LEFT JOIN
        ${prefix}ACT_RU_IDENTITYLINK I
    ON
        I.TASK_ID_ = T.ID_

    <where>
      T.ASSIGNEE_ IS NULL
      <bind name="columnPrefix" value="'T.'"/>
      <include refid="org.camunda.bpm.engine.impl.persistence.entity.TenantEntity.queryTenantCheckWithPrefix" />
    </where>

    GROUP BY
        I.GROUP_ID_
    ORDER BY
        GROUP_NAME_
    ASC
  </select>

</mapper>


text:
"""Tests for the SQLite database parser."""

import sys
import unittest

from plaso.parsers import sqlite
# Register all plugins.
from plaso.parsers import sqlite_plugins  # pylint: disable=unused-import

from tests import test_lib as shared_test_lib
from tests.parsers import test_lib

class SQLiteParserTest(test_lib.ParserTestCase):
  """Tests for the SQLite database parser."""

  # pylint: disable=protected-access

  def testEnablePlugins(self):
    """Tests the EnablePlugins function."""
    parser_object = sqlite.SQLiteParser()
    parser_object.EnablePlugins([u'chrome_history'])

    self.assertIsNotNone(parser_object)
    self.assertIsNone(parser_object._default_plugin)
    self.assertNotEqual(parser_object._plugin_objects, [])
    self.assertEqual(len(parser_object._plugin_objects), 1)

  @shared_test_lib.skipUnlessHasTestFile([u'contacts2.db'])
  def testFileParserChainMaintenance(self):
    """Tests that the parser chain is correctly maintained by the parser."""
    parser_object = sqlite.SQLiteParser()
    storage_writer = self._ParseFile([u'contacts2.db'], parser_object)

    for event in storage_writer.events:
      chain = event.parser
      self.assertEqual(1, chain.count(u'/'))

  @shared_test_lib.skipUnlessHasTestFile([u'wal_database.db'])
  @shared_test_lib.skipUnlessHasTestFile([u'wal_database.db-wal'])
  def testQueryDatabaseWithWAL(self):
    """Tests the Query function on a database with a WAL file."""
    database_file = self._GetTestFilePath([u'wal_database.db'])
    wal_file = self._GetTestFilePath([u'wal_database.db-wal'])

    database = sqlite.SQLiteDatabase(u'wal_database.db')
    with open(database_file, 'rb') as database_file_object:
      with open(wal_file, 'rb') as wal_file_object:
        database.Open(database_file_object, wal_file_object=wal_file_object)

    row_results = []
    for row in database.Query(u'SELECT * FROM MyTable'):
      # Note that pysqlite does not accept a Unicode string in row['string'] and
      # will raise "IndexError: Index must be int or string".
      # Also, Field3 needs to be converted to a string if Python 2 is used
      # because it is a read-write buffer.
      field3 = row['Field3']
      if sys.version_info[0] < 3:
        field3 = str(field3)
      row_results.append((
          row['Field1'], row['Field2'], field3))

    expected_results = [
        (u'Committed Text 1', 1, b'None'),
        (u'Committed Text 2', 2, b'None'),
        (u'Modified Committed Text 3', 4, b'None'),
        (u'Committed Text 4', 5, b'None'),
        (u'Committed Text 5', 7, b'None'),
        (u'Committed Text 6', 8, b'None'),
        (u'Committed Text 7', 9, b'None'),
        (u'Unhashable Row 1', 10, b'Binary Text!\x01\x02\x03'),
        (u'Unhashable Row 2', 11, b'More Binary Text!\x01\x02\x03'),
        (u'New Text 1', 12, b'None'),
        (u'New Text 2', 13, b'None')]

    self.assertEqual(expected_results, row_results)

  @shared_test_lib.skipUnlessHasTestFile([u'wal_database.db'])
  def testQueryDatabaseWithoutWAL(self):
    """Tests the Query function on a database without a WAL file."""
    database_file = self._GetTestFilePath([u'wal_database.db'])

    database = sqlite.SQLiteDatabase(u'wal_database.db')
    with open(database_file, u'rb') as database_file_object:
      database.Open(database_file_object)

    row_results = []
    for row in database.Query(u'SELECT * FROM MyTable'):
      # Note that pysqlite does not accept a Unicode string in row['string'] and
      # will raise "IndexError: Index must be int or string".
      # Also, Field3 needs to be converted to a string if Python 2 is used
      # because it is a read-write buffer.
      field3 = row['Field3']
      if sys.version_info[0] < 3:
        field3 = str(field3)
      row_results.append((
          row['Field1'], row['Field2'], field3))

    expected_results = [
        (u'Committed Text 1', 1, b'None'),
        (u'Committed Text 2', 2, b'None'),
        (u'Deleted Text 1', 3, b'None'),
        (u'Committed Text 3', 4, b'None'),
        (u'Committed Text 4', 5, b'None'),
        (u'Deleted Text 2', 6, b'None'),
        (u'Committed Text 5', 7, b'None'),
        (u'Committed Text 6', 8, b'None'),
        (u'Committed Text 7', 9, b'None'),
        (u'Unhashable Row 1', 10, b'Binary Text!\x01\x02\x03')]

    self.assertEqual(expected_results, row_results)

if __name__ == '__main__':
  unittest.main()

redpajama_set_name: RedPajamaGithub


text:
\newglossaryentry{topn}
{
name=top-N recommendations list,
description={The recommender engine suggest $N$ specific items that are likely appealing to him. This 'best bet' is called top-N recommendation list}
}

\newglossaryentry{topnt}
{
name=top-N recommendation task,
description={The recommender engine shows the user $N$ items that are likely appealing to him but the predicted ratings for the items are not shown. This is refered to as top-N recommendation task}
}

\newglossaryentry{indicator}
{
name={indicator},
plural={indicators},
description={Indicator are Item ID's associated with a particular item $i$. The indicators to $i$ are  ID's of similar items. Indicators are derived from user actions. They lead to other items that are recommendable for the same action. For example if you wish a user to purchase something and you collect all users purchase interactions you can create purchase indicator for every item based on these interactions}
}

\newglossaryentry{coocc}
{
name={co-occur\-rence},
description={Co-occurrence in the context of user-item interactions describes the number of shared users that interacted with a two particular items. Co-occurence can be interpreted as an indicator of similiarity between the two items}
}

\newglossaryentry{tag}
{
name={tag},
plural={tags},
description={A tag is a non-hierarchical keyword or term assigned to an item (e.g. movie). It describes an item and allows it to be found again by browsing or searching. Tags are generally chosen informally and personally by users who visit an item}
}

\newglossaryentry{scalable}
{
name={scaleable},
description={Scalability is the ability of a system, network, or process to handle a growing amount of work in a capable manner or its ability to be enlarged to accommodate that growth}
}

\newglossaryentry{multimodal}
{
name={multimodal},
description={Multimodal interaction means that the user can interact in multiple modes with a system}
}

\newglossaryentry{precision}
{
name={precision},
description={Precision is the fraction of retrieved instances that are relevant}
}

\newglossaryentry{recall}
{
name={recall},
description={recall (also known as sensitivity) is the fraction of relevant instances that are retrieve}d
}

\newglossaryentry{preference}
{
name={preference},
plural={preferences},
description={A preference is the association of a user and an item and a number expressing the strength of the user's preference for the item}
}

\newglossaryentry{llr}
{
name={log-likelihood},
description={The log-likelihood ratio is a probabilistic measure of the importance of a co-occurrence}
}

\newglossaryentry{indicatorm}
{
name={indicator matrix},
description={An indicator matrix is an $n \times n$ matrix where the values are log-likelihood ratio strengths of the co-occurences}
}

\newglossaryentry{like}
{
name={like},
plural={likes},
description={A like is a positive feedback of a user associated with an item. The user interface provides a button to like an item}
}

\newglossaryentry{useraction}
{
name={user action},
plural={user actions},
description={A user action describes the interaction of a user with the GUI. Examples are: view, purchase, like }
}
\newglossaryentry{rec}
{
name={co-occurrence based recommender},
plural={co-occurrence based recommenders},
description={An itembased recommender engine that uses log-likelihood ratio of co-occurences of items in the users action history. It uses a search engine to produce recommendations. The query for the search engine are formed from the user's history }
}

\newglossaryentry{rankedretrieval}
{
name={ranked retrieval},
description={Ranked retrieval is the process of sorting document by their relevance to a query. The most relevant document are listed first}
}

\newglossaryentry{history}
{
name={action history},
description={A user's action history is the stored past behavior of a user an a website}
}

\newglossaryentry{content}
{
name={Content-based},
description={Content-based filtering methods are based on a description of the item and a profile of the user's preference. For instance tags could be used to describe an item. For every user there is a profile to indicate the type of item this user likes. Conten-based filtering algorithm recommend items that are similar to those defined in a user's profile}
}

\newglossaryentry{mapreduce}
{
name={MapReduce},
description={MapReduce is a programming model for processing and generating large data sets with a parallel, distributed algorithm on a cluster}
}

\newglossaryentry{ir}
{
name={information retrieval},
description={Information retrieval (IR) is finding material (usually documents) of an
unstructured nature (usually text) that satisfies an information need from
within large collections (usually stored on computers) \cite{Manning}
}
}

\newglossaryentry{mae}
{
name={Mean Absolute Error},
description={ Mean Absolute Error (MAE) is a quantity used to measure how close the prediction of a rating value is to the actual rating}
}

\newglossaryentry{itembased}
{
name={item-based},
description={Item-based is a form of collaborative filtering based on the similarity between items calculated using user's ratings of those items \cite{jannach11}
}
}

\newglossaryentry{au}
{
name={active user},
description={The active user is the user whom the recommendations is for}
}

\newglossaryentry{field}
{
name={field},
plural={fields},
description={A document stored in a search engine  contains one or more fields. Fields can be of different type but in most cases they are a sequence of terms.}
}

\newglossaryentry{indicatorfield}
{
name={indicator field},
plural={indicator fields},
description={Indicator fields contain items that are similar to the one represented by the document}
}


text:
import os
import sys
import theano
import theano.tensor as T
import numpy
import numpy as np
import mahotas
import partition_comparison
import StringIO
import glob

base_path = os.path.dirname(__file__)
sys.path.insert(1,os.path.join(base_path, '../../common'))
sys.path.insert(2,os.path.join(base_path, '../../database'))
from db import DB
from project import Project
from performance import Performance

from cnn import CNN

if __name__ == '__main__':

    # load the model to use for performance evaluation

    x = T.matrix('x')

    rng = numpy.random.RandomState(1234)

    # retrieve the project settings from the database
    project = DB.getProject('evalcnn')

    print 'measuring offline performance...'

    # create the model based on the project
    model = CNN(
            rng=rng,
            input=x,
            offline=True,
            batch_size=project.batchSize,
            patch_size=project.patchSize,
            nkerns=project.nKernels,
            kernel_sizes=project.kernelSizes,
            hidden_sizes=project.hiddenUnits,
            train_time=project.trainTime,
            momentum=project.momentum,
            learning_rate=project.learningRate,
            path=project.path_offline,
            id=project.id)

    # Generate offline performance results
    # NOTE: this assumes an offline model has been fully trained.  This code
    # will generate variation of information and pixel errors for test images
    # specified in Paths.TestGrayscale
    nTests = 10
    Performance.measureOffline(model, project.id, mean=project.mean, std=project.std,maxNumTests=nTests)

    print 'measuring online performance...'

    model = CNN(
            rng=rng,
            input=x,
            batch_size=project.batchSize,
            patch_size=project.patchSize,
            nkerns=project.nKernels,
            kernel_sizes=project.kernelSizes,
            hidden_sizes=project.hiddenUnits,
            train_time=project.trainTime,
            momentum=project.momentum,
            learning_rate=project.learningRate,
            path=project.path,
            id=project.id)

    Performance.measureOnline(model, project.id, mean=project.mean, std=project.std,maxNumTests=nTests)
    #Performance.measureBaseline(model, project.id,maxNumTests=nTests)


text:
<!DOCTYPE html>

Initial generation is: [2,1],[2,2],[2,3]

When you click "Get next generation", a function will be called.

The function will display a message.

<button onclick="getNextGeneration()">Get next generation</button>


text:
/*
 * @test
 * @bug      4131628 4664607 7025314 8023700 7198273 8025633 8026567
 * @summary  Make sure the Next/Prev Class links iterate through all types.
 *           Make sure the navagation is 2 columns, not 3.
 * @author   jamieh
 * @library  ../lib/
 * @build    JavadocTester TestNavigation
 * @run main TestNavigation
 */

public class TestNavigation extends JavadocTester {

    //Test information.
    private static final String BUG_ID = "4131628-4664607";

    //Javadoc arguments.
    private static final String[] ARGS = new String[] {
        "-d", BUG_ID, "-sourcepath", SRC_DIR, "pkg"
    };

    //Input for string search tests.
    private static final String[][] TEST = {
        {BUG_ID + FS + "pkg" + FS + "A.html", "
Prev Class
"},
        {BUG_ID + FS + "pkg" + FS + "A.html",
            "Next Class"},
        {BUG_ID + FS + "pkg" + FS + "C.html",
            "Prev Class"},
        {BUG_ID + FS + "pkg" + FS + "C.html",
            "Next Class"},
        {BUG_ID + FS + "pkg" + FS + "E.html",
            "Prev Class"},
        {BUG_ID + FS + "pkg" + FS + "E.html",
            "Next Class"},
        {BUG_ID + FS + "pkg" + FS + "I.html",
            "Prev Class"},
        {BUG_ID + FS + "pkg" + FS + "I.html", "
Next Class
"},
        // Test for 4664607
        {BUG_ID + FS + "pkg" + FS + "I.html",
            "
Skip navigation links
" + NL + "" + NL +
            "" + NL + ""}
    };
    private static final String[][] NEGATED_TEST = NO_TEST;

    /**
     * The entry point of the test.
     * @param args the array of command line arguments.
     */
    public static void main(String[] args) {
        TestNavigation tester = new TestNavigation();
        run(tester, ARGS, TEST, NEGATED_TEST);
        tester.printSummary();
    }

    /**
     * {@inheritDoc}
     */
    public String getBugId() {
        return BUG_ID;
    }

    /**
     * {@inheritDoc}
     */
    public String getBugName() {
        return getClass().getName();
    }
}


text:
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
/**
 * Created by Administrator on 2016/7/1.
 */
var core_1 = require('@angular/core');
var CronTabsComponent = (function () {
    function CronTabsComponent(cronService) {
        this.cronService = cronService;
        this.cronTabs = [];
        this.error = null;
        debugger;
    }
    CronTabsComponent.prototype.ngOnInit = function () {
        var _this = this;
        //this.cronTabs = this.cronService.getCronTabs();
        debugger;
        this.cronService
            .getCronTabs()
            .then(function (r) { return _this.cronTabs = r; })
            .catch(function (error) { return _this.error = error; });
    };
    CronTabsComponent = __decorate([
        core_1.Component({
            selector: 'my-crontabs',
            templateUrl: 'template/tools/cronTabs/cronTabs.component.html',
            styleUrls: ['css/tools/app.component.css']
        })
    ], CronTabsComponent);
    return CronTabsComponent;
})();
exports.CronTabsComponent = CronTabsComponent;
//# sourceMappingURL=cronTabs.component.js.map


text:
package main

import (
	"bufio"
	"bytes"
	"fmt"
	"net"
	"regexp"
	"strings"

	"github.com/01org/ciao/networking/libsnnet"
	"github.com/01org/ciao/payloads"
	"github.com/golang/glog"
	"gopkg.in/yaml.v2"
)

type payloadError struct {
	err  error
	code string
}

type extractedDoc struct {
	doc       []string
	realStart int
	realEnd   int
}

var indentedRegexp *regexp.Regexp
var startRegexp *regexp.Regexp
var uuidRegexp *regexp.Regexp

func init() {
	indentedRegexp = regexp.MustCompile("\\s+.*")
	startRegexp = regexp.MustCompile("^start\\s*:\\s*$")
	uuidRegexp = regexp.MustCompile("^[0-9a-fA-F]+(-[0-9a-fA-F]+)*$")
}

func printCloudinit(data *payloads.Start) {
	start := &data.Start
	glog.Info("cloud-init file content")
	glog.Info("-----------------------")
	glog.Infof("Instance UUID:        %v", start.InstanceUUID)
	glog.Infof("Docker image:         %v", start.DockerImage)
	glog.Infof("FW Type:              %v", start.FWType)
	glog.Infof("VM Type:              %v", start.VMType)
	glog.Infof("TenantUUID:           %v", start.TenantUUID)
	net := &start.Networking
	glog.Infof("VnicMAC:              %v", net.VnicMAC)
	glog.Infof("VnicIP:               %v", net.PrivateIP)
	glog.Infof("ConcIP:               %v", net.ConcentratorIP)
	glog.Infof("SubnetIP:             %v", net.Subnet)
	glog.Infof("ConcUUID:             %v", net.ConcentratorUUID)
	glog.Infof("VnicUUID:             %v", net.VnicUUID)
	glog.Infof("Migration:            %t", start.Migration)

	glog.Info("Requested resources:")
	for i := range start.RequestedResources {
		glog.Infof("%8s:     %v", start.RequestedResources[i].Type,
			start.RequestedResources[i].Value)
	}

	for _, storage := range start.Storage {
		if storage.ID != "" {
			glog.Info("Volumes:")
			glog.Infof("  %s Bootable=%t", storage.ID, storage.Bootable)
		}
	}
}

func computeSSHPort(networkNode bool, vnicIP string) int {
	if networkNode || vnicIP == "" {
		return 0
	}

	ip := net.ParseIP(vnicIP)
	if ip == nil {
		return 0
	}

	ip = ip.To4()
	if ip == nil {
		return 0
	}

	port, err := libsnnet.DebugSSHPortForIP(ip)
	if err != nil {
		return 0
	}

	return port
}

func parseVMTtype(start *payloads.StartCmd) (bool, error) {
	vmType := start.VMType
	if vmType != "" && vmType != payloads.QEMU && vmType != payloads.Docker {
		return false, fmt.Errorf("Invalid vmtype received: %s", vmType)
	}

	return vmType == payloads.Docker, nil
}

func parseStartPayload(data []byte) (*vmConfig, *payloadError) {
	var clouddata payloads.Start

	err := yaml.Unmarshal(data, &clouddata)
	if err != nil {
		return nil, &payloadError{err, payloads.InvalidPayload}
	}
	printCloudinit(&clouddata)

	start := &clouddata.Start

	instance := strings.TrimSpace(start.InstanceUUID)
	if !uuidRegexp.MatchString(instance) {
		err = fmt.Errorf("Invalid instance id received: %s", instance)
		return nil, &payloadError{err, payloads.InvalidData}
	}

	fwType := start.FWType
	if fwType != "" && fwType != payloads.Legacy && fwType != payloads.EFI {
		err = fmt.Errorf("Invalid fwtype received: %s", fwType)
		return nil, &payloadError{err, payloads.InvalidData}
	}
	legacy := fwType == payloads.Legacy

	var cpus, mem int
	var networkNode bool
	container, err := parseVMTtype(start)
	if err != nil {
		return nil, &payloadError{err, payloads.InvalidData}
	}

	for i := range start.RequestedResources {
		switch start.RequestedResources[i].Type {
		case payloads.VCPUs:
			cpus = start.RequestedResources[i].Value
		case payloads.MemMB:
			mem = start.RequestedResources[i].Value
		case payloads.NetworkNode:
			networkNode = start.RequestedResources[i].Value != 0
		}
	}

	net := &start.Networking
	vnicIP := strings.TrimSpace(net.PrivateIP)
	sshPort := computeSSHPort(networkNode, vnicIP)
	var volumes []volumeConfig
	for _, storage := range start.Storage {
		if storage.ID != "" {
			volumes = append(volumes, volumeConfig{
				UUID:     storage.ID,
				Bootable: storage.Bootable,
			})
		} else {
			/* See github issue #972:
			   A storage.ID == "" implies an auto-created-by-launcher
			   local disk.  This is not yet supported. */
			return nil, &payloadError{err, payloads.InvalidData}
		}
	}

	return &vmConfig{Cpus: cpus,
		Mem:         mem,
		Instance:    instance,
		DockerImage: start.DockerImage,
		Legacy:      legacy,
		Container:   container,
		NetworkNode: networkNode,
		VnicMAC:     strings.TrimSpace(net.VnicMAC),
		VnicIP:      vnicIP,
		ConcIP:      strings.TrimSpace(net.ConcentratorIP),
		SubnetIP:    strings.TrimSpace(net.Subnet),
		TenantUUID:  strings.TrimSpace(start.TenantUUID),
		ConcUUID:    strings.TrimSpace(net.ConcentratorUUID),
		VnicUUID:    strings.TrimSpace(net.VnicUUID),
		SSHPort:     sshPort,
		Volumes:     volumes,
		Migration:   clouddata.Start.Migration,
	}, nil
}

func generateStartError(instance string, startErr *startError) (out []byte, err error) {
	sf := &payloads.ErrorStartFailure{
		InstanceUUID: instance,
		Reason:       startErr.code,
		Migration:    startErr.migration,
	}
	return yaml.Marshal(sf)
}

func generateDeleteError(instance string, deleteErr *deleteError) (out []byte, err error) {
	df := &payloads.ErrorDeleteFailure{
		InstanceUUID: instance,
		Reason:       deleteErr.code,
	}
	return yaml.Marshal(df)
}

func generateAttachVolumeError(instance, volume string, ave *attachVolumeError) (out []byte, err error) {
	avf := &payloads.ErrorAttachVolumeFailure{
		InstanceUUID: instance,
		VolumeUUID:   volume,
		Reason:       ave.code,
	}
	return yaml.Marshal(avf)
}

func generateDetachVolumeError(instance, volume string, dve *detachVolumeError) (out []byte, err error) {
	dvf := &payloads.ErrorDetachVolumeFailure{
		InstanceUUID: instance,
		VolumeUUID:   volume,
		Reason:       dve.code,
	}
	return yaml.Marshal(dvf)
}

func generateNetEventPayload(ssntpEvent *libsnnet.SsntpEventInfo, agentUUID string) ([]byte, error) {
	var event interface{}
	var eventData *payloads.TenantAddedEvent

	switch ssntpEvent.Event {
	case libsnnet.SsntpTunAdd:
		add := &payloads.EventTenantAdded{}
		event = add
		eventData = &add.TenantAdded
	case libsnnet.SsntpTunDel:
		del := &payloads.EventTenantRemoved{}
		event = del
		eventData = &del.TenantRemoved
	default:
		return nil, fmt.Errorf("Unsupported ssntpEventInfo type: %d",
			ssntpEvent.Event)
	}

	eventData.AgentUUID = agentUUID
	eventData.AgentIP = ssntpEvent.CnIP
	eventData.TenantUUID = ssntpEvent.TenantID
	eventData.TenantSubnet = ssntpEvent.SubnetID
	eventData.ConcentratorUUID = ssntpEvent.ConcID
	eventData.ConcentratorIP = ssntpEvent.CnciIP
	eventData.SubnetKey = ssntpEvent.SubnetKey

	return yaml.Marshal(event)
}

func parseDeletePayload(data []byte) (string, bool, *payloadError) {
	var clouddata payloads.Delete

	err := yaml.Unmarshal(data, &clouddata)
	if err != nil {
		return "", false, &payloadError{err, payloads.DeleteInvalidPayload}
	}

	instance := strings.TrimSpace(clouddata.Delete.InstanceUUID)
	if !uuidRegexp.MatchString(instance) {
		err = fmt.Errorf("Invalid instance id received: %s", instance)
		return "", false, &payloadError{err, payloads.DeleteInvalidData}
	}
	return instance, clouddata.Delete.Migration, nil
}

func extractVolumeInfo(cmd *payloads.VolumeCmd, errString string) (string, string, *payloadError) {
	instance := strings.TrimSpace(cmd.InstanceUUID)
	if !uuidRegexp.MatchString(instance) {
		err := fmt.Errorf("Invalid instance id received: %s", instance)
		return "", "", &payloadError{err, errString}
	}

	volume := strings.TrimSpace(cmd.VolumeUUID)
	if !uuidRegexp.MatchString(volume) {
		err := fmt.Errorf("Invalid volume id received: %s", volume)
		return "", "", &payloadError{err, errString}
	}
	return instance, volume, nil
}

func parseAttachVolumePayload(data []byte) (string, string, *payloadError) {
	var clouddata payloads.AttachVolume

	err := yaml.Unmarshal(data, &clouddata)
	if err != nil {
		glog.Errorf("YAML error: %v", err)
		return "", "", &payloadError{err, payloads.AttachVolumeInvalidPayload}
	}

	return extractVolumeInfo(&clouddata.Attach, payloads.AttachVolumeInvalidData)
}

func parseDetachVolumePayload(data []byte) (string, string, *payloadError) {
	var clouddata payloads.DetachVolume

	err := yaml.Unmarshal(data, &clouddata)
	if err != nil {
		glog.Errorf("YAML error: %v", err)
		return "", "", &payloadError{err, payloads.DetachVolumeInvalidPayload}
	}

	return extractVolumeInfo(&clouddata.Detach, payloads.DetachVolumeInvalidData)
}

func linesToBytes(doc []string, buf *bytes.Buffer) {
	for _, line := range doc {
		_, _ = buf.WriteString(line)
		_, _ = buf.WriteString("\n")
	}
}

func extractDocument(doc *extractedDoc, buf *bytes.Buffer) {
	linesToBytes(doc.doc[doc.realStart:doc.realEnd], buf)
}

func extractStartYaml(lines []string, start int, s, ci *bytes.Buffer) {
	cnStart := 0

	docStartFound := false
	for ; cnStart < start; cnStart++ {
		line := lines[cnStart]
		if strings.HasPrefix(line, "---") {
			docStartFound = true
			cnStart++
			break
		}
	}

	if !docStartFound {
		cnStart = 0
	}

	linesToBytes(lines[cnStart:start], ci)

	i := start
	if i < len(lines) {
		_, _ = s.WriteString(lines[i])
		_, _ = s.WriteString("\n")
		i++
	}
	for ; i < len(lines) && (indentedRegexp.MatchString(lines[i]) || lines[i] == ""); i++ {
		_, _ = s.WriteString(lines[i])
		_, _ = s.WriteString("\n")
	}

	if i < len(lines) && !strings.HasPrefix(lines[i], "...") {
		linesToBytes(lines[i:], ci)
	}
}

func findDocument(lines []string) (doc *extractedDoc, endOfNextDoc int) {
	var realStart int
	var realEnd int
	docStartFound := false
	docEndFound := false

	start := len(lines) - 1
	line := lines[start]
	if strings.HasPrefix(line, "...") {
		docEndFound = true
		realEnd = start
		start--
	}

	for ; start >= 0; start-- {
		line := lines[start]
		if strings.HasPrefix(line, "---") {
			docStartFound = true
			break
		}
		if strings.HasPrefix(line, "...") {
			start++
			break
		}
	}

	if docStartFound {
		realStart = start + 1
		for start = start - 1; start >= 0; start-- {
			line := lines[start]
			if !strings.HasPrefix(line, "%") {
				break
			}
		}
		start++
	} else {
		if start < 0 {
			start = 0
		}
		realStart = start
	}

	if !docEndFound {
		realEnd = len(lines)
	}

	realStart -= start
	realEnd -= start

	return &extractedDoc{lines[start:], realStart, realEnd}, start
}

func splitYaml(data []byte) ([]byte, []byte, []byte) {

	var s bytes.Buffer
	var ci bytes.Buffer
	var md bytes.Buffer

	foundStart := -1
	lines := make([]string, 0, 256)
	docs := make([]*extractedDoc, 0, 3)

	reader := bytes.NewReader(data)
	scanner := bufio.NewScanner(reader)
	for scanner.Scan() {
		line := scanner.Text()
		if foundStart == -1 && startRegexp.MatchString(line) {
			foundStart = len(lines)
		}
		lines = append(lines, line)
	}

	endOfNextDoc := len(lines)

	for endOfNextDoc > 0 {
		var doc *extractedDoc
		doc, endOfNextDoc = findDocument(lines[:endOfNextDoc])
		docs = append([]*extractedDoc{doc}, docs...)
	}

	if len(docs) == 1 {
		if foundStart != -1 {
			extractStartYaml(docs[0].doc, foundStart, &s, &ci)
		} else {
			extractDocument(docs[0], &ci)
		}
	} else if len(docs) == 2 {
		if foundStart != -1 {
			if foundStart < len(docs[0].doc) {
				extractStartYaml(docs[0].doc, foundStart, &s, &ci)
				extractDocument(docs[1], &md)
			} else {
				extractStartYaml(docs[1].doc, foundStart-len(docs[0].doc), &s, &ci)
				extractDocument(docs[0], &md)
			}
		} else {
			extractDocument(docs[0], &ci)
			extractDocument(docs[1], &md)
		}
	} else if foundStart != -1 && foundStart < len(docs[0].doc)+len(docs[1].doc)+len(docs[2].doc) {
		notStart := make([]*extractedDoc, 0, 2)
		sum := 0
		for i := 0; i < 3; i++ {
			newSum := sum + len(docs[i].doc)
			if foundStart >= sum && foundStart < newSum {
				extractDocument(docs[i], &s)
			} else {
				notStart = append(notStart, docs[i])
			}
			sum = newSum
		}
		extractDocument(notStart[0], &ci)
		extractDocument(notStart[1], &md)
	} else {
		glog.Warning("Unable to split payload into documents")
	}

	return s.Bytes(), ci.Bytes(), md.Bytes()
}


text:
package circuit

import (
	"fmt"
	"sync"
	"time"
)

var defaultStatsPrefixf = "circuit.%s"

// Statter interface provides a way to gather statistics from breakers
type Statter interface {
	Counter(sampleRate float32, bucket string, n ...int)
	Timing(sampleRate float32, bucket string, d ...time.Duration)
	Gauge(sampleRate float32, bucket string, value ...string)
}

// PanelEvent wraps a BreakerEvent and provides the string name of the breaker
type PanelEvent struct {
	Name  string
	Event BreakerEvent
}

// Panel tracks a group of circuit breakers by name.
type Panel struct {
	Statter      Statter
	StatsPrefixf string

	Circuits map[string]*Breaker

	lastTripTimes  map[string]time.Time
	tripTimesLock  sync.RWMutex
	panelLock      sync.RWMutex
	eventReceivers []chan PanelEvent
}

// NewPanel creates a new Panel
func NewPanel() *Panel {
	return &Panel{
		Circuits:      make(map[string]*Breaker),
		Statter:       &noopStatter{},
		StatsPrefixf:  defaultStatsPrefixf,
		lastTripTimes: make(map[string]time.Time)}
}

// Add sets the name as a reference to the given circuit breaker.
func (p *Panel) Add(name string, cb *Breaker) {
	p.panelLock.Lock()
	p.Circuits[name] = cb
	p.panelLock.Unlock()

	events := cb.Subscribe()

	go func() {
		for event := range events {
			for _, receiver := range p.eventReceivers {
				receiver <- PanelEvent{name, event}
			}
			switch event {
			case BreakerTripped:
				p.breakerTripped(name)
			case BreakerReset:
				p.breakerReset(name)
			case BreakerFail:
				p.breakerFail(name)
			case BreakerReady:
				p.breakerReady(name)
			}
		}
	}()
}

// Get retrieves a circuit breaker by name.  If no circuit breaker exists, it
// returns the NoOp one and sets ok to false.
func (p *Panel) Get(name string) (*Breaker, bool) {
	p.panelLock.RLock()
	cb, ok := p.Circuits[name]
	p.panelLock.RUnlock()

	if ok {
		return cb, ok
	}

	return NewBreaker(), ok
}

// Subscribe returns a channel of PanelEvents. Whenever a breaker changes state,
// the PanelEvent will be sent over the channel. See BreakerEvent for the types of events.
func (p *Panel) Subscribe() <-chan PanelEvent {
	eventReader := make(chan PanelEvent)
	output := make(chan PanelEvent, 100)

	go func() {
		for v := range eventReader {
			select {
			case output <- v:
			default:
				<-output
				output <- v
			}
		}
	}()
	p.eventReceivers = append(p.eventReceivers, eventReader)
	return output
}

func (p *Panel) breakerTripped(name string) {
	p.Statter.Counter(1.0, fmt.Sprintf(p.StatsPrefixf, name)+".tripped", 1)
	p.tripTimesLock.Lock()
	p.lastTripTimes[name] = time.Now()
	p.tripTimesLock.Unlock()
}

func (p *Panel) breakerReset(name string) {
	bucket := fmt.Sprintf(p.StatsPrefixf, name)

	p.Statter.Counter(1.0, bucket+".reset", 1)

	p.tripTimesLock.RLock()
	lastTrip := p.lastTripTimes[name]
	p.tripTimesLock.RUnlock()

	if !lastTrip.IsZero() {
		p.Statter.Timing(1.0, bucket+".trip-time", time.Since(lastTrip))
		p.tripTimesLock.Lock()
		p.lastTripTimes[name] = time.Time{}
		p.tripTimesLock.Unlock()
	}
}

func (p *Panel) breakerFail(name string) {
	p.Statter.Counter(1.0, fmt.Sprintf(p.StatsPrefixf, name)+".fail", 1)
}

func (p *Panel) breakerReady(name string) {
	p.Statter.Counter(1.0, fmt.Sprintf(p.StatsPrefixf, name)+".ready", 1)
}

type noopStatter struct {
}

func (*noopStatter) Counter(sampleRate float32, bucket string, n ...int)          {}
func (*noopStatter) Timing(sampleRate float32, bucket string, d ...time.Duration) {}
func (*noopStatter) Gauge(sampleRate float32, bucket string, value ...string)     {}


text:
package com.intellij.build.events;

import org.jetbrains.annotations.Nls;

import java.lang.annotation.ElementType;
import java.lang.annotation.Target;

//@ApiStatus.Experimental
public class BuildEventsNls {
  //@NlsContext(prefix = "build.event.message")
  @Nls
  @Target({ElementType.TYPE_USE, ElementType.METHOD, ElementType.PARAMETER})
  public @interface Message {
  }

  @Nls(capitalization = Nls.Capitalization.Sentence)
  @Target(ElementType.TYPE_USE)
  public @interface Hint {
  }

  //@NlsContext(prefix = "build.event.description")
  @Nls(capitalization = Nls.Capitalization.Sentence)
  @Target({ElementType.TYPE_USE, ElementType.METHOD})
  public @interface Description {
  }

  //@NlsContext(prefix = "build.event.title")
  @Nls(capitalization = Nls.Capitalization.Title)
  @Target({ElementType.TYPE_USE, ElementType.METHOD, ElementType.PARAMETER})
  public @interface Title {
  }

}


text:
@interface UIImage (WYAddition)

+ (UIImage *)wy_imageWithColor:(UIColor *)color size:(CGSize)size;

+ (UIImage *)wy_imageWithColor:(UIColor *)color size:(CGSize)size opaque:(BOOL)opaque;

@end


text:
/*
Make a function that looks through an array of objects (first argument)
and returns an array of all objects that have matching property
and value pairs (second argument). Each property and value pair of the source object
has to be present in the object from the collection if it is to be included in the returned array.

For example, if the first argument is [{ first: "Romeo", last: "Montague" },
{ first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }],
and the second argument is { last: "Capulet" },
then you must return the third object from the array (the first argument),
because it contains the property and its value, that was passed on as the second argument.
*/

function whatIsInAName(collection, source) {

    keyArr = Object.keys(source);

    var pairsCheck = true;
    var arr = [];
    for( var i = 0 ; i < collection.length ; ++i )
    {
        for( var j = 0 ; j < keyArr.length ; ++j )
        {
            if( ! ( collection[i][keyArr[j]] == source[keyArr[j]] ) )
            {
                pairsCheck = false;
                break;        // if the pair is not equal, break out of loop
            }
        }
        if( pairsCheck ) arr.push(collection[i]);
        pairsCheck = true;
    }
    return arr;
}

console.log( whatIsInAName([{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 }], { "a": 1, "c": 2 }) );


text:
<?xml version="1.0"?>

<!--

	ADOBE SYSTEMS INCORPORATED
	Copyright 2007 Adobe Systems Incorporated
	All Rights Reserved.

	NOTICE: Adobe permits you to use, modify, and distribute this file
	in accordance with the terms of the license agreement accompanying it.

-->

<componentPackage>

    <component id="Consumer" class="mx.messaging.Consumer"/>
    <component id="HTTPService" class="mx.rpc.http.mxml.HTTPService"/>
    <component id="HTTPMultiService" class="mx.rpc.http.mxml.HTTPMultiService"/>
    <component id="HTTPOperation" class="mx.rpc.http.Operation"/>
    <component id="Producer" class="mx.messaging.Producer"/>
    <component id="RemoteObject" class="mx.rpc.remoting.mxml.RemoteObject"/>
    <component id="RemoteObjectOperation" class="mx.rpc.remoting.mxml.Operation"/>
    <component id="WebService" class="mx.rpc.soap.mxml.WebService"/>
    <component id="WebServiceOperation" class="mx.rpc.soap.mxml.Operation"/>
    <component id="AsyncToken" class="mx.rpc.AsyncToken"/>
    <component id="CallResponder" class="mx.rpc.CallResponder"/>
    <component id="MultiTopicProducer" class="mx.messaging.MultiTopicProducer"/>
    <component id="MultiTopicConsumer" class="mx.messaging.MultiTopicConsumer"/>

</componentPackage>


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

using RequireJsNet.Models;

namespace RequireJsNet.Configuration
{
	public class JsonReader : IConfigReader
	{
		private readonly string path;

		private readonly ConfigLoaderOptions options;

		private readonly IFileReader fileReader;

		public JsonReader(string path, ConfigLoaderOptions options)
		{
			this.path = path;
			this.options = options;
		}

		public JsonReader(string path, ConfigLoaderOptions options, IFileReader reader)
		{
			this.path = path;
			this.options = options;
			this.fileReader = reader;
		}

		public string Path
		{
			get
			{
				return this.path;
			}
		}

		public ConfigurationCollection ReadConfig()
		{
			string text;
			if (fileReader == null)
			{
				text = File.ReadAllText(Path);
			}
			else
			{
				text = fileReader.ReadFile(path);
			}

			var collection = new ConfigurationCollection();
			var deserialized = (JObject)JsonConvert.DeserializeObject(text);
			collection.FilePath = Path;
			collection.Paths = GetPaths(deserialized);
			collection.Shim = GetShim(deserialized);
			collection.BundlePaths = GetPaths(deserialized, "bundlePaths");

			collection.Bundles = GetBundles(deserialized);

			return collection;
		}

		private RequirePaths GetPaths(JObject document, string key = "paths")
		{
			var paths = new RequirePaths();
			paths.PathList = new List<RequirePath>();
			if (document != null && document[key] != null)
			{
                paths.PathList = document[key].Select(r => new RequirePath { Key = ((JProperty)r).Name, Value = ((JProperty)r).Value.Value<string>() }).ToList();
			}

			return paths;
		}

		private RequireShim GetShim(JObject document)
		{
			var shim = new RequireShim();
			shim.ShimEntries = new List<ShimEntry>();
			if (document != null && document["shim"] != null)
			{
				shim.ShimEntries = document["shim"].Select(
					r =>
						{
							var result = new ShimEntry();
							var prop = (JProperty)r;
							result.For = prop.Name;
							var shimObj = (JObject)prop.Value;
							result.Exports = shimObj["exports"] != null ? shimObj["exports"].ToString() : null;
							var depArr = (JArray)shimObj["deps"];
							result.Dependencies = new List<RequireDependency>();
							if (depArr != null)
							{
								result.Dependencies = depArr.Select(dep => new RequireDependency
																			   {
																				   Dependency = dep.ToString()
																			   })
															.ToList();
							}

							return result;
						})
						.ToList();
			}

			return shim;
		}

		private RequireBundles GetBundles(JObject document)
		{
			var bundles = new RequireBundles();
			if (document != null && document["bundles"] != null && this.options.LoadOverrides)
			{
                bundles =  JsonConvert.DeserializeObject<RequireBundles>(document["bundles"].ToString());
			}

			return bundles;
		}
	}
}


text:
layout: post
title: mysql集群安装配置
categories: mysql
---

准备工作:

下载二进制mysql_cluster集群
http://dev.mysql.com/get/Downloads/MySQL-Cluster-7.4/mysql-cluster-gpl-7.4.9-linux-glibc2.5-x86_64.tar.gz

安装:

========================
SQL nodes.(SQL节点)
========================
1、创建Mysql用户组
shell> groupadd mysql
shell> useradd -g mysql -s /bin/false mysql

2、解压mysql_cluster源文件,如:

shell> cd /var/tmp
shell> tar -C /usr/local -xzvf mysql-cluster-gpl-7.4.9-linux2.6.tar.gz
shell> ln -s /usr/local/mysql-cluster-gpl-7.4.9-linux2.6-i686 /usr/local/mysql

3、安装系统数据库
shell> cd mysql
shell> scripts/mysql_install_db --user=mysql

4、设置mysql服务权限组为mysql,
data权限mysql:mysql

shell> chown -R root .
shell> chown -R mysql data
shell> chgrp -R mysql .

5、复制启动脚本,设置为可执行

shell> cp support-files/mysql.server /etc/rc.d/init.d/
shell> chmod +x /etc/rc.d/init.d/mysql.server
shell> chkconfig --add mysql.server

=======================
Data nodes.(数据节点)
=======================

1、复制编译好的可执行文件ndbd、ndbmtd到相应目录/usr/local/bin
shell> cd /var/tmp
shell> tar -zxvf mysql-5.6.27-ndb-7.4.9-linux-i686-glibc23.tar.gz
shell> cd mysql-5.6.27-ndb-7.4.9-linux-i686-glibc23
shell> cp bin/ndbd /usr/local/bin/ndbd 【单线程】
shell> cp bin/ndbmtd /usr/local/bin/ndbmtd 【多线程】

2、将其设置为可执行

shell> cd /usr/local/bin
shell> chmod +x ndb*

Note:数据节点的存储 路径为/usr/local/mysql/data,可在管理节点点配置文件中设置

The data directory on each machine hosting a data node is /usr/local/mysql/data. This piece of information is essential when configuring the management node. (See Section 18.2.4, "Initial Configuration of MySQL Cluster".)

=============================
Management nodes.(管理节点)
=============================
1、复制编译好的可执行文件 ndb_mgm(client管理客户端) 、 ndb_mgmd(管理服务端)到相应目录/usr/local/bin
shell> cd /var/tmp
shell> tar -zxvf mysql-5.6.27-ndb-7.4.9-linux2.6-i686.tar.gz
shell> cd mysql-5.6.27-ndb-7.4.9-linux2.6-i686
shell> cp bin/ndb_mgm* /usr/local/bin

2、将其设置为可执行
shell> cd /usr/local/bin
shell> chmod +x ndb_mgm*

配置:
============
1、配置SQL nodes 和 Data nodes节点
Configuring the data nodes and SQL nodes. The my.cnf file needed for the data nodes is fairly simple. The configuration file should be located in the /etc directory and can be edited using any text editor. (Create the file if it does not exist.) For example:

shell> vi /etc/my.cnf

[mysqld]
# Options for mysqld process:
ndbcluster                      # run NDB storage engine

[mysql_cluster]
# Options for MySQL Cluster processes:
ndb-connectstring=192.168.0.10  # location of management server

2、管理节点配置
Configuring the management node. The first step in configuring the management node is to create the directory in which the configuration file can be found and then to create the file itself. For example (running as root):

shell> mkdir /var/lib/mysql-cluster
shell> cd /var/lib/mysql-cluster
shell> vi config.ini

[ndbd default]
# Options affecting ndbd processes on all data nodes:
NoOfReplicas=2    # Number of replicas
DataMemory=80M    # How much memory to allocate for data storage
IndexMemory=18M   # How much memory to allocate for index storage
                  # For DataMemory and IndexMemory, we have used the
                  # default values. Since the "world" database takes up
                  # only about 500KB, this should be more than enough for
                  # this example Cluster setup.

[tcp default]
# TCP/IP options:
portnumber=2202   # This the default; however, you can use any
                  # port that is free for all the hosts in the cluster
                  # Note: It is recommended that you do not specify the port
                  # number at all and simply allow the default value to be used
                  # instead

[ndb_mgmd]
# Management process options:
hostname=192.168.0.10           # Hostname or IP address of MGM node
datadir=/var/lib/mysql-cluster  # Directory for MGM node log files

[ndbd]
# Options for data node "A":
                                # (one [ndbd] section per data node)
hostname=192.168.0.30           # Hostname or IP address
datadir=/usr/local/mysql/data   # Directory for this data node's data files

[ndbd]
# Options for data node "B":
hostname=192.168.0.40           # Hostname or IP address
datadir=/usr/local/mysql/data   # Directory for this data node's data files

[mysqld]
# SQL node options:
hostname=192.168.0.20           # Hostname or IP address
                                # (additional mysqld connections can be
                                # specified for this node for various
                                # purposes such as running ndb_restore)

=======
修改远程访问权限,密码
./mysqladmin -password newpassword;
./mysqladmin -poldpassword password newpassword;

grant all privileges on *.* to 'root'@'%' identified by '123456';
flush privileges;

=======

============
创建、修改数据表
============

SQL节点

需要使用 ENGINE=NDBCLUSTER; 或ENGINE=NDB
For a table to be replicated in the cluster, it must use the NDBCLUSTER storage engine. To specify this, use the ENGINE=NDBCLUSTER or ENGINE=NDB option when creating the table:

CREATE TABLE tbl_name (col_name column_definitions) ENGINE=NDBCLUSTER;

create table `person` (`id` int(11) not null auto_increment,`name` varchar(30) not null default '',primary key (`id`)) engine=ndbcluster default charset=utf8;

insert into `person` (name) values('hello');

Alternatively, for an existing table that uses a different storage engine, use ALTER TABLE to change the table to use NDBCLUSTER:

ALTER TABLE tbl_name ENGINE=NDBCLUSTER;

======
导入mysql
======

利用mysqldump导入SQL文件,2个方法

1、导入之前,需要替换为ENGINE=NDBCLUSTER;
2、不需要替换,导入之后用alter table修改引擎ENGINE=NDBCLUSTER;

shell> mysqldump --add-drop-table world City > city_table.sql

本地搭建测试

8986
8922-
8923
8906
8907

172.17.163.203 manager.cluster.com  91bade15b55b 10.0.0.23       91bade15b55b
172.17.163.203 ndb1.cluster.com 1af160e4c354        10.0.0.20 1af160e4c354
172.17.163.203 ndb2.cluster.com 09902374aac7     10.0.0.19 09902374aac7
172.17.163.203 mysqld1.cluster.com ee0629f25a4f      10.0.0.22 ee0629f25a4f
172.17.163.203 mysqld2.cluster.com 8f0654dc44ea      10.0.0.21 8f0654dc44ea


text:
desc 'bit-slicer' do
  item = sparkle('https://zgcoder.net/bitslicer/update/appcast.xml').first
  version = item.enclosure.shortVersionString
  url = item.enclosure.url
  Latest.new(version: version, url: url)
end


text:
.. _associationproxy:

associationproxy
================

.. module:: sqlalchemy.ext.associationproxy

``associationproxy`` is used to create a simplified, read/write view of a
relationship.  It can be used to cherry-pick fields from a collection of
related objects or to greatly simplify access to associated objects in an
association relationship.

Simplifying Relationships
-------------------------

Consider this "association object" mapping::

    users_table = Table('users', metadata,
        Column('id', Integer, primary_key=True),
        Column('name', String(64)),
    )

    keywords_table = Table('keywords', metadata,
        Column('id', Integer, primary_key=True),
        Column('keyword', String(64))
    )

    userkeywords_table = Table('userkeywords', metadata,
        Column('user_id', Integer, ForeignKey("users.id"),
               primary_key=True),
        Column('keyword_id', Integer, ForeignKey("keywords.id"),
               primary_key=True)
    )

    class User(object):
        def __init__(self, name):
            self.name = name

    class Keyword(object):
        def __init__(self, keyword):
            self.keyword = keyword

    mapper(User, users_table, properties={
        'kw': relationship(Keyword, secondary=userkeywords_table)
        })
    mapper(Keyword, keywords_table)

Above are three simple tables, modeling users, keywords and a many-to-many
relationship between the two.  These ``Keyword`` objects are little more
than a container for a name, and accessing them via the relationship is
awkward::

    user = User('jek')
    user.kw.append(Keyword('cheese inspector'))
    print user.kw
    # [<__main__.Keyword object at 0xb791ea0c>]
    print user.kw[0].keyword
    # 'cheese inspector'
    print [keyword.keyword for keyword in user.kw]
    # ['cheese inspector']

With ``association_proxy`` you have a "view" of the relationship that contains
just the ``.keyword`` of the related objects.  The proxy is a Python
property, and unlike the mapper relationship, is defined in your class::

    from sqlalchemy.ext.associationproxy import association_proxy

    class User(object):
        def __init__(self, name):
            self.name = name

        # proxy the 'keyword' attribute from the 'kw' relationship
        keywords = association_proxy('kw', 'keyword')

    # ...
    >>> user.kw
    [<__main__.Keyword object at 0xb791ea0c>]
    >>> user.keywords
    ['cheese inspector']
    >>> user.keywords.append('snack ninja')
    >>> user.keywords
    ['cheese inspector', 'snack ninja']
    >>> user.kw
    [<__main__.Keyword object at 0x9272a4c>, <__main__.Keyword object at 0xb7b396ec>]

The proxy is read/write.  New associated objects are created on demand when
values are added to the proxy, and modifying or removing an entry through
the proxy also affects the underlying collection.

 - The association proxy property is backed by a mapper-defined relationship,
   either a collection or scalar.

 - You can access and modify both the proxy and the backing
   relationship. Changes in one are immediate in the other.

 - The proxy acts like the type of the underlying collection.  A list gets a
   list-like proxy, a dict a dict-like proxy, and so on.

 - Multiple proxies for the same relationship are fine.

 - Proxies are lazy, and won't trigger a load of the backing relationship until
   they are accessed.

 - The relationship is inspected to determine the type of the related objects.

 - To construct new instances, the type is called with the value being
   assigned, or key and value for dicts.

 - A ````creator```` function can be used to create instances instead.

Above, the ``Keyword.__init__`` takes a single argument ``keyword``, which
maps conveniently to the value being set through the proxy.  A ``creator``
function could have been used instead if more flexibility was required.

Because the proxies are backed by a regular relationship collection, all of the
usual hooks and patterns for using collections are still in effect.  The
most convenient behavior is the automatic setting of "parent"-type
relationships on assignment.  In the example above, nothing special had to
be done to associate the Keyword to the User.  Simply adding it to the
collection is sufficient.

Simplifying Association Object Relationships
--------------------------------------------

Association proxies are also useful for keeping ``association objects`` out
the way during regular use.  For example, the ``userkeywords`` table
might have a bunch of auditing columns that need to get updated when changes
are made- columns that are updated but seldom, if ever, accessed in your
application.  A proxy can provide a very natural access pattern for the
relationship.

.. sourcecode:: python

    from sqlalchemy.ext.associationproxy import association_proxy

    # users_table and keywords_table tables as above, then:

    def get_current_uid():
        """Return the uid of the current user."""
        return 1  # hardcoded for this example

    userkeywords_table = Table('userkeywords', metadata,
        Column('user_id', Integer, ForeignKey("users.id"), primary_key=True),
        Column('keyword_id', Integer, ForeignKey("keywords.id"), primary_key=True),
        # add some auditing columns
        Column('updated_at', DateTime, default=datetime.now),
        Column('updated_by', Integer, default=get_current_uid, onupdate=get_current_uid),
    )

    def _create_uk_by_keyword(keyword):
        """A creator function."""
        return UserKeyword(keyword=keyword)

    class User(object):
        def __init__(self, name):
            self.name = name
        keywords = association_proxy('user_keywords', 'keyword', creator=_create_uk_by_keyword)

    class Keyword(object):
        def __init__(self, keyword):
            self.keyword = keyword
        def __repr__(self):
            return 'Keyword(%s)' % repr(self.keyword)

    class UserKeyword(object):
        def __init__(self, user=None, keyword=None):
            self.user = user
            self.keyword = keyword

    mapper(User, users_table)
    mapper(Keyword, keywords_table)
    mapper(UserKeyword, userkeywords_table, properties={
        'user': relationship(User, backref='user_keywords'),
        'keyword': relationship(Keyword),
    })

    user = User('log')
    kw1  = Keyword('new_from_blammo')

    # Creating a UserKeyword association object will add a Keyword.
    # the "user" reference assignment in the UserKeyword() constructor
    # populates "user_keywords" via backref.
    UserKeyword(user, kw1)

    # Accessing Keywords requires traversing UserKeywords
    print user.user_keywords[0]
    # <__main__.UserKeyword object at 0xb79bbbec>

    print user.user_keywords[0].keyword
    # Keyword('new_from_blammo')

    # Lots of work.

    # It's much easier to go through the association proxy!
    for kw in (Keyword('its_big'), Keyword('its_heavy'), Keyword('its_wood')):
        user.keywords.append(kw)

    print user.keywords
    # [Keyword('new_from_blammo'), Keyword('its_big'), Keyword('its_heavy'), Keyword('its_wood')]

Building Complex Views
----------------------

.. sourcecode:: python

    stocks_table = Table("stocks", meta,
       Column('symbol', String(10), primary_key=True),
       Column('last_price', Numeric)
    )

    brokers_table = Table("brokers", meta,
       Column('id', Integer,primary_key=True),
       Column('name', String(100), nullable=False)
    )

    holdings_table = Table("holdings", meta,
      Column('broker_id', Integer, ForeignKey('brokers.id'), primary_key=True),
      Column('symbol', String(10), ForeignKey('stocks.symbol'), primary_key=True),
      Column('shares', Integer)
    )

Above are three tables, modeling stocks, their brokers and the number of
shares of a stock held by each broker.  This situation is quite different
from the association example above.  ``shares`` is a *property of the
relationship*, an important one that we need to use all the time.

For this example, it would be very convenient if ``Broker`` objects had a
dictionary collection that mapped ``Stock`` instances to the shares held for
each.  That's easy::

    from sqlalchemy.ext.associationproxy import association_proxy
    from sqlalchemy.orm.collections import attribute_mapped_collection

    def _create_holding(stock, shares):
        """A creator function, constructs Holdings from Stock and share quantity."""
        return Holding(stock=stock, shares=shares)

    class Broker(object):
        def __init__(self, name):
            self.name = name

        holdings = association_proxy('by_stock', 'shares', creator=_create_holding)

    class Stock(object):
        def __init__(self, symbol):
            self.symbol = symbol
            self.last_price = 0

    class Holding(object):
        def __init__(self, broker=None, stock=None, shares=0):
            self.broker = broker
            self.stock = stock
            self.shares = shares

    mapper(Stock, stocks_table)
    mapper(Broker, brokers_table, properties={
        'by_stock': relationship(Holding,
            collection_class=attribute_mapped_collection('stock'))
    })
    mapper(Holding, holdings_table, properties={
        'stock': relationship(Stock),
        'broker': relationship(Broker)
    })

Above, we've set up the ``by_stock`` relationship collection to act as a
dictionary, using the ``.stock`` property of each Holding as a key.

Populating and accessing that dictionary manually is slightly inconvenient
because of the complexity of the Holdings association object::

    stock = Stock('ZZK')
    broker = Broker('paj')

    broker.by_stock[stock] = Holding(broker, stock, 10)
    print broker.by_stock[stock].shares
    # 10

The ``holdings`` proxy we've added to the ``Broker`` class hides the details
of the ``Holding`` while also giving access to ``.shares``::

    for stock in (Stock('JEK'), Stock('STPZ')):
        broker.holdings[stock] = 123

    for stock, shares in broker.holdings.items():
        print stock, shares

    session.add(broker)
    session.commit()

    # lets take a peek at that holdings_table after committing changes to the db
    print list(holdings_table.select().execute())
    # [(1, 'ZZK', 10), (1, 'JEK', 123), (1, 'STEPZ', 123)]

Further examples can be found in the ``examples/`` directory in the
SQLAlchemy distribution.

API
---

.. autofunction:: association_proxy

.. autoclass:: AssociationProxy
   :members:
   :undoc-members: