text:
var apiResponse = require('express-api-response');
var projectRepository = require('../repositories/projectRepository');

module.exports = function(app) {
	app.get('/api/project/', function (req,res,next) {
		projectRepository.getAll(function (err,data) {
			res.data = data;
			res.err = err;
			res.json(data);
			next();
		});
	},apiResponse);

	app.get('/api/project/:id', function(req, res, next) {
		projectRepository.getById(req.params.id, function(err, data) {
			res.data = data;
			res.err = err;
			res.json(data);
			next();
		});
	}, apiResponse);

	app.post('/api/project/', function(req, res, next) {
		projectRepository.add(req.body, function(err, data) {
			res.data = data;
			res.err = err;
			res.json(data);
			next();
		});
	}, apiResponse);

	app.put('/api/project/:id', function(req, res, next) {
		projectRepository.update(req.params.id, req.body,function(err, data) {
			res.data = data;
			res.json(data);
			res.err = err;
			next();
		});
	}, apiResponse);

	app.delete('/api/project/:id', function(req, res, next) {
		projectRepository.delete(req.params.id, function(err, data) {
			res.data = data;
			res.json(data);
			res.err = err;
			next();
		});
	}, apiResponse);
};


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.flowable.engine.impl.persistence.entity.HistoricActivityInstanceEntityImpl">

  <!-- HISTORIC ACTIVITY INSTANCE INSERT -->

  <insert id="insertHistoricActivityInstance" parameterType="org.flowable.engine.impl.persistence.entity.HistoricActivityInstanceEntityImpl">
      insert into ${prefix}ACT_HI_ACTINST (
        ID_,
        PROC_DEF_ID_,
        PROC_INST_ID_,
        EXECUTION_ID_,
        ACT_ID_,
        TASK_ID_,
        CALL_PROC_INST_ID_,
        ACT_NAME_,
        ACT_TYPE_,
        ASSIGNEE_,
        START_TIME_,
        END_TIME_,
        DURATION_,
        DELETE_REASON_,
        TENANT_ID_
      ) values (
        #{id ,jdbcType=VARCHAR},
        #{processDefinitionId, jdbcType=VARCHAR},
        #{processInstanceId, jdbcType=VARCHAR},
        #{executionId, jdbcType=VARCHAR},
        #{activityId ,jdbcType=VARCHAR},
        #{taskId ,jdbcType=VARCHAR},
        #{calledProcessInstanceId ,jdbcType=VARCHAR},
        #{activityName ,jdbcType=VARCHAR},
        #{activityType ,jdbcType=VARCHAR},
        #{assignee ,jdbcType=VARCHAR},
        #{startTime, jdbcType=TIMESTAMP},
        #{endTime, jdbcType=TIMESTAMP},
        #{durationInMillis ,jdbcType=BIGINT},
        #{deleteReason, jdbcType=VARCHAR},
        #{tenantId, jdbcType=VARCHAR}
      )
  </insert>

  <insert id="bulkInsertHistoricActivityInstance" parameterType="java.util.List">
      insert into ${prefix}ACT_HI_ACTINST (
        ID_,
        PROC_DEF_ID_,
        PROC_INST_ID_,
        EXECUTION_ID_,
        ACT_ID_,
        TASK_ID_,
        CALL_PROC_INST_ID_,
        ACT_NAME_,
        ACT_TYPE_,
        ASSIGNEE_,
        START_TIME_,
        END_TIME_,
        DURATION_,
        DELETE_REASON_,
        TENANT_ID_
      ) values
      <foreach collection="list" item="historicActivityInstance" index="index" separator=",">
         (#{historicActivityInstance.id ,jdbcType=VARCHAR},
          #{historicActivityInstance.processDefinitionId, jdbcType=VARCHAR},
          #{historicActivityInstance.processInstanceId, jdbcType=VARCHAR},
          #{historicActivityInstance.executionId, jdbcType=VARCHAR},
          #{historicActivityInstance.activityId ,jdbcType=VARCHAR},
          #{historicActivityInstance.taskId ,jdbcType=VARCHAR},
          #{historicActivityInstance.calledProcessInstanceId ,jdbcType=VARCHAR},
          #{historicActivityInstance.activityName ,jdbcType=VARCHAR},
          #{historicActivityInstance.activityType ,jdbcType=VARCHAR},
          #{historicActivityInstance.assignee ,jdbcType=VARCHAR},
          #{historicActivityInstance.startTime, jdbcType=TIMESTAMP},
          #{historicActivityInstance.endTime, jdbcType=TIMESTAMP},
          #{historicActivityInstance.durationInMillis ,jdbcType=BIGINT},
          #{historicActivityInstance.deleteReason ,jdbcType=VARCHAR},
          #{historicActivityInstance.tenantId, jdbcType=VARCHAR})
      </foreach>
  </insert>

  <insert id="bulkInsertHistoricActivityInstance" databaseId="oracle" parameterType="java.util.List">
      INSERT ALL
      <foreach collection="list" item="historicActivityInstance" index="index">
        INTO ${prefix}ACT_HI_ACTINST (
          ID_,
          PROC_DEF_ID_,
          PROC_INST_ID_,
          EXECUTION_ID_,
          ACT_ID_,
          TASK_ID_,
          CALL_PROC_INST_ID_,
          ACT_NAME_,
          ACT_TYPE_,
          ASSIGNEE_,
          START_TIME_,
          END_TIME_,
          DURATION_,
          DELETE_REASON_,
          TENANT_ID_
        ) VALUES
           (#{historicActivityInstance.id ,jdbcType=VARCHAR},
            #{historicActivityInstance.processDefinitionId, jdbcType=VARCHAR},
            #{historicActivityInstance.processInstanceId, jdbcType=VARCHAR},
            #{historicActivityInstance.executionId, jdbcType=VARCHAR},
            #{historicActivityInstance.activityId ,jdbcType=VARCHAR},
            #{historicActivityInstance.taskId ,jdbcType=VARCHAR},
            #{historicActivityInstance.calledProcessInstanceId ,jdbcType=VARCHAR},
            #{historicActivityInstance.activityName ,jdbcType=VARCHAR},
            #{historicActivityInstance.activityType ,jdbcType=VARCHAR},
            #{historicActivityInstance.assignee ,jdbcType=VARCHAR},
            #{historicActivityInstance.startTime, jdbcType=TIMESTAMP},
            #{historicActivityInstance.endTime, jdbcType=TIMESTAMP},
            #{historicActivityInstance.durationInMillis ,jdbcType=BIGINT},
            #{historicActivityInstance.deleteReason ,jdbcType=VARCHAR},
            #{historicActivityInstance.tenantId, jdbcType=VARCHAR})
      </foreach>
    SELECT * FROM dual
  </insert>

  <!-- HISTORIC ACTIVITY INSTANCE UPDATE -->

  <update id="updateHistoricActivityInstance" parameterType="org.flowable.engine.impl.persistence.entity.HistoricActivityInstanceEntityImpl">
    update ${prefix}ACT_HI_ACTINST set
      EXECUTION_ID_ = #{executionId, jdbcType=VARCHAR},
      ASSIGNEE_ = #{assignee, jdbcType=VARCHAR},
      END_TIME_ = #{endTime, jdbcType=TIMESTAMP},
      DURATION_ = #{durationInMillis ,jdbcType=BIGINT},
      DELETE_REASON_ = #{deleteReason, jdbcType=VARCHAR}
    where ID_ = #{id}
  </update>

  <!-- HISTORIC ACTIVITY INSTANCE DELETE -->

  <delete id="deleteHistoricActivityInstancesByProcessInstanceId">
    delete from ${prefix}ACT_HI_ACTINST where PROC_INST_ID_ = #{processInstanceId}
  </delete>

  <!-- HISTORIC ACTIVITY INSTANCE RESULT MAP -->

  <resultMap id="historicActivityInstanceResultMap" type="org.flowable.engine.impl.persistence.entity.HistoricActivityInstanceEntityImpl">
    <id property="id" column="ID_" jdbcType="VARCHAR" />
    <result property="processDefinitionId" column="PROC_DEF_ID_" jdbcType="VARCHAR" />
    <result property="processInstanceId" column="PROC_INST_ID_" jdbcType="VARCHAR" />
    <result property="executionId" column="EXECUTION_ID_" jdbcType="VARCHAR" />
    <result property="activityId" column="ACT_ID_" jdbcType="VARCHAR" />
    <result property="taskId" column="TASK_ID_" jdbcType="VARCHAR" />
    <result property="calledProcessInstanceId" column="CALL_PROC_INST_ID_" jdbcType="VARCHAR" />
    <result property="activityName" column="ACT_NAME_" jdbcType="VARCHAR" />
    <result property="activityType" column="ACT_TYPE_" jdbcType="VARCHAR" />
    <result property="assignee" column="ASSIGNEE_" jdbcType="VARCHAR" />
    <result property="startTime" column="START_TIME_" jdbcType="TIMESTAMP" />
    <result property="endTime" column="END_TIME_" jdbcType="TIMESTAMP" />
    <result property="durationInMillis" column="DURATION_" jdbcType="BIGINT" />
    <result property="deleteReason" column="DELETE_REASON_" jdbcType="VARCHAR" />
    <result property="tenantId" column="TENANT_ID_" jdbcType="VARCHAR" />
  </resultMap>

  <!-- HISTORIC ACTIVITY INSTANCE SELECT -->

  <select id="selectHistoricActivityInstance" resultMap="historicActivityInstanceResultMap">
    select * from ${prefix}ACT_HI_ACTINST where ACT_ID_ = #{activityId} and PROC_INST_ID_ = #{processInstanceId}
  </select>

  <select id="selectHistoricActivityInstancesByQueryCriteria" parameterType="org.flowable.engine.impl.HistoricActivityInstanceQueryImpl" resultMap="historicActivityInstanceResultMap">
    ${limitBefore}
    select RES.* ${limitBetween}
    <include refid="selectHistoricActivityInstancesByQueryCriteriaSql"/>
    ${orderBy}
    ${limitAfter}
  </select>

  <select id="selectHistoricActivityInstanceCountByQueryCriteria" parameterType="org.flowable.engine.impl.HistoricActivityInstanceQueryImpl" resultType="long">
    select count(RES.ID_)
    <include refid="selectHistoricActivityInstancesByQueryCriteriaSql"/>
  </select>

  <sql id="selectHistoricActivityInstancesByQueryCriteriaSql">
    from ${prefix}ACT_HI_ACTINST RES
    <where>
      <if test="processInstanceId != null">
        RES.PROC_INST_ID_ = #{processInstanceId}
      </if>
      <if test="activityInstanceId != null">
        and RES.ID_ = #{activityInstanceId}
      </if>
      <if test="executionId != null">
        and RES.EXECUTION_ID_ = #{executionId}
      </if>
      <if test="processDefinitionId != null">
        and RES.PROC_DEF_ID_ = #{processDefinitionId}
      </if>
      <if test="activityId != null">
        and RES.ACT_ID_ = #{activityId}
      </if>
      <if test="activityName != null">
        and RES.ACT_NAME_ = #{activityName}
      </if>
      <if test="activityType != null">
        and RES.ACT_TYPE_ = #{activityType}
      </if>
      <if test="assignee != null">
        and RES.ASSIGNEE_ = #{assignee}
      </if>
      <if test="tenantId != null">
        and RES.TENANT_ID_ = #{tenantId}
      </if>
      <if test="tenantIdLike != null">
        and RES.TENANT_ID_ like #{tenantIdLike}${wildcardEscapeClause}
      </if>
      <if test="withoutTenantId">
        and (RES.TENANT_ID_ = '' or RES.TENANT_ID_ is null)
      </if>
      <if test="unfinished">
        and RES.END_TIME_ is null
      </if>
      <if test="finished">
       and RES.END_TIME_ is not null
      </if>
      <if test="deleteReason != null">
        and RES.DELETE_REASON_ = #{deleteReason}
      </if>
      <if test="deleteReasonLike != null">
        and RES.DELETE_REASON_ like #{deleteReasonLike}${wildcardEscapeClause}
      </if>
    </where>
  </sql>

  <select id="selectHistoricActivityInstanceByNativeQuery" parameterType="java.util.Map" resultMap="historicActivityInstanceResultMap">
  	<include refid="org.flowable.engine.db.common.selectByNativeQuery"/>
  </select>

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

  <select id="selectUnfinishedHistoricActivityInstanceExecutionIdAndActivityId" parameterType="org.flowable.engine.common.impl.db.ListQueryParameterObject" resultMap="historicActivityInstanceResultMap">
    select * from ${prefix}ACT_HI_ACTINST RES
    where EXECUTION_ID_ = #{parameter.executionId, jdbcType=VARCHAR} and ACT_ID_ = #{parameter.activityId, jdbcType=VARCHAR} and END_TIME_ is null
  </select>

   <select id="selectUnfinishedHistoricActivityInstanceByProcessInstanceId" parameterType="org.flowable.engine.common.impl.db.ListQueryParameterObject" resultMap="historicActivityInstanceResultMap">
    select * from ${prefix}ACT_HI_ACTINST RES
    where PROC_INST_ID_ = #{parameter.processInstanceId, jdbcType=VARCHAR} and END_TIME_ is null
  </select>

</mapper>

redpajama_set_name: RedPajamaGithub


text:
**I** ([named][0] _i_ [/ˈaɪ/][1], plural _ies_)[\[1\]][2] is the ninth [letter][3] and the third [vowel][4] in the [ISO basic Latin alphabet][5].

## History

In the [Phoenician alphabet][6], the letter may have originated in a [hieroglyph][7] for an arm that represented a [voiced pharyngeal fricative][8] (/ʕ/) in [Egyptian][9], but was reassigned to /j/ (as in English "**y**es") by Semites, because their word for "arm" began with that sound. This letter could also be used to represent /i/, the [close front unrounded vowel][10], mainly in foreign words.

The Greeks adopted a form of this [Phoenician][6] _yodh_ as their letter _[iota][11]_ (⟨Ι, ι⟩) to represent /i/, the same as in the [Old Italic alphabet][12]. In Latin (as in Modern Greek), it was also used to represent /j/ and this use persists in the languages that descended from Latin. The modern letter '[j][13]' originated as a variation of 'i', and both were used interchangeably for both the vowel and the consonant, coming to be differentiated only in the 16th century.[\[2\]][14] The dot over the lowercase 'i' is sometimes called a _[tittle][15]_. In the [Turkish alphabet][16], [dotted and dotless I][17] are considered separate letters, representing a front and back vowel, respectively, and both have uppercase ('I', '[İ][17]') and lowercase ('ı', 'i') forms.

## Use in writing systems

## English

In [Modern English][18] [spelling][19], ⟨i⟩ represents several different sounds, either the diphthong [/aɪ/][1] ("long" ⟨i⟩) as in _kite_, the short [/ɪ/][1] as in _bill_, or the ⟨ee⟩ sound [/iː/][1] in the last syllable of _machine_. The diphthong /aɪ/ developed from [Middle English][20] /iː/ through a series of vowel shifts. In the [Great Vowel Shift][21], Middle English /iː/ changed to [Early Modern English][22] /ei/, which later changed to /əi/ and finally to the Modern English diphthong /aɪ/ in [General American][23] and [Received Pronunciation][24]. Because the diphthong /aɪ/ developed from a Middle English long vowel, it is called "long" ⟨i⟩ in traditional English grammar.\[_[citation needed][25]_\]

The letter ⟨i⟩ is the fifth most common letter in the [English language][26].[\[3\]][27]

The English first-person singular nominative pronoun is "I", pronounced [/aɪ/][1] and always written with a capital letter. This pattern arose for basically the same reason that lowercase ⟨i⟩ acquired a dot: so it wouldn't get lost in manuscripts before the age of printing:

The capitalized "I" first showed up about 1250 in the northern and midland dialects of England, according to the _Chambers Dictionary of Etymology_.

_Chambers_ notes, however, that the capitalized form didn't become established in the south of England "until the 1700s (although it appears sporadically before that time).

Capitalizing the pronoun, _Chambers_ explains, made it more distinct, thus "avoiding misreading handwritten manuscripts."[\[4\]][28]

## Other languages

In many languages' orthographies, ⟨i⟩ is used to represent the sound /i/ or, more rarely, /ɪ/.

## Other uses

The [Roman numeral][29] Ⅰ represents the number [1][30].[\[5\]][31][\[6\]][32]

## Forms and variants

In some [sans serif][33] [typefaces][34], the uppercase letter I, 'I' may be difficult to distinguish from the lowercase [letter L][35], 'l', the [vertical bar character][36] '|', or the [digit one][30] '1'. In serifed typefaces, the capital form of the letter has both a baseline and a cap-height serif, while the lowercase L has generally a hooked ascender and a baseline serif.

The uppercase I does not have a dot ([tittle][15]) while the lowercase i has one in most Latin-derived alphabets. However, some schemes, such as the [Turkish alphabet][16], have two kinds of I: [dotted (İi) and dotless (Iı)][17].

The uppercase I has two kinds of shapes, with serifs ([![I with crossbars.svg](//upload.wikimedia.org/wikipedia/commons/thumb/e/ee/I_with_crossbars.svg/6px-I_with_crossbars.svg.png)][37]) and without serifs ([![I without crossbars.svg](//upload.wikimedia.org/wikipedia/commons/thumb/5/5f/I_without_crossbars.svg/2px-I_without_crossbars.svg.png)][38]). Usually these are considered equivalent, but they are distinguished in some extended Latin alphabet systems such as the [1978 version of the African reference alphabet][39]. In that system, the former is the uppercase counterpart of [ɪ][40] and the latter is the counterpart of 'i'.

## Computing codes

## Other representations

## Related characters

## Descendants and related characters in the Latin alphabet

## Ancestors and siblings in other alphabets

## See also

## References

## External links

[0]: /wiki/English_alphabet#Letter_names "English alphabet"
[1]: /wiki/Help:IPA_for_English "Help:IPA for English"
[2]: #cite_note-1
[3]: /wiki/Letter_(alphabet) "Letter (alphabet)"
[4]: /wiki/Vowel "Vowel"
[5]: /wiki/ISO_basic_Latin_alphabet "ISO basic Latin alphabet"
[6]: /wiki/Phoenician_alphabet "Phoenician alphabet"
[7]: /wiki/Egyptian_hieroglyphs "Egyptian hieroglyphs"
[8]: /wiki/Voiced_pharyngeal_fricative "Voiced pharyngeal fricative"
[9]: /wiki/Egyptian_language "Egyptian language"
[10]: /wiki/Close_front_unrounded_vowel "Close front unrounded vowel"
[11]: /wiki/Iota "Iota"
[12]: /wiki/Old_Italic_alphabet "Old Italic alphabet"
[13]: /wiki/J "J"
[14]: #cite_note-UofD-2
[15]: /wiki/Tittle "Tittle"
[16]: /wiki/Turkish_alphabet "Turkish alphabet"
[17]: /wiki/Dotted_and_dotless_I "Dotted and dotless I"
[18]: /wiki/Modern_English "Modern English"
[19]: /wiki/English_orthography "English orthography"
[20]: /wiki/Middle_English "Middle English"
[21]: /wiki/Great_Vowel_Shift "Great Vowel Shift"
[22]: /wiki/Early_Modern_English "Early Modern English"
[23]: /wiki/General_American "General American"
[24]: /wiki/Received_Pronunciation "Received Pronunciation"
[25]: /wiki/Wikipedia:Citation_needed "Wikipedia:Citation needed"
[26]: /wiki/English_language "English language"
[27]: #cite_note-3
[28]: #cite_note-4
[29]: /wiki/Roman_numeral "Roman numeral"
[30]: /wiki/1_(number) "1 (number)"
[31]: #cite_note-Gordon-5
[32]: #cite_note-6
[33]: /wiki/Sans_serif "Sans serif"
[34]: /wiki/Typefaces "Typefaces"
[35]: /wiki/L "L"
[36]: /wiki/Vertical_bar "Vertical bar"
[37]: /wiki/File:I_with_crossbars.svg
[38]: /wiki/File:I_without_crossbars.svg
[39]: /wiki/African_reference_alphabet#1978_version "African reference alphabet"
[40]: /wiki/%C9%AA "ɪ"


text:
select case when (select count(*)
                  from store_sales
                  where ss_quantity between 1 and 20) > 44666436
            then (select avg(ss_ext_list_price)
                  from store_sales
                  where ss_quantity between 1 and 20)
            else (select avg(ss_net_profit)
                  from store_sales
                  where ss_quantity between 1 and 20) end bucket1 ,
       case when (select count(*)
                  from store_sales
                  where ss_quantity between 21 and 40) > 42475251
            then (select avg(ss_ext_list_price)
                  from store_sales
                  where ss_quantity between 21 and 40)
            else (select avg(ss_net_profit)
                  from store_sales
                  where ss_quantity between 21 and 40) end bucket2,
       case when (select count(*)
                  from store_sales
                  where ss_quantity between 41 and 60) > 1168869
            then (select avg(ss_ext_list_price)
                  from store_sales
                  where ss_quantity between 41 and 60)
            else (select avg(ss_net_profit)
                  from store_sales
                  where ss_quantity between 41 and 60) end bucket3,
       case when (select count(*)
                  from store_sales
                  where ss_quantity between 61 and 80) > 12980570
            then (select avg(ss_ext_list_price)
                  from store_sales
                  where ss_quantity between 61 and 80)
            else (select avg(ss_net_profit)
                  from store_sales
                  where ss_quantity between 61 and 80) end bucket4,
       case when (select count(*)
                  from store_sales
                  where ss_quantity between 81 and 100) > 42510209
            then (select avg(ss_ext_list_price)
                  from store_sales
                  where ss_quantity between 81 and 100)
            else (select avg(ss_net_profit)
                  from store_sales
                  where ss_quantity between 81 and 100) end bucket5
from reason
where r_reason_sk = 1
;


text:
#ifndef __OBJC_ARC_INCLUDED__
#define __OBJC_ARC_INCLUDED__
/**
 * Autoreleases the argument.  Equivalent to [obj autorelease].
 */
id objc_autorelease(id obj);
/**
 * Autoreleases a return value.  This is equivalent to [obj autorelease], but
 * may also store the object somewhere where it can be quickly removed without
 * the need for any message sending.
 */
id objc_autoreleaseReturnValue(id obj);
/**
 * Initializes object as a weak pointer and stores value in it, or nil if value
 * has already begun deallocation.
 */
id objc_initWeak(id *object, id value);
/**
 * Loads the object.  Returns nil if the object stored at this address has
 * already begun deallocation.
 */
id objc_loadWeak(id* object);
/**
 * Loads a weak value and retains it.
 */
id objc_loadWeakRetained(id* obj);
/**
 * Retains the argument.  Equivalent to [obj retain].
 */
id objc_retain(id obj);
/**
 * Retains and autoreleases an object.  Equivalent to [[obj retain] autorelease].
 */
id objc_retainAutorelease(id obj);
/**
 * Retains and releases a return value.  Equivalent to
 * objc_retain(objc_autoreleaseReturnValue(obj)).
 */
id objc_retainAutoreleaseReturnValue(id obj);
/**
 * Retains a return value that has previously been autoreleased and returned.
 * This is equivalent to objc_retainAutoreleaseReturnValue(), but may support a
 * fast path, skipping the autorelease pool entirely.
 */
id objc_retainAutoreleasedReturnValue(id obj);
/**
 * Retains a block.
 */
id objc_retainBlock(id b);
/**
 * Stores value in addr.  This first retains value, then releases the old value
 * at addr, and stores the retained value in the address.
 */
id objc_storeStrong(id *addr, id value);
/**
 * Stores obj in zeroing weak pointer addr.  If obj has begun deallocation,
 * then this stores nil.
 */
id objc_storeWeak(id *addr, id obj);
/**
 * Allocates an autorelease pool and pushes it onto the top of the autorelease
 * pool stack.  Note that the returned autorelease pool is not required to be
 * an object.
 */
void *objc_autoreleasePoolPush(void);
/**
 * Pops the specified autorelease pool from the stack, sending release messages
 * to every object that has been autreleased since the pool was created.
 */
void objc_autoreleasePoolPop(void *pool);
/**
 * Initializes dest as a weak pointer and stores the value stored in src into
 * it.
 */
void objc_copyWeak(id *dest, id *src);
/**
 * Destroys addr as a weak pointer.
 */
void objc_destroyWeak(id* addr);
/**
 * Equivalent to objc_copyWeak(), but may also set src to nil.
 */
void objc_moveWeak(id *dest, id *src);
/**
 * Releases an object.  Equivalent to [obj release].
 */
void objc_release(id obj);
/**
 * Mark the object as about to begin deallocation.  All subsequent reads of
 * weak pointers will return 0.  This function should be called in -release,
 * before calling [self dealloc].
 *
 * Nonstandard extension.
 */
void objc_delete_weak_refs(id obj);
#endif // __OBJC_ARC_INCLUDED__


text:
<?php

namespace ExampleNamespace;

class Example
{

}


text:
const {expect} = require('chai');
const {runUnitTests} = require('../../../infra/testing/webdriver/runUnitTests');
const activateAndControlSW = require('../../../infra/testing/activate-and-control');
const crossOriginServer = require('../../../infra/testing/server/cross-origin-server');
const upath = require('upath');

// Store local references of these globals.
const {webdriver, server} = global.__workbox;

describe(`[workbox-streams]`, function () {
  it(`passes all SW unit tests`, async function () {
    await runUnitTests('/test/workbox-streams/sw/');
  });
});

describe(`[workbox-streams] Integration Tests`, function () {
  const testServerAddress = server.getAddress();
  const testingURL = `${testServerAddress}/test/workbox-streams/static/`;
  const swURL = `${testingURL}sw.js`;
  let crossOriginURL;

  before(async function () {
    await webdriver.get(testingURL);
    await activateAndControlSW(swURL);
    const crossOrigin = await crossOriginServer.start(
      upath.join('..', 'static'),
    );
    crossOriginURL = `${crossOrigin}/4.txt`;
  });

  after(function () {
    crossOriginServer.stop();
  });

  for (const testCase of ['concatenate', 'concatenateToResponse', 'strategy']) {
    it(`should return the expected response for the '${testCase}' approach`, async function () {
      const {text, headers} = await webdriver.executeAsyncScript(
        async (testCase, cb) => {
          try {
            const response = await fetch(new URL(testCase, location));
            const headers = [...response.headers].sort((a, b) => {
              return a[0] > b[0];
            });
            const text = await response.text();
            cb({headers, text});
          } catch (error) {
            cb({text: error.message});
          }
        },
        testCase,
      );

      if (text === 'No streams support') {
        this.skip();
      } else {
        expect(text).to.eql('01234\n');
        expect(headers).to.eql([
          ['content-type', 'text/plain'],
          ['x-test-case', testCase],
        ]);
      }
    });
  }

  it(`should error when a stream source results in an opaque response`, async function () {
    const {text} = await webdriver.executeAsyncScript(
      async (crossOriginURL, cb) => {
        try {
          const url = new URL('/crossOriginURL', location);
          url.searchParams.set('cross-origin-url', crossOriginURL);

          const response = await fetch(url);
          const text = await response.text();
          cb({text});
        } catch (error) {
          cb({text: error.name});
        }
      },
      crossOriginURL,
    );

    if (text === 'No streams support') {
      this.skip();
    } else {
      // The exception name varies from browser to browser.
      expect(text).to.be.oneOf(['TypeError', 'AbortError']);
    }
  });
});


text:
Welcome <?php echo $user->first_name.' '.$user->last_name; ?>

Email: <?php echo $user->email; ?>

Phone: <?php echo $user->phone; ?>

   <a class="btn btn-lg btn-success btn-block" role="button" href="<?php echo base_url(); ?>users/updateinfo">Update Info

 - or -

	<a class="btn btn-lg btn-primary btn-block" role="button" href="<?php echo base_url(); ?>users/logout">Log Out


text: wget -r --cut-dirs=2 -np -nH http://www.physionet.org/physiobank/database/ptbdb/


text:
package com.jivesoftware.os.lab;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.jivesoftware.os.jive.utils.collections.bah.LRUConcurrentBAHLinkedHash;
import com.jivesoftware.os.lab.api.NoOpFormatTransformerProvider;
import com.jivesoftware.os.lab.api.RawEntryFormat;
import com.jivesoftware.os.lab.api.exceptions.LABClosedException;
import com.jivesoftware.os.lab.api.rawhide.LABRawhide;
import com.jivesoftware.os.lab.guts.LABCSLMIndex;
import com.jivesoftware.os.lab.guts.LABIndexProvider;
import com.jivesoftware.os.lab.guts.Leaps;
import com.jivesoftware.os.lab.guts.StripingBolBufferLocks;
import com.jivesoftware.os.lab.guts.allocators.LABAppendOnlyAllocator;
import com.jivesoftware.os.lab.guts.allocators.LABConcurrentSkipListMap;
import com.jivesoftware.os.lab.guts.allocators.LABConcurrentSkipListMemory;
import com.jivesoftware.os.lab.guts.allocators.LABIndexableMemory;
import com.jivesoftware.os.lab.io.BolBuffer;
import com.jivesoftware.os.lab.io.api.UIO;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.commons.io.FileUtils;
import org.testng.Assert;
import org.testng.annotations.Test;

/**
 * @author jonathan.colt
 */
public class LABValidationNGTest {

    @Test(enabled = true, invocationCount = 1, singleThreaded = true)
    public void testClose() throws Exception {

        ExecutorService compact = Executors.newFixedThreadPool(2,
            new ThreadFactoryBuilder().setNameFormat("lab-compact-%d").build());

        ExecutorService destroy = Executors.newFixedThreadPool(1,
            new ThreadFactoryBuilder().setNameFormat("lab-destroy-%d").build());

        ExecutorService scheduler = LABEnvironment.buildLABSchedulerThreadPool(1);

        File walRoot = com.google.common.io.Files.createTempDir();
        File root = com.google.common.io.Files.createTempDir();
        File finalRoot = com.google.common.io.Files.createTempDir();
        int entriesBetweenLeaps = 2;
        LRUConcurrentBAHLinkedHash<Leaps> leapsCache = LABEnvironment.buildLeapsCache(100, 8);
        LABStats labStats = new LABStats();
        LabHeapPressure labHeapPressure = new LabHeapPressure(labStats,
            LABEnvironment.buildLABHeapSchedulerThreadPool(1),
            "default",
            1024 * 1024 * 10,
            1024 * 1024 * 10,
            new AtomicLong(),
            LabHeapPressure.FreeHeapStrategy.mostBytesFirst);

        StripingBolBufferLocks stripingBolBufferLocks = new StripingBolBufferLocks(1024);

        LabWAL wal = new LabWAL(labStats, walRoot, 1024 * 1024 * 10, 1000, 1024 * 1024 * 10, 1024 * 1024 * 10);

        LABIndexProvider indexProvider = (rawhide1, poweredUpTo) -> {
            if (true) {
                LABAppendOnlyAllocator allocator = new LABAppendOnlyAllocator("test", Math.max(3, poweredUpTo));
                LABIndexableMemory memory = new LABIndexableMemory( allocator);
                LABConcurrentSkipListMemory skipList = new LABConcurrentSkipListMemory(rawhide1, memory);
                return new LABConcurrentSkipListMap(labStats, skipList, stripingBolBufferLocks);
            } else {
                return new LABCSLMIndex(rawhide1, stripingBolBufferLocks);
            }
        };

        LAB lab = new LAB(labStats,
            NoOpFormatTransformerProvider.NO_OP,
            LABRawhide.NAME,
            LABRawhide.SINGLETON,
            new RawEntryFormat(0, 0),
            scheduler,
            compact,
            destroy,
            root,
            wal,
            "lab".getBytes(),
            "lab",
            entriesBetweenLeaps,
            labHeapPressure,
            1024 * 1024 * 10,
            4,
            8,
            128,
            0,
            0,
            leapsCache,
            indexProvider,
            false,
            TestUtils.indexType,
            0.75d,
            true);

        int writerCount = 12;
        ExecutorService writers = Executors.newFixedThreadPool(writerCount, new ThreadFactoryBuilder().setNameFormat("writers-%d").build());
        int commitCount = 100;
        int batchSize = 1;
        AtomicLong value = new AtomicLong();
        AtomicLong version = new AtomicLong();
        AtomicLong count = new AtomicLong();
        boolean fsync = true;
        AtomicBoolean close = new AtomicBoolean(false);

        AtomicLong nextId = new AtomicLong();
        AtomicLong running = new AtomicLong();
        List<Future> writerFutures = new ArrayList<>();
        for (int i = 0; i < writerCount; i++) {
            int wi = i;
            running.incrementAndGet();
            writerFutures.add(writers.submit(() -> {
                try {
                    BolBuffer rawEntryBuffer = new BolBuffer();
                    BolBuffer keyBuffer = new BolBuffer();
                    for (int c = 0; c < commitCount; c++) {

                        if (version.get() > (writerCount * commitCount * batchSize) / 2) {
                            if (close.compareAndSet(false, true)) {
                                System.out.println("****** Closing lab during writes... ****** ");
                                lab.close(true, fsync);
                                System.out.println("****** Lab closed... ****** ");

                                try {
                                    FileUtils.forceMkdir(new File(finalRoot, "foobar"));
                                    Files.move(root.toPath(), new File(finalRoot, "foobar").toPath(), StandardCopyOption.ATOMIC_MOVE);
                                } catch (Exception x) {
                                    Assert.fail();
                                }
                                System.out.println("****** Lab moved... ****** ");
                            }
                        }
                        lab.append((stream) -> {
                            for (int b = 0; b < batchSize; b++) {
                                count.incrementAndGet();
                                stream.stream(-1,
                                    UIO.longBytes(nextId.incrementAndGet(), new byte[8], 0),
                                    System.currentTimeMillis(),
                                    false,
                                    version.incrementAndGet(),
                                    UIO.longBytes(value.incrementAndGet(), new byte[8], 0));
                            }
                            return true;
                        }, fsync, rawEntryBuffer, keyBuffer);

                        lab.commit(fsync, true);
                    }
                    System.out.println("Writer " + wi + " done...");
                    return null;
                } catch (Exception x) {
                    if (close.get() && (x instanceof LABClosedException)) {
                        System.out.println("Writer " + wi + " exiting because: " + x);
                        return null;
                    } else {
                        x.printStackTrace();
                        throw x;
                    }
                } finally {
                    running.decrementAndGet();
                }
            }));
        }

        for (Future f : writerFutures) {
            f.get();
        }
        writers.shutdownNow();
        scheduler.shutdownNow();
        compact.shutdownNow();
        destroy.shutdownNow();

    }

    @Test(enabled = true, invocationCount = 1, singleThreaded = true)
    public void testConcurrencyMethod() throws Exception {

        ExecutorService compact = Executors.newFixedThreadPool(2,
            new ThreadFactoryBuilder().setNameFormat("lab-compact-%d").build());

        ExecutorService destroy = Executors.newFixedThreadPool(1,
            new ThreadFactoryBuilder().setNameFormat("lab-destroy-%d").build());

        ExecutorService scheduler = LABEnvironment.buildLABSchedulerThreadPool(1);

        File walRoot = com.google.common.io.Files.createTempDir();
        File root = com.google.common.io.Files.createTempDir();
        int entriesBetweenLeaps = 2;
        LRUConcurrentBAHLinkedHash<Leaps> leapsCache = LABEnvironment.buildLeapsCache(100, 8);
        LABStats labStats = new LABStats();
        LabHeapPressure labHeapPressure = new LabHeapPressure(labStats,
            LABEnvironment.buildLABHeapSchedulerThreadPool(1),
            "default",
            1024 * 1024 * 10,
            1024 * 1024 * 10,
            new AtomicLong(),
            LabHeapPressure.FreeHeapStrategy.mostBytesFirst);

        LabWAL wal = new LabWAL(labStats, walRoot, 1024 * 1024 * 10, 1000, 1024 * 1024 * 10, 1024 * 1024 * 10);

        StripingBolBufferLocks stripingBolBufferLocks = new StripingBolBufferLocks(1024);

        LABRawhide rawhide = LABRawhide.SINGLETON;

        LABIndexProvider indexProvider = (rawhide1, poweredUpTo) -> {
            if (true) {
                LABAppendOnlyAllocator allocator = new LABAppendOnlyAllocator("test", Math.max(3, poweredUpTo));
                LABIndexableMemory memory = new LABIndexableMemory(allocator);
                LABConcurrentSkipListMemory skipList = new LABConcurrentSkipListMemory(rawhide1, memory);
                return new LABConcurrentSkipListMap(labStats, skipList, stripingBolBufferLocks);
            } else {
                return new LABCSLMIndex(rawhide1, stripingBolBufferLocks);
            }
        };

        LAB lab = new LAB(
            labStats,
            NoOpFormatTransformerProvider.NO_OP,
            LABRawhide.NAME, rawhide,
            new RawEntryFormat(0, 0),
            scheduler,
            compact,
            destroy,
            root,
            wal,
            "lab".getBytes(),
            "lab",
            entriesBetweenLeaps,
            labHeapPressure,
            1024 * 1024 * 10,
            4, 8, 128, 0, 0,
            leapsCache,
            indexProvider,
            false,
            TestUtils.indexType,
            0.75d,
            true);

        validationTest(lab);

        lab.close(true, true);
        scheduler.shutdownNow();
        compact.shutdownNow();
        destroy.shutdownNow();

    }

    private void validationTest(LAB lab) throws InterruptedException, Exception, ExecutionException {
        int writerCount = 30;
        int readerCount = 2;

        AtomicLong hits = new AtomicLong();
        AtomicLong version = new AtomicLong();
        AtomicLong value = new AtomicLong();
        AtomicLong count = new AtomicLong();

        int commitCount = 30;
        int batchSize = 1;
        boolean fsync = true;

        ExecutorService writers = Executors.newFixedThreadPool(writerCount, new ThreadFactoryBuilder().setNameFormat("writers-%d").build());
        ExecutorService readers = Executors.newFixedThreadPool(readerCount, new ThreadFactoryBuilder().setNameFormat("readers-%d").build());

        AtomicLong nextId = new AtomicLong();
        AtomicLong running = new AtomicLong();
        List<Future> writerFutures = new ArrayList<>();
        for (int i = 0; i < writerCount; i++) {
            running.incrementAndGet();
            writerFutures.add(writers.submit(() -> {
                try {
                    BolBuffer rawEntryBuffer = new BolBuffer();
                    BolBuffer keyBuffer = new BolBuffer();
                    for (int c = 0; c < commitCount; c++) {
                        lab.append((stream) -> {
                            for (int b = 0; b < batchSize; b++) {
                                count.incrementAndGet();
                                stream.stream(-1,
                                    UIO.longBytes(nextId.incrementAndGet(), new byte[8], 0),
                                    System.currentTimeMillis(),
                                    false,
                                    version.incrementAndGet(),
                                    UIO.longBytes(value.incrementAndGet(), new byte[8], 0));
                            }
                            return true;
                        }, fsync, rawEntryBuffer, keyBuffer);
                        lab.commit(fsync, true);
                        System.out.println((c + 1) + " out of " + commitCount + " gets:" + hits.get() + " debt:" + lab.debt());
                    }
                    return null;
                } catch (Exception x) {
                    x.printStackTrace();
                    throw x;
                } finally {
                    running.decrementAndGet();
                }
            }));
        }

        AtomicLong passed = new AtomicLong();
        AtomicLong failed = new AtomicLong();
        List<String> log = new ArrayList<>();

        List<Future> readerFutures = new ArrayList<>();
        for (int r = 0; r < readerCount; r++) {
            int readerId = r;
            readerFutures.add(readers.submit(() -> {
                try {
                    int overRun = 25;
                    while (running.get() > 0 || overRun > 0) {
                        long maxId = nextId.get();
                        if (maxId == 0) {
                            Thread.yield();
                            continue;
                        }
                        Set<Long> found = new HashSet<>();
                        for (int i = 1; i <= maxId; i++) {
                            int ii = i;
                            lab.get(
                                (keyStream) -> {
                                    byte[] key = UIO.longBytes(ii, new byte[8], 0);
                                    keyStream.key(0, key, 0, key.length);
                                    return true;
                                },
                                (index, key, timestamp, tombstoned, version1, value1) -> {
                                    hits.incrementAndGet();
                                    found.add(key == null ? 0 : key.getLong(0));
                                    return true;
                                }, true);
                        }

                        if (maxId == found.size()) {
                            passed.incrementAndGet();
                            System.out.println("PASSED: " + found.size() + "  vs " + maxId);
                            log.add("PASSED: " + found.size() + "  vs " + maxId);
                            failed.set(0);
                        } else {
                            failed.incrementAndGet();
                            List<Long> missing = new ArrayList<>();
                            for (long i = 1; i <= maxId; i++) {
                                if (!found.contains(i)) {
                                    missing.add(i);
                                }
                            }
                            System.out.println("FAILED: " + found.size() + "  vs " + maxId + " missing=" + missing + " " + missing.size());
                            log.add("FAILED: " + found.size() + "  vs " + maxId + " missing=" + missing + " " + missing.size());
                        }
                        if (running.get() <= 0) {
                            overRun--;
                            Thread.sleep(10);
                        }

                    }
                    System.out.println("Reader (" + readerId + ") finished.");
                    return null;
                } catch (Exception x) {
                    log.add(x.getMessage());
                    x.printStackTrace();
                    throw x;
                }
            }));
        }

        for (Future f : writerFutures) {
            f.get();
        }

        for (Future f : readerFutures) {
            f.get();
        }
        System.out.println("------------------------- READERS ARE DONE -----------------------");

        System.out.println("------------------------------------------------------------------");
        System.out.println("------------------------- ALL DONE -------------------------------");
        System.out.println("------------------------------------------------------------------");

        writers.shutdownNow();
        readers.shutdownNow();

        if (failed.get() > 0) {
            for (String failure : log) {
                System.out.println(":( " + failure);
            }
            Assert.fail();
        }
    }

}


text:
Contributions are welcome!

## Scope

Terminal++ is a C++-14 library aimed at providing an easy-to-use API for managing communication to and from terminal emulators, such as Xterm, PuTTY, Tinyfugue, and so on.  It provides both core knowledge about how to communicate with all kinds of terminals, as well as as set of abstractions (e.g. "screen" and "terminal") that can be used to communicate in more general ways.  Finally, Terminal++ aims to build a database of terminal capabilities so that output can be tailored to the terminal being used.

## Contributing

Contributions can be in several forms:
* Opening issues - the simplest way of contributing can be to say how you would like to use the library.  Or, alternatively, what you couldn't work out from the documentation.  Every ticket closed ends up improving the library!
* Providing fixes - any size welcome.  Spotted a typo?  You can edit this online and submit a pull request.  Have a complete new feature you want to develop and integrate?  Awesome!  You can fork the repo, develop on a branch, and then submit that as a pull request.

## Guidelines

This is a C++-14 codebase, with a Standard Library/Boost look-and-feel.  Please let your tests drive your development, and keep it to around 80 characters per line to make it easier to read.  The rest is negotiable during integration.


text:
package org.vitrivr.cineast.core.features;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.vitrivr.cineast.core.config.QueryConfig;
import org.vitrivr.cineast.core.config.ReadableQueryConfig;
import org.vitrivr.cineast.core.data.CorrespondenceFunction;
import org.vitrivr.cineast.core.data.FloatVectorImpl;
import org.vitrivr.cineast.core.data.distance.DistanceElement;
import org.vitrivr.cineast.core.data.distance.SegmentDistanceElement;
import org.vitrivr.cineast.core.data.m3d.ReadableMesh;
import org.vitrivr.cineast.core.data.score.ScoreElement;
import org.vitrivr.cineast.core.data.segments.SegmentContainer;
import org.vitrivr.cineast.core.features.abstracts.StagedFeatureModule;
import org.vitrivr.cineast.core.render.JOGLOffscreenRenderer;
import org.vitrivr.cineast.core.render.Renderer;
import org.vitrivr.cineast.core.util.LogHelper;

import com.twelvemonkeys.image.ImageUtil;

/**
 * An abstract base class for light field based feature modules as proposed by [1].
 *
 * [1] Chen, D.-Y., Tian, X.-P., Shen, Y.-T., & Ouh. (2003).
 *      On Visual Similarity Based 3D Model Retrieval. In Eurographics (Vol. 22, pp. 313–318). http://doi.org/KE.2008.4730947
 *
 * @author rgasser
 * @version 1.0
 * @created 17.03.17
 */
public abstract class Lightfield extends StagedFeatureModule {

    /** Size of the rendering environment. */
    protected final static int RENDERING_SIZE = 256;

    /** Default value for an unknown pose index. */
    protected final static int POSEIDX_UNKNOWN = -1;

    /**
     *  Camera positions used to create lightfield descriptions.
     *  - First index indicates the position-index
     *  - Second index can be used to address the x,y and z coordinates.
     *
     *  The array must be 1x3 at least, excess elements in the second dimension
     *  are being ignored.
     */
    private final double[][] camerapositions;

    /** Offscreen rendering environment used to create Lightfield images. */
    private final Renderer renderer;

    /**
     *
     * @param tableName
     * @param maxDist
     * @param camerapositions
     */
    protected Lightfield(String tableName, float maxDist, double[][] camerapositions) {
        super(tableName, maxDist);
        if (camerapositions.length == 0) {
          throw new IllegalArgumentException("You must specify at least one camera position!");
        }
        for (double[] position : camerapositions) {
            if (position.length < 3) {
              throw new IllegalArgumentException("Each position must have at least three coordinates.");
            }
        }
        this.camerapositions = camerapositions;

        /*
         * Instantiate JOGLOffscreenRenderer.
         * Handle the case where it cannot be created due to missing OpenGL support.
         */
        JOGLOffscreenRenderer renderer = null;
        try {
            renderer = new JOGLOffscreenRenderer(RENDERING_SIZE, RENDERING_SIZE);
        } catch (Exception exception) {
            LOGGER.error("Could not instantiate JOGLOffscreenRenderer! This instance of {} will not create any results or features!", this.getClass().getSimpleName());
        } finally {
            this.renderer = renderer;
        }
    }

    /**
     * This method represents the first step that's executed when processing query. The associated SegmentContainer is
     * examined and feature-vectors are being generated. The generated vectors are returned by this method together with an
     * optional weight-vector.
     *

     * Important:  The weight-vector must have the same size as the feature-vectors returned by the method.
     *
     * @param sc SegmentContainer that was submitted to the feature module
     * @param qc A QueryConfig object that contains query-related configuration parameters. Can still be edited.
     * @return A pair containing a List of features and an optional weight vector.
     */
    @Override
    protected List<float[]> preprocessQuery(SegmentContainer sc, ReadableQueryConfig qc) {
        /* Check if renderer could be initialised. */
        if (this.renderer == null) {
            LOGGER.error("No renderer found. {} does not return any results.", this.getClass().getSimpleName());
            return new ArrayList<>(0);
        }

        /* Extract features from either the provided Mesh (1) or image (2). */
        ReadableMesh mesh = sc.getNormalizedMesh();
        List<float[]> features;
        if (mesh.isEmpty()) {
            BufferedImage image = ImageUtil.createResampled(sc.getAvgImg().getBufferedImage(), RENDERING_SIZE, RENDERING_SIZE, Image.SCALE_SMOOTH);
            features = this.featureVectorsFromImage(image,POSEIDX_UNKNOWN);
        } else {
            features = this.featureVectorsFromMesh(mesh);
        }

        return features;
    }

    /**
     * This method represents the last step that's executed when processing a query. A list of partial-results (DistanceElements) returned by
     * the lookup stage is processed based on some internal method and finally converted to a list of ScoreElements. The filtered list of
     * ScoreElements is returned by the feature module during retrieval.
     *
     * @param partialResults List of partial results returned by the lookup stage.
     * @param qc             A ReadableQueryConfig object that contains query-related configuration parameters.
     * @return List of final results. Is supposed to be de-duplicated and the number of items should not exceed the number of items per module.
     */
    @Override
    protected List<ScoreElement> postprocessQuery(List<SegmentDistanceElement> partialResults, ReadableQueryConfig qc) {
        /* Perform search for each extracted feature and adjust scores.  */
        HashMap<String,DistanceElement> map = new HashMap<>();
        for (DistanceElement result : partialResults) {
            map.merge(result.getId(), result, (v1, v2) -> {
                if (v1.getDistance() < v2.getDistance()) {
                    return v1;
                } else {
                    return v2;
                }
            });
        }

        /* Add results to list and return list of results. */
        final CorrespondenceFunction correspondence = qc.getCorrespondenceFunction().orElse(this.linearCorrespondence);
        return ScoreElement.filterMaximumScores(map.entrySet().stream().map((e) -> e.getValue().toScore(correspondence)));
    }

    /**
     * Merges the provided QueryConfig with the default QueryConfig enforced by the
     * feature module.
     *
     * @param qc QueryConfig provided by the caller of the feature module.
     * @return Modified QueryConfig.
     */
    @Override
    protected ReadableQueryConfig setQueryConfig(ReadableQueryConfig qc) {
        return new QueryConfig(qc)
                .setCorrespondenceFunctionIfEmpty(this.linearCorrespondence)
                .setDistanceIfEmpty(QueryConfig.Distance.euclidean);
    }

    /**
     * Processes a single segment. Extracts the mesh and persists all associated features. Segments
     * that have no mesh or an empty mesh will not be processed.
     *
     * @param sc
     */
    @Override
    public void processSegment(SegmentContainer sc) {
        /* Check for renderer. */
        if (this.renderer == null) {
            LOGGER.error("No renderer found! {} does not create any features.", this.getClass().getSimpleName());
            return;
        }

        /* If Mesh is empty, no feature is persisted. */
        ReadableMesh mesh = sc.getNormalizedMesh();
        if (mesh == null || mesh.isEmpty()) {
            return;
        }

        /* Extract and persist all features. */
        List<float[]> features = this.featureVectorsFromMesh(mesh);
        for (float[] feature : features) {
            this.persist(sc.getId(), new FloatVectorImpl(feature));
        }
    }

    /**
     * Extracts the Lightfield Fourier descriptors from a provided Mesh. The returned list contains
     * elements of which each holds a pose-index (relative to the camera-positions used by the feature module)
     * and the associated feature-vector (s).
     *
     * @param mesh Mesh for which to extract the Lightfield Fourier descriptors.
     * @return List of descriptors for mesh.
     */
    protected List<float[]> featureVectorsFromMesh(ReadableMesh mesh) {
        /* Prepare empty list of features. */
        List<float[]> features = new ArrayList<>(20);

        /* Retains the renderer and returns if retention fails. */
        if (!this.renderer.retain()) {
          return features;
        }

        /* Everything happens in the try-catch block so as to make sure, that if any exception occurs,
         * the renderer is released again.
         */
        try {
            /* Clears the renderer and assembles a new Mesh. */
            this.renderer.clear();
            this.renderer.assemble(mesh);

            /* Obtains rendered image from configured perspective. */
            for (int i = 0; i < this.camerapositions.length; i++) {
                /* Adjust the camera and render the image. */
                this.renderer.positionCamera((float) this.camerapositions[i][0], (float) this.camerapositions[i][1], (float) this.camerapositions[i][2]);
                this.renderer.render();
                BufferedImage image = this.renderer.obtain();
                if (image == null) {
                    LOGGER.error("Could not generate feature for {} because no image could be obtained from JOGOffscreenRenderer.", this.getClass().getSimpleName());
                    return features;
                }
                features.addAll(this.featureVectorsFromImage(image, i));
            }

        } catch (Exception exception) {
            LOGGER.error("Could not generate feature for {} because an unknown exception occurred ({}).", this.getClass().getSimpleName(), LogHelper.getStackTrace(exception));
        } finally {
            /* Release the rendering context. */
            this.renderer.release();
        }

        /* Extract and persist the feature descriptors. */
        return features;
    }

    /**
     *
     * @param image
     * @param poseidx
     * @return
     */
    protected abstract List<float[]> featureVectorsFromImage(BufferedImage image, int poseidx);

    /**
     *
     * @param poseidx
     * @return
     */
    public double[] positionsForPoseidx(int poseidx) {
        if (poseidx < this.camerapositions.length) {
            return this.camerapositions[poseidx];
        } else {
            return null;
        }
    }
}


text:
<?php
Class Addons_M extends CI_Model {
	private $table='addons';
	 public function __construct()
    {
        // Call the CI_Model constructor
        parent::__construct();
		 $this->load->helper('string');
    }

	public function allAddons() {

	$this->db->select('*');
	$query = $this->db->get($this->table);
	$addons = ($query->result());
	return $addons;

	}

	public function addons_list() {

	$this->db->select('addons_id');
	$this->db->where('email',$this->session->userdata('email'));
	///$this->db->join('addons', 'addons.id = cg_orders.addons_id', 'inner');
	$query = $this->db->get('cg_orders');
	$addons = ($query->result());
	$addonslist = array();

	foreach($addons as $addon) {
		if(!empty($addon->addons_id)) {
		$id=explode(',',$addon->addons_id);
		array_push($addonslist,$id);
		}
	}
	$addonslist=array_reduce($addonslist, 'array_merge', array());

	$this->db->select('*');
	$this->db->where_in('id',$addonslist);
	$query = $this->db->get($this->table);
	$plans = ($query->result());

	return $plans;

	}

	public function plans_list_y() {

	$this->db->select('*');
	$this->db->where('plan_type','y');
	$query = $this->db->get($this->table);
	$plans = ($query->result());

	return $plans;

	}

	public function single_addon($id) {

	$this->db->select('*');
	$this->db->where('id',$id);
	$query = $this->db->get($this->table);
	$addons = ($query->row());

	return $addons;

	}

}


text:
import React from 'react'
import ComponentExample from 'docs/src/components/ComponentDoc/ComponentExample'
import ExampleSection from 'docs/src/components/ComponentDoc/ExampleSection'

const InputUsageExamples = () => (
  <ExampleSection title='Usage'>
    <ComponentExample
      title='Focus'
      description='An input can be focused via a ref.'
      examplePath='elements/Input/Usage/InputExampleRefFocus'
    />
    <ComponentExample
      title='Input Element'
      description='You can pass props (specially data attributes) to input by including an input element in children.'
      examplePath='elements/Input/Usage/InputExampleInputElementProps'
    />
    <ComponentExample
      title='Datalist'
      description={

          An input can be used with a datalist.

      }
      examplePath='elements/Input/Usage/InputExampleDatalist'
    />
  </ExampleSection>
)

export default InputUsageExamples


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <RelativeLayout
        android:id="@+id/parent_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/search_results_list"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginEnd="5dp"
            android:layout_marginStart="5dp"
            android:clipToPadding="false"
            android:paddingTop="60dp" />

        <android.support.design.widget.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <com.arlib.floatingsearchview.FloatingSearchView
                android:id="@+id/floating_search_view"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:floatingSearch_close_search_on_keyboard_dismiss="false"
                app:floatingSearch_dimBackground="false"
                app:floatingSearch_dismissOnOutsideTouch="true"
                app:floatingSearch_leftActionMode="showHome"
                app:floatingSearch_searchBarMarginLeft="@dimen/search_view_inset"
                app:floatingSearch_searchBarMarginRight="@dimen/search_view_inset"
                app:floatingSearch_searchBarMarginTop="@dimen/search_view_inset"
                app:floatingSearch_searchHint="Search..."
                app:floatingSearch_showSearchKey="true"
                app:floatingSearch_suggestionsListAnimDuration="250" />
        </android.support.design.widget.AppBarLayout>

    </RelativeLayout>
</android.support.design.widget.CoordinatorLayout>


text:
<?php

namespace Google\Service\Contentwarehouse;

class GoogleCloudContentwarehouseV1AccessControlAction extends \Google\Model
{
  /**
   * @var string
   */
  public $operationType;
  protected $policyType = GoogleIamV1Policy::class;
  protected $policyDataType = '';

  /**
   * @param string
   */
  public function setOperationType($operationType)
  {
    $this->operationType = $operationType;
  }
  /**
   * @return string
   */
  public function getOperationType()
  {
    return $this->operationType;
  }
  /**
   * @param GoogleIamV1Policy
   */
  public function setPolicy(GoogleIamV1Policy $policy)
  {
    $this->policy = $policy;
  }
  /**
   * @return GoogleIamV1Policy
   */
  public function getPolicy()
  {
    return $this->policy;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(GoogleCloudContentwarehouseV1AccessControlAction::class, 'Google_Service_Contentwarehouse_GoogleCloudContentwarehouseV1AccessControlAction');


text:
ENV['RACK_ENV'] = 'test'
ENV['RAILS_ENV'] = 'test'

require File.expand_path("../dummy/config/environment", __FILE__)
require 'rspec/rails'

ActiveRecord::Migrator.migrations_paths = ActiveRecord::Tasks::DatabaseTasks.migrations_paths
ActiveRecord::Tasks::DatabaseTasks.drop_current
ActiveRecord::Tasks::DatabaseTasks.create_current
ActiveRecord::Tasks::DatabaseTasks.migrate

Dir[File.expand_path("../support/**/*.rb", __FILE__)].each { |f| require f }

RSpec.configure do |config|
  config.expect_with :rspec do |c|
    c.syntax = :expect
  end
  config.order = "random"
  config.treat_symbols_as_metadata_keys_with_true_values = true
  config.full_backtrace = true
end


text:
int main(int argc, char* argv[])
{
    std::clog << "OS X is not currently supported by topcube\n";
    return 0;
}

#else

#include <string.h> // for strcmp
#include <cstdlib> // for exit
#include <gtk/gtk.h>
#include <webkit/webkit.h>
#include <webkit/webkitwebview.h>

GtkWidget *window;
GtkWidget *scrolled_window;
GtkWidget *web_view;
WebKitWebSettings *settings;

void destroy (void)
{
  gtk_main_quit ();
}

void title_change (void)
{
  gtk_window_set_title(GTK_WINDOW (window), webkit_web_view_get_title(WEBKIT_WEB_VIEW (web_view)));
}

void new_window (
  WebKitWebView *web_view,
  WebKitWebFrame *frame,
  WebKitNetworkRequest *request)
{
  gchar *argv[3];
  argv[0] = const_cast<char*>("/usr/bin/xdg-open");
  argv[1] = const_cast<char*>(webkit_network_request_get_uri(request));
  argv[2] = NULL;
  g_spawn_async(NULL, argv, NULL, G_SPAWN_LEAVE_DESCRIPTORS_OPEN, NULL, NULL, NULL, NULL);
}

static gboolean download (
  WebKitWebView *web_view,
  WebKitWebFrame *frame,
  WebKitNetworkRequest *request,
  const char *mime_type,
  WebKitWebPolicyDecision *decision,
  gpointer user_data)
{
  // Any other mime types we should handle?
  if (strcmp(mime_type, "text/html") != 0) {
    WebKitDownload *download = webkit_download_new(request);
    GtkWidget *window = gtk_widget_get_toplevel (GTK_WIDGET(web_view));
    GtkWidget *dialog = gtk_file_chooser_dialog_new ("Save file",
      GTK_WINDOW(window),
      GTK_FILE_CHOOSER_ACTION_SAVE,
      GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
      GTK_STOCK_SAVE, GTK_RESPONSE_ACCEPT,
      NULL);
    gtk_file_chooser_set_do_overwrite_confirmation (GTK_FILE_CHOOSER (dialog), TRUE);
    gtk_file_chooser_set_current_name (GTK_FILE_CHOOSER (dialog), webkit_download_get_suggested_filename(download));

    // @TODO getting a warning 'Unable to retrieve the file info' for the
    // file as it does not exist yet... track down why?
    if (gtk_dialog_run (GTK_DIALOG (dialog)) == GTK_RESPONSE_ACCEPT) {
      gchar *destination = g_filename_to_uri(gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (dialog)), NULL, NULL);
      webkit_download_set_destination_uri (download, destination);
      webkit_download_start(download);
      g_free(destination);
    } else {
      webkit_download_cancel(download);
      g_object_unref(download);
    }

    gtk_widget_destroy (dialog);
    webkit_web_policy_decision_ignore(decision);
  }
  return TRUE;
}

int main(int argc, char* argv[])
{
  static gchar *url = const_cast<char*>("http://google.com");
  static gchar *name = const_cast<char*>("TopCube");
  static gint width = 800;
  static gint height = 600;
  static gint minwidth = 600;
  static gint minheight = 400;
  static GOptionEntry entries[] = {
    { "url", 'u', 0, G_OPTION_ARG_STRING, &url, "URL", NULL },
    { "name", 'n', 0, G_OPTION_ARG_STRING, &name, "Window name", NULL },
    { "width", 'W', 0, G_OPTION_ARG_INT, &width, "Width", NULL },
    { "height", 'H', 0, G_OPTION_ARG_INT, &height, "Height", NULL },
    { "minwidth", 'w', 0, G_OPTION_ARG_INT, &minwidth, "Minimum width", NULL },
    { "minheight", 'h', 0, G_OPTION_ARG_INT, &minheight, "Minimum height", NULL }
  };
  GError *error = NULL;
  GOptionContext *options;
  options = g_option_context_new("topcube options");
  g_option_context_add_main_entries (options, entries, NULL);
  g_option_context_add_group (options, gtk_get_option_group(TRUE));
  if (!g_option_context_parse (options, &argc, &argv, &error)) {
    g_print ("Error parsing options: %s\n", error->message);
    exit (1);
  }

  gtk_init (&argc, &argv);
  window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
  scrolled_window = gtk_scrolled_window_new (NULL, NULL);
  web_view = webkit_web_view_new ();

  // Modify default settings - disable right click menus.
  settings = webkit_web_view_get_settings (WEBKIT_WEB_VIEW(web_view));
  g_object_set(settings, "enable-default-context-menu", FALSE, NULL);

  gtk_signal_connect (GTK_OBJECT (window), "destroy", GTK_SIGNAL_FUNC (destroy), NULL);
  gtk_signal_connect (GTK_OBJECT (web_view), "title-changed", GTK_SIGNAL_FUNC (title_change), NULL);
  gtk_signal_connect (GTK_OBJECT (web_view), "mime-type-policy-decision-requested", GTK_SIGNAL_FUNC (download), NULL);
  gtk_signal_connect (GTK_OBJECT (web_view), "new-window-policy-decision-requested", GTK_SIGNAL_FUNC (new_window), NULL);

  gtk_container_add (GTK_CONTAINER (scrolled_window), web_view);
  gtk_container_add (GTK_CONTAINER (window), scrolled_window);

  webkit_web_view_load_uri (WEBKIT_WEB_VIEW (web_view), url);

  gtk_window_set_wmclass (GTK_WINDOW (window), name, name);
  gtk_window_set_default_size (GTK_WINDOW (window), width, height);

  GdkGeometry hints;
  hints.min_width = minwidth;
  hints.min_height = minheight;
  gtk_window_set_geometry_hints(GTK_WINDOW (window), GTK_WIDGET (scrolled_window), &hints, GDK_HINT_MIN_SIZE);

  gtk_widget_grab_focus (GTK_WIDGET(web_view));
  gtk_widget_show_all (window);
  gtk_main ();

  return 0;
}

#endif // linux


text:
configuring speech recognition engines (Dragon NaturallySpeaking being the most configurable), such a voice command calls back to arbitrary Haskell when the recognition is matched.

e.g. https://github.com/sboosali/commands-spiros/blob/windows/config/Commands/Plugins/Spiros/Edit.hs

the core type is an Applicative for defining grammars, so that you can simultaneously generate a parser (to parse recognitions) and a serialized grammar that's consistent with it (to bias recognitions when loaded by the speech engine).
For example, given this grammar

data Action = Copy | Google
 deriving (Show, Enum, Bounded)

data Region = Word | Line | Selection | Clipboard
 deriving (Show, Enum, Bounded)

data Phrase
 = KnownPhrase  Region
 | SpokenPhrase [String]
 deriving (Show)

data Command = Command Action Phrase
 deriving (Show)
 -- the root of our grammar

-- :: RHS Region
gRegion = "<region>"
 <=> Word      $> "this word"
 <|> Line      $> "this line"
 <|> Selection $> "that"
 <|> Clipboard $> "the clipboard"

-- :: RHS Action
gAction = "<action>"
 <=> defaultGrammarWith (fmap toLower)

-- defaultGrammarWith :: (Show a, Enum a, Bounded a) => (String -> String) -> RHS a
-- it enumerates the constructors and munges them

{- equivalent to

    Copy      $> "copy"
<|> Google    $> "google"

-}

-- :: RHS Phrase
gPhrase = "<phrase>"
 <=> KnownPhrase  <$> gRegion
 <|> SpokenPhrase <$> gDictation

-- gDictation :: RHS [String]
-- gDictation is a built-in, it represents arbitrary dictation, i.e. one or more words from the English lexicon

gCommand = "<command>" <=> gCommand <$> gAction <*> gPhrase

-- note, we could also just use strings directly, since there is a little boilerplate for defining the Command type and its descendants, but I prefer going FULLHASKELL (to get the usual benefits from validation, like debugability)

And these command handlers:

-- execute a command
eCommand :: Command -> IO ()
eCommand (Command Copy   phrase) = do
 selectPhrase
 defaultCopy
eCommand (Command Google phrase) = do
 s <- getPhrase
 google s

eAction = \case
 Copy | Google

eRegion = \case
 Word | Line | Selection | Clipboard

getPhrase = \case
 KnownPhrase  r  -> getRegion r
 SpokenPhrase ws -> return ws

-- highlight or access
getRegion = \case
 Clipboard -> do
               -- directly access the clipboard
               getClipboard
 Selection -> do
               -- first copy whatever is currently highlighted
               copy
 Word      -> do
               -- first highlight the current word
               press "A-b"   -- go to the start
               press "S-A-f" -- drag across to the end
               copy
 Line      -> do
               -- first highlight the current line
               press "C-a"   -- go to the statt
               press "S-C-e" -- drag across to the end
               copy

copy = defaultCopy

-- copy whatever is currently highlighted
-- uses the default keyboard shortcut of ctrl+c
-- the pause gives the current application enough time to process and handle the event (it should be almost instantaneous, but most apps are very slow)
defaultCopy :: IO String
defaultCopy = do
 press "C-c"
 delayMilliseconds 50
 getClipboard

google s = do
 openUrl $ "https://www.google.com/search?q=" <> urlEncode s

given bindings to the operating system's accessibility / automation features:

getClipboard :: IO String
openUrl :: String -> IO ()
-- from the `workflow` package

We get both a parser:

createParser :: RHS a -> Parser a
pCommand = createParser gCommand

>>> runParser pCommand ["google", "the", "clipboard"]
Right (Command Google (KnownPhrase Clipboard))

>>> runParser pCommand ["google", "some", "arbitrary", "dictation"]
Right (Command Google (SpokenPhrase ["some", "arbitrary", "dictation"]))

And a serialized grammar:

renderGrammar :: RHS a -> String
sCommand = renderGrammar gCommand
writeGrammar g = saveFile ".../grammar.bnf" (renderGrammar g)
 -- the grammar file is automatically reloaded by the speech engine
 -- other shims exist, like a network call or clicking through a GUI

>>> putStrLn $ renderGrammar gCommand
export <command>
<command> = <action> <phrase>
<action>  = copy | google
<phrase>  = <region> | <dictation>
<region>  = this word | this line | that | the clipboard

And we can execute the recognition:

>>> execCommand (Command Google (KnownPhrase Clipboard))
...

{- equivalent to

do
   s <- getClipboard
   openUrl $ "https://www.google.com/search?q=" <> urlEncode s

-}


text:
struct _tmp_parser_def {
    spicy_parser* parser;
    hlt_type_info* pobj;
};

static struct _tmp_parser_def* _tmp_parsers = 0;
static int _tmp_parsers_size = 0;

static void _register_parser(spicy_parser* parser, hlt_type_info* pobj, hlt_exception** excpt,
                             hlt_execution_context* ctx)
{
    parser->type_info = pobj;
    hlt_list_push_back(__spicy_globals()->parsers, &hlt_type_info_hlt_SpicyHilti_Parser, &parser,
                       excpt, ctx);
    spicyhilti_mime_register_parser(parser, excpt, ctx);
    GC_DTOR(parser, hlt_SpicyHilti_Parser, ctx);
}

void __spicy_register_pending_parsers()
{
    if ( ! _tmp_parsers )
        return;

    hlt_exception* excpt = 0;
    hlt_execution_context* ctx = hlt_global_execution_context();

    for ( int i = 0; i < _tmp_parsers_size; i++ )
        _register_parser(_tmp_parsers[i].parser, _tmp_parsers[i].pobj, &excpt, ctx);

    free(_tmp_parsers);
}

hlt_list* spicy_parsers(hlt_exception** excpt, hlt_execution_context* ctx)
{
    return __spicy_globals()->parsers;
}

void spicy_enable_debugging(int8_t enabled)
{
    // Should be (sufficiently) thread-safe.
    __spicy_globals()->debugging = enabled;
}

int8_t spicy_debugging_enabled(hlt_exception** excpt, hlt_execution_context* ctx)
{
    return __spicy_globals()->debugging;
}

int8_t spicyhilti_debugging_enabled(hlt_exception** excpt, hlt_execution_context* ctx)
{
    return spicy_debugging_enabled(excpt, ctx);
}

void spicy_fatal_error(const char* msg)
{
    fprintf(stderr, "fatal Spicy error: %s", msg);
}

// Note that this function can be called before spicy_init().
void spicyhilti_register_parser(spicy_parser* parser, hlt_type_info* pobj, hlt_exception** excpt,
                                hlt_execution_context* ctx)
{
    GC_CCTOR(parser, hlt_SpicyHilti_Parser, ctx);

    if ( __spicy_globals_initialized() )
        _register_parser(parser, pobj, excpt, ctx);

    else {
        int new_size = (_tmp_parsers_size + 1);
        _tmp_parsers = realloc(_tmp_parsers, new_size * sizeof(struct _tmp_parser_def));
        _tmp_parsers[_tmp_parsers_size].parser = parser;
        _tmp_parsers[_tmp_parsers_size].pobj = pobj;
        _tmp_parsers_size = new_size;
    }
}

void call_init_func(void (*func)(hlt_exception** excpt, hlt_execution_context* ctx))
{
    hlt_exception* excpt = 0;
    hlt_execution_context* ctx = hlt_global_execution_context();

    (*func)(&excpt, ctx);

    if ( excpt )
        hlt_exception_print_uncaught(excpt, ctx);
}

void spicy_debug_print_ptr(hlt_string tag, const hlt_type_info* type, void** ptr,
                           hlt_exception** excpt, hlt_execution_context* ctx)
{
    assert(false);
}


text:
import * as _ from 'lodash';

import { Matrix } from './Matrix';
import { Point } from './Point';

/** Returns the floor modulus of the integer argument. */
export function floorMod(num: number, maxNum: number) {
  return (num % maxNum + maxNum) % maxNum;
}

/** Linearly interpolate between a and b using time t. */
export function lerp(a: number, b: number, t: number) {
  return a + (b - a) * t;
}

/** Returns true if the points are collinear. */
export function areCollinear(...points: Point[]) {
  if (points.length < 3) {
    return true;
  }
  const { x: a, y: b } = points[0];
  const { x: m, y: n } = points[1];
  return points.every(({ x, y }) => {
    // The points are collinear if the area of the triangle they form
    // is equal to (or in this case, close to) zero.
    return Math.abs(a * (n - y) + m * (y - b) + x * (b - n)) < 1e-9;
  });
}

/** Applies a list of transformation matrices to the specified point. */
export function transformPoint(point: Point, ...matrices: Matrix[]) {
  return matrices.reduce((p: Point, m: Matrix) => {
    // [a c e]   [p.x]
    // [b d f] * [p.y]
    // [0 0 1]   [ 1 ]
    const x = round(m.a * p.x + m.c * p.y + m.e * 1);
    const y = round(m.b * p.x + m.d * p.y + m.f * 1);
    return { x, y };
  }, point);
}

/** Calculates the distance between two points. */
export function distance(p1: Point, p2: Point) {
  return Math.hypot(p1.x - p2.x, p1.y - p2.y);
}

/** Returns true if the two points are equal. */
export function arePointsEqual(p1: Point, p2: Point) {
  return p1 && p2 && distance(p1, p2) < 1e-9;
}

/** Rounds the number to a prespecified precision. */
export function round(n: number) {
  return _.round(n, 9);
}