text:
import logging

import tensorflow as tf
from tensorflow.keras.layers import Layer

from ludwig.modules.attention_modules import FeedForwardAttentionReducer
from ludwig.utils.misc_utils import get_from_registry
from ludwig.utils.tf_utils import sequence_length_3D

logger = logging.getLogger(__name__)

class SequenceReducer(Layer):

    def __init__(self, reduce_mode=None):
        super().__init__()
        # save as private variable for debugging
        self._reduce_mode = reduce_mode

        # use registry to find required reduction function
        self._reduce_obj = get_from_registry(
            reduce_mode,
            reduce_mode_registry
        )()

    def call(self, inputs, training=None, mask=None):
        return self._reduce_obj(inputs, training=training, mask=mask)

class ReduceLast(Layer):

    def call(self, inputs, training=None, mask=None):
        batch_size = tf.shape(inputs)[0]
        sequence_length = sequence_length_3D(inputs)
        # gather the correct outputs from the the RNN outputs (the outputs after sequence_length are all 0s)
        gathered = tf.gather_nd(
            inputs,
            tf.stack(
                [tf.range(batch_size), tf.maximum(sequence_length - 1, 0)],
                axis=1
            )
        )
        return gathered

class ReduceSum(Layer):

    def call(self, inputs, training=None, mask=None):
        return tf.reduce_sum(inputs, axis=1)

class ReduceMean(Layer):

    def call(self, inputs, training=None, mask=None):
        return tf.reduce_mean(inputs, axis=1)

class ReduceMax(Layer):

    def call(self, inputs, training=None, mask=None):
        return tf.reduce_max(inputs, axis=1)

class ReduceConcat(Layer):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.reduce_last = ReduceLast()

    def call(self, inputs, training=None, mask=None):
        if (inputs.shape.as_list()[-2] is None or
                inputs.shape.as_list()[-1] is None):
            # this the case of outputs coming from rnn encoders
            logger.warning('  WARNING: '
                           'The sequence length dimension is undefined '
                           '(probably because of an RNN based encoder), '
                           'so the sequence cannot be reduced '
                           'by concatenation. '
                           'Last will be used instead.')
            return self.reduce_last(inputs)
        else:
            return tf.reshape(
                inputs,
                [-1, inputs.shape[-2] * inputs.shape[-1]]
            )

class ReduceNone(Layer):

    def call(self, inputs, training=None, mask=None):
        return inputs

reduce_mode_registry = {
    'last': ReduceLast,
    'sum': ReduceSum,
    'mean': ReduceMean,
    'avg': ReduceMean,
    'max': ReduceMax,
    'concat': ReduceConcat,
    'attention': FeedForwardAttentionReducer,
    'none': ReduceNone,
    'None': ReduceNone,
    None: ReduceNone
}


text:
package org.carrot2.core;

import static org.carrot2.core.test.assertions.Carrot2CoreAssertions.*;
import static org.fest.assertions.Assertions.assertThat;
import static org.junit.Assert.assertEquals;

import java.util.*;

import org.fest.assertions.Assertions;
import org.junit.Test;

import com.google.common.collect.Lists;

/**
 * Test cases for {@link Cluster}.
 */
public class ClusterTest
{
    @Test
    public void testAllDocumentsEmptyFlat()
    {
        final Cluster flatCluster = new Cluster();
        assertEquals(0, flatCluster.size());
        Assertions.assertThat(flatCluster.getAllDocuments()).isEmpty();
    }

    @Test
    public void testAllDocumentsEmptyHierarchical()
    {
        final Cluster hierarchicalCluster = new Cluster();
        final Cluster subcluster = new Cluster();

        hierarchicalCluster.addSubclusters(subcluster);
        subcluster.addSubclusters(new Cluster());

        assertEquals(0, hierarchicalCluster.size());
        Assertions.assertThat(hierarchicalCluster.getAllDocuments()).isEmpty();
    }

    @Test
    public void testSizeNonEmptyFlat()
    {
        final Cluster flatCluster = new Cluster();
        final List<Document> documents = Lists.newArrayList(new Document(),
            new Document());

        flatCluster.addDocuments(documents);
        assertEquals(2, flatCluster.size());
        assertEquals(documents, flatCluster.getAllDocuments());
    }

    @Test
    public void testSizeNonEmptyHierarchicalWithoutOverlap()
    {
        final Cluster hierarchicalCluster = new Cluster();
        final Cluster subcluster = new Cluster();

        hierarchicalCluster.addSubclusters(subcluster);

        final Document documentA = new Document();
        hierarchicalCluster.addDocuments(documentA);
        final Document documentB = new Document();
        subcluster.addDocuments(documentB);

        final List<Document> expectedAllDocuments = Lists.newArrayList(documentA,
            documentB);

        assertEquals(2, hierarchicalCluster.size());
        assertEquals(expectedAllDocuments, hierarchicalCluster.getAllDocuments());
    }

    @Test
    public void testSizeNonEmptyHierarchicalWithOverlap()
    {
        final Cluster hierarchicalCluster = new Cluster();
        final Cluster subcluster = new Cluster();
        hierarchicalCluster.addSubclusters(subcluster);

        final Document document1 = new Document();

        hierarchicalCluster.addDocuments(document1);
        final Document documentB = new Document();
        hierarchicalCluster.addDocuments(documentB);
        subcluster.addDocuments(document1);
        final Document documentC = new Document();
        subcluster.addDocuments(documentC);

        final List<Document> expectedAllDocuments = Lists.newArrayList(document1,
            documentB, documentC);

        assertEquals(3, hierarchicalCluster.size());
        assertEquals(expectedAllDocuments, hierarchicalCluster.getAllDocuments());
    }

    @Test
    public void testByLabelComparator()
    {
        final Cluster clusterA = new Cluster();
        clusterA.addPhrases("A");

        final Cluster clusterB = new Cluster();
        clusterB.addPhrases("b");

        final Cluster clusterNull = new Cluster();

        checkOrder(Lists.newArrayList(clusterNull, clusterA, clusterB),
            Cluster.BY_SIZE_COMPARATOR);
    }

    @Test
    public void testBySizeComparator()
    {
        final Cluster clusterA = new Cluster();
        clusterA.addDocuments(new Document(), new Document());

        final Cluster clusterB = new Cluster();

        checkOrder(Lists.newArrayList(clusterB, clusterA), Cluster.BY_SIZE_COMPARATOR);
    }

    @Test
    public void testByReversedSizeAndLabelComparator()
    {
        final Cluster clusterA = new Cluster();
        clusterA.addPhrases("A");
        clusterA.addDocuments(new Document(), new Document());

        final Cluster clusterB = new Cluster();
        clusterB.addPhrases("B");
        clusterB.addDocuments(new Document(), new Document());

        final Cluster clusterC = new Cluster();
        clusterC.addPhrases("C");
        clusterC.addDocuments(new Document(), new Document(), new Document());

        checkOrder(Lists.newArrayList(clusterC, clusterA, clusterB),
            Cluster.BY_REVERSED_SIZE_AND_LABEL_COMPARATOR);
    }

    @Test
    public void testByReversedWeightedScoreAndSizeComparatorOnlySize()
    {
        checkOrder(createSizeAndScoreClusters(1, 2, 0), Cluster
            .byReversedWeightedScoreAndSizeComparator(0));
    }

    @Test
    public void testByReversedWeightedScoreAndSizeComparatorOnlyScore()
    {
        checkOrder(createSizeAndScoreClusters(1, 0, 2), Cluster
            .byReversedWeightedScoreAndSizeComparator(1));
    }

    private List<Cluster> createSizeAndScoreClusters(int a, int b, int c)
    {
        Cluster [] clusters = new Cluster [3];
        final Cluster clusterA = new Cluster();
        clusterA.addPhrases("A");
        clusterA.setAttribute(Cluster.SCORE, 1.0);
        clusterA.addDocuments(new Document(), new Document());
        clusters[a] = clusterA;

        final Cluster clusterB = new Cluster();
        clusterB.addPhrases("B");
        clusterB.setAttribute(Cluster.SCORE, 2.0);
        clusterB.addDocuments(new Document(), new Document());
        clusters[b] = clusterB;

        final Cluster clusterC = new Cluster();
        clusterC.addPhrases("C");
        clusterC.setAttribute(Cluster.SCORE, 0.1);
        clusterC.addDocuments(new Document(), new Document(), new Document());
        clusters[c] = clusterC;

        return Arrays.asList(clusters);
    }

    private void checkOrder(List<Cluster> expected, Comparator<Cluster> comparator)
    {
        List<Cluster> toSort = Lists.newArrayList(expected);
        Collections.sort(toSort, comparator);
        Assertions.assertThat(toSort).isEqualTo(expected);
    }

    @Test()
    public void testNoIdentifiers()
    {
        final Cluster d1 = new Cluster();
        final Cluster d2 = new Cluster();
        final Cluster d3 = new Cluster();

        Cluster.assignClusterIds(Lists.newArrayList(d1, d2, d3));
        assertThat(d1.id).isEqualTo(0);
        assertThat(d2.id).isEqualTo(1);
        assertThat(d3.id).isEqualTo(2);
    }

    @Test()
    public void testSubclusterIdentifiers()
    {
        final Cluster d1 = new Cluster();
        final Cluster d2 = new Cluster();
        final Cluster d3 = new Cluster();
        final Cluster d4 = new Cluster();
        d1.addSubclusters(d2);
        d2.addSubclusters(d4);

        Cluster.assignClusterIds(Lists.newArrayList(d1, d3));
        assertThat(d1.id).isEqualTo(0);
        assertThat(d2.id).isEqualTo(1);
        assertThat(d4.id).isEqualTo(2);
        assertThat(d3.id).isEqualTo(3);
    }

    @Test()
    public void testSomeIdentifiers()
    {
        final Cluster d1 = new Cluster();
        d1.id = 2;
        final Cluster d2 = new Cluster();
        final Cluster d3 = new Cluster();
        final Cluster d4 = new Cluster();
        d4.id = 5;
        final Cluster d5 = new Cluster();

        Cluster.assignClusterIds(Lists.newArrayList(d1, d2, d3, d4, d5));
        assertThat(d1.id).isEqualTo(2);
        assertThat(d2.id).isEqualTo(6);
        assertThat(d3.id).isEqualTo(7);
        assertThat(d4.id).isEqualTo(5);
        assertThat(d5.id).isEqualTo(8);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testNonUniqueIdentifiers()
    {
        final Cluster d1 = new Cluster();
        d1.id = 0;
        final Cluster d2 = new Cluster();
        d2.id = 0;

        Cluster.assignClusterIds(Lists.newArrayList(d1, d2));
    }

    @Test
    public void testFindRootCluster()
    {
        final Cluster c1 = new Cluster();
        c1.id = 0;
        final Cluster c2 = new Cluster();
        c2.id = 1;

        Assertions.assertThat(Cluster.find(1, Lists.newArrayList(c1, c2))).isSameAs(c2);
    }

    @Test
    public void testFindSubcluster()
    {
        final Cluster c1 = new Cluster();
        c1.id = 0;
        final Cluster c2 = new Cluster();
        c2.id = 1;
        c1.addSubclusters(c2);
        final Cluster c3 = new Cluster();
        c3.id = 2;
        c2.addSubclusters(c3);

        Assertions.assertThat(Cluster.find(2, Lists.newArrayList(c1))).isSameAs(c3);
    }

    @Test
    public void testFindNotFound()
    {
        final Cluster c1 = new Cluster();
        c1.id = 0;
        final Cluster c2 = new Cluster();
        c2.id = 1;
        c1.addSubclusters(c2);
        final Cluster c3 = new Cluster();
        c3.id = 2;
        c2.addSubclusters(c3);

        Assertions.assertThat(Cluster.find(3, Lists.newArrayList(c1))).isNull();
    }

    @Test
    public void testBuildOtherTopicsNonAssigned()
    {
        final Document d1 = new Document();
        final Document d2 = new Document();
        final Document d3 = new Document();
        final List<Document> allDocuments = Lists.newArrayList(d1, d2, d3);

        final Cluster c1 = new Cluster();
        final Cluster c2 = new Cluster();
        final Cluster c3 = new Cluster();
        c2.addSubclusters(c3);
        final List<Cluster> clusters = Lists.newArrayList(c1, c2);

        final Cluster otherTopics = Cluster.buildOtherTopics(allDocuments, clusters);

        assertThatDocuments(otherTopics.getDocuments()).isEquivalentTo(allDocuments);
    }

    @Test
    public void testBuildOtherTopicsSomeAssigned()
    {
        final Document d1 = new Document();
        final Document d2 = new Document();
        final Document d3 = new Document();
        final List<Document> allDocuments = Lists.newArrayList(d1, d2, d3);

        final Cluster c1 = new Cluster();
        final Cluster c2 = new Cluster();
        final Cluster c3 = new Cluster();
        c2.addSubclusters(c3);
        c3.addDocuments(d2);
        final List<Cluster> clusters = Lists.newArrayList(c1, c2);

        final Cluster otherTopics = Cluster.buildOtherTopics(allDocuments, clusters);

        assertThatDocuments(otherTopics.getDocuments()).isEquivalentTo(Lists.newArrayList(d1, d3));
    }

    @Test
    public void testBuildOtherTopicsAllAssigned()
    {
        final Document d1 = new Document();
        final Document d2 = new Document();
        final Document d3 = new Document();
        final List<Document> allDocuments = Lists.newArrayList(d1, d2, d3);

        final Cluster c1 = new Cluster();
        final Cluster c2 = new Cluster();
        final Cluster c3 = new Cluster();
        c2.addSubclusters(c3);
        c3.addDocuments(d2);
        c1.addDocuments(d1);
        c2.addDocuments(d3);
        final List<Cluster> clusters = Lists.newArrayList(c1, c2);

        final Cluster otherTopics = Cluster.buildOtherTopics(allDocuments, clusters);

        assertThatDocuments(otherTopics.getDocuments()).isEquivalentTo(
            Lists.<Document> newArrayList());
    }
}

redpajama_set_name: RedPajamaGithub


text:
package kantan.mongodb
package query

sealed abstract class Sort extends Product with Serializable {
  def asc(field: String): Sort           = Sort.Compound(List(Sort.Ascending(field), this))
  def desc(field: String): Sort          = Sort.Compound(List(Sort.Descending(field), this))
  def metaTextScore(field: String): Sort = Sort.Compound(List(Sort.MetaTextScore(field), this))
}

object Sort {
  final case class Ascending(field: String)     extends Sort
  final case class Descending(field: String)    extends Sort
  final case class MetaTextScore(field: String) extends Sort
  final case class Compound(sorts: List[Sort]) extends Sort {
    override def asc(field: String)           = copy(sorts = Ascending(field) :: sorts)
    override def desc(field: String)          = copy(sorts = Descending(field) :: sorts)
    override def metaTextScore(field: String) = copy(sorts = MetaTextScore(field) :: sorts)
  }

  implicit val sortDocumentEncoder: BsonDocumentEncoder[Sort] = BsonDocumentEncoder.from {
    case Ascending(field)     ⇒ BsonDocument(Map(field → BsonInt(1)))
    case Descending(field)    ⇒ BsonDocument(Map(field → BsonInt(-1)))
    case MetaTextScore(field) ⇒ BsonDocument(Map(field → BsonDocument(Map("$meta" → BsonString("textScore")))))
    case Compound(sorts) ⇒
      BsonDocument(sorts.foldLeft(Map.empty[String, BsonValue]) { (m, s) ⇒
        m ++ BsonDocumentEncoder[Sort].encode(s).value
      })
  }
}


text:
module Data.Comparaptor (SafeEq(..), SafeOrd(..)) where

import Data.Comparaptor.Eq (SafeEq(..))
import Data.Comparaptor.Ord (SafeOrd(..))


text:
// Implementation is in its own file so that we can enable compiler optimizations for these functions only.

#include <Algorithms/Hasher.h>

namespace Passenger {

void
JenkinsHash::update(const char *data, unsigned int size) {
	const char *end = data + size;

	while (data < end) {
		hash += *data;
		hash += (hash << 10);
		hash ^= (hash >> 6);
		data++;
	}
}

boost::uint32_t
JenkinsHash::finalize() {
	hash += (hash << 3);
	hash ^= (hash >> 11);
	hash += (hash << 15);
	return hash;
}

} // namespace Passenger


text:
Barkskin

**Source** [_barkskin_](spells/barkskin#_barkskin)

The target also gains DR/magic equal to the double the enhancement bonus the spell provides to the target's natural armor bonus.

**Augmented (6th)** : If you expend two uses of mythic power, the spell grants DR/epic rather than DR/magic.


text:
using Newtonsoft.Json;
using System;
using System.Security.Claims;

namespace IdentityServer3.Dapper.Serialization
{
    public class ClaimConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return typeof(Claim) == objectType;
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var source = serializer.Deserialize<ClaimLite>(reader);
            var target = new Claim(source.Type, source.Value);
            return target;
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            Claim source = (Claim)value;

            var target = new ClaimLite
            {
                Type = source.Type,
                Value = source.Value
            };
            serializer.Serialize(writer, target);
        }
    }
}


text:
create class xoo ( id int auto_increment(2147483646,1) , title varchar(100));

insert into xoo(title) values ('aaa');
insert into xoo(title) values ('bbb');
insert into xoo(title) values ('ccc');

select * from xoo order by 1;

drop class xoo;


text:
namespace EmployeeManager.Views
{
    public partial class SectionPage
    {
        public SectionPage()
        {
            InitializeComponent();
        }
    }
}


text:
/* -------------------------------------------------------------------------- */
/* Copyright 2002-2011, OpenNebula Project Leads (OpenNebula.org)             */
/*                                                                            */
/* 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.                                             */
/* -------------------------------------------------------------------------- */

#ifndef POOL_SQL_H_
#define POOL_SQL_H_

#include <map>
#include <string>
#include <queue>

#include "SqlDB.h"
#include "PoolObjectSQL.h"
#include "Log.h"
#include "Hook.h"

using namespace std;

/**
 * PoolSQL class. Provides a base class to implement persistent generic pools.
 * The PoolSQL provides a synchronization mechanism (mutex) to operate in
 * multithreaded applications. Any modification or access function to the pool
 * SHOULD block the mutex.
 */
class PoolSQL: public Callbackable, public Hookable
{
public:

    /**
     * Initializes the oid counter. This function sets lastOID to
     * the last used Object identifier by querying the corresponding database
     * table. This function SHOULD be called before any pool related function.
     *   @param _db a pointer to the database
     *   @param table the name of the table supporting the pool (to set the oid
     *   counter). If null the OID counter is not updated.
     */
    PoolSQL(SqlDB * _db, const char * table);

    virtual ~PoolSQL();

    /**
     *  Allocates a new object, writting it in the pool database. No memory is
     *  allocated for the object.
     *   @param objsql an initialized ObjectSQL
     *   @return the oid assigned to the object or -1 in case of failure
     */
    virtual int allocate(
        PoolObjectSQL   *objsql,
        string&          error_str);

    /**
     *  Gets an object from the pool (if needed the object is loaded from the
     *  database).
     *   @param oid the object unique identifier
     *   @param lock locks the object if true
     *
     *   @return a pointer to the object, 0 in case of failure
     */
    virtual PoolObjectSQL * get(
        int     oid,
        bool    lock);

    /**
     *  Finds a set objects that satisfies a given condition
     *   @param oids a vector with the oids of the objects.
     *   @param the name of the DB table.
     *   @param where condition in SQL format.
     *
     *   @return 0 on success
     */
    virtual int search(
        vector<int>&    oids,
        const char *    table,
        const string&   where);

    /**
     *  Updates the object's data in the data base. The object mutex SHOULD be
     *  locked.
     *    @param objsql a pointer to the object
     *
     *    @return 0 on success.
     */
    virtual int update(
        PoolObjectSQL * objsql)
    {
        int rc;

        rc = objsql->update(db);

        if ( rc == 0 )
        {
            do_hooks(objsql, Hook::UPDATE);
        }

        return rc;
    };

    /**
     *  Drops the object's data in the data base. The object mutex SHOULD be
     *  locked.
     *    @param objsql a pointer to the object
     *    @return 0 on success.
     */
    virtual int drop(
        PoolObjectSQL * objsql)
    {
       return objsql->drop(db);
    };

    /**
     *  Removes all the elements from the pool
     */
    void clean();

    /**
     *  Dumps the pool in XML format. A filter can be also added to the
     *  query
     *  @param oss the output stream to dump the pool contents
     *  @param where filter for the objects, defaults to all
     *
     *  @return 0 on success
     */
    virtual int dump(ostringstream& oss, const string& where) = 0;

protected:

    /**
     *  Pointer to the database.
     */
    SqlDB * db;

private:

    pthread_mutex_t             mutex;

    /**
     *  Max size for the pool, to control the memory footprint of the pool. This
     *  number MUST be greater than the max. number of objects that are
     *  accessed simultaneously.
     */
    static const unsigned int   MAX_POOL_SIZE;

    /**
     *  Last object ID assigned to an object. It must be initialized by the
     *  target pool.
     */
    int                         lastOID;

    /**
     *  The pool is implemented with a Map of SQL object pointers, using the
     *  OID as key.
     */
    map<int,PoolObjectSQL *>    pool;

    /**
     *  Factory method, must return an ObjectSQL pointer to an allocated pool
     *  specific object.
     */
    virtual PoolObjectSQL * create() = 0;

    /**
     *  OID queue to implement a FIFO-like replacement policy for the pool
     *  cache.
     */
    queue<int>                  oid_queue;

    /**
     *  Function to lock the pool
     */
    void lock()
    {
        pthread_mutex_lock(&mutex);
    };

    /**
     *  Function to unlock the pool
     */
    void unlock()
    {
        pthread_mutex_unlock(&mutex);
    };

    /**
     *  FIFO-like replacement policy function. Before removing an object (pop)
     *  from  the cache its lock is checked. The object is removed only if
     *  the associated mutex IS NOT blocked. Otherwise the oid is sent to the
     *  back of the queue.
     */
    void replace();

    /**
     *  Callback to set the lastOID (PoolSQL::PoolSQL)
     */
    int  init_cb(void *nil, int num, char **values, char **names);

    /**
     *  Callback to store the IDs of pool objects (PoolSQL::search)
     */
    int  search_cb(void *_oids, int num, char **values, char **names);
};

#endif /*POOL_SQL_H_*/


text:
// Copyright 2017 PingCAP, Inc.
//
// 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,
// See the License for the specific language governing permissions and
// limitations under the License.

package stmtctx

import (
	"math"
	"sort"
	"strconv"
	"sync"
	"time"

	"github.com/pingcap/parser"
	"github.com/pingcap/parser/model"
	"github.com/pingcap/parser/mysql"
	"github.com/pingcap/tidb/util/execdetails"
	"github.com/pingcap/tidb/util/memory"
	"go.uber.org/zap"
)

const (
	// WarnLevelError represents level "Error" for 'SHOW WARNINGS' syntax.
	WarnLevelError = "Error"
	// WarnLevelWarning represents level "Warning" for 'SHOW WARNINGS' syntax.
	WarnLevelWarning = "Warning"
	// WarnLevelNote represents level "Note" for 'SHOW WARNINGS' syntax.
	WarnLevelNote = "Note"
)

// SQLWarn relates a sql warning and it's level.
type SQLWarn struct {
	Level string
	Err   error
}

// StatementContext contains variables for a statement.
// It should be reset before executing a statement.
type StatementContext struct {
	// Set the following variables before execution

	// IsDDLJobInQueue is used to mark whether the DDL job is put into the queue.
	// If IsDDLJobInQueue is true, it means the DDL job is in the queue of storage, and it can be handled by the DDL worker.
	IsDDLJobInQueue        bool
	InInsertStmt           bool
	InUpdateStmt           bool
	InDeleteStmt           bool
	InSelectStmt           bool
	InLoadDataStmt         bool
	InExplainStmt          bool
	IgnoreTruncate         bool
	IgnoreZeroInDate       bool
	DupKeyAsWarning        bool
	BadNullAsWarning       bool
	DividedByZeroAsWarning bool
	TruncateAsWarning      bool
	OverflowAsWarning      bool
	InShowWarning          bool
	UseCache               bool
	PadCharToFullLength    bool
	BatchCheck             bool
	InNullRejectCheck      bool
	AllowInvalidDate       bool
	// CastStrToIntStrict is used to control the way we cast float format string to int.
	// If ConvertStrToIntStrict is false, we convert it to a valid float string first,
	// then cast the float string to int string. Otherwise, we cast string to integer
	// prefix in a strict way, only extract 0-9 and (+ or - in first bit).
	CastStrToIntStrict bool

	// StartTime is the query start time.
	StartTime time.Time
	// DurationParse is the duration of pasing SQL string to AST.
	DurationParse time.Duration
	// DurationCompile is the duration of compiling AST to execution plan.
	DurationCompile time.Duration

	// mu struct holds variables that change during execution.
	mu struct {
		sync.Mutex

		affectedRows uint64
		foundRows    uint64

		/*
			following variables are ported from 'COPY_INFO' struct of MySQL server source,
			they are used to count rows for INSERT/REPLACE/UPDATE queries:
			  If a row is inserted then the copied variable is incremented.
			  If a row is updated by the INSERT ... ON DUPLICATE KEY UPDATE and the
			     new data differs from the old one then the copied and the updated
			     variables are incremented.
			  The touched variable is incremented if a row was touched by the update part
			     of the INSERT ... ON DUPLICATE KEY UPDATE no matter whether the row
			     was actually changed or not.

			see https://github.com/mysql/mysql-server/blob/d2029238d6d9f648077664e4cdd611e231a6dc14/sql/sql_data_change.h#L60 for more details
		*/
		records uint64
		updated uint64
		copied  uint64
		touched uint64

		message           string
		warnings          []SQLWarn
		errorCount        uint16
		histogramsNotLoad bool
		execDetails       execdetails.ExecDetails
		allExecDetails    []*execdetails.ExecDetails
	}
	// PrevAffectedRows is the affected-rows value(DDL is 0, DML is the number of affected rows).
	PrevAffectedRows int64
	// PrevLastInsertID is the last insert ID of previous statement.
	PrevLastInsertID uint64
	// LastInsertID is the auto-generated ID in the current statement.
	LastInsertID uint64
	// InsertID is the given insert ID of an auto_increment column.
	InsertID uint64

	// Copied from SessionVars.TimeZone.
	TimeZone         *time.Location
	Priority         mysql.PriorityEnum
	NotFillCache     bool
	MemTracker       *memory.Tracker
	RuntimeStatsColl *execdetails.RuntimeStatsColl
	TableIDs         []int64
	IndexIDs         []int64
	nowTs            time.Time // use this variable for now/current_timestamp calculation/cache for one stmt
	stmtTimeCached   bool
	StmtType         string
	OriginalSQL      string
	digestMemo       struct {
		sync.Once
		normalized string
		digest     string
	}
	Tables []TableEntry
}

// GetNowTsCached getter for nowTs, if not set get now time and cache it
func (sc *StatementContext) GetNowTsCached() time.Time {
	if !sc.stmtTimeCached {
		now := time.Now()
		sc.nowTs = now
		sc.stmtTimeCached = true
	}
	return sc.nowTs
}

// ResetNowTs resetter for nowTs, clear cached time flag
func (sc *StatementContext) ResetNowTs() {
	sc.stmtTimeCached = false
}

// SQLDigest gets normalized and digest for provided sql.
// it will cache result after first calling.
func (sc *StatementContext) SQLDigest() (normalized, sqlDigest string) {
	sc.digestMemo.Do(func() {
		sc.digestMemo.normalized, sc.digestMemo.digest = parser.NormalizeDigest(sc.OriginalSQL)
	})
	return sc.digestMemo.normalized, sc.digestMemo.digest
}

// TableEntry presents table in db.
type TableEntry struct {
	DB    string
	Table string
}

// AddAffectedRows adds affected rows.
func (sc *StatementContext) AddAffectedRows(rows uint64) {
	sc.mu.Lock()
	sc.mu.affectedRows += rows
	sc.mu.Unlock()
}

// AffectedRows gets affected rows.
func (sc *StatementContext) AffectedRows() uint64 {
	sc.mu.Lock()
	rows := sc.mu.affectedRows
	sc.mu.Unlock()
	return rows
}

// FoundRows gets found rows.
func (sc *StatementContext) FoundRows() uint64 {
	sc.mu.Lock()
	rows := sc.mu.foundRows
	sc.mu.Unlock()
	return rows
}

// AddFoundRows adds found rows.
func (sc *StatementContext) AddFoundRows(rows uint64) {
	sc.mu.Lock()
	sc.mu.foundRows += rows
	sc.mu.Unlock()
}

// RecordRows is used to generate info message
func (sc *StatementContext) RecordRows() uint64 {
	sc.mu.Lock()
	rows := sc.mu.records
	sc.mu.Unlock()
	return rows
}

// AddRecordRows adds record rows.
func (sc *StatementContext) AddRecordRows(rows uint64) {
	sc.mu.Lock()
	sc.mu.records += rows
	sc.mu.Unlock()
}

// UpdatedRows is used to generate info message
func (sc *StatementContext) UpdatedRows() uint64 {
	sc.mu.Lock()
	rows := sc.mu.updated
	sc.mu.Unlock()
	return rows
}

// AddUpdatedRows adds updated rows.
func (sc *StatementContext) AddUpdatedRows(rows uint64) {
	sc.mu.Lock()
	sc.mu.updated += rows
	sc.mu.Unlock()
}

// CopiedRows is used to generate info message
func (sc *StatementContext) CopiedRows() uint64 {
	sc.mu.Lock()
	rows := sc.mu.copied
	sc.mu.Unlock()
	return rows
}

// AddCopiedRows adds copied rows.
func (sc *StatementContext) AddCopiedRows(rows uint64) {
	sc.mu.Lock()
	sc.mu.copied += rows
	sc.mu.Unlock()
}

// TouchedRows is used to generate info message
func (sc *StatementContext) TouchedRows() uint64 {
	sc.mu.Lock()
	rows := sc.mu.touched
	sc.mu.Unlock()
	return rows
}

// AddTouchedRows adds touched rows.
func (sc *StatementContext) AddTouchedRows(rows uint64) {
	sc.mu.Lock()
	sc.mu.touched += rows
	sc.mu.Unlock()
}

// GetMessage returns the extra message of the last executed command, if there is no message, it returns empty string
func (sc *StatementContext) GetMessage() string {
	sc.mu.Lock()
	msg := sc.mu.message
	sc.mu.Unlock()
	return msg
}

// SetMessage sets the info message generated by some commands
func (sc *StatementContext) SetMessage(msg string) {
	sc.mu.Lock()
	sc.mu.message = msg
	sc.mu.Unlock()
}

// GetWarnings gets warnings.
func (sc *StatementContext) GetWarnings() []SQLWarn {
	sc.mu.Lock()
	warns := make([]SQLWarn, len(sc.mu.warnings))
	copy(warns, sc.mu.warnings)
	sc.mu.Unlock()
	return warns
}

// WarningCount gets warning count.
func (sc *StatementContext) WarningCount() uint16 {
	if sc.InShowWarning {
		return 0
	}
	sc.mu.Lock()
	wc := uint16(len(sc.mu.warnings))
	sc.mu.Unlock()
	return wc
}

const zero = "0"

// NumErrorWarnings gets warning and error count.
func (sc *StatementContext) NumErrorWarnings() (ec, wc string) {
	var (
		ecNum uint16
		wcNum int
	)
	sc.mu.Lock()
	ecNum = sc.mu.errorCount
	wcNum = len(sc.mu.warnings)
	sc.mu.Unlock()

	if ecNum == 0 {
		ec = zero
	} else {
		ec = strconv.Itoa(int(ecNum))
	}

	if wcNum == 0 {
		wc = zero
	} else {
		wc = strconv.Itoa(wcNum)
	}
	return
}

// SetWarnings sets warnings.
func (sc *StatementContext) SetWarnings(warns []SQLWarn) {
	sc.mu.Lock()
	sc.mu.warnings = warns
	for _, w := range warns {
		if w.Level == WarnLevelError {
			sc.mu.errorCount++
		}
	}
	sc.mu.Unlock()
}

// AppendWarning appends a warning with level 'Warning'.
func (sc *StatementContext) AppendWarning(warn error) {
	sc.mu.Lock()
	if len(sc.mu.warnings) < math.MaxUint16 {
		sc.mu.warnings = append(sc.mu.warnings, SQLWarn{WarnLevelWarning, warn})
	}
	sc.mu.Unlock()
}

// AppendNote appends a warning with level 'Note'.
func (sc *StatementContext) AppendNote(warn error) {
	sc.mu.Lock()
	if len(sc.mu.warnings) < math.MaxUint16 {
		sc.mu.warnings = append(sc.mu.warnings, SQLWarn{WarnLevelNote, warn})
	}
	sc.mu.Unlock()
}

// AppendError appends a warning with level 'Error'.
func (sc *StatementContext) AppendError(warn error) {
	sc.mu.Lock()
	if len(sc.mu.warnings) < math.MaxUint16 {
		sc.mu.warnings = append(sc.mu.warnings, SQLWarn{WarnLevelError, warn})
		sc.mu.errorCount++
	}
	sc.mu.Unlock()
}

// SetHistogramsNotLoad sets histogramsNotLoad.
func (sc *StatementContext) SetHistogramsNotLoad() {
	sc.mu.Lock()
	sc.mu.histogramsNotLoad = true
	sc.mu.Unlock()
}

// HandleTruncate ignores or returns the error based on the StatementContext state.
func (sc *StatementContext) HandleTruncate(err error) error {
	// TODO: At present we have not checked whether the error can be ignored or treated as warning.
	// We will do that later, and then append WarnDataTruncated instead of the error itself.
	if err == nil {
		return nil
	}
	if sc.IgnoreTruncate {
		return nil
	}
	if sc.TruncateAsWarning {
		sc.AppendWarning(err)
		return nil
	}
	return err
}

// HandleOverflow treats ErrOverflow as warnings or returns the error based on the StmtCtx.OverflowAsWarning state.
func (sc *StatementContext) HandleOverflow(err error, warnErr error) error {
	if err == nil {
		return nil
	}

	if sc.OverflowAsWarning {
		sc.AppendWarning(warnErr)
		return nil
	}
	return err
}

// ResetForRetry resets the changed states during execution.
func (sc *StatementContext) ResetForRetry() {
	sc.mu.Lock()
	sc.mu.affectedRows = 0
	sc.mu.foundRows = 0
	sc.mu.records = 0
	sc.mu.updated = 0
	sc.mu.copied = 0
	sc.mu.touched = 0
	sc.mu.message = ""
	sc.mu.errorCount = 0
	sc.mu.warnings = nil
	sc.mu.execDetails = execdetails.ExecDetails{}
	sc.mu.allExecDetails = make([]*execdetails.ExecDetails, 0, 4)
	sc.mu.Unlock()
	sc.TableIDs = sc.TableIDs[:0]
	sc.IndexIDs = sc.IndexIDs[:0]
	sc.StartTime = time.Now()
	sc.DurationCompile = time.Duration(0)
	sc.DurationParse = time.Duration(0)
}

// MergeExecDetails merges a single region execution details into self, used to print
// the information in slow query log.
func (sc *StatementContext) MergeExecDetails(details *execdetails.ExecDetails, commitDetails *execdetails.CommitDetails) {
	sc.mu.Lock()
	if details != nil {
		sc.mu.execDetails.ProcessTime += details.ProcessTime
		sc.mu.execDetails.WaitTime += details.WaitTime
		sc.mu.execDetails.BackoffTime += details.BackoffTime
		sc.mu.execDetails.RequestCount++
		sc.mu.execDetails.TotalKeys += details.TotalKeys
		sc.mu.execDetails.ProcessedKeys += details.ProcessedKeys
		sc.mu.allExecDetails = append(sc.mu.allExecDetails, details)
	}
	sc.mu.execDetails.CommitDetail = commitDetails
	sc.mu.Unlock()
}

// GetExecDetails gets the execution details for the statement.
func (sc *StatementContext) GetExecDetails() execdetails.ExecDetails {
	var details execdetails.ExecDetails
	sc.mu.Lock()
	details = sc.mu.execDetails
	sc.mu.Unlock()
	return details
}

// ShouldClipToZero indicates whether values less than 0 should be clipped to 0 for unsigned integer types.
// This is the case for `insert`, `update`, `alter table` and `load data infile` statements, when not in strict SQL mode.
// see https://dev.mysql.com/doc/refman/5.7/en/out-of-range-and-overflow.html
func (sc *StatementContext) ShouldClipToZero() bool {
	// TODO: Currently altering column of integer to unsigned integer is not supported.
	// If it is supported one day, that case should be added here.
	return sc.InInsertStmt || sc.InLoadDataStmt
}

// ShouldIgnoreOverflowError indicates whether we should ignore the error when type conversion overflows,
// so we can leave it for further processing like clipping values less than 0 to 0 for unsigned integer types.
func (sc *StatementContext) ShouldIgnoreOverflowError() bool {
	if (sc.InInsertStmt && sc.TruncateAsWarning) || sc.InLoadDataStmt {
		return true
	}
	return false
}

// PushDownFlags converts StatementContext to tipb.SelectRequest.Flags.
func (sc *StatementContext) PushDownFlags() uint64 {
	var flags uint64
	if sc.InInsertStmt {
		flags |= model.FlagInInsertStmt
	} else if sc.InUpdateStmt || sc.InDeleteStmt {
		flags |= model.FlagInUpdateOrDeleteStmt
	} else if sc.InSelectStmt {
		flags |= model.FlagInSelectStmt
	}
	if sc.IgnoreTruncate {
		flags |= model.FlagIgnoreTruncate
	} else if sc.TruncateAsWarning {
		flags |= model.FlagTruncateAsWarning
	}
	if sc.OverflowAsWarning {
		flags |= model.FlagOverflowAsWarning
	}
	if sc.IgnoreZeroInDate {
		flags |= model.FlagIgnoreZeroInDate
	}
	if sc.DividedByZeroAsWarning {
		flags |= model.FlagDividedByZeroAsWarning
	}
	if sc.PadCharToFullLength {
		flags |= model.FlagPadCharToFullLength
	}
	if sc.InLoadDataStmt {
		flags |= model.FlagInLoadDataStmt
	}
	return flags
}

// CopTasksDetails returns some useful information of cop-tasks during execution.
func (sc *StatementContext) CopTasksDetails() *CopTasksDetails {
	sc.mu.Lock()
	defer sc.mu.Unlock()
	n := len(sc.mu.allExecDetails)
	d := &CopTasksDetails{NumCopTasks: n}
	if n == 0 {
		return d
	}
	d.AvgProcessTime = sc.mu.execDetails.ProcessTime / time.Duration(n)
	d.AvgWaitTime = sc.mu.execDetails.WaitTime / time.Duration(n)

	sort.Slice(sc.mu.allExecDetails, func(i, j int) bool {
		return sc.mu.allExecDetails[i].ProcessTime < sc.mu.allExecDetails[j].ProcessTime
	})
	d.P90ProcessTime = sc.mu.allExecDetails[n*9/10].ProcessTime
	d.MaxProcessTime = sc.mu.allExecDetails[n-1].ProcessTime
	d.MaxProcessAddress = sc.mu.allExecDetails[n-1].CalleeAddress

	sort.Slice(sc.mu.allExecDetails, func(i, j int) bool {
		return sc.mu.allExecDetails[i].WaitTime < sc.mu.allExecDetails[j].WaitTime
	})
	d.P90WaitTime = sc.mu.allExecDetails[n*9/10].WaitTime
	d.MaxWaitTime = sc.mu.allExecDetails[n-1].WaitTime
	d.MaxWaitAddress = sc.mu.allExecDetails[n-1].CalleeAddress
	return d
}

//CopTasksDetails collects some useful information of cop-tasks during execution.
type CopTasksDetails struct {
	NumCopTasks int

	AvgProcessTime    time.Duration
	P90ProcessTime    time.Duration
	MaxProcessAddress string
	MaxProcessTime    time.Duration

	AvgWaitTime    time.Duration
	P90WaitTime    time.Duration
	MaxWaitAddress string
	MaxWaitTime    time.Duration
}

// ToZapFields wraps the CopTasksDetails as zap.Fileds.
func (d *CopTasksDetails) ToZapFields() (fields []zap.Field) {
	if d.NumCopTasks == 0 {
		return
	}
	fields = make([]zap.Field, 0, 10)
	fields = append(fields, zap.Int("num_cop_tasks", d.NumCopTasks))
	fields = append(fields, zap.String("process_avg_time", strconv.FormatFloat(d.AvgProcessTime.Seconds(), 'f', -1, 64)+"s"))
	fields = append(fields, zap.String("process_p90_time", strconv.FormatFloat(d.P90ProcessTime.Seconds(), 'f', -1, 64)+"s"))
	fields = append(fields, zap.String("process_max_time", strconv.FormatFloat(d.MaxProcessTime.Seconds(), 'f', -1, 64)+"s"))
	fields = append(fields, zap.String("process_max_addr", d.MaxProcessAddress))
	fields = append(fields, zap.String("wait_avg_time", strconv.FormatFloat(d.AvgWaitTime.Seconds(), 'f', -1, 64)+"s"))
	fields = append(fields, zap.String("wait_p90_time", strconv.FormatFloat(d.P90WaitTime.Seconds(), 'f', -1, 64)+"s"))
	fields = append(fields, zap.String("wait_max_time", strconv.FormatFloat(d.MaxWaitTime.Seconds(), 'f', -1, 64)+"s"))
	fields = append(fields, zap.String("wait_max_addr", d.MaxWaitAddress))
	return fields
}


text:
require 'helper'

module Arel
  module Visitors
    describe 'the mssql visitor' do
      before do
        @visitor = MSSQL.new Table.engine.connection
        @table = Arel::Table.new "users"
      end

      def compile node
        @visitor.accept(node, Collectors::SQLString.new).value
      end

      it 'should not modify query if no offset or limit' do
        stmt = Nodes::SelectStatement.new
        sql = compile(stmt)
        sql.must_be_like "SELECT"
      end

      it 'should go over table PK if no .order() or .group()' do
        stmt = Nodes::SelectStatement.new
        stmt.cores.first.from = @table
        stmt.limit = Nodes::Limit.new(10)
        sql = compile(stmt)
        sql.must_be_like "SELECT _t.* FROM (SELECT ROW_NUMBER() OVER (ORDER BY \"users\".\"id\") as _row_num FROM \"users\") as _t WHERE _row_num BETWEEN 1 AND 10"
      end

      it 'caches the PK lookup for order' do
        connection = MiniTest::Mock.new
        connection.expect(:primary_key, ["id"], ["users"])

        # We don't care how many times these methods are called
        def connection.quote_table_name(*); ""; end
        def connection.quote_column_name(*); ""; end

        @visitor = MSSQL.new(connection)
        stmt = Nodes::SelectStatement.new
        stmt.cores.first.from = @table
        stmt.limit = Nodes::Limit.new(10)

        compile(stmt)
        compile(stmt)

        connection.verify
      end

      it 'should use TOP for limited deletes' do
        stmt = Nodes::DeleteStatement.new
        stmt.relation = @table
        stmt.limit = Nodes::Limit.new(10)
        sql = compile(stmt)

        sql.must_be_like "DELETE TOP (10) FROM \"users\""
      end

      it 'should go over query ORDER BY if .order()' do
        stmt = Nodes::SelectStatement.new
        stmt.limit = Nodes::Limit.new(10)
        stmt.orders << Nodes::SqlLiteral.new('order_by')
        sql = compile(stmt)
        sql.must_be_like "SELECT _t.* FROM (SELECT ROW_NUMBER() OVER (ORDER BY order_by) as _row_num) as _t WHERE _row_num BETWEEN 1 AND 10"
      end

      it 'should go over query GROUP BY if no .order() and there is .group()' do
        stmt = Nodes::SelectStatement.new
        stmt.cores.first.groups << Nodes::SqlLiteral.new('group_by')
        stmt.limit = Nodes::Limit.new(10)
        sql = compile(stmt)
        sql.must_be_like "SELECT _t.* FROM (SELECT ROW_NUMBER() OVER (ORDER BY group_by) as _row_num GROUP BY group_by) as _t WHERE _row_num BETWEEN 1 AND 10"
      end

      it 'should use BETWEEN if both .limit() and .offset' do
        stmt = Nodes::SelectStatement.new
        stmt.limit = Nodes::Limit.new(10)
        stmt.offset = Nodes::Offset.new(20)
        sql = compile(stmt)
        sql.must_be_like "SELECT _t.* FROM (SELECT ROW_NUMBER() OVER (ORDER BY ) as _row_num) as _t WHERE _row_num BETWEEN 21 AND 30"
      end

      it 'should use >= if only .offset' do
        stmt = Nodes::SelectStatement.new
        stmt.offset = Nodes::Offset.new(20)
        sql = compile(stmt)
        sql.must_be_like "SELECT _t.* FROM (SELECT ROW_NUMBER() OVER (ORDER BY ) as _row_num) as _t WHERE _row_num >= 21"
      end

      it 'should generate subquery for .count' do
        stmt = Nodes::SelectStatement.new
        stmt.limit = Nodes::Limit.new(10)
        stmt.cores.first.projections << Nodes::Count.new('*')
        sql = compile(stmt)
        sql.must_be_like "SELECT COUNT(1) as count_id FROM (SELECT _t.* FROM (SELECT ROW_NUMBER() OVER (ORDER BY ) as _row_num) as _t WHERE _row_num BETWEEN 1 AND 10) AS subquery"
      end

    end
  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Exor.Core;

namespace Exor.Compiler
{
    public class CompileException<TCodeSource> : ExorLoaderException
        where TCodeSource : ICodeSource
    {
        public IEnumerable<ExorCompilerResults<TCodeSource>> Results { get; private set; }

        public CompileException(IEnumerable<ExorCompilerResults<TCodeSource>> results)
            : base("One or more code sources failed to compile.")
        {
            Results = results;
        }
    }
}


text:
/**
 *  @file exit.h
 *  @brief Abstract class who defines Exit operations
 *  @author Eric Fehr (ricofehr@nextdeploy.io, github: ricofehr)
 */

#ifndef NEXTFLOOR_CORE_EXITPROGRAM_H_
#define NEXTFLOOR_CORE_EXITPROGRAM_H_

namespace nextfloor {

namespace core {

/**
 *  @class Exit
 *  @brief pure interface who defines Exit operations
 */
class Exit {

public:
    virtual ~Exit() = default;

    virtual void ExitOnError() const = 0;
    virtual void ExitOnSuccess() const = 0;
};

}  // namespace core

}  // namespace nextfloor

#endif  // NEXTFLOOR_CORE_EXITPROGRAM_H_


text:
FORK of the repo at

http://angular-dragdrop.github.io/angular-dragdrop/


text:
package com.digreamon.app.deviceinfo;

import java.util.Calendar;
import java.util.HashMap;
import java.util.LinkedHashMap;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity {

	ListView deviceInfoList;

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

		deviceInfoList = (ListView)findViewById(R.id.deviceInfoList);

		deviceInfoList.addHeaderView(
				DeviceInfoAdapter.getHeaderView(this));
		deviceInfoList.setAdapter(
				DeviceInfoAdapter.getDeviceInfoAdapter(this));
	}

	public static class DeviceInfoAdapter extends ArrayAdapter<String> {

		private final static String DEVICE_INFO_NAME_HEAD = "Name";
		private final static String DEVICE_INFO_VALUE_HEAD = "Value";

		public static View getHeaderView(Context context){
			View view = LayoutInflater.from(context).inflate(R.layout.list_header_layout, null);
			TextView name_head = (TextView)view.findViewById(R.id.name_head);
			TextView value_head = (TextView)view.findViewById(R.id.value_head);
			view.setBackgroundColor(Color.LTGRAY);
			name_head.setText(DEVICE_INFO_NAME_HEAD);
			value_head.setText(DEVICE_INFO_VALUE_HEAD);
			return view;
		}

		public static DeviceInfoAdapter getDeviceInfoAdapter(Context context){
			LinkedHashMap<String, Object> table = new LinkedHashMap<String, Object>();

			table.put("CalendarMillis", Calendar.getInstance().getTimeInMillis());
			table.put("BOARD", Build.BOARD);
			table.put("BOOTLOADER", Build.BOOTLOADER);
			table.put("BRAND", Build.BRAND);
			table.put("CPU_ABI", Build.CPU_ABI);
			table.put("CPU_ABI2", Build.CPU_ABI2);
			table.put("DEVICE", Build.DEVICE);
			table.put("DISPLAY", Build.DISPLAY);
			table.put("FINGERPRINT", Build.FINGERPRINT);
			table.put("HARDWARE", Build.HARDWARE);
			table.put("HOST", Build.HOST);
			table.put("ID", Build.ID);
			table.put("MANUFACTURER", Build.MANUFACTURER);
			table.put("MODEL", Build.MODEL);
			table.put("PRODUCT", Build.PRODUCT);
			table.put("SERIAL", Build.SERIAL);
			table.put("TAGS", Build.TAGS);
			table.put("TIME", Build.TIME);
			table.put("TYPE", Build.TYPE);
			table.put("USER", Build.USER);

			table.put("VERSION.CODENAME", Build.VERSION.CODENAME);
			table.put("VERSION.RELEASE", Build.VERSION.RELEASE);

			return new DeviceInfoAdapter(context, table);
		}

		HashMap<String, Object> table;

		private DeviceInfoAdapter(Context context, HashMap<String, Object> table) {
			super(context, R.layout.list_item_layout,
					R.id.title, table.keySet().toArray(new String[]{}));
			this.table = table;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if(convertView==null){
				convertView = LayoutInflater.from(
						getContext()).inflate(R.layout.list_item_layout, null);
			}

			convertView.setBackgroundColor(((position%2==0)?Color.argb(80, 173, 255, 47):Color.argb(80, 50, 205, 50)));

			TextView title = (TextView)convertView.findViewById(R.id.title);
			TextView value = (TextView)convertView.findViewById(R.id.value);

			String key = getItem(position);
			title.setText(key);
			value.setText(String.valueOf(table.get(key)));

			return super.getView(position, convertView, parent);
		}
	}
}


text:
import React from 'react';
// eslint-disable-next-line
import CallingSettingsPanel from 'ringcentral-widgets/components/CallingSettingsPanel';

const props = {};
props.brand = 'test string';
props.currentLocale = 'en-US';
props.callWithOptions = ['test string'];
props.callWith = 'test string';
props.myLocation = 'test string';
props.ringoutPrompt = false;
props.availableNumbers = {};
props.onBackButtonClick = () => null;
props.onSave = () => null;

/**
 * A example of `CallingSettingsPanel`
 */
const CallingSettingsPanelDemo = () => (
  <div style={{
    position: 'relative',
    height: '500px',
    width: '300px',
    border: '1px solid #f3f3f3',
  }}>
    <CallingSettingsPanel
      {...props}
    />
  </div>
);
export default CallingSettingsPanelDemo;


text:
typedef NS_ENUM(NSUInteger, XAxisLabelPosition) {
    XAxisLabelPositionTop = 0,
    XAxisLabelPositionBottom = 1,
    XAxisLabelPositionBothSided = 2,
    XAxisLabelPositionTopInside = 3,
    XAxisLabelPositionBottomInside = 4
};

typedef NS_ENUM(NSUInteger, XAxisLabelSite) {
    XAxisLabelSiteCenter = 0,
    XAxisLabelSiteLeft,
    XAxisLabelSiteRight
};

@class LNChartData;
@interface LNXAxis : LNAxisBase
@property (nonatomic, copy) NSString *dateFormatter;     //X轴时间格式
@property (nonatomic, assign) NSInteger labelCount;
@property (nonatomic, strong) NSMutableArray *values;
@property (nonatomic, assign) XAxisLabelSite labelSite;
@property (nonatomic, assign) XAxisLabelPosition labelPosition;

- (void)setupLineValues:(LNChartData *)data;
- (void)setupKLineValues:(LNChartData *)data;
- (void)setupVolumeValues:(LNChartData *)data;

@end


text:
// Cfg.Net
// An Alternative .NET Configuration Handler
// Copyright 2015-2022 Dale Newman
//
// 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.
using System.Collections.Generic;
using System.Linq;
using Cfg.Net.Contracts;
using Newtonsoft.Json.Linq;

namespace Cfg.Net.Parsers.Json.Net {

    public class JsonNetNode : INode {

        public string Name { get; }
        public List<IAttribute> Attributes { get; }
        public List<INode> SubNodes { get; }

        public JsonNetNode(string name, JObject node) {

            Name = name;
            Attributes = new List<IAttribute>();
            SubNodes = new List<INode>();

            if (node == null)
                return;

            foreach (var pair in node) {
                var key = pair.Key;
                var token = pair.Value;
                switch (token.Type) {
                    case JTokenType.Object:
                        break;
                    case JTokenType.Property:
                        break;
                    case JTokenType.None:
                        break;
                    case JTokenType.Null:
                        break;
                    case JTokenType.Array:
                        var subNode = new JsonNetNode(key, null);
                        foreach (var item in (JArray)token) {
                            subNode.SubNodes.Add(new JsonNetNode("add", (JObject)item));
                        }
                        SubNodes.Add(subNode);
                        break;
                    default:  // a value
                        Attributes.Add(new NodeAttribute() { Name = key, Value = token });
                        break;
                }
            }

        }

        public bool TryAttribute(string name, out IAttribute attr) {
            if (Attributes.Any()) {
                if (Attributes.Exists(a => a.Name == name)) {
                    attr = Attributes.First(a => a.Name == name);
                    return true;
                }
            }
            attr = null;
            return false;
        }
    }
}


text:
r"""Bijector Ops.

An API for reversible (bijective) transformations of random variables.

## Background

Differentiable, bijective transformations of continuous random variables alter
the calculations made in the cumulative/probability distribution functions and
sample function.  This module provides a standard interface for making these
manipulations.

For more details and examples, see the `Bijector` docstring.

To apply a `Bijector`, use `distributions.TransformedDistribution`.

## Bijectors

@@Bijector
@@Identity
@@Inline
@@Exp
@@ScaleAndShift

"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import abc
import contextlib
import six

from tensorflow.contrib.distributions.python.ops.shape import _DistributionShape
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import linalg_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import nn_ops

@six.add_metaclass(abc.ABCMeta)
class Bijector(object):
  """Interface for transforming a `Distribution` via `TransformedDistribution`.

  A `Bijector` implements a bijective, differentiable function by transforming
  an input `Tensor`. The output `Tensor` shape is constrained by the input
  `sample`, `batch`, and `event` shape.  A `Bijector` is characterized by three
  operations:

  1. Forward Evaluation

     Useful for turning one random outcome into another random outcome from a
     different distribution.

  2. Inverse Evaluation

     Useful for "reversing" a transformation to compute one probability in
     terms of another.

  3. (log o det o Jacobian o inverse)(x)

     "The log of the determinant of the matrix of all first-order partial
     derivatives of the inverse function."
     Useful for inverting a transformation to compute one probability in terms
     of another.  Geometrically, the det(Jacobian) is the volume of the
     transformation and is used to scale the probability.

  By convention, transformations of random variables are named in terms of the
  forward transformation. The forward transformation creates samples, the
  inverse is useful for computing probabilities.

  Example Use:

    - Basic properties:

    ```python
    x = ... # A tensor.
    # Evaluate forward transformation.
    fwd_x = my_bijector.forward(x)
    x == my_bijector.inverse(fwd_x)
    x != my_bijector.forward(fwd_x)  # Not equal because g(x) != g(g(x)).
    ```

    - Computing a log-likelihood:

    ```python
    def transformed_log_pdf(bijector, log_pdf, x):
      return (bijector.inverse_log_det_jacobian(x) +
              log_pdf(bijector.inverse(x)))
    ```

    - Transforming a random outcome:

    ```python
    def transformed_sample(bijector, x):
      return bijector.forward(x)
    ```

  Example transformations:

    - "Exponential"

      ```
      Y = g(X) = exp(X)
      X ~ Normal(0, 1)  # Univariate.
      ```

      Implies:

      ```
        g^{-1}(Y) = log(Y)
        |Jacobian(g^{-1})(y)| = 1 / y
        Y ~ LogNormal(0, 1), i.e.,
        prob(Y=y) = |Jacobian(g^{-1})(y)| * prob(X=g^{-1}(y))
                  = (1 / y) Normal(log(y); 0, 1)
      ```

    - "ScaleAndShift"

      ```
      Y = g(X) = sqrtSigma * X + mu
      X ~ MultivariateNormal(0, I_d)
      ```

      Implies:

      ```
        g^{-1}(Y) = inv(sqrtSigma) * (Y - mu)
        |Jacobian(g^{-1})(y)| = det(inv(sqrtSigma))
        Y ~ MultivariateNormal(mu, sqrtSigma) , i.e.,
        prob(Y=y) = |Jacobian(g^{-1})(y)| * prob(X=g^{-1}(y))
                  = det(sqrtSigma)^(-d) *
                    MultivariateNormal(inv(sqrtSigma) * (y - mu); 0, I_d)
      ```

  Example of why a `Bijector` needs to understand sample, batch, event
  partitioning:

  - Consider the `Exp` `Bijector` applied to a `Tensor` which has sample, batch,
    and event (S, B, E) shape semantics.  Suppose
    the `Tensor`'s partitioned-shape is `(S=[4], B=[2], E=[3, 3])`.

    For `Exp`, the shape of the `Tensor` returned by `forward` and `inverse` is
    unchanged, i.e., `[4, 2, 3, 3]`. However the shape returned by
    `inverse_log_det_jacobian` is `[4, 2]` because the Jacobian is a reduction
    over the event dimensions.

  Subclass Requirements:

  - Subclasses are expected to implement `_forward` and one or both of:
      - `_inverse`, `_inverse_log_det_jacobian`,
      - `_inverse_and_inverse_log_det_jacobian`.

  - If computation can be shared among `_inverse` and
    `_inverse_log_det_jacobian` it is preferable to implement
    `_inverse_and_inverse_log_det_jacobian`. This usually reduces
    graph-construction overhead because a `Distribution`'s implementation of
    `log_prob` will need to evaluate both the inverse Jacobian as well as the
    inverse function.

  - If an additional use case needs just `inverse` or just
    `inverse_log_det_jacobian` then he or she may also wish to implement these
    functions to avoid computing the `inverse_log_det_jacobian` or the
    `inverse`, respectively.
  """

  @abc.abstractmethod
  def __init__(self,
               batch_ndims=None,
               event_ndims=None,
               parameters=None,
               is_constant_jacobian=False,
               validate_args=False,
               dtype=None,
               name=None):
    """Constructs Bijector.

    A `Bijector` transforms random variables into new random variables.

    Examples:

    ```python
    # Create the Y = g(X) = X transform which operates on 4-Tensors of vectors.
    identity = Identity(batch_ndims=4, event_ndims=1)

    # Create the Y = g(X) = exp(X) transform which operates on matrices.
    exp = Exp(batch_ndims=0, event_ndims=2)
    ```

    See `Bijector` subclass docstring for more details and specific examples.

    Args:
      batch_ndims: number of dimensions associated with batch coordinates.
      event_ndims: number of dimensions associated with event coordinates.
      parameters: Dictionary of parameters used by this `Bijector`
      is_constant_jacobian: `Boolean` indicating that the Jacobian is not a
        function of the input.
      validate_args: `Boolean`, default `False`.  Whether to validate input with
        asserts. If `validate_args` is `False`, and the inputs are invalid,
        correct behavior is not guaranteed.
      dtype: `tf.dtype` supported by this `Bijector`. `None` means dtype is not
        enforced.
      name: The name to give Ops created by the initializer.
    """
    if batch_ndims is None or event_ndims is None:
      self._shaper = None  # Apparently subclass will create.
    else:
      self._shaper = _DistributionShape(
          batch_ndims=batch_ndims,
          event_ndims=event_ndims,
          validate_args=validate_args)
    self._parameters = parameters or {}
    self._is_constant_jacobian = is_constant_jacobian
    self._validate_args = validate_args
    self._dtype = dtype
    self._name = name or type(self).__name__

  @property
  def shaper(self):
    """Returns shape object used to manage shape constraints."""
    return self._shaper

  @property
  def parameters(self):
    """Returns this `Bijector`'s parameters as a name/value dictionary."""
    return self._parameters

  @property
  def is_constant_jacobian(self):
    """Returns true iff the Jacobian is not a function of x.

    Note: Jacobian is either constant for both forward and inverse or neither.

    Returns:
      `Boolean`.
    """
    return self._is_constant_jacobian

  @property
  def validate_args(self):
    """Returns True if Tensor arguments will be validated."""
    return self._validate_args

  @property
  def dtype(self):
    """dtype of `Tensor`s transformable by this distribution."""
    return self._dtype

  @property
  def name(self):
    """Returns the string name of this `Bijector`."""
    return self._name

  def _forward(self, x):
    raise NotImplementedError("forward is not implemented.")

  def forward(self, x, name="forward"):
    """Returns the forward `Bijector` evaluation, i.e., X = g(Y).

    Args:
      x: `Tensor`. The input to the "forward" evaluation.
      name: The name to give this op.

    Returns:
      `Tensor`.

    Raises:
      TypeError: if `self.dtype` is specified and `x.dtype` is not
        `self.dtype`.
      NotImplementedError: if `_forward` is not implemented.
    """
    with self._name_scope(name, [x]):
      x = ops.convert_to_tensor(x, name="x")
      self._maybe_assert_dtype(x)
      return self._forward(x)

  def _inverse(self, x):
    raise NotImplementedError("inverse is not implemented")

  def inverse(self, x, name="inverse"):
    """Returns the inverse `Bijector` evaluation, i.e., X = g^{-1}(Y).

    Args:
      x: `Tensor`. The input to the "inverse" evaluation.
      name: The name to give this op.

    Returns:
      `Tensor`.

    Raises:
      TypeError: if `self.dtype` is specified and `x.dtype` is not
        `self.dtype`.
      NotImplementedError: if neither `_inverse` nor
        `_inverse_and_inverse_log_det_jacobian` are implemented.
    """
    with self._name_scope(name, [x]):
      x = ops.convert_to_tensor(x, name="x")
      self._maybe_assert_dtype(x)
      try:
        return self._inverse(x)
      except NotImplementedError:
        # Since _inverse was not implemented, try to see if it's implemented
        # by the _inverse_and_inverse_log_det_jacobian member.
        return self._inverse_and_inverse_log_det_jacobian(x)[0]

  def _inverse_log_det_jacobian(self, x):
    raise NotImplementedError("inverse_log_det_jacobian is not implemented")

  def inverse_log_det_jacobian(self, x, name="inverse_log_det_jacobian"):
    """Returns the (log o det o Jacobian o inverse)(x).

    Mathematically, returns: log(det(dY/dX g^{-1}))(Y).

    Note that forward_log_det_jacobian is the negative of this function. (See
    is_constant_jacobian for related proof.)

    Args:
      x: `Tensor`. The input to the "inverse" Jacobian evaluation.
      name: The name to give this op.

    Returns:
      `Tensor`.

    Raises:
      TypeError: if `self.dtype` is specified and `x.dtype` is not
        `self.dtype`.
      NotImplementedError: if neither `_inverse_log_det_jacobian` nor
        `_inverse_and_inverse_log_det_jacobian` are implemented.
    """
    with self._name_scope(name, [x]):
      x = ops.convert_to_tensor(x, name="x")
      self._maybe_assert_dtype(x)
      try:
        return self._inverse_log_det_jacobian(x)
      except NotImplementedError:
        # Since _inverse_log_det_jacobian was not implemented, try to see if
        # it's implemented by the _inverse_and_inverse_log_det_jacobian member.
        return self._inverse_and_inverse_log_det_jacobian(x)[1]

  def _inverse_and_inverse_log_det_jacobian(self, x):
    raise NotImplementedError(
        "inverse_and_inverse_log_det_jacobian is not implemented.")

  def inverse_and_inverse_log_det_jacobian(
      self, x, name="inverse_and_inverse_log_det_jacobian"):
    """Returns both the inverse evaluation and inverse_log_det_jacobian.

    Enables possibly more efficient calculation when both inverse and
    corresponding Jacobian are needed.

    See `inverse()`, `inverse_log_det_jacobian()` for more details.

    Args:
      x: `Tensor`. The input to the "inverse" Jacobian evaluation.
      name: The name to give this op.

    Returns:
      `Tensor`.

    Raises:
      TypeError: if `self.dtype` is specified and `x.dtype` is not
        `self.dtype`.
      NotImplementedError: if neither `_inverse_and_inverse_log_det_jacobian`
        nor {`_inverse`, `_inverse_log_det_jacobian`} are implemented.
    """
    with self._name_scope(name, [x]):
      x = ops.convert_to_tensor(x, name="x")
      self._maybe_assert_dtype(x)
      try:
        return self._inverse_and_inverse_log_det_jacobian(x)
      except NotImplementedError:
        # Since _inverse_and_inverse_log_det_jacobian was not implemented, try
        # to see if we can separately use _inverse and
        # _inverse_log_det_jacobian members.
        return self._inverse(x), self._inverse_log_det_jacobian(x)

  @contextlib.contextmanager
  def _name_scope(self, name=None, values=None):
    """Helper function to standardize op scope."""
    with ops.name_scope(self.name):
      with ops.name_scope(name, values=(
          (values or []) + list(self.parameters.values()))) as scope:
        yield scope

  def _maybe_assert_dtype(self, x):
    """Helper to check dtype when self.dtype is known."""
    if self.dtype is not None and self.dtype.base_dtype != x.dtype.base_dtype:
      raise TypeError("Input had dtype %s but expected %s." %
                      (self.dtype, x.dtype))

class Identity(Bijector):
  """Bijector which computes Y = g(X) = X.

    Example Use:

    ```python
    # Create the Y=g(X)=X transform which is intended for Tensors with 1 batch
    # ndim and 1 event ndim (i.e., vector of vectors).
    identity = Identity(batch_ndims=1, event_ndims=1)
    x = [[1., 2],
         [3, 4]]
    x == identity.forward(x) == identity.inverse(x)
    ```

  """

  def __init__(self, validate_args=False, name="Identity"):
    super(Identity, self).__init__(
        batch_ndims=0,
        event_ndims=0,
        is_constant_jacobian=True,
        validate_args=validate_args,
        name=name)
    self._is_constant_jacobian = True

  def _forward(self, x):
    return x

  def _inverse(self, x):
    return x

  def _inverse_log_det_jacobian(self, x):
    return constant_op.constant(0., dtype=x.dtype)

class Inline(Bijector):
  # pylint: disable=line-too-long
  """Bijector constructed from callables implementing forward, inverse, and inverse_log_det_jacobian.

  Example Use:

  ```python
  exp = Inline(
    forward_fn=tf.exp,
    inverse_fn=tf.log,
    inverse_log_det_jacobian_fn=(
      lambda y: -tf.reduce_sum(tf.log(y), reduction_indices=-1)),
    name="Exp")
  ```

  The above example is equivalent to the `Bijector` `Exp(event_ndims=1)`.
  """
  # pylint: enable=line-too-long

  def __init__(self, forward_fn, inverse_fn, inverse_log_det_jacobian_fn,
               is_constant_jacobian=False, name="Inline"):
    """Creates a `Bijector` from callables.

    Args:
      forward_fn: Python callable implementing the forward transformation.
      inverse_fn: Python callable implementing the inverse transformation.
      inverse_log_det_jacobian_fn: Python callable implementing the
        inverse_log_det_jacobian transformation.
      is_constant_jacobian: `Boolean` indicating that the Jacobian is constant
        for all input arguments.
      name: `String`, name given to ops managed by this object.
    """
    super(Inline, self).__init__(
        batch_ndims=0,
        event_ndims=0,
        is_constant_jacobian=is_constant_jacobian,
        validate_args=False,
        name=name)
    self._forward_fn = forward_fn
    self._inverse_fn = inverse_fn
    self._inverse_log_det_jacobian_fn = inverse_log_det_jacobian_fn

  def _forward(self, x):
    return self._forward_fn(x)

  def _inverse(self, y):
    return self._inverse_fn(y)

  def _inverse_log_det_jacobian(self, y):
    return self._inverse_log_det_jacobian_fn(y)

class Exp(Bijector):
  """Bijector which computes Y = g(X) = exp(X).

    Example Use:

    ```python
    # Create the Y=g(X)=exp(X) transform which works only on Tensors with 1
    # batch ndim and 2 event ndims (i.e., vector of matrices).
    exp = Exp(batch_ndims=1, event_ndims=2)
    x = [[[1., 2],
           [3, 4]],
          [[5, 6],
           [7, 8]]]
    exp(x) == exp.forward(x)
    log(x) == exp.inverse(x)
    ```

    Note: the exp(.) is applied element-wise but the Jacobian is a reduction
    over the event space.
  """

  def __init__(self,
               event_ndims=0,
               validate_args=False,
               name="Exp"):
    super(Exp, self).__init__(
        batch_ndims=0,
        event_ndims=event_ndims,
        validate_args=validate_args,
        name=name)

  def _forward(self, x):
    return math_ops.exp(x)

  def _inverse(self, x):
    return math_ops.log(x)

  def _inverse_log_det_jacobian(self, x):
    if self.shaper is None:
      raise ValueError("Jacobian cannot be computed with unknown event_ndims")
    _, _, event_dims = self.shaper.get_dims(x)
    return -math_ops.reduce_sum(math_ops.log(x), reduction_indices=event_dims)

  def _inverse_and_inverse_log_det_jacobian(self, x):
    if self.shaper is None:
      raise ValueError("Jacobian cannot be computed with unknown event_ndims")
    y = math_ops.log(x)
    _, _, event_dims = self.shaper.get_dims(x)
    return y, -math_ops.reduce_sum(y, reduction_indices=event_dims)

class ScaleAndShift(Bijector):
  """Bijector which computes Y = g(X; loc, scale) = scale * X + loc.

  Example Use:

  ```python
  # No batch, scalar.
  mu = 0     # shape=[]
  sigma = 1  # shape=[]
  b = ScaleAndShift(loc=mu, scale=sigma)
  # b.shaper.batch_ndims == 0
  # b.shaper.event_ndims == 0

  # One batch, scalar.
  mu = ...    # shape=[b], b>0
  sigma = ... # shape=[b], b>0
  b = ScaleAndShift(loc=mu, scale=sigma)
  # b.shaper.batch_ndims == 1
  # b.shaper.event_ndims == 0

  # No batch, multivariate.
  mu = ...    # shape=[d],    d>0
  sigma = ... # shape=[d, d], d>0
  b = ScaleAndShift(loc=mu, scale=sigma, event_ndims=1)
  # b.shaper.batch_ndims == 0
  # b.shaper.event_ndims == 1

  # (B1*B2*...*Bb)-batch, multivariate.
  mu = ...    # shape=[B1,...,Bb, d],    b>0, d>0
  sigma = ... # shape=[B1,...,Bb, d, d], b>0, d>0
  b = ScaleAndShift(loc=mu, scale=sigma, event_ndims=1)
  # b.shaper.batch_ndims == b
  # b.shaper.event_ndims == 1

  # Mu is broadcast:
  mu = 1
  sigma = [I, I]  # I is a 3x3 identity matrix.
  b = ScaleAndShift(loc=mu, scale=sigma, event_ndims=1)
  x = numpy.ones(S + sigma.shape)
  b.forward(x) # == x + 1
  ```

  """

  def __init__(self,
               loc,
               scale,
               event_ndims=0,
               validate_args=False,
               name="ScaleAndShift"):
    self._parameters = {}
    self._name = name
    with self._name_scope("init", values=[loc, scale, event_ndims]):
      self._loc = ops.convert_to_tensor(loc, name="loc")
      self._scale = ops.convert_to_tensor(scale, name="scale")
      event_ndims = ops.convert_to_tensor(event_ndims, name="event_ndims")
      if self.loc.dtype.base_dtype != self.scale.dtype.base_dtype:
        raise TypeError("%s.dtype=%s does not match %s.dtype=%s" %
                        (self.loc.name, self.loc.dtype, self.scale.name,
                         self.scale.dtype))
      if event_ndims.dtype.base_dtype != dtypes.int32.base_dtype:
        raise TypeError("%s.dtype=%s does not match %s" %
                        (event_ndims.name, event_ndims.dtype, dtypes.int32))
      self._scale, batch_ndims = self._process_scale(self.scale, event_ndims)
      super(ScaleAndShift, self).__init__(
          batch_ndims=batch_ndims,
          event_ndims=event_ndims,
          parameters={"loc": self.loc, "scale": self.scale},
          is_constant_jacobian=True,
          validate_args=validate_args,
          name=name)

  def _process_scale(self, scale, event_ndims):
    """Helper to __init__ which gets scale in batch-ready form.

    This function expands dimensions of `scale` according to the following
    table:
                     event_ndims
    scale.ndims   0            1
              0  [1]+S+[1,1]   "silent error"
              1  [ ]+S+[1,1]   "silent error"
              2  [ ]+S+[1,1]   [1]+S+[ ]
              3  [ ]+S+[1,1]   [ ]+S+[ ]
            ...  (same)        (same)

    The idea is that we want to convert `scale` into something which can always
    work for, say, the left-hand argument of `batch_matmul`.

    Args:
      scale: `Tensor`.
      event_ndims: `Tensor` (0D, `int32`).

    Returns:
      scale: `Tensor` with dims expanded according to [above] table.
      batch_ndims: `Tensor` (0D, `int32`).  The ndims of the `batch` portion.
    """
    ndims = array_ops.rank(scale)
    left = math_ops.select(
        math_ops.reduce_any([
            math_ops.reduce_all([
                math_ops.equal(ndims, 0),
                math_ops.equal(event_ndims, 0)
            ]),
            math_ops.reduce_all([
                math_ops.equal(ndims, 2),
                math_ops.equal(event_ndims, 1)
            ])]), 1, 0)
    right = math_ops.select(math_ops.equal(event_ndims, 0), 2, 0)
    pad = array_ops.concat(0, (
        array_ops.ones([left], dtype=dtypes.int32),
        array_ops.shape(scale),
        array_ops.ones([right], dtype=dtypes.int32)))
    scale = array_ops.reshape(scale, pad)
    batch_ndims = ndims - 2 + right
    return scale, batch_ndims

  @property
  def loc(self):
    return self._loc

  @property
  def scale(self):
    return self._scale

  def _forward(self, x):
    x, sample_shape = self.shaper.make_batch_of_event_sample_matrices(x)
    x = math_ops.batch_matmul(self.scale, x)
    x = self.shaper.undo_make_batch_of_event_sample_matrices(x, sample_shape)
    x += self.loc
    return x

  def _inverse(self, x):
    x -= self.loc
    x, sample_shape = self.shaper.make_batch_of_event_sample_matrices(x)
    x = linalg_ops.matrix_triangular_solve(self.scale, x)
    x = self.shaper.undo_make_batch_of_event_sample_matrices(x, sample_shape)
    return x

  def _inverse_log_det_jacobian(self, x):  # pylint: disable=unused-argument
    return -math_ops.reduce_sum(
        math_ops.log(array_ops.matrix_diag_part(self.scale)),
        reduction_indices=[-1])

class Softplus(Bijector):
  """Bijector which computes `Y = g(X) = Log[1 + exp(X)]`.

  The softplus `Bijector` has the following two useful properties:

  * The domain is the positive real numbers
  * `softplus(x) approx x`, for large `x`, so it does not overflow as easily as
    the `Exp` `Bijector`.

    Example Use:

    ```python
    # Create the Y=g(X)=softplus(X) transform which works only on Tensors with 1
    # batch ndim and 2 event ndims (i.e., vector of matrices).
    softplus = Softplus(batch_ndims=1, event_ndims=2)
    x = [[[1., 2],
           [3, 4]],
          [[5, 6],
           [7, 8]]]
    log(1 + exp(x)) == softplus.forward(x)
    log(exp(x) - 1) == softplus.inverse(x)
    ```

    Note: log(.) and exp(.) are applied element-wise but the Jacobian is a
    reduction over the event space.
  """

  def __init__(self,
               event_ndims=0,
               validate_args=False,
               name="Softplus"):
    super(Softplus, self).__init__(
        batch_ndims=0,
        event_ndims=event_ndims,
        validate_args=validate_args,
        name=name)

  def _forward(self, x):
    return nn_ops.softplus(x)

  def _inverse(self, x):
    # The most stable inverse of softplus is not the most direct one.
    # y = softplus(x) = Log[1 + exp{x}], (which means y > 0).
    # ==> exp{y} = 1 + exp{x}
    # ==> x = Log[exp{y} - 1]
    #       = Log[(exp{y} - 1) / exp{y}] + Log[exp{y}]
    #       = Log[(1 - exp{-y}) / 1] + Log[exp{y}]
    #       = Log[1 - exp{-y}] + y
    # Recalling y > 0, you see that this is more stable than Log[exp{y} - 1].
    return x + math_ops.log(1. - math_ops.exp(-x))

  def _inverse_log_det_jacobian(self, x):
    # Stable inverse log det jacobian.
    # Y = Log[1 + exp{X}] ==> X = Log[exp{Y} - 1]
    # ==> dX/dY = exp{Y} / (exp{Y} - 1)
    #           = 1 / (1 - exp{-Y}),
    # which is the most stable for Y > 0.
    if self.shaper is None:
      raise ValueError("Jacobian cannot be computed with unknown event_ndims")
    _, _, event_dims = self.shaper.get_dims(x)
    return -math_ops.reduce_sum(
        math_ops.log(1. - math_ops.exp(-x)), reduction_indices=event_dims)

  def _inverse_and_inverse_log_det_jacobian(self, x):
    if self.shaper is None:
      raise ValueError("Jacobian cannot be computed with unknown event_ndims")
    _, _, event_dims = self.shaper.get_dims(x)
    log_one_minus_exp_neg = math_ops.log(1. - math_ops.exp(-x))
    y = x + log_one_minus_exp_neg
    ildj = -math_ops.reduce_sum(
        log_one_minus_exp_neg, reduction_indices=event_dims)
    return y, ildj


text:
exports.server = require('./dist/server');

// This exposes the bare browserchannel implementation.
//exports.goog = require('./dist/node-browserchannel.js');

var BCSocket = require('./dist/node-bcsocket.js');
exports.BCSocket = BCSocket.BCSocket;
exports.setDefaultLocation = BCSocket.setDefaultLocation;


text:
<?php

namespace CompanyBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class CompanyBundle extends Bundle
{
}


text:
package com.eaw1805.www.shared.stores.map;

import com.eaw1805.data.HibernateUtil;
import com.eaw1805.data.constants.RegionConstants;
import com.eaw1805.data.constants.StyleConstants;
import com.eaw1805.www.client.widgets.MapLine;
import com.eaw1805.www.shared.stores.GameStore;
import com.eaw1805.www.shared.stores.support.MapConstants;
import org.vaadin.gwtgraphics.client.Group;

public class MapGridGroup extends Group implements MapConstants,
        RegionConstants, StyleConstants {

    private final int regionId;

    private final int scenarioId;

    private final int[] regionSizeX, regionSizeY;

    public MapGridGroup(final int regionId) {
        this.regionId = regionId;
        scenarioId = GameStore.getInstance().getScenarioId();
        switch (scenarioId) {
            case HibernateUtil.DB_FREE:
                regionSizeX = RegionConstants.REGION_1804_SIZE_X;
                regionSizeY = RegionConstants.REGION_1804_SIZE_Y;
                break;

            case HibernateUtil.DB_S3:
                regionSizeX = RegionConstants.REGION_1808_SIZE_X;
                regionSizeY = RegionConstants.REGION_1808_SIZE_Y;
                break;

            case HibernateUtil.DB_S1:
            case HibernateUtil.DB_S2:
            default:
                regionSizeX = RegionConstants.REGION_1805_SIZE_X;
                regionSizeY = RegionConstants.REGION_1805_SIZE_Y;
                break;
        }

        this.clear();
        for (int i = 0; i < regionSizeX[regionId - 1]; i++) {
            final MapLine gridLine = new MapLine(MapStore.getInstance().getPointY(i) - 1,
                    0,
                    MapStore.getInstance().getPointY(i) + 1,
                    MapStore.getInstance().getPointY(regionSizeY[regionId - 1]));
            gridLine.setStrokeColor(COLOR_BLACK);
            this.add(gridLine);
        }
        for (int i = 0; i < regionSizeY[regionId - 1]; i++) {
            final MapLine gridLine = new MapLine(0,
                    MapStore.getInstance().getPointY(i) - 1,
                    MapStore.getInstance().getPointY(regionSizeX[regionId - 1]),
                    MapStore.getInstance().getPointY(i) + 1);
            gridLine.setStrokeColor(COLOR_BLACK);
            this.add(gridLine);
        }
    }
}


text:
package uk.ac.ebi.arrayexpress.lucene;

import java.io.IOException;
import java.util.Stack;

import org.apache.lucene.analysis.TokenFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.TermAttribute;
import org.apache.lucene.util.AttributeSource;

public class SynonymFilter extends TokenFilter {
	public static final String TOKEN_TYPE_SYNONYM = "SYNONYM";
	private Stack synonymStack;
	private SynonymEngine engine;
	private TermAttribute termAttr;
	private AttributeSource save;

	public SynonymFilter(TokenStream in, SynonymEngine engine) {
		super(in);
		synonymStack = new Stack(); // #1
		termAttr = (TermAttribute) addAttribute(TermAttribute.class);
		save = in.cloneAttributes();
		this.engine = engine;
	}

	public boolean incrementToken() throws IOException {
		if (synonymStack.size() > 0) { // #2
			State syn = (State) synonymStack.pop(); // #2
			restoreState(syn); // #2
			return true;
		}
		if (!input.incrementToken()) // #3
			return false;
		addAliasesToStack(); // #4
		return true; // #5
	}

	private void addAliasesToStack() throws IOException {
		String[] synonyms = engine.getSynonyms(termAttr.term()); // #6
		if (synonyms == null)
			return;
		State current = captureState();
		for (int i = 0; i < synonyms.length; i++) { // #7
			save.restoreState(current);
			AnalyzerUtils.setTerm(save, synonyms[i]); // #7

			AnalyzerUtils.setType(save, TOKEN_TYPE_SYNONYM); // #7
			AnalyzerUtils.setPositionIncrement(save, 0); // #8
			synonymStack.push(save.captureState()); // #7
		}
	}
}


text:
import { TestBed } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { AppModule } from './app.module';

describe('AppComponent', () => {
  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [AppComponent],
      imports: [AppModule],
    }).compileComponents();
  });

  it('should create the app', () => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.componentInstance;
    expect(app).toBeTruthy();
  });
});


text:
namespace blink {

namespace {

class ScopedScrollbarPainter {
 public:
  ScopedScrollbarPainter(cc::PaintCanvas& canvas, float device_scale_factor)
      : canvas_(canvas) {
    builder_.Context().SetDeviceScaleFactor(device_scale_factor);
  }
  ~ScopedScrollbarPainter() { canvas_.drawPicture(builder_.EndRecording()); }

  GraphicsContext& Context() { return builder_.Context(); }

 private:
  cc::PaintCanvas& canvas_;
  PaintRecordBuilder builder_;
};

}  // namespace

ScrollbarLayerDelegate::ScrollbarLayerDelegate(blink::Scrollbar& scrollbar,
                                               float device_scale_factor)
    : scrollbar_(&scrollbar), device_scale_factor_(device_scale_factor) {
  // Custom scrollbars are either non-composited or use cc::PictureLayers
  // which don't need ScrollbarLayerDelegate.
  DCHECK(!scrollbar.IsCustomScrollbar());
}

ScrollbarLayerDelegate::~ScrollbarLayerDelegate() = default;

bool ScrollbarLayerDelegate::IsSame(const cc::Scrollbar& other) const {
  return scrollbar_.Get() ==
         static_cast<const ScrollbarLayerDelegate&>(other).scrollbar_.Get();
}

cc::ScrollbarOrientation ScrollbarLayerDelegate::Orientation() const {
  if (scrollbar_->Orientation() == kHorizontalScrollbar)
    return cc::HORIZONTAL;
  return cc::VERTICAL;
}

bool ScrollbarLayerDelegate::IsLeftSideVerticalScrollbar() const {
  return scrollbar_->IsLeftSideVerticalScrollbar();
}

bool ScrollbarLayerDelegate::HasThumb() const {
  return scrollbar_->GetTheme().HasThumb(*scrollbar_);
}

bool ScrollbarLayerDelegate::IsSolidColor() const {
  return scrollbar_->GetTheme().IsSolidColor();
}

bool ScrollbarLayerDelegate::IsOverlay() const {
  return scrollbar_->IsOverlayScrollbar();
}

gfx::Rect ScrollbarLayerDelegate::ThumbRect() const {
  IntRect track_rect = scrollbar_->GetTheme().ThumbRect(*scrollbar_);
  track_rect.MoveBy(-scrollbar_->Location());
  return track_rect;
}

gfx::Rect ScrollbarLayerDelegate::TrackRect() const {
  IntRect track_rect = scrollbar_->GetTheme().TrackRect(*scrollbar_);
  track_rect.MoveBy(-scrollbar_->Location());
  return track_rect;
}

bool ScrollbarLayerDelegate::SupportsDragSnapBack() const {
  return scrollbar_->GetTheme().SupportsDragSnapBack();
}

gfx::Rect ScrollbarLayerDelegate::BackButtonRect() const {
  IntRect back_button_rect = scrollbar_->GetTheme().BackButtonRect(*scrollbar_);
  if (!back_button_rect.IsEmpty())
    back_button_rect.MoveBy(-scrollbar_->Location());
  return back_button_rect;
}

gfx::Rect ScrollbarLayerDelegate::ForwardButtonRect() const {
  IntRect forward_button_rect =
      scrollbar_->GetTheme().ForwardButtonRect(*scrollbar_);
  if (!forward_button_rect.IsEmpty())
    forward_button_rect.MoveBy(-scrollbar_->Location());
  return forward_button_rect;
}

float ScrollbarLayerDelegate::Opacity() const {
  return scrollbar_->GetTheme().Opacity(*scrollbar_);
}

bool ScrollbarLayerDelegate::NeedsRepaintPart(cc::ScrollbarPart part) const {
  if (part == cc::THUMB)
    return scrollbar_->ThumbNeedsRepaint();
  return scrollbar_->TrackNeedsRepaint();
}

bool ScrollbarLayerDelegate::UsesNinePatchThumbResource() const {
  return scrollbar_->GetTheme().UsesNinePatchThumbResource();
}

gfx::Size ScrollbarLayerDelegate::NinePatchThumbCanvasSize() const {
  DCHECK(scrollbar_->GetTheme().UsesNinePatchThumbResource());
  return static_cast<gfx::Size>(
      scrollbar_->GetTheme().NinePatchThumbCanvasSize(*scrollbar_));
}

gfx::Rect ScrollbarLayerDelegate::NinePatchThumbAperture() const {
  DCHECK(scrollbar_->GetTheme().UsesNinePatchThumbResource());
  return scrollbar_->GetTheme().NinePatchThumbAperture(*scrollbar_);
}

bool ScrollbarLayerDelegate::ShouldPaint() const {
  // TODO(crbug.com/860499): Remove this condition, it should not occur.
  // Layers may exist and be painted for a |scrollbar_| that has had its
  // ScrollableArea detached. This seems weird because if the area is detached
  // the layer should be destroyed but here we are. https://crbug.com/860499.
  if (!scrollbar_->GetScrollableArea())
    return false;
  // When the frame is throttled, the scrollbar will not be painted because
  // the frame has not had its lifecycle updated. Thus the actual value of
  // HasTickmarks can't be known and may change once the frame is unthrottled.
  if (scrollbar_->GetScrollableArea()->IsThrottled())
    return false;
  return true;
}

bool ScrollbarLayerDelegate::HasTickmarks() const {
  return ShouldPaint() && scrollbar_->HasTickmarks();
}

void ScrollbarLayerDelegate::PaintPart(cc::PaintCanvas* canvas,
                                       cc::ScrollbarPart part,
                                       const gfx::Rect& rect) {
  if (!ShouldPaint())
    return;

  auto& theme = scrollbar_->GetTheme();
  ScopedScrollbarPainter painter(*canvas, device_scale_factor_);
  // The canvas coordinate space is relative to the part's origin.
  switch (part) {
    case cc::THUMB:
      theme.PaintThumb(painter.Context(), *scrollbar_, IntRect(rect));
      scrollbar_->ClearThumbNeedsRepaint();
      break;
    case cc::TRACK_BUTTONS_TICKMARKS: {
      DCHECK_EQ(IntSize(rect.size()), scrollbar_->FrameRect().Size());
      IntPoint offset(IntPoint(rect.origin()) -
                      scrollbar_->FrameRect().Location());
      theme.PaintTrackButtonsTickmarks(painter.Context(), *scrollbar_, offset);
      scrollbar_->ClearTrackNeedsRepaint();
      break;
    }
    default:
      NOTREACHED();
  }
}

}  // namespace blink


text:
package telegraf

import (
	"time"

	// TODO remove
	"github.com/influxdata/influxdb/client/v2"
)

// ValueType is an enumeration of metric types that represent a simple value.
type ValueType int

// Possible values for the ValueType enum.
const (
	_ ValueType = iota
	Counter
	Gauge
	Untyped
)

type Metric interface {
	Serialize() []byte
	String() string // convenience function for string(Serialize())
	Copy() Metric
	// Split will attempt to return multiple metrics with the same timestamp
	// whose string representations are no longer than maxSize.
	// Metrics with a single field may exceed the requested size.
	Split(maxSize int) []Metric

	// Tag functions
	HasTag(key string) bool
	AddTag(key, value string)
	RemoveTag(key string)

	// Field functions
	HasField(key string) bool
	AddField(key string, value interface{})
	RemoveField(key string) error

	// Name functions
	SetName(name string)
	SetPrefix(prefix string)
	SetSuffix(suffix string)

	// Getting data structure functions
	Name() string
	Tags() map[string]string
	Fields() map[string]interface{}
	Time() time.Time
	UnixNano() int64
	Type() ValueType
	Len() int // returns the length of the serialized metric, including newline
	HashID() uint64

	// aggregator things:
	SetAggregate(bool)
	IsAggregate() bool

	// Point returns a influxdb client.Point object
	// TODO remove this function
	Point() *client.Point
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycol. Notes (Cincinnati) 5(no. 60): 875 (1919)

#### Original name
Tremella samoensis var. samoensis Lloyd

### Remarks
null


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Threading;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Commanding;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
using Roslyn.Utilities;
using VSCommanding = Microsoft.VisualStudio.Commanding;

namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.Completion
{
    internal partial class Controller
    {
        VSCommanding.CommandState IChainedCommandHandler<BackspaceKeyCommandArgs>.GetCommandState(BackspaceKeyCommandArgs args, System.Func<VSCommanding.CommandState> nextHandler)
        {
            AssertIsForeground();
            return nextHandler();
        }

        void IChainedCommandHandler<BackspaceKeyCommandArgs>.ExecuteCommand(BackspaceKeyCommandArgs args, Action nextHandler, CommandExecutionContext context)
        {
            ExecuteBackspaceOrDelete(args.TextView, nextHandler, isDelete: false);
        }

        private void ExecuteBackspaceOrDelete(ITextView textView, Action nextHandler, bool isDelete)
        {
            AssertIsForeground();

            char? deletedChar;
            var subjectBufferCaretPoint = GetCaretPointInSubjectBuffer();
            var viewBufferCaretPoint = GetCaretPointInViewBuffer();
            if (isDelete)
            {
                deletedChar = viewBufferCaretPoint.Position >= 0 && viewBufferCaretPoint.Position < textView.TextBuffer.CurrentSnapshot.Length
                    ? textView.TextBuffer.CurrentSnapshot[viewBufferCaretPoint.Position]
                    : default;
            }
            else
            {
                // backspace
                deletedChar = viewBufferCaretPoint > 0
                    ? textView.TextBuffer.CurrentSnapshot[viewBufferCaretPoint - 1]
                    : default;
            }

            if (sessionOpt == null)
            {
                // No computation. Disconnect from caret position changes, send the backspace through,
                // and start a computation.
                this.TextView.TextBuffer.PostChanged -= OnTextViewBufferPostChanged;
                this.TextView.Caret.PositionChanged -= OnCaretPositionChanged;
                try
                {
                    nextHandler();
                }
                finally
                {
                    this.TextView.TextBuffer.PostChanged += OnTextViewBufferPostChanged;
                    this.TextView.Caret.PositionChanged += OnCaretPositionChanged;
                }

                var trigger = CompletionTrigger.CreateDeletionTrigger(deletedChar.GetValueOrDefault());
                var completionService = this.GetCompletionService();

                if (completionService != null)
                {
                    this.StartNewModelComputation(completionService, trigger);
                }

                return;
            }
            else
            {
                var textBeforeDeletion = SubjectBuffer.AsTextContainer().CurrentText;
                var documentBeforeDeletion = textBeforeDeletion.GetDocumentWithFrozenPartialSemantics(CancellationToken.None);

                this.TextView.TextBuffer.PostChanged -= OnTextViewBufferPostChanged;
                this.TextView.Caret.PositionChanged -= OnCaretPositionChanged;
                try
                {
                    nextHandler();
                }
                finally
                {
                    this.TextView.TextBuffer.PostChanged += OnTextViewBufferPostChanged;
                    this.TextView.Caret.PositionChanged += OnCaretPositionChanged;
                }

                var model = sessionOpt.Computation.InitialUnfilteredModel;

                // DismissIfLastCharacterDeleted should be applied only when started with Insertion, and then Deleted all characters typed.
                // This confirms with the original VS 2010 behavior.
                if ((model == null && CaretHasLeftDefaultTrackingSpan(subjectBufferCaretPoint, documentBeforeDeletion)) ||
                    (model != null && this.IsCaretOutsideAllItemBounds(model, this.GetCaretPointInViewBuffer())) ||
                    (model != null && model.Trigger.Kind == CompletionTriggerKind.Insertion && model.OriginalList.Rules.DismissIfLastCharacterDeleted && AllFilterTextsEmpty(model, GetCaretPointInViewBuffer())))
                {
                    // If the caret moved out of bounds of our items, then we want to dismiss the list.
                    this.DismissSessionIfActive();
                    return;
                }
                else if (model != null)
                {
                    sessionOpt.FilterModel(CompletionFilterReason.Deletion, filterState: null);
                }
            }
        }

        private bool CaretHasLeftDefaultTrackingSpan(int caretPoint, Document document)
        {
            var completionService = GetCompletionService();
            if (completionService == null)
            {
                // SubjectBuffer no longer even has a workspace mapping
                return true;
            }

            // We haven't finished computing the model, but we may need to dismiss.
            // Get the context span and see if we're outside it.
            var text = document.GetTextSynchronously(CancellationToken.None);
            var contextSpan = completionService.GetDefaultCompletionListSpan(text, caretPoint);
            var newCaretPoint = GetCaretPointInViewBuffer();
            return !contextSpan.IntersectsWith(new TextSpan(newCaretPoint, 0));
        }

        internal bool AllFilterTextsEmpty(Model model, SnapshotPoint caretPoint)
        {
            var textSpanToTextCache = new Dictionary<TextSpan, string>();
            var textSpanToViewSpanCache = new Dictionary<TextSpan, ViewTextSpan>();

            foreach (var item in model.TotalItems)
            {
                if (!IsFilterTextEmpty(model, caretPoint, item, textSpanToTextCache, textSpanToViewSpanCache))
                {
                    return false;
                }
            }

            return true;
        }

        private bool IsFilterTextEmpty(
           Model model,
           SnapshotPoint caretPoint,
           CompletionItem item,
           Dictionary<TextSpan, string> textSpanToText,
           Dictionary<TextSpan, ViewTextSpan> textSpanToViewSpan)
        {
            // Easy first check.  See if the caret point is before the start of the item.
            if (!textSpanToViewSpan.TryGetValue(item.Span, out var filterSpanInViewBuffer))
            {
                filterSpanInViewBuffer = model.GetViewBufferSpan(item.Span);
                textSpanToViewSpan[item.Span] = filterSpanInViewBuffer;
            }

            if (caretPoint < filterSpanInViewBuffer.TextSpan.Start)
            {
                return true;
            }

            var textSnapshot = caretPoint.Snapshot;

            var currentText = model.GetCurrentTextInSnapshot(item.Span, textSnapshot, textSpanToText);

            return currentText.Length == 0;
        }
    }
}