text:
package org.jrebirth.af.core.service.basic;

import static org.jrebirth.af.core.wave.WBuilder.waveType;

import java.io.File;

import javafx.scene.Scene;

import org.jrebirth.af.api.wave.contract.WaveType;
import org.jrebirth.af.core.service.DefaultService;

/**
 * The class StyleSheetTrackerService.
 *
 * @author Sébastien Bordes
 */
public class StyleSheetTrackerService extends DefaultService {

    /** Wave type use to load events. */
    public static final WaveType DO_OPEN_STAGE = waveType("OPEN_STAGE").returnAction("STAGE_OPENED");

    /** Wave type to return events loaded. */
    // public static final WaveType RE_STAGE_OPENED = WaveType.create("STAGE_OPENED");

    /** The class logger. */
    // private static final Logger LOGGER = LoggerFactory.getLogger(StyleSheetTrackerService.class);

    // /**
    // * {@inheritDoc}
    // */
    // @Override
    // public void ready() throws CoreException {
    // super.ready();
    //
    // // registerCallback(DO_OPEN_STAGE, RE_STAGE_OPENED);
    // }

    /**
     * Listen new style sheet path.
     *
     * @param styleSheetPath the style hseet path
     * @param scene the root scene
     */
    public void listen(final String styleSheetPath, final Scene scene) {

        final File file = new File(styleSheetPath);

        file.lastModified();

        // StyleManager.getInstance().reloadStylesheets(scene);

    }

    /**
     * Start the service.
     */
    public void start() {
        // Nothing to do yet

    }

}


text:
import os
import sys

BASE_PATH = os.path.dirname(os.path.abspath(__file__))
BINTREES_PATH = os.path.join(
    BASE_PATH, os.pardir, os.pardir, 'third_party', 'bintrees')
sys.path.insert(0, BINTREES_PATH)

from bintrees import FastRBTree  # pylint: disable=F0401

class ExclusiveRangeDict(object):
  """A class like dict whose key is a range [begin, end) of integers.

  It has an attribute for each range of integers, for example:
  [10, 20) => Attribute(0),
  [20, 40) => Attribute(1),
  [40, 50) => Attribute(2),
  ...

  An instance of this class is accessed only via iter_range(begin, end).
  The instance is accessed as follows:

  1) If the given range [begin, end) is not covered by the instance,
  the range is newly created and iterated.

  2) If the given range [begin, end) exactly covers ranges in the instance,
  the ranges are iterated.
  (See test_set() in tests/range_dict_tests.py.)

  3) If the given range [begin, end) starts at and/or ends at a mid-point of
  an existing range, the existing range is split by the given range, and
  ranges in the given range are iterated.  For example, consider a case that
  [25, 45) is given to an instance of [20, 30), [30, 40), [40, 50).  In this
  case, [20, 30) is split into [20, 25) and [25, 30), and [40, 50) into
  [40, 45) and [45, 50).  Then, [25, 30), [30, 40), [40, 45) are iterated.
  (See test_split() in tests/range_dict_tests.py.)

  4) If the given range [begin, end) includes non-existing ranges in an
  instance, the gaps are filled with new ranges, and all ranges are iterated.
  For example, consider a case that [25, 50) is given to an instance of
  [30, 35) and [40, 45).  In this case, [25, 30), [35, 40) and [45, 50) are
  created in the instance, and then [25, 30), [30, 35), [35, 40), [40, 45)
  and [45, 50) are iterated.
  (See test_fill() in tests/range_dict_tests.py.)
  """
  class RangeAttribute(object):
    def __init__(self):
      pass

    def __str__(self):
      return '<RangeAttribute>'

    def __repr__(self):
      return '<RangeAttribute>'

    def copy(self):  # pylint: disable=R0201
      return ExclusiveRangeDict.RangeAttribute()

  def __init__(self, attr=RangeAttribute):
    self._tree = FastRBTree()
    self._attr = attr

  def iter_range(self, begin=None, end=None):
    if not begin:
      begin = self._tree.min_key()
    if not end:
      end = self._tree.max_item()[1][0]

    # Assume that self._tree has at least one element.
    if self._tree.is_empty():
      self._tree[begin] = (end, self._attr())

    # Create a beginning range (border)
    try:
      bound_begin, bound_value = self._tree.floor_item(begin)
      bound_end = bound_value[0]
      if begin >= bound_end:
        # Create a blank range.
        try:
          new_end, _ = self._tree.succ_item(bound_begin)
        except KeyError:
          new_end = end
        self._tree[begin] = (min(end, new_end), self._attr())
      elif bound_begin < begin and begin < bound_end:
        # Split the existing range.
        new_end = bound_value[0]
        new_value = bound_value[1]
        self._tree[bound_begin] = (begin, new_value.copy())
        self._tree[begin] = (new_end, new_value.copy())
      else:  # bound_begin == begin
        # Do nothing (just saying it clearly since this part is confusing)
        pass
    except KeyError:  # begin is less than the smallest element.
      # Create a blank range.
      # Note that we can assume self._tree has at least one element.
      self._tree[begin] = (min(end, self._tree.min_key()), self._attr())

    # Create an ending range (border)
    try:
      bound_begin, bound_value = self._tree.floor_item(end)
      bound_end = bound_value[0]
      if end > bound_end:
        # Create a blank range.
        new_begin = bound_end
        self._tree[new_begin] = (end, self._attr())
      elif bound_begin < end and end < bound_end:
        # Split the existing range.
        new_end = bound_value[0]
        new_value = bound_value[1]
        self._tree[bound_begin] = (end, new_value.copy())
        self._tree[end] = (new_end, new_value.copy())
      else:  # bound_begin == begin
        # Do nothing (just saying it clearly since this part is confusing)
        pass
    except KeyError:  # end is less than the smallest element.
      # It must not happen.  A blank range [begin,end) has already been created
      # even if [begin,end) is less than the smallest range.
      # Do nothing (just saying it clearly since this part is confusing)
      raise

    missing_ranges = []

    prev_end = None
    for range_begin, range_value in self._tree.itemslice(begin, end):
      range_end = range_value[0]
      # Note that we can assume that we have a range beginning with |begin|
      # and a range ending with |end| (they may be the same range).
      if prev_end and prev_end != range_begin:
        missing_ranges.append((prev_end, range_begin))
      prev_end = range_end

    for missing_begin, missing_end in missing_ranges:
      self._tree[missing_begin] = (missing_end, self._attr())

    for range_begin, range_value in self._tree.itemslice(begin, end):
      yield range_begin, range_value[0], range_value[1]

  def __str__(self):
    return str(self._tree)

redpajama_set_name: RedPajamaGithub


text:
package de.uni_hannover.sra.minimax_simulator.ui.gui.components;

import javafx.scene.control.TextField;

/**
 * The {@code NumberTextField} is a {@link TextField} but only the empty String or a numeric String is allowed.
 *
 * @author Philipp Rohde
 */
public class NumberTextField extends TextField {

    @Override
    public void replaceText(int start, int end, String text) {
        if (validate(text)) {
            super.replaceText(start, end, text);
        }
    }

    @Override
    public void replaceSelection(String text) {
        if (validate(text)) {
            super.replaceSelection(text);
        }
    }

    /**
     * Checks if a {@link String} is empty or numeric.
     *
     * @param text
     *          the String to validate
     * @return
     *          {@code true} if the String is empty or a number, {@code false} otherwise
     */
    private static boolean validate(String text) {
        return "".equals(text) || text.matches("[0-9]");
    }
}


text:
<?php
namespace Ratchet\WebSocket\Encoding;

class ToggleableValidator implements ValidatorInterface {
    /**
     * Toggle if checkEncoding checks the encoding or not
     * @var bool
     */
    public $on;

    /**
     * @var Validator
     */
    private $validator;

    public function __construct($on = true) {
        $this->validator = new Validator;
        $this->on        = (boolean)$on;
    }

    /**
     * {@inheritdoc}
     */
    public function checkEncoding($str, $encoding) {
        if (!(boolean)$this->on) {
            return true;
        }

        return $this->validator->checkEncoding($str, $encoding);
    }
}


text:
package org.efaps.admin.access.user;

import java.util.UUID;

import org.efaps.admin.access.AccessType;
import org.efaps.db.Instance;
import org.efaps.util.cache.CacheLogListener;
import org.efaps.util.cache.InfinispanCache;
import org.infinispan.Cache;
import org.infinispan.query.Search;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * The Class Cache.
 *
 * @author The eFaps Team
 */
public final class AccessCache
{

    /**
     * Name of the Cache for AccessKey.
     */
    public static final String PERMISSIONCACHE = AccessCache.class.getName() + ".PermissionCache";

    /**
     * Name of the Cache for AccessKey.
     */
    public static final String STATUSCACHE = AccessCache.class.getName() + ".StatusCache";

    /**
     * Logging instance used in this class.
     */
    private static final Logger LOG = LoggerFactory.getLogger(AccessCache.class);

    /**
     * Instantiates a new access cache.
     */
    private AccessCache()
    {
    }

    /**
     * Method to initialize the Cache of this CacheObjectInterface.
     */
    public static void initialize()
    {
        if (InfinispanCache.get().exists(AccessCache.PERMISSIONCACHE)) {
            InfinispanCache.get().<UUID, AccessType>getCache(AccessCache.PERMISSIONCACHE).clear();
        } else {
            InfinispanCache.get().<UUID, AccessType>getCache(AccessCache.PERMISSIONCACHE)
                            .addListener(new CacheLogListener(AccessCache.LOG));
        }
        if (InfinispanCache.get().exists(AccessCache.STATUSCACHE)) {
            InfinispanCache.get().<Long, AccessType>getCache(AccessCache.STATUSCACHE).clear();
        } else {
            InfinispanCache.get().<Long, AccessType>getCache(AccessCache.STATUSCACHE)
                            .addListener(new CacheLogListener(AccessCache.LOG));
        }
    }

    /**
     * @return the Cache for AccessKey
     */
    public static Cache<Key, PermissionSet> getPermissionCache()
    {
        return InfinispanCache.get().<Key, PermissionSet>getIgnReCache(AccessCache.PERMISSIONCACHE);
    }

    /**
     * @return the Cache for AccessKey
     */
    public static Cache<String, Long> getStatusCache()
    {
        return InfinispanCache.get().<String, Long>getIgnReCache(AccessCache.STATUSCACHE);
    }

    /**
     * @param _instance Instance the update will be registered for
     */
    public static void registerUpdate(final Instance _instance)
    {
        AccessCache.LOG.debug("Registered Update for: {}", _instance);
        AccessCache.getStatusCache().remove(_instance.getKey());
    }

    /**
     * @param _personId personid the access cache must be clean for
     */
    public static void clean4Person(final long _personId)
    {
        AccessCache.LOG.debug("Cleaning cache for Person: {}", _personId);
        final Cache<Key, PermissionSet> cache = AccessCache.getPermissionCache();
        final var queryFactory = Search.getQueryFactory(cache);
        final var query = queryFactory.<PermissionSet>create("FROM org.efaps.admin.access.user.PermissionSet p "
                        + "WHERE p.personId = " + _personId);
        query.execute().list().forEach(set -> {
            cache.remove(set.getKey());
        });
    }
}


text:
package mesosphere.marathon.event.http

import java.util.concurrent.Executors

import akka.actor.{ ActorRef, ActorSystem, Props }
import akka.pattern.ask
import akka.util.Timeout
import com.google.inject.name.Named
import com.google.inject.{ AbstractModule, Provides, Scopes }
import mesosphere.marathon.ModuleNames.STORE_EVENT_SUBSCRIBERS
import mesosphere.marathon.core.base.Clock
import mesosphere.marathon.event.{ MarathonSubscriptionEvent, Subscribe }
import mesosphere.marathon.state.EntityStore
import org.rogach.scallop.ScallopConf
import org.slf4j.LoggerFactory

import scala.concurrent.ExecutionContext
import scala.concurrent.duration._
import scala.language.postfixOps

trait HttpEventConfiguration extends ScallopConf {

  lazy val httpEventEndpoints = opt[String]("http_endpoints",
    descr = "The URLs of the event endpoints added to the current list of subscribers on startup. " +
      "You can manage this list during runtime by using the /v2/eventSubscriptions API endpoint.",
    required = false,
    noshort = true).map(parseHttpEventEndpoints)

  lazy val httpEventCallbackSlowConsumerTimeout = opt[Long]("http_event_callback_slow_consumer_timeout",
    descr = "A http event callback consumer is considered slow, if the delivery takes longer than this timeout (ms)",
    required = false,
    noshort = true,
    default = Some(10.seconds.toMillis)
  )

  private[this] def parseHttpEventEndpoints(str: String): List[String] =
    str.split(',').map(_.trim).toList

  def slowConsumerTimeout: FiniteDuration = httpEventCallbackSlowConsumerTimeout().millis
}

class HttpEventModule(httpEventConfiguration: HttpEventConfiguration) extends AbstractModule {

  val log = LoggerFactory.getLogger(getClass.getName)

  def configure() {
    bind(classOf[HttpEventActor.HttpEventActorMetrics]).in(Scopes.SINGLETON)
    bind(classOf[HttpCallbackEventSubscriber]).asEagerSingleton()
    bind(classOf[HttpCallbackSubscriptionService]).in(Scopes.SINGLETON)
    bind(classOf[HttpEventConfiguration]).toInstance(httpEventConfiguration)
  }

  @Provides
  @Named(HttpEventModule.StatusUpdateActor)
  def provideStatusUpdateActor(system: ActorSystem,
                               @Named(HttpEventModule.SubscribersKeeperActor) subscribersKeeper: ActorRef,
                               metrics: HttpEventActor.HttpEventActorMetrics,
                               clock: Clock): ActorRef = {
    system.actorOf(Props(new HttpEventActor(httpEventConfiguration, subscribersKeeper, metrics, clock)))
  }

  @Provides
  @Named(HttpEventModule.SubscribersKeeperActor)
  def provideSubscribersKeeperActor(conf: HttpEventConfiguration,
                                    system: ActorSystem,
                                    @Named(STORE_EVENT_SUBSCRIBERS) store: EntityStore[EventSubscribers]): ActorRef = {
    implicit val timeout = HttpEventModule.timeout
    val local_ip = java.net.InetAddress.getLocalHost.getHostAddress

    val actor = system.actorOf(Props(new SubscribersKeeperActor(store)))
    conf.httpEventEndpoints.get foreach { urls =>
      log.info(s"http_endpoints($urls) are specified at startup. Those will be added to subscribers list.")
      urls foreach { url =>
        val f = (actor ? Subscribe(local_ip, url)).mapTo[MarathonSubscriptionEvent]
        f.onFailure {
          case th: Throwable =>
            log.warn(s"Failed to add $url to event subscribers. exception message => ${th.getMessage}")
        }(ExecutionContext.global)
      }
    }

    actor
  }
}

object HttpEventModule {
  final val StatusUpdateActor = "EventsActor"
  final val SubscribersKeeperActor = "SubscriberKeeperActor"

  //TODO(everpeace) this should be configurable option?
  val timeout = Timeout(10 seconds)
}


text:
wipro: Wire Protocol Generator
==============================

`h12.io/wipro` is a Go code generator for Kafka like wire protocol over TCP. It
can generate Go structs as well as their marshaling/unmarshaling methods from
compatible BNF notations.


text:
namespace chimera {
    namespace runtime {
        namespace types {
            void push_vector_library(lua_State* const L, size_t pid_vector);
            int lua_vector_new(lua_State* const L);
        }
    }
}

#endif // LUA_VECTOR_COMMON_H


text:
 package com.indeed.flamdex.utils;

import com.indeed.util.core.sort.Quicksortables;
import com.indeed.flamdex.api.DocIdStream;
import com.indeed.flamdex.api.FlamdexReader;
import com.indeed.flamdex.api.IntTermIterator;
import com.indeed.flamdex.api.StringTermIterator;
import com.indeed.flamdex.writer.FlamdexWriter;
import com.indeed.flamdex.writer.IntFieldWriter;
import com.indeed.flamdex.writer.StringFieldWriter;
import com.indeed.util.core.sort.RadixSort;

import java.io.IOException;

/**
 * @author jsgroth
 */
public class FlamdexSort {
    private static final int MAGIC_SORTING_NUMBER = 50000;

    // this method DOES close the FlamdexWriter upon completion
    public static void sort(FlamdexReader r, FlamdexWriter w, int[] oldDocIdToNewDocId) throws IOException {
        sort(r, w, oldDocIdToNewDocId, r.getIntFields(), r.getStringFields());
    }

    public static void sort(FlamdexReader r, FlamdexWriter w, int[] oldDocIdToNewDocId, Iterable<String> intFields, Iterable<String> stringFields) throws IOException {
        final int[] docIdBuffer = new int[r.getNumDocs()];
        final int[] scratch = new int[r.getNumDocs()];
        final int[] countScratch = new int[65536]; // magic number

        final DocIdStream dis = r.getDocIdStream();

        for (final String intField : intFields) {
            System.out.println("intField:"+intField);
            final IntTermIterator iter = r.getIntTermIterator(intField);
            final IntFieldWriter ifw = w.getIntFieldWriter(intField);
            while (iter.next()) {
                ifw.nextTerm(iter.term());
                dis.reset(iter);
                final int n = dis.fillDocIdBuffer(docIdBuffer);
                for (int i = 0; i < n; ++i) {
                    docIdBuffer[i] = oldDocIdToNewDocId[docIdBuffer[i]];
                }
                if (n >= MAGIC_SORTING_NUMBER) {
                    RadixSort.radixSort(docIdBuffer, n, scratch, countScratch);
                } else {
                    Quicksortables.sort(Quicksortables.getQuicksortableIntArray(docIdBuffer), n);
                }
                for (int i = 0; i < n; ++i) {
                    ifw.nextDoc(docIdBuffer[i]);
                }
            }
            iter.close();
            ifw.close();
        }

        for (final String stringField : stringFields) {
            System.out.println("stringField:"+stringField);
            final StringTermIterator iter = r.getStringTermIterator(stringField);
            final StringFieldWriter sfw = w.getStringFieldWriter(stringField);
            while (iter.next()) {
                sfw.nextTerm(iter.term());
                dis.reset(iter);
                final int n = dis.fillDocIdBuffer(docIdBuffer);
                for (int i = 0; i < n; ++i) {
                    docIdBuffer[i] = oldDocIdToNewDocId[docIdBuffer[i]];
                }
                if (n >= MAGIC_SORTING_NUMBER) {
                    RadixSort.radixSort(docIdBuffer, n, scratch, countScratch);
                } else {
                    Quicksortables.sort(Quicksortables.getQuicksortableIntArray(docIdBuffer), n);
                }
                for (int i = 0; i < n; ++i) {
                    sfw.nextDoc(docIdBuffer[i]);
                }
            }
            iter.close();
            sfw.close();
        }

        dis.close();
        w.close();
    }
}


text:
Full Text Indexes in Marten are built based on [GIN or GiST indexes](/documents/indexing/gin-gist-indexes) utilizing [Postgres built in Text Search functions](https://www.postgresql.org/docs/10/textsearch-controls.html). This enables the possibility to do more sophisticated searching through text fields.

::: warning
To use this feature, you will need to use PostgreSQL version 10.0 or above, as this is the first version that support text search function on jsonb column - this is also the data type that Marten use to store it's data.
:::

## Defining Full Text Index through Store options

Full Text Indexes can be created using the fluent interface of `StoreOptions` like this:

* one index for whole document - all document properties values will be indexed

```cs
var store = DocumentStore.For(_ =>
{
    _.Connection(ConnectionSource.ConnectionString);

    // This creates
    _.Schema.For<User>().FullTextIndex();
});
```
snippet source | anchor

::: tip INFO
If you don't specify language (regConfig) - by default it will be created with 'english' value.
:::

* single property - there is possibility to specify specific property to be indexed

```cs
var store = DocumentStore.For(_ =>
{
    _.Connection(ConnectionSource.ConnectionString);

    // This creates
    _.Schema.For<User>().FullTextIndex(d => d.FirstName);
});
```
snippet source | anchor

* single property with custom settings

```cs
var store = DocumentStore.For(_ =>
{
    _.Connection(ConnectionSource.ConnectionString);

    // This creates
    _.Schema.For<User>().FullTextIndex(
        index =>
        {
            index.Name = "mt_custom_italian_user_fts_idx";
            index.RegConfig = "italian";
        },
        d => d.FirstName);
});
```
snippet source | anchor

* multiple properties

```cs
var store = DocumentStore.For(_ =>
{
    _.Connection(ConnectionSource.ConnectionString);

    // This creates
    _.Schema.For<User>().FullTextIndex(d => d.FirstName, d => d.LastName);
});
```
snippet source | anchor

* multiple properties with custom settings

```cs
var store = DocumentStore.For(_ =>
{
    _.Connection(ConnectionSource.ConnectionString);

    // This creates
    _.Schema.For<User>().FullTextIndex(
        index =>
        {
            index.Name = "mt_custom_italian_user_fts_idx";
            index.RegConfig = "italian";
        },
        d => d.FirstName, d => d.LastName);
});
```
snippet source | anchor

* more than one index for document with different languages (regConfig)

```cs
var store = DocumentStore.For(_ =>
{
    _.Connection(ConnectionSource.ConnectionString);

    // This creates
    _.Schema.For<User>()
        .FullTextIndex(d => d.FirstName) //by default it will use "english"
        .FullTextIndex("italian", d => d.LastName);
});
```
snippet source | anchor

## Defining Full Text  Index through Attribute

Full Text  Indexes can be created using the `[FullTextIndex]` attribute like this:

* one index for whole document - by setting attribute on the class all document properties values will be indexed

```cs
[FullTextIndex]
public class Book
{
    public Guid Id { get; set; }

    public string Title { get; set; }

    public string Author { get; set; }

    public string Information { get; set; }
}
```
snippet source | anchor

* single property

```cs
public class UserProfile
{
    public Guid Id { get; set; }

    [FullTextIndex]
    public string Information { get; set; }
}
```
snippet source | anchor

::: tip INFO
If you don't specify regConfig - by default it will be created with 'english' value.
:::

* single property with custom settings

```cs
public class UserDetails
{
    private const string FullTextIndexName = "mt_custom_user_details_fts_idx";

    public Guid Id { get; set; }

    [FullTextIndex(IndexName = FullTextIndexName, RegConfig = "italian")]
    public string Details { get; set; }
}
```
snippet source | anchor

* multiple properties

```cs
public class Article
{
    public Guid Id { get; set; }

    [FullTextIndex]
    public string Heading { get; set; }

    [FullTextIndex]
    public string Text { get; set; }
}
```
snippet source | anchor

::: tip INFO
To group multiple properties into single index you need to specify the same values in `IndexName` parameters.
:::

* multiple indexes for multiple properties with custom settings

```cs
public class BlogPost
{
    public Guid Id { get; set; }

    public string Category { get; set; }

    [FullTextIndex]
    public string EnglishText { get; set; }

    [FullTextIndex(RegConfig = "italian")]
    public string ItalianText { get; set; }

    [FullTextIndex(RegConfig = "french")]
    public string FrenchText { get; set; }
}
```
snippet source | anchor

## Text Search

Postgres contains built in [Text Search functions](https://www.postgresql.org/docs/10/textsearch-controls.html). They enable the possibility to do more sophisticated searching through text fields. Marten gives possibility to define (full text indexes)(/documents/configuration/full_text) and perform queries on them.
Currently four types of full Text Search functions are supported:

* regular Search (to_tsquery)

```cs
var posts = session.Query<BlogPost>()
    .Where(x => x.Search("somefilter"))
    .ToList();
```
snippet source | anchor

* plain text Search (plainto_tsquery)

```cs
var posts = session.Query<BlogPost>()
    .Where(x => x.PlainTextSearch("somefilter"))
    .ToList();
```
snippet source | anchor

* phrase Search (phraseto_tsquery)

```cs
var posts = session.Query<BlogPost>()
    .Where(x => x.PhraseSearch("somefilter"))
    .ToList();
```
snippet source | anchor

* web-style Search (websearch_to_tsquery, [supported from Postgres 11+](https://www.postgresql.org/docs/11/textsearch-controls.html)

```cs
var posts = session.Query<BlogPost>()
    .Where(x => x.WebStyleSearch("somefilter"))
    .ToList();
```
snippet source | anchor

All types of Text Searches can be combined with other Linq queries

```cs
var posts = session.Query<BlogPost>()
    .Where(x => x.Category == "LifeStyle")
    .Where(x => x.PhraseSearch("somefilter"))
    .ToList();
```
snippet source | anchor

They allow also to specify language (regConfig) of the text search query (by default `english` is being used)

```cs
var posts = session.Query<BlogPost>()
    .Where(x => x.PhraseSearch("somefilter", "italian"))
    .ToList();
```
snippet source | anchor

## Partial text search in a multi-word text (NGram search)

Marten provides the ability to search partial text or words in a string containing multiple words using NGram search. This is quite similar in functionality to [NGrams in Elastic Search](https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-ngram-tokenizer.html). As an example, we can now accurately match `rich com text` within `Communicating Across Contexts (Enriched)`. NGram search uses English by default. NGram search also encompasses and handles unigrams, bigrams and trigrams. This functionality is added in v5.

```cs
var result = await session
    .Query<User>()
    .Where(x => x.UserName.NgramSearch(term))
    .ToListAsync();
```
snippet source | anchor


text:
class AddDeletedAtAndPhoneNumberToDonor < ActiveRecord::Migration[5.0][5.0]
  def change
    add_column :donors, :deleted_at, :datetime
    add_column :donors, :phone_number, :string
  end
end


text:
class ExamplesController < BaseController
  skip_before_filter :authenticate_user_from_token!, :only => [:example_public]
  skip_before_filter :block_unauthenticated_user!, :only => [:example_public]

  def example_public
    render body: 'Public'
  end

  def example_private
    render body: 'Private'
  end
end


text:
<?php

namespace Elcodi\Component\Product\ImageResolver;

use Elcodi\Component\Media\Entity\Interfaces\ImageInterface;
use Elcodi\Component\Product\Entity\Interfaces\PackInterface;
use Elcodi\Component\Product\Entity\Interfaces\PurchasableInterface;
use Elcodi\Component\Product\ImageResolver\Abstracts\AbstractImageResolverWithImageResolver;
use Elcodi\Component\Product\ImageResolver\Interfaces\PurchasableImageResolverInterface;

/**
 * Class PackImageResolver.
 */
class PackImageResolver extends AbstractImageResolverWithImageResolver implements PurchasableImageResolverInterface
{
    /**
     * Get the entity interface.
     *
     * @return string Namespace
     */
    public function getPurchasableNamespace()
    {
        return 'Elcodi\Component\Product\Entity\Interfaces\PackInterface';
    }

    /**
     * Get valid Image.
     *
     * @param PurchasableInterface $purchasable Purchasable
     *
     * @return ImageInterface|false Image resolved
     */
    public function getValidImage(PurchasableInterface $purchasable)
    {
        $namespace = $this->getPurchasableNamespace();
        if (!$purchasable instanceof $namespace) {
            return false;
        }

        /**
         * @var PackInterface $purchasable
         */
        $packImage = $this
            ->imageResolver
            ->resolveImage($purchasable);

        if ($packImage instanceof ImageInterface) {
            return $packImage;
        }

        foreach ($purchasable->getPurchasables() as $purchasable) {
            $purchasableImage = $this->getValidImageByCollection($purchasable);
            if ($purchasableImage instanceof ImageInterface) {
                return $purchasableImage;
            }
        }

        return false;
    }
}


text:
using System;
using System.Collections.Generic;
using ICSharpCode.NRefactory.Semantics;
using System.Linq;
using ICSharpCode.NRefactory.CSharp.Resolver;
using ICSharpCode.NRefactory.CSharp.Analysis;
using System.Threading;
using ICSharpCode.NRefactory.TypeSystem;
using System.Threading.Tasks;

namespace ICSharpCode.NRefactory.CSharp.Refactoring.ExtractMethod
{
	[ContextAction("Extract method", Description = "Creates a new method out of selected text.")]
	public class ExtractMethodAction : ICodeActionProvider
	{
		public IEnumerable<CodeAction> GetActions(RefactoringContext context)
		{
			if (!context.IsSomethingSelected)
				yield break;
			var selected = new List<AstNode>(context.GetSelectedNodes());
			if (selected.Count == 0)
				yield break;

			if (selected.Count == 1 && selected [0] is Expression) {
				var codeAction = CreateFromExpression(context, (Expression)selected [0]);
				if (codeAction == null)
					yield break;
				yield return codeAction;
			}

			foreach (var node in selected) {
				if (!(node is Statement))
					yield break;
			}
			var action = CreateFromStatements (context, new List<Statement> (selected.OfType<Statement> ()));
			if (action != null)
				yield return action;
		}

		CodeAction CreateFromExpression(RefactoringContext context, Expression expression)
		{
			var resolveResult = context.Resolve(expression);
			if (resolveResult.IsError)
				return null;

			return new CodeAction(context.TranslateString("Extract method"), script => {
				string methodName = "NewMethod";
				var method = new MethodDeclaration() {
					ReturnType = context.CreateShortType(resolveResult.Type),
					Name = methodName,
					Body = new BlockStatement() {
						new ReturnStatement(expression.Clone())
					}
				};
				if (!StaticVisitor.UsesNotStaticMember(context, expression))
					method.Modifiers |= Modifiers.Static;
				var task = script.InsertWithCursor(context.TranslateString("Extract method"), Script.InsertPosition.Before, method);

				Action<Task> replaceStatements = delegate {
					var target = new IdentifierExpression(methodName);
					script.Replace(expression, new InvocationExpression(target));
					script.Link(target, method.NameToken);
				};

				if (task.IsCompleted) {
					replaceStatements (null);
				} else {
					task.ContinueWith (replaceStatements, TaskScheduler.FromCurrentSynchronizationContext ());
				}
			});
		}

		CodeAction CreateFromStatements(RefactoringContext context, List<Statement> statements)
		{
			if (!(statements [0].Parent is Statement))
				return null;

			return new CodeAction(context.TranslateString("Extract method"), script => {
				string methodName = "NewMethod";
				var method = new MethodDeclaration() {
					ReturnType = new PrimitiveType("void"),
					Name = methodName,
					Body = new BlockStatement()
				};
				bool usesNonStaticMember = false;
				foreach (Statement node in statements) {
					usesNonStaticMember |= StaticVisitor.UsesNotStaticMember(context, node);
					method.Body.Add(node.Clone());
				}
				if (!usesNonStaticMember)
					method.Modifiers |= Modifiers.Static;

				var target = new IdentifierExpression(methodName);
				var invocation = new InvocationExpression(target);

				var usedVariables = VariableLookupVisitor.Analyze(context, statements);

				var inExtractedRegion = new VariableUsageAnalyzation (context, usedVariables);
				var lastStatement = statements [statements.Count - 1];

				var stmt = statements [0].GetParent<BlockStatement>();
				while (stmt.GetParent<BlockStatement> () != null) {
					stmt = stmt.GetParent<BlockStatement>();
				}

				inExtractedRegion.SetAnalyzedRange(statements [0], lastStatement);
				stmt.AcceptVisitor (inExtractedRegion);

				var beforeExtractedRegion = new VariableUsageAnalyzation (context, usedVariables);
				beforeExtractedRegion.SetAnalyzedRange(statements [0].Parent, statements [0], true, false);
				stmt.AcceptVisitor (beforeExtractedRegion);

				var afterExtractedRegion = new VariableUsageAnalyzation (context, usedVariables);
				afterExtractedRegion.SetAnalyzedRange(lastStatement, stmt.Statements.Last(), false, true);
				stmt.AcceptVisitor (afterExtractedRegion);
				usedVariables.Sort ((l, r) => l.Region.Begin.CompareTo (r.Region.Begin));

				IVariable generatedReturnVariable = null;
				foreach (var variable in usedVariables) {
					if ((variable is IParameter) || beforeExtractedRegion.Has (variable) || !afterExtractedRegion.Has (variable))
						continue;
					generatedReturnVariable = variable;
					method.ReturnType = context.CreateShortType (variable.Type);
					method.Body.Add (new ReturnStatement (new IdentifierExpression (variable.Name)));
					break;
				}

				foreach (var variable in usedVariables) {
					if (!(variable is IParameter) && !beforeExtractedRegion.Has (variable) && !afterExtractedRegion.Has (variable))
						continue;
					if (variable == generatedReturnVariable)
						continue;
					Expression argumentExpression = new IdentifierExpression(variable.Name);

					ParameterModifier mod = ParameterModifier.None;
					if (inExtractedRegion.GetStatus (variable) == VariableState.Changed) {
						if (beforeExtractedRegion.GetStatus (variable) == VariableState.None) {
							mod = ParameterModifier.Out;
							argumentExpression = new DirectionExpression(FieldDirection.Out, argumentExpression);
						} else {
							mod = ParameterModifier.Ref;
							argumentExpression = new DirectionExpression(FieldDirection.Ref, argumentExpression);
						}
					}

					method.Parameters.Add(new ParameterDeclaration(context.CreateShortType(variable.Type), variable.Name, mod));
					invocation.Arguments.Add(argumentExpression);
				}
				var task = script.InsertWithCursor(context.TranslateString("Extract method"), Script.InsertPosition.Before, method);
				Action<Task> replaceStatements = delegate {
					foreach (var node in statements.Skip (1)) {
						script.Remove(node);
					}
					foreach (var variable in usedVariables) {
						if ((variable is IParameter) || beforeExtractedRegion.Has (variable) || !afterExtractedRegion.Has (variable))
							continue;
						if (variable == generatedReturnVariable)
							continue;
						script.InsertBefore (statements [0], new VariableDeclarationStatement (context.CreateShortType(variable.Type), variable.Name));
					}
					AstNode invocationStatement;

					if (generatedReturnVariable != null) {
						invocationStatement = new VariableDeclarationStatement (new SimpleType ("var"), generatedReturnVariable.Name, invocation);
					} else {
						invocationStatement = new ExpressionStatement(invocation);
					}
					script.Replace(statements [0], invocationStatement);

					script.Link(target, method.NameToken);
				};

				if (task.IsCompleted) {
					replaceStatements (null);
				} else {
					task.ContinueWith (replaceStatements, TaskScheduler.FromCurrentSynchronizationContext ());
				}
			});
		}
	}
}


text:
Current Subscription

			You are subscribed to the @{{ currentPlan.name }}
			(@{{ currentPlan.currencySymbol }}@{{ currentPlan.price }} / @{{ currentPlan.interval | capitalize}}) plan.

			<button class="btn btn-primary" @click.prevent="confirmPlanChange" v-if="plans.length > 1">
				Change Plan
			</button>


text:
/* ###
 * IP: GHIDRA
 *
 * 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.
 */
package agent.dbgeng.manager;

import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

import org.apache.commons.lang3.tuple.Pair;

import agent.dbgeng.dbgeng.*;
import agent.dbgeng.manager.breakpoint.DbgBreakpointInfo;
import agent.dbgeng.manager.breakpoint.DbgBreakpointInsertions;
import agent.dbgeng.manager.impl.DbgManagerImpl;

public interface DbgManager extends AutoCloseable, DbgBreakpointInsertions {

	/**
	 * Possible values for {@link DbgThread#step(ExecSuffix)}
	 */
	public enum ExecSuffix {
		/** Equivalent to {@code finish} in the CLI */
		FINISH("finish"),
		/** Equivalent to {@code next} in the CLI */
		NEXT("next"),
		/** Equivalent to {@code nexti} in the CLI */
		NEXT_INSTRUCTION("next-instruction"),
		/** Equivalent to {@code return} in the CLI */
		RETURN("return"),
		/** Equivalent to {@code step} in the CLI */
		STEP("step"),
		/** Equivalent to {@code stepi} in the CLI */
		STEP_INSTRUCTION("step-instruction"),
		/** Equivalent to {@code until} in the CLI */
		UNTIL("until"),
		/** Equivalent to {@code ext} in the CLI */
		EXTENDED("ext"),;

		final String str;

		ExecSuffix(String str) {
			this.str = str;
		}

		@Override
		public String toString() {
			return str;
		}
	}

	static DbgManager newInstance() {
		//return new DbgManagerModelImpl();
		return new DbgManagerImpl();
	}

	/**
	 * Launch dbgeng
	 *
	 * @param args cmd plus args
	 * @return a future which completes when dbgeng is ready to accept commands
	 */
	CompletableFuture<Void> start(String[] args);

	/**
	 * Terminate dbgeng
	 */
	void terminate();

	/**
	 * Check if GDB is alive
	 *
	 * Note this is not about the state of inferiors in GDB. If the GDB controlling process is
	 * alive, GDB is alive.
	 *
	 * @return true if GDB is alive, false otherwise
	 */
	boolean isRunning();

	/**
	 * Add a listener for dbgeng's state
	 *
	 * @see #getState()
	 * @param listener the listener to add
	 */
	void addStateListener(DbgStateListener listener);

	/**
	 * Remove a listener for dbgeng's state
	 *
	 * @see #getState()
	 * @param listener the listener to remove
	 */
	void removeStateListener(DbgStateListener listener);

	/**
	 * Add a listener for events on processes
	 *
	 * @param listener the listener to add
	 */
	void addEventsListener(DbgEventsListener listener);

	/**
	 * Remove a listener for events on inferiors
	 *
	 * @param listener the listener to remove
	 */
	void removeEventsListener(DbgEventsListener listener);

	/**
	 * Get a thread by its dbgeng-assigned ID
	 *
	 * dbgeng numbers its threads using a global counter. These IDs are unrelated to the OS-assigned
	 * TID. This method can retrieve a thread by its ID no matter which inferior it belongs to.
	 *
	 * @param id the dbgeng-asigned thread ID
	 * @return a handle to the thread, if it exists
	 */
	DbgThread getThread(DebugThreadId id);

	/**
	 * Get an process by its dbgeng-assigned ID
	 *
	 * dbgeng numbers processes incrementally. All inferiors and created and destroyed by the user.
	 * See {@link #addProcess()}.
	 *
	 * @param id the process ID
	 * @return a handle to the process, if it exists
	 */
	DbgProcess getProcess(DebugProcessId id);

	/**
	 * Get an session by its dbgeng-assigned ID
	 *
	 * dbgeng numbers processes incrementally. All inferiors and created and destroyed by the user.
	 * See {@link #addSession()}.
	 *
	 * @param id the process ID
	 * @return a handle to the process, if it exists
	 */
	DbgSession getSession(DebugSessionId id);

	/**
	 * Get all threads known to the manager
	 *
	 * This does not ask dbgeng to lists its known threads. Rather it returns a read-only view of
	 * the manager's understanding of the current threads based on its tracking of dbgeng events.
	 *
	 * @return a map of dbgeng-assigned thread IDs to corresponding thread handles
	 */
	Map<DebugThreadId, DbgThread> getKnownThreads();

	/**
	 * Get all processes known to the manager
	 *
	 * This does not ask dbgeng to list its processes. Rather it returns a read-only view of the
	 * manager's understanding of the current processes based on its tracking of dbgeng events.
	 *
	 * @return a map of process IDs to corresponding process handles
	 */
	Map<DebugProcessId, DbgProcess> getKnownProcesses();

	/**
	 * Get all sessions known to the manager
	 *
	 * This does not ask dbgeng to list its processes. Rather it returns a read-only view of the
	 * manager's understanding of the current inferiors based on its tracking of dbgeng events.
	 *
	 * @return a map of session IDs to corresponding session handles
	 */
	Map<DebugSessionId, DbgSession> getKnownSessions();

	/**
	 * Get all breakpoints known to the manager
	 *
	 * This does not ask dbgeng to list its breakpoints. Rather it returns a read-only view of the
	 * manager's understanding of the current breakpoints based on its tracking of dbgeng events.
	 *
	 * @return a map of dbgeng-assigned breakpoint IDs to corresponding breakpoint information
	 */
	Map<Long, DbgBreakpointInfo> getKnownBreakpoints();

	/**
	 * Get all memory regions known to the manager
	 *
	 * This does not ask dbgeng to list its regions. Rather it returns a read-only view of the
	 * manager's understanding of the current ememory based on its tracking of dbgeng events.
	 *
	 * @return a map of dbgeng-assigned breakpoint IDs to corresponding breakpoint information
	 */
	Map<Long, DbgModuleMemory> getKnownMemoryRegions();

	/**
	 * Send an interrupt to dbgeng regardless of other queued commands
	 *
	 * This may be useful if the manager's command queue is stalled because an inferior is running.
	 *
	 */
	void sendInterruptNow();

	/**
	 * Get the state of the dbgeng session
	 *
	 * In all-stop mode, if any thread is running, dbgeng is said to be in the running state and is
	 * unable to process commands. Otherwise, if all threads are stopped, then dbgeng is said to be
	 * in the stopped state and can accept and process commands. This manager has not been tested in
	 * non-stop mode.
	 *
	 * @return the state
	 */
	DbgState getState();

	/**
	 * Add a process
	 *
	 * @return a future which completes with the handle to the new process
	 */
	CompletableFuture<DbgProcess> addProcess();

	/**
	 * Remove a process
	 *
	 * @param process the process to remove
	 * @return a future which completes then dbgeng has executed the command
	 */
	CompletableFuture<Void> removeProcess(DbgProcess process);

	/**
	 * Add a session
	 *
	 * @return a future which completes with the handle to the new process
	 */
	CompletableFuture<DbgSession> addSession();

	/**
	 * Remove a session
	 *
	 * @param process the session to remove
	 * @return a future which completes then dbgeng has executed the command
	 */
	CompletableFuture<Void> removeSession(DbgSession session);

	/**
	 * Add a memory region
	 *
	 * @return a future which completes with the handle to the new process
	 */
	CompletableFuture<Void> addMemory(DbgModuleMemory region);

	/**
	 * Remove a memory region
	 *
	 * @param regionId the region to remove
	 * @return a future which completes then dbgeng has executed the command
	 */
	CompletableFuture<Void> removeMemory(Long regionId);

	/**
	 * Execute an arbitrary CLI command, printing output to the CLI console
	 *
	 * Note: to ensure a certain thread or inferior has focus for a console command, see
	 * {@link DbgThread#console(String)}.
	 *
	 * @param command the command to execute
	 * @return a future that completes when dbgeng has executed the command
	 */
	CompletableFuture<Void> console(String command);

	/**
	 * Execute an arbitrary CLI command, capturing its console output
	 *
	 * The output will not be printed to the CLI console. To ensure a certain thread or inferior has
	 * focus for a console command, see {@link DbgThread#consoleCapture(String)} and
	 * {@link DbgProcess#consoleCapture(String)}.
	 *
	 * @param command the command to execute
	 * @return a future that completes with the captured output when dbgeng has executed the command
	 */
	CompletableFuture<String> consoleCapture(String command);

	/**
	 * List dbgeng's processes
	 *
	 * @return a future that completes with a map of process IDs to process handles
	 */
	CompletableFuture<Map<DebugProcessId, DbgProcess>> listProcesses();

	/**
	 * List the available processes on target
	 *
	 * @return a future that completes with a list of PIDs
	 */
	CompletableFuture<List<Pair<Integer, String>>> listAvailableProcesses();

	/**
	 * List dbgeng's sessions
	 *
	 * @return a future that completes with a map of session IDs to session handles
	 */
	CompletableFuture<Map<String, DbgSession>> listSessions();

	/**
	 * List information for all breakpoints
	 *
	 * @return a future that completes with a list of information for all breakpoints
	 */
	CompletableFuture<Map<Long, DbgBreakpointInfo>> listBreakpoints();

	/**
	 * Disable the given breakpoints
	 *
	 * This is equivalent to the CLI command {@code disable breakpoint [NUMBER]}.
	 *
	 * @param numbers the dbgeng-assigned breakpoint numbers
	 * @return a future that completes when dbgeng has executed the command
	 */
	CompletableFuture<Void> disableBreakpoints(long... numbers);

	/**
	 * Enable the given breakpoints
	 *
	 * This is equivalent to the CLI command {@code enable breakpoint [NUMBER]}.
	 *
	 * @param numbers the dbgeng-assigned breakpoint numbers
	 * @return a future that completes when dbgeng has executed the command
	 */
	CompletableFuture<Void> enableBreakpoints(long... numbers);

	/**
	 * Delete a breakpoint
	 *
	 * This is equivalent to the CLI command {@code delete breakpoint [NUMBER]}.
	 *
	 * @param numbers the dbgeng-assigned breakpoint numbers
	 * @return a future that completes when dbgeng has executed the command
	 */
	CompletableFuture<Void> deleteBreakpoints(long... numbers);

	CompletableFuture<?> launch(List<String> args);

	CompletableFuture<Void> launch(Map<String, ?> args);

	/********** NEEDED FOR TESTING ************/

	/**
	 * Returns the current process
	 *
	 * @return the current process
	 */
	DbgProcess currentProcess();

	CompletableFuture<Void> waitForState(DbgState stopped);

	CompletableFuture<Void> waitForPrompt();

	CompletableFuture<Void> waitForEventEx();

	<T> CompletableFuture<T> execute(DbgCommand<? extends T> cmd);

	DebugEventInformation getLastEventInformation();

	DbgSession getSessionComputeIfAbsent(DebugSessionId debugSessionId, boolean b);

}


text:
/*
 *	Copyright (c) 1988 AT&T
 *	  All Rights Reserved
 *
 * Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#ifndef _SYS_LINK_H
#define	_SYS_LINK_H

#pragma ident	"@(#)link.h	1.72	06/03/27 SMI"

#ifndef	_ASM
#include <sys/types.h>

#if !defined(__APPLE__)
#include <sys/elftypes.h>
#else /* is Apple Mac OS X */
#include "elftypes.h" /* In lieu of Solaris <sys/types.h> */
#endif /* __APPLE__ */

#endif

#ifdef	__cplusplus
extern "C" {
#endif

/*
 * Communication structures for the runtime linker.
 */

/*
 * The following data structure provides a self-identifying union consisting
 * of a tag from a known list and a value.
 */
#ifndef	_ASM
typedef struct {
	Elf32_Sword d_tag;		/* how to interpret value */
	union {
		Elf32_Word	d_val;
		Elf32_Addr	d_ptr;
		Elf32_Off	d_off;
	} d_un;
} Elf32_Dyn;

#if defined(_LP64) || defined(_LONGLONG_TYPE)
typedef struct {
	Elf64_Xword d_tag;		/* how to interpret value */
	union {
		Elf64_Xword	d_val;
		Elf64_Addr	d_ptr;
	} d_un;
} Elf64_Dyn;
#endif	/* defined(_LP64) || defined(_LONGLONG_TYPE) */
#endif	/* _ASM */

/*
 * Tag values
 */
#define	DT_NULL		0	/* last entry in list */
#define	DT_NEEDED	1	/* a needed object */
#define	DT_PLTRELSZ	2	/* size of relocations for the PLT */
#define	DT_PLTGOT	3	/* addresses used by procedure linkage table */
#define	DT_HASH		4	/* hash table */
#define	DT_STRTAB	5	/* string table */
#define	DT_SYMTAB	6	/* symbol table */
#define	DT_RELA		7	/* addr of relocation entries */
#define	DT_RELASZ	8	/* size of relocation table */
#define	DT_RELAENT	9	/* base size of relocation entry */
#define	DT_STRSZ	10	/* size of string table */
#define	DT_SYMENT	11	/* size of symbol table entry */
#define	DT_INIT		12	/* _init addr */
#define	DT_FINI		13	/* _fini addr */
#define	DT_SONAME	14	/* name of this shared object */
#define	DT_RPATH	15	/* run-time search path */
#define	DT_SYMBOLIC	16	/* shared object linked -Bsymbolic */
#define	DT_REL		17	/* addr of relocation entries */
#define	DT_RELSZ	18	/* size of relocation table */
#define	DT_RELENT	19	/* base size of relocation entry */
#define	DT_PLTREL	20	/* relocation type for PLT entry */
#define	DT_DEBUG	21	/* pointer to r_debug structure */
#define	DT_TEXTREL	22	/* text relocations remain for this object */
#define	DT_JMPREL	23	/* pointer to the PLT relocation entries */
#define	DT_BIND_NOW	24	/* perform all relocations at load of object */
#define	DT_INIT_ARRAY	25	/* pointer to .initarray */
#define	DT_FINI_ARRAY	26	/* pointer to .finiarray */
#define	DT_INIT_ARRAYSZ	27	/* size of .initarray */
#define	DT_FINI_ARRAYSZ	28	/* size of .finiarray */
#define	DT_RUNPATH	29	/* run-time search path */
#define	DT_FLAGS	30	/* state flags - see DF_* */

#define	DT_ENCODING		32    /* DT_* encoding rules start after this */
#define	DT_PREINIT_ARRAY	32    /* pointer to .preinitarray segment */
#define	DT_PREINIT_ARRAYSZ	33    /* size of .preinitarray segment */

#define	DT_MAXPOSTAGS		34	/* number of positive tags */

#define	DT_LOOS			0x6000000d	/* OS specific range */
#define	DT_SUNW_AUXILIARY	0x6000000d	/* symbol auxiliary name */
#define	DT_SUNW_RTLDINF		0x6000000e	/* ld.so.1 info (private) */
#define	DT_SUNW_FILTER		0x6000000f	/* symbol filter name */
#define	DT_SUNW_CAP		0x60000010	/* hardware/software */
						/*	capabilities */
#define	DT_HIOS			0x6ffff000

/*
 * The following values have been deprecated and remain here to allow
 * compatibility with older binaries.
 */
#define	DT_DEPRECATED_SPARC_REGISTER	0x7000001

/*
 * DT_* entries which fall between DT_VALRNGHI & DT_VALRNGLO use the
 * Dyn.d_un.d_val field of the Elf*_Dyn structure.
 */
#define	DT_VALRNGLO	0x6ffffd00
#define	DT_CHECKSUM	0x6ffffdf8	/* elf checksum */
#define	DT_PLTPADSZ	0x6ffffdf9	/* pltpadding size */
#define	DT_MOVEENT	0x6ffffdfa	/* move table entry size */
#define	DT_MOVESZ	0x6ffffdfb	/* move table size */
#define	DT_FEATURE_1	0x6ffffdfc	/* feature holder */
#define	DT_POSFLAG_1	0x6ffffdfd	/* flags for DT_* entries, effecting */
					/*	the following DT_* entry. */
					/*	See DF_P1_* definitions */
#define	DT_SYMINSZ	0x6ffffdfe	/* syminfo table size (in bytes) */
#define	DT_SYMINENT	0x6ffffdff	/* syminfo entry size (in bytes) */
#define	DT_VALRNGHI	0x6ffffdff

/*
 * DT_* entries which fall between DT_ADDRRNGHI & DT_ADDRRNGLO use the
 * Dyn.d_un.d_ptr field of the Elf*_Dyn structure.
 *
 * If any adjustment is made to the ELF object after it has been
 * built, these entries will need to be adjusted.
 */
#define	DT_ADDRRNGLO	0x6ffffe00
#define	DT_CONFIG	0x6ffffefa	/* configuration information */
#define	DT_DEPAUDIT	0x6ffffefb	/* dependency auditing */
#define	DT_AUDIT	0x6ffffefc	/* object auditing */
#define	DT_PLTPAD	0x6ffffefd	/* pltpadding (sparcv9) */
#define	DT_MOVETAB	0x6ffffefe	/* move table */
#define	DT_SYMINFO	0x6ffffeff	/* syminfo table */
#define	DT_ADDRRNGHI	0x6ffffeff

/*
 * The following DT_* entries should have been assigned within one of the
 * DT_* ranges, but existed before such ranges had been established.
 */
#define	DT_VERSYM	0x6ffffff0	/* version symbol table - unused */

#define	DT_RELACOUNT	0x6ffffff9	/* number of RELATIVE relocations */
#define	DT_RELCOUNT	0x6ffffffa	/* number of RELATIVE relocations */
#define	DT_FLAGS_1	0x6ffffffb	/* state flags - see DF_1_* defs */
#define	DT_VERDEF	0x6ffffffc	/* version definition table and */
#define	DT_VERDEFNUM	0x6ffffffd	/*	associated no. of entries */
#define	DT_VERNEED	0x6ffffffe	/* version needed table and */
#define	DT_VERNEEDNUM	0x6fffffff	/* 	associated no. of entries */

/*
 * DT_* entries between DT_HIPROC and DT_LOPROC are reserved for processor
 * specific semantics.
 */
#define	DT_LOPROC	0x70000000	/* processor specific range */
#define	DT_AUXILIARY	0x7ffffffd	/* shared library auxiliary name */
#define	DT_USED		0x7ffffffe	/* ignored - same as needed */
#define	DT_FILTER	0x7fffffff	/* shared library filter name */
#define	DT_HIPROC	0x7fffffff

/*
 * Values for DT_FLAGS
 */
#define	DF_ORIGIN	0x00000001	/* ORIGIN processing required */
#define	DF_SYMBOLIC	0x00000002	/* symbolic bindings in effect */
#define	DF_TEXTREL	0x00000004	/* text relocations remain */
#define	DF_BIND_NOW	0x00000008	/* process all relocations */
#define	DF_STATIC_TLS	0x00000010	/* obj. contains static TLS refs */

/*
 * Values for the DT_POSFLAG_1 .dynamic entry.
 * These values only affect the following DT_* entry.
 */
#define	DF_P1_LAZYLOAD	0x00000001	/* following object is to be */
					/*	lazy loaded */
#define	DF_P1_GROUPPERM	0x00000002	/* following object's symbols are */
					/*	not available for general */
					/*	symbol bindings. */
/*
 * Values for the DT_FLAGS_1 .dynamic entry.
 */
#define	DF_1_NOW	0x00000001	/* set RTLD_NOW for this object */
#define	DF_1_GLOBAL	0x00000002	/* set RTLD_GLOBAL for this object */
#define	DF_1_GROUP	0x00000004	/* set RTLD_GROUP for this object */
#define	DF_1_NODELETE	0x00000008	/* set RTLD_NODELETE for this object */
#define	DF_1_LOADFLTR	0x00000010	/* trigger filtee loading at runtime */
#define	DF_1_INITFIRST	0x00000020	/* set RTLD_INITFIRST for this object */
#define	DF_1_NOOPEN	0x00000040	/* set RTLD_NOOPEN for this object */
#define	DF_1_ORIGIN	0x00000080	/* ORIGIN processing required */
#define	DF_1_DIRECT	0x00000100	/* direct binding enabled */
#define	DF_1_TRANS	0x00000200
#define	DF_1_INTERPOSE	0x00000400	/* object is an 'interposer' */
#define	DF_1_NODEFLIB	0x00000800	/* ignore default library search path */
#define	DF_1_NODUMP	0x00001000	/* object can't be dldump(3x)'ed */
#define	DF_1_CONFALT	0x00002000	/* configuration alternative created */
#define	DF_1_ENDFILTEE	0x00004000	/* filtee terminates filters search */
#define	DF_1_DISPRELDNE	0x00008000	/* disp reloc applied at build time */
#define	DF_1_DISPRELPND	0x00010000	/* disp reloc applied at run-time */
#define	DF_1_NODIRECT	0x00020000	/* object contains symbols that */
					/*	cannot be directly bound to */
#define	DF_1_IGNMULDEF	0x00040000	/* internal: krtld ignore muldefs */
#define	DF_1_NOKSYMS	0x00080000	/* internal: don't export object's */
					/*	symbols via /dev/ksyms */
#define	DF_1_NOHDR	0x00100000	/* mapfile ?N:1st segment mapping */
					/*	omits ELF & program headers */
#define	DF_1_NORELOC	0x00400000	/* internal: unrelocated object */

/*
 * Values set to DT_FEATURE_1 tag's d_val.
 */
#define	DTF_1_PARINIT	0x00000001	/* partially initialization feature */
#define	DTF_1_CONFEXP	0x00000002	/* configuration file expected */

/*
 * Version structures.  There are three types of version structure:
 *
 *  o	A definition of the versions within the image itself.
 *	Each version definition is assigned a unique index (starting from
 *	VER_NDX_BGNDEF)	which is used to cross-reference symbols associated to
 *	the version.  Each version can have one or more dependencies on other
 *	version definitions within the image.  The version name, and any
 *	dependency names, are specified in the version definition auxiliary
 *	array.  Version definition entries require a version symbol index table.
 *
 *  o	A version requirement on a needed dependency.  Each needed entry
 *	specifies the shared object dependency (as specified in DT_NEEDED).
 *	One or more versions required from this dependency are specified in the
 *	version needed auxiliary array.
 *
 *  o	A version symbol index table.  Each symbol indexes into this array
 *	to determine its version index.  Index values of VER_NDX_BGNDEF or
 *	greater indicate the version definition to which a symbol is associated.
 *	(the size of a symbol index entry is recorded in the sh_info field).
 */
#ifndef	_ASM

typedef struct {			/* Version Definition Structure. */
	Elf32_Half	vd_version;	/* this structures version revision */
	Elf32_Half	vd_flags;	/* version information */
	Elf32_Half	vd_ndx;		/* version index */
	Elf32_Half	vd_cnt;		/* no. of associated aux entries */
	Elf32_Word	vd_hash;	/* version name hash value */
	Elf32_Word	vd_aux;		/* no. of bytes from start of this */
					/*	verdef to verdaux array */
	Elf32_Word	vd_next;	/* no. of bytes from start of this */
} Elf32_Verdef;				/*	verdef to next verdef entry */

typedef struct {			/* Verdef Auxiliary Structure. */
	Elf32_Word	vda_name;	/* first element defines the version */
					/*	name. Additional entries */
					/*	define dependency names. */
	Elf32_Word	vda_next;	/* no. of bytes from start of this */
} Elf32_Verdaux;			/*	verdaux to next verdaux entry */

typedef	struct {			/* Version Requirement Structure. */
	Elf32_Half	vn_version;	/* this structures version revision */
	Elf32_Half	vn_cnt;		/* no. of associated aux entries */
	Elf32_Word	vn_file;	/* name of needed dependency (file) */
	Elf32_Word	vn_aux;		/* no. of bytes from start of this */
					/*	verneed to vernaux array */
	Elf32_Word	vn_next;	/* no. of bytes from start of this */
} Elf32_Verneed;			/*	verneed to next verneed entry */

typedef struct {			/* Verneed Auxiliary Structure. */
	Elf32_Word	vna_hash;	/* version name hash value */
	Elf32_Half	vna_flags;	/* version information */
	Elf32_Half	vna_other;
	Elf32_Word	vna_name;	/* version name */
	Elf32_Word	vna_next;	/* no. of bytes from start of this */
} Elf32_Vernaux;			/*	vernaux to next vernaux entry */

typedef	Elf32_Half 	Elf32_Versym;	/* Version symbol index array */

typedef struct {
	Elf32_Half	si_boundto;	/* direct bindings - symbol bound to */
	Elf32_Half	si_flags;	/* per symbol flags */
} Elf32_Syminfo;

#if defined(_LP64) || defined(_LONGLONG_TYPE)
typedef struct {
	Elf64_Half	vd_version;	/* this structures version revision */
	Elf64_Half	vd_flags;	/* version information */
	Elf64_Half	vd_ndx;		/* version index */
	Elf64_Half	vd_cnt;		/* no. of associated aux entries */
	Elf64_Word	vd_hash;	/* version name hash value */
	Elf64_Word	vd_aux;		/* no. of bytes from start of this */
					/*	verdef to verdaux array */
	Elf64_Word	vd_next;	/* no. of bytes from start of this */
} Elf64_Verdef;				/*	verdef to next verdef entry */

typedef struct {
	Elf64_Word	vda_name;	/* first element defines the version */
					/*	name. Additional entries */
					/*	define dependency names. */
	Elf64_Word	vda_next;	/* no. of bytes from start of this */
} Elf64_Verdaux;			/*	verdaux to next verdaux entry */

typedef struct {
	Elf64_Half	vn_version;	/* this structures version revision */
	Elf64_Half	vn_cnt;		/* no. of associated aux entries */
	Elf64_Word	vn_file;	/* name of needed dependency (file) */
	Elf64_Word	vn_aux;		/* no. of bytes from start of this */
					/*	verneed to vernaux array */
	Elf64_Word	vn_next;	/* no. of bytes from start of this */
} Elf64_Verneed;			/*	verneed to next verneed entry */

typedef struct {
	Elf64_Word	vna_hash;	/* version name hash value */
	Elf64_Half	vna_flags;	/* version information */
	Elf64_Half	vna_other;
	Elf64_Word	vna_name;	/* version name */
	Elf64_Word	vna_next;	/* no. of bytes from start of this */
} Elf64_Vernaux;			/*	vernaux to next vernaux entry */

typedef	Elf64_Half	Elf64_Versym;

typedef struct {
	Elf64_Half	si_boundto;	/* direct bindings - symbol bound to */
	Elf64_Half	si_flags;	/* per symbol flags */
} Elf64_Syminfo;
#endif	/* defined(_LP64) || defined(_LONGLONG_TYPE) */

#endif	/* _ASM */

/*
 * Versym symbol index values.  Values greater than VER_NDX_GLOBAL
 * and less then VER_NDX_LORESERVE associate symbols with user
 * specified version descriptors.
 */
#define	VER_NDX_LOCAL		0	/* symbol is local */
#define	VER_NDX_GLOBAL		1	/* symbol is global and assigned to */
					/*	the base version */
#define	VER_NDX_LORESERVE	0xff00	/* beginning of RESERVED entries */
#define	VER_NDX_ELIMINATE	0xff01	/* symbol is to be eliminated */

/*
 * Verdef and Verneed (via Veraux) flags values.
 */
#define	VER_FLG_BASE		0x1	/* version definition of file itself */
#define	VER_FLG_WEAK		0x2	/* weak version identifier */

/*
 * Verdef version values.
 */
#define	VER_DEF_NONE		0	/* Ver_def version */
#define	VER_DEF_CURRENT		1
#define	VER_DEF_NUM		2

/*
 * Verneed version values.
 */
#define	VER_NEED_NONE		0	/* Ver_need version */
#define	VER_NEED_CURRENT	1
#define	VER_NEED_NUM		2

/*
 * Syminfo flag values
 */
#define	SYMINFO_FLG_DIRECT	0x0001	/* symbol ref has direct association */
					/*	to object containing defn. */
#define	SYMINFO_FLG_PASSTHRU	0x0002	/* ignored - see SYMINFO_FLG_FILTER */
#define	SYMINFO_FLG_COPY	0x0004	/* symbol is a copy-reloc */
#define	SYMINFO_FLG_LAZYLOAD	0x0008	/* object containing defn should be */
					/*	lazily-loaded */
#define	SYMINFO_FLG_DIRECTBIND	0x0010	/* ref should be bound directly to */
					/*	object containing defn. */
#define	SYMINFO_FLG_NOEXTDIRECT	0x0020	/* don't let an external reference */
					/*	directly bind to this symbol */
#define	SYMINFO_FLG_FILTER	0x0002	/* symbol ref is associated to a */
#define	SYMINFO_FLG_AUXILIARY	0x0040	/* 	standard or auxiliary filter */

/*
 * Syminfo.si_boundto values.
 */
#define	SYMINFO_BT_SELF		0xffff	/* symbol bound to self */
#define	SYMINFO_BT_PARENT	0xfffe	/* symbol bound to parent */
#define	SYMINFO_BT_NONE		0xfffd	/* no special symbol binding */
#define	SYMINFO_BT_EXTERN	0xfffc	/* symbol defined as external */
#define	SYMINFO_BT_LOWRESERVE	0xff00	/* beginning of reserved entries */

/*
 * Syminfo version values.
 */
#define	SYMINFO_NONE		0	/* Syminfo version */
#define	SYMINFO_CURRENT		1
#define	SYMINFO_NUM		2

/*
 * Public structure defined and maintained within the runtime linker
 */
#ifndef	_ASM

typedef struct link_map	Link_map;

struct link_map {
	unsigned long	l_addr;		/* address at which object is mapped */
	char 		*l_name;	/* full name of loaded object */
#ifdef _LP64
	Elf64_Dyn	*l_ld;		/* dynamic structure of object */
#else
	Elf32_Dyn	*l_ld;		/* dynamic structure of object */
#endif
	Link_map	*l_next;	/* next link object */
	Link_map	*l_prev;	/* previous link object */
	char		*l_refname;	/* filters reference name */
};

#ifdef _SYSCALL32
typedef struct link_map32 Link_map32;

struct link_map32 {
	Elf32_Word	l_addr;
	Elf32_Addr	l_name;
	Elf32_Addr	l_ld;
	Elf32_Addr	l_next;
	Elf32_Addr	l_prev;
	Elf32_Addr	l_refname;
};
#endif

typedef enum {
	RT_CONSISTENT,
	RT_ADD,
	RT_DELETE
} r_state_e;

typedef enum {
	RD_FL_NONE = 0,		/* no flags */
	RD_FL_ODBG = (1<<0),	/* old style debugger present */
	RD_FL_DBG = (1<<1)	/* debugging enabled */
} rd_flags_e;

/*
 * Debugging events enabled inside of the runtime linker.  To
 * access these events see the librtld_db interface.
 */
typedef enum {
	RD_NONE = 0,		/* no event */
	RD_PREINIT,		/* the Initial rendezvous before .init */
	RD_POSTINIT,		/* the Second rendezvous after .init */
	RD_DLACTIVITY		/* a dlopen or dlclose has happened */
} rd_event_e;

struct r_debug {
	int		r_version;	/* debugging info version no. */
	Link_map	*r_map;		/* address of link_map */
	unsigned long	r_brk;		/* address of update routine */
	r_state_e	r_state;
	unsigned long	r_ldbase;	/* base addr of ld.so */
	Link_map	*r_ldsomap;	/* address of ld.so.1's link map */
	rd_event_e	r_rdevent;	/* debug event */
	rd_flags_e	r_flags;	/* misc flags. */
};

#ifdef _SYSCALL32
struct r_debug32 {
	Elf32_Word	r_version;	/* debugging info version no. */
	Elf32_Addr	r_map;		/* address of link_map */
	Elf32_Word	r_brk;		/* address of update routine */
	r_state_e	r_state;
	Elf32_Word	r_ldbase;	/* base addr of ld.so */
	Elf32_Addr	r_ldsomap;	/* address of ld.so.1's link map */
	rd_event_e	r_rdevent;	/* debug event */
	rd_flags_e	r_flags;	/* misc flags. */
};
#endif

#define	R_DEBUG_VERSION	2		/* current r_debug version */
#endif	/* _ASM */

/*
 * Attribute/value structures used to bootstrap ELF-based dynamic linker.
 */
#ifndef	_ASM
typedef struct {
	Elf32_Sword eb_tag;		/* what this one is */
	union {				/* possible values */
		Elf32_Word eb_val;
		Elf32_Addr eb_ptr;
		Elf32_Off  eb_off;
	} eb_un;
} Elf32_Boot;

#if defined(_LP64) || defined(_LONGLONG_TYPE)
typedef struct {
	Elf64_Xword eb_tag;		/* what this one is */
	union {				/* possible values */
		Elf64_Xword eb_val;
		Elf64_Addr eb_ptr;
		Elf64_Off eb_off;
	} eb_un;
} Elf64_Boot;
#endif	/* defined(_LP64) || defined(_LONGLONG_TYPE) */
#endif	/* _ASM */

/*
 * Attributes
 */
#define	EB_NULL		0		/* (void) last entry */
#define	EB_DYNAMIC	1		/* (*) dynamic structure of subject */
#define	EB_LDSO_BASE	2		/* (caddr_t) base address of ld.so */
#define	EB_ARGV		3		/* (caddr_t) argument vector */
#define	EB_ENVP		4		/* (char **) environment strings */
#define	EB_AUXV		5		/* (auxv_t *) auxiliary vector */
#define	EB_DEVZERO	6		/* (int) fd for /dev/zero */
#define	EB_PAGESIZE	7		/* (int) page size */
#define	EB_MAX		8		/* number of "EBs" */
#define	EB_MAX_SIZE32	64		/* size in bytes, _ILP32 */
#define	EB_MAX_SIZE64	128		/* size in bytes, _LP64 */

#ifndef	_ASM

#ifdef __STDC__

/*
 * Concurrency communication structure for libc callbacks.
 */
extern void	_ld_libc(void *);
#else /* __STDC__ */
extern void	_ld_libc();
#endif /* __STDC__ */

#pragma unknown_control_flow(_ld_libc)
#endif /* _ASM */

#ifdef	__cplusplus
}
#endif

#endif	/* _SYS_LINK_H */


text:
class OfcpScoring::HandCategorizer

  def initialize(organizer = OfcpScoring::HandOrganizer.new)
    @organizer = organizer
  end

  def categorize(hand)
    return "" if hand.nil?

    organized_hand = @organizer.organize(hand)

    categorization = OfcpScoring::HighCard
    categorization = OfcpScoring::Pair if organized_hand.two_cards_match?
    categorization = OfcpScoring::TwoPair if organized_hand.two_different_cards_match?
    categorization = OfcpScoring::ThreeOfAKind if organized_hand.three_cards_match?

    unless organized_hand.three_card_hand?
      categorization = OfcpScoring::Straight if organized_hand.ranks_in_order?
      categorization = OfcpScoring::Flush if organized_hand.all_suits_match?
      categorization = OfcpScoring::FullHouse if organized_hand.three_cards_match? && organized_hand.two_cards_match?
      categorization = OfcpScoring::FourOfAKind if organized_hand.four_cards_match?
      categorization = OfcpScoring::StraightFlush if organized_hand.all_suits_match? && organized_hand.ranks_in_order?
      categorization = OfcpScoring::RoyalFlush if organized_hand.all_suits_match? && organized_hand.ranks_in_order? && organized_hand.high_card_ace?
    end

    return categorization.new(organized_hand)

  end

end


text:
package io.atomix.catalyst.serializer.lang;

import io.atomix.catalyst.buffer.BufferInput;
import io.atomix.catalyst.buffer.BufferOutput;
import io.atomix.catalyst.serializer.Serializer;
import io.atomix.catalyst.serializer.TypeSerializer;

/**
 * Integer array serializer.
 *
 * @author Jordan Halterman
 */
public class IntegerArraySerializer implements TypeSerializer<int[]> {

  @Override
  public void write(int[] ints, BufferOutput buffer, Serializer serializer) {
    buffer.writeUnsignedShort(ints.length);
    for (int i : ints) {
      buffer.writeInt(i);
    }
  }

  @Override
  public int[] read(Class<int[]> type, BufferInput buffer, Serializer serializer) {
    int[] ints = new int[buffer.readUnsignedShort()];
    for (int i = 0; i < ints.length; i++) {
      ints[i] = buffer.readInt();
    }
    return ints;
  }

}


text:
<?php declare(strict_types=1);

namespace DrdPlus\Tests\Codes\Environment;

use DrdPlus\Tests\Codes\AbstractCodeTest;

class LightSourceCodeTest extends AbstractCodeTest
{

}


text:
id: 5900f44e1000cf542c50ff60
challengeType: 5
title: 'Problem 225: Tribonacci non-divisors'
---

## Description

The sequence 1, 1, 1, 3, 5, 9, 17, 31, 57, 105, 193, 355, 653, 1201 ...
is defined by T1 = T2 = T3 = 1 and Tn = Tn-1 + Tn-2 + Tn-3.

It can be shown that 27 does not divide any terms of this sequence.In fact, 27 is the first odd number with this property.

Find the 124th odd number that does not divide any terms of the above sequence.

## Instructions

## Tests

```yml
tests:
  - text: <code>euler225()</code> should return 2009.
    testString: assert.strictEqual(euler225(), 2009, '<code>euler225()</code> should return 2009.');

```

## Challenge Seed

```js
function euler225() {
  // Good luck!
  return true;
}

euler225();
```

## Solution

```js
// solution required
```


text:
require 'mina/git'
require 'mina/rails'
require 'mina/rvm'
require 'mina/rbenv'
require 'mina/chruby'
require 'pry'
#

set :domain, 'localhost'
set :deploy_to, "#{Dir.pwd}/deploy"
set :repository, "#{Mina.root_path}"
set :shared_paths, ['config/database.yml', 'log']
set :keep_releases, 2

task :environment do
  invoke :'rbenv:load'
end
#
# desc "Deploys."
task :deploy do
  run :local do
    puts 'buja'
  end

  deploy do
    invoke :'git:clone'
    invoke :'deploy:link_shared_paths'
    invoke :'bundle:install'
    invoke :'rails:db_migrate'
    invoke :'deploy:cleanup'

    on :launch do
      comment %{in launch}
    end
  end
end

desc 'Task description'
task :test do
  run :remote do
    comment %{PWD}
    in_path('/Users') do
      command %{ls -al}
    end
    on :after do
      command %{pwd}
    end
  end

  run :local do
    command %{ls -al}
  end
end

desc 'Fails test'
task :fail do
  run :remote do
    run :local do
      command "pwd"
    end
  end
end

task :local_environment do
  comment 'local environment run'
  command 'export HERE=local'
end

task :remote_environment do
  comment 'remote environment run'
  command 'export HERE=remote'
end

task test_envs: :environment do
  run(:local) do
    command 'echo $HERE'
  end

  run(:remote) do
    command 'echo $HERE'
  end

  run(:local) do
    command 'echo $HERE'
  end

  run(:remote) do
    command 'echo $HERE'
  end
end


text:
import * as tf from '@tensorflow/tfjs-core';

import {connectedPartIndices} from './keypoints';
import {PoseNetOutputStride} from './posenet_model';
import {Keypoint, Padding, Pose, PosenetInput, TensorBuffer3D, Vector2D} from './types';

function eitherPointDoesntMeetConfidence(
    a: number, b: number, minConfidence: number): boolean {
  return (a < minConfidence || b < minConfidence);
}

export function getAdjacentKeyPoints(
    keypoints: Keypoint[], minConfidence: number): Keypoint[][] {
  return connectedPartIndices.reduce(
      (result: Keypoint[][], [leftJoint, rightJoint]): Keypoint[][] => {
        if (eitherPointDoesntMeetConfidence(
                keypoints[leftJoint].score, keypoints[rightJoint].score,
                minConfidence)) {
          return result;
        }

        result.push([keypoints[leftJoint], keypoints[rightJoint]]);

        return result;
      }, []);
}

const {NEGATIVE_INFINITY, POSITIVE_INFINITY} = Number;
export function getBoundingBox(keypoints: Keypoint[]):
    {maxX: number, maxY: number, minX: number, minY: number} {
  return keypoints.reduce(({maxX, maxY, minX, minY}, {position: {x, y}}) => {
    return {
      maxX: Math.max(maxX, x),
      maxY: Math.max(maxY, y),
      minX: Math.min(minX, x),
      minY: Math.min(minY, y)
    };
  }, {
    maxX: NEGATIVE_INFINITY,
    maxY: NEGATIVE_INFINITY,
    minX: POSITIVE_INFINITY,
    minY: POSITIVE_INFINITY
  });
}

export function getBoundingBoxPoints(keypoints: Keypoint[]): Vector2D[] {
  const {minX, minY, maxX, maxY} = getBoundingBox(keypoints);
  return [
    {x: minX, y: minY}, {x: maxX, y: minY}, {x: maxX, y: maxY},
    {x: minX, y: maxY}
  ];
}

export async function toTensorBuffer<rank extends tf.Rank>(
    tensor: tf.Tensor<rank>,
    type: 'float32'|'int32' = 'float32'): Promise<tf.TensorBuffer<rank>> {
  const tensorData = await tensor.data();

  return tf.buffer(tensor.shape, type, tensorData as Float32Array) as
      tf.TensorBuffer<rank>;
}

export async function toTensorBuffers3D(tensors: tf.Tensor3D[]):
    Promise<TensorBuffer3D[]> {
  return Promise.all(tensors.map(tensor => toTensorBuffer(tensor, 'float32')));
}

export function scalePose(
    pose: Pose, scaleY: number, scaleX: number, offsetY = 0,
    offsetX = 0): Pose {
  return {
    score: pose.score,
    keypoints: pose.keypoints.map(({score, part, position}) => ({
                                    score,
                                    part,
                                    position: {
                                      x: position.x * scaleX + offsetX,
                                      y: position.y * scaleY + offsetY
                                    }
                                  }))
  };
}

export function scalePoses(
    poses: Pose[], scaleY: number, scaleX: number, offsetY = 0, offsetX = 0) {
  if (scaleX === 1 && scaleY === 1 && offsetY === 0 && offsetX === 0) {
    return poses;
  }
  return poses.map(pose => scalePose(pose, scaleY, scaleX, offsetY, offsetX));
}

export function flipPoseHorizontal(pose: Pose, imageWidth: number): Pose {
  return {
    score: pose.score,
    keypoints: pose.keypoints.map(
        ({score, part, position}) => ({
          score,
          part,
          position: {x: imageWidth - 1 - position.x, y: position.y}
        }))
  };
}

export function flipPosesHorizontal(poses: Pose[], imageWidth: number) {
  if (imageWidth <= 0) {
    return poses;
  }
  return poses.map(pose => flipPoseHorizontal(pose, imageWidth));
}

export function getValidResolution(
    imageScaleFactor: number, inputDimension: number,
    outputStride: PoseNetOutputStride): number {
  const evenResolution = inputDimension * imageScaleFactor - 1;

  return evenResolution - (evenResolution % outputStride) + 1;
}

export function getInputTensorDimensions(input: PosenetInput):
    [number, number] {
  return input instanceof tf.Tensor ? [input.shape[0], input.shape[1]] :
                                      [input.height, input.width];
}

export function toInputTensor(input: PosenetInput) {
  return input instanceof tf.Tensor ? input : tf.browser.fromPixels(input);
}

export function toResizedInputTensor(
    input: PosenetInput, resizeHeight: number, resizeWidth: number,
    flipHorizontal: boolean): tf.Tensor3D {
  return tf.tidy(() => {
    const imageTensor = toInputTensor(input);

    if (flipHorizontal) {
      return imageTensor.reverse(1).resizeBilinear([resizeHeight, resizeWidth]);
    } else {
      return imageTensor.resizeBilinear([resizeHeight, resizeWidth]);
    }
  });
}

export function padAndResizeTo(
    input: PosenetInput, [targetH, targetW]: [number, number]):
    {resized: tf.Tensor3D, padding: Padding} {
  const [height, width] = getInputTensorDimensions(input);
  const targetAspect = targetW / targetH;
  const aspect = width / height;
  let [padT, padB, padL, padR] = [0, 0, 0, 0];
  if (aspect < targetAspect) {
    // pads the width
    padT = 0;
    padB = 0;
    padL = Math.round(0.5 * (targetAspect * height - width));
    padR = Math.round(0.5 * (targetAspect * height - width));
  } else {
    // pads the height
    padT = Math.round(0.5 * ((1.0 / targetAspect) * width - height));
    padB = Math.round(0.5 * ((1.0 / targetAspect) * width - height));
    padL = 0;
    padR = 0;
  }

  const resized: tf.Tensor3D = tf.tidy(() => {
    let imageTensor = toInputTensor(input);
    imageTensor = tf.pad3d(imageTensor, [[padT, padB], [padL, padR], [0, 0]]);

    return imageTensor.resizeBilinear([targetH, targetW]);
  })

  return {
    resized, padding: {top: padT, left: padL, right: padR, bottom: padB}
  }
}

export function scaleAndFlipPoses(
    poses: Pose[], [height, width]: [number, number],
    [inputResolutionHeight, inputResolutionWidth]: [number, number],
    padding: Padding, flipHorizontal: boolean): Pose[] {
  const scaleY =
      (height + padding.top + padding.bottom) / (inputResolutionHeight);
  const scaleX =
      (width + padding.left + padding.right) / (inputResolutionWidth);

  const scaledPoses =
      scalePoses(poses, scaleY, scaleX, -padding.top, -padding.left);

  if (flipHorizontal) {
    return flipPosesHorizontal(scaledPoses, width);
  } else {
    return scaledPoses;
  }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.kaazing</groupId>
    <artifactId>specification.httpxe</artifactId>
    <name>HTTP Extension and Emulation Protocol Specification</name>
    <description>Specification for HTTP Extension and Emulation protocol</description>
    <url>https://github.com/kaazing/specification.httpxe</url>
    <packaging>jar</packaging>
    <version>1.0.0-alpha-1-SNAPSHOT</version>

    <licenses>
        <license>
            <name>The Apache Software License, Version 2.0</name>
            <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
            <distribution>repo</distribution>
        </license>
    </licenses>
    <inceptionYear>2014</inceptionYear>

    <scm>
        <url>https://github.com/kaazing/specification.httpxe.git</url>
        <connection>scm:git:https://github.com/kaazing/specification.httpxe.git</connection>
    </scm>

    <properties>
        <project.build.resourceEncoding>UTF-8</project.build.resourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
    </properties>

    <distributionManagement>
        <snapshotRepository>
            <id>ossrh</id>
            <url>https://oss.sonatype.org/content/repositories/snapshots</url>
        </snapshotRepository>
        <repository>
            <id>ossrh</id>
            <url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
        </repository>
    </distributionManagement>

    <developers>
        <developer>
            <name>Kaazing Corporation</name>
            <url>https://github.com/kaazing</url>
            <organization>Kaazing Corporation</organization>
            <organizationUrl>http://kaazing.org</organizationUrl>
        </developer>
    </developers>

    <profiles>
        <profile>
            <id>release</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.sonatype.plugins</groupId>
                        <artifactId>nexus-staging-maven-plugin</artifactId>
                        <version>1.6.2</version>
                        <extensions>true</extensions>
                        <configuration>
                            <serverId>ossrh</serverId>
                            <nexusUrl>https://oss.sonatype.org/</nexusUrl>
                            <autoReleaseAfterClose>true</autoReleaseAfterClose>
                        </configuration>
                    </plugin>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-gpg-plugin</artifactId>
                        <version>1.5</version>
                        <executions>
                            <execution>
                                <id>sign-artifacts</id>
                                <phase>verify</phase>
                                <goals>
                                    <goal>sign</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>

    <dependencies>
        <dependency>
            <groupId>org.kaazing</groupId>
            <artifactId>k3po.junit</artifactId>
            <version>2.0.0-alpha-3</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>src/main/scripts</directory>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.kaazing</groupId>
                <artifactId>k3po-maven-plugin</artifactId>
                <version>2.0.0-alpha-7</version>
                <configuration>
                    <skipTests>${skipITs}</skipTests>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>start</goal>
                            <goal>stop</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <artifactId>maven-failsafe-plugin</artifactId>
                <version>2.17</version>
                <configuration>
                    <skipTests>${skipITs}</skipTests>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>integration-test</goal>
                            <goal>verify</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>


text:
package hex.glm;

import hex.FrameTask;
import hex.glm.GLMParams.Family;
import hex.glm.GLMParams.Link;
import hex.gram.Gram;

import java.util.Arrays;

import water.H2O.H2OCountedCompleter;
import water.*;
import water.fvec.Chunk;
import water.util.Utils;

/**
 * Contains all GLM related tasks.
 *
 * @author tomasnykodym
 *
 */

public abstract class GLMTask<T extends GLMTask<T>> extends FrameTask<T> {
  final protected GLMParams _glm;

  public GLMTask(Key jobKey, DataInfo dinfo, GLMParams glm){this(jobKey,dinfo,glm,null);}
  public GLMTask(Key jobKey, DataInfo dinfo, GLMParams glm,H2OCountedCompleter cmp){super(jobKey,dinfo,cmp);_glm = glm;}

  //helper function to compute eta - i.e. beta * row
  protected final double computeEta(final int ncats, final int [] cats, final int nnums, final double [] nums, final double [] beta){
    double res = 0;
    for(int i = 0; i < ncats; ++i)res += beta[cats[i]];
    final int numStart = _dinfo.numStart();
    for (int i = 0; i < nnums; ++i) res += nums[i] * beta[numStart + i];
    if(_dinfo._hasIntercept)
      res += beta[beta.length-1]; // intercept
    return res;
  }
  /**
   * Helper task to compute precise mean of response and number of observations.
   * (We skip rows with NAs, so we can't use Vec's mean in general.
   *
   * @author tomasnykodym
   *
   */
  static class YMUTask extends FrameTask<YMUTask>{
    private long []  _nobs;
    protected double [] _ymu;
    public double [] _ymin;
    public double [] _ymax;
    final int _nfolds;
    public YMUTask(Key jobKey, DataInfo dinfo,int nfolds) {this(jobKey,dinfo, nfolds, null);}
    public YMUTask(Key jobKey, DataInfo dinfo,int nfolds,  H2OCountedCompleter cmp) {
      super(jobKey,dinfo,cmp);
      _nfolds = nfolds;
    }
    @Override public void chunkInit(){
      super.chunkInit();
      _ymu = new double[_nfolds+1];
      _nobs = new long[_nfolds+1];
      _ymax = new double[_nfolds+1];
      _ymin = new double[_nfolds+1];
      Arrays.fill(_ymax,Double.NEGATIVE_INFINITY);
      Arrays.fill(_ymax,Double.POSITIVE_INFINITY);
    }
    @Override protected void processRow(long gid, double[] nums, int ncats, int[] cats, double [] responses) {
      double response = responses[0];
      _ymu[0] += response;
      ++_nobs[0];
      if(response < _ymin[0])_ymin[0] = response;
      if(response > _ymax[0])_ymax[0] = response;
      for(int i = 1; i < _nfolds+1; ++i) {
        if(gid % _nfolds == (i-1))
          continue;
        _ymu[i] += response;
        ++_nobs[i];
        if(response < _ymin[0])_ymin[i] = response;
        if(response > _ymax[i])_ymax[i] = response;
      }
    }
    @Override public void reduce(YMUTask t){
      if(t._nobs[0] != 0){
        if(_nobs[0] == 0){
          _ymu = t._ymu;
          _nobs = t._nobs;
          _ymin = t._ymin;
          _ymax = t._ymax;
        } else {
          for(int i = 0; i < _nfolds+1; ++i) {
            if(_nobs[i] + t._nobs[i] == 0)continue;
            _ymu[i] = _ymu[i] * ((double) _nobs[i] / (_nobs[i] + t._nobs[i])) + t._ymu[i] * t._nobs[i] / (_nobs[i] + t._nobs[i]);
            _nobs[i] += t._nobs[i];
            if(t._ymax[i] > _ymax[i])
              _ymax[i] = t._ymax[i];
            if(t._ymin[i] < _ymin[i])
              _ymin[i] = t._ymin[i];
          }
        }
      }
    }
    @Override protected void chunkDone(long n){
      for(int i = 0; i < _ymu.length; ++i)
        if(_nobs[i] != 0)_ymu[i] /= _nobs[i];
    }
    public double ymu(){return ymu(-1);}
    public long nobs(){return nobs(-1);}
    public double ymu(int foldId){return _ymu[foldId+1];}
    public long nobs(int foldId){return _nobs[foldId+1];}
  }

  public static class GLMLineSearchTask extends GLMTask<GLMLineSearchTask> {
    public GLMLineSearchTask(int noff, Key jobKey, DataInfo dinfo, GLMParams glm, double[] oldBeta, double[] newBeta, double betaEps, double ymu, long nobs, H2OCountedCompleter cmp) {
      super(jobKey, dinfo, glm, cmp);
      double [][] betas = new double[32][];
      double step = GLM2.LS_STEP;
      for(int i = 0; i < betas.length; ++i){
        betas[i] = MemoryManager.malloc8d(newBeta.length);
        for(int j = 0; j < oldBeta.length; ++j)
          betas[i][j] = oldBeta[j] + step*(newBeta[j] - oldBeta[j]);
        step *= GLM2.LS_STEP;
      }
      // public GLMIterationTask(Key jobKey, DataInfo dinfo, GLMParams glm, boolean computeGram, boolean validate, boolean computeGradient, double [] beta, double ymu, double reg, float [] thresholds, H2OCountedCompleter cmp) {
      _glmts = new GLMIterationTask[betas.length];
      for(int i = 0; i < _glmts.length; ++i)
        _glmts[i] = new GLMIterationTask(noff, jobKey,dinfo,glm,false,true,true,betas[i],ymu,1.0/nobs,new float[]{0} /* don't really want CMs!*/,null);
    }
    GLMIterationTask [] _glmts;
    @Override public void chunkInit(){
      _glmts = _glmts.clone();
      for(int i = 0; i < _glmts.length; ++i)
        (_glmts[i] = _glmts[i].clone()).chunkInit();
    }
    @Override public void chunkDone(long n){
      for(int i = 0; i < _glmts.length; ++i)
        _glmts[i].chunkDone(n);
    }
    @Override public void postGlobal(){
      for(int i = 0; i < _glmts.length; ++i)
        _glmts[i].postGlobal();
    }
    @Override public final void processRow(long gid, final double [] nums, final int ncats, final int [] cats, double [] responses){
      for(int i = 0; i < _glmts.length; ++i)
        _glmts[i].processRow(gid,nums,ncats,cats,responses);
    }
    @Override
    public void reduce(GLMLineSearchTask git){
      for(int i = 0; i < _glmts.length; ++i)
        _glmts[i].reduce(git._glmts[i]);
    }
  }

  public static class GLMInterceptTask extends MRTask2<GLMInterceptTask> {
    double _xy;
    double _xx;
    double _icpt;
    final double _sub;
    final double _mul;
    final GLMParams _glm;
    public GLMInterceptTask(GLMParams glm, double sub, double mul, double icpt){
      _glm = glm;
      _sub = sub;
      _mul = mul;
      _icpt = icpt ;
    }
    @Override public void map(Chunk offset, Chunk response){
      for(int i = 0; i < offset._len; ++i){
        if(offset.isNA0(i) || response.isNA0(i)) continue;
        double eta = _icpt;
        double y = response.at0(i);
        double mu = _glm.linkInv(eta+(offset.at0(i)-_sub)*_mul);
        double var = _glm.variance(mu);
        if(var < 1e-5) var = 1e-5; // avoid numerical problems with 0 variance
        double d = _glm.linkDeriv(mu);
        double w = 1.0/(var*d*d);
        double z = eta + (y-mu)*d;
        _xy += w*z;
        _xx += w;
      }
    }
    @Override public void reduce(GLMInterceptTask other){
      _xx += other._xx;
      _xy += other._xy;
    }
    @Override public  void postGlobal(){
      _icpt = _xy/_xx;
    }
  }
  /**
   * One iteration of glm, computes weighted gram matrix and t(x)*y vector and t(y)*y scalar.
   *
   * @author tomasnykodym
   */
  public static class GLMIterationTask extends GLMTask<GLMIterationTask> {
    final double [] _beta;
    protected Gram      _gram;
    double [] _xy;
    protected double [] _grad;
    double    _yy;
    GLMValidation _val; // validation of previous model
    protected final double _reg;
    long _nobs;
    final boolean _validate;
    final float [] _thresholds;
    float [][] _newThresholds;
    int [] _ti;
    final boolean _computeGradient;
    final boolean _computeGram;
    public static final int N_THRESHOLDS = 50;
    final int _noffsets;
    final double _ymu;

    public GLMIterationTask(int noff, Key jobKey, DataInfo dinfo, GLMParams glm, boolean computeGram, boolean validate, boolean computeGradient, double [] beta, double ymu, double reg, float [] thresholds, H2OCountedCompleter cmp) {
      super(jobKey, dinfo,glm,cmp);
      assert beta != null;

      _ymu = ymu;
      _noffsets = noff;
      assert beta == null || beta.length == (dinfo.fullN()+(_dinfo._hasIntercept?1:0)-_noffsets):"beta.length != dinfo.fullN(), beta = " + beta.length + " dinfo = " + dinfo.fullN() + ", noffsets = " + _noffsets;
      _beta = beta;
      _reg = reg;
      _computeGram = computeGram;
      _validate = validate;
      assert thresholds != null;
      _thresholds = _validate?thresholds:null;

      _computeGradient = computeGradient;
      assert !_computeGradient || validate;
    }

    private void sampleThresholds(int yi){
      _ti[yi] = (_newThresholds[yi].length >> 2);
      try{ Arrays.sort(_newThresholds[yi]);} catch(Throwable t){
        System.out.println("got AIOOB during sort?! ary = " + Arrays.toString(_newThresholds[yi]));
        return;
      } // sort throws AIOOB sometimes!
      for (int i = 0; i < _newThresholds.length; i += 4)
        _newThresholds[yi][i >> 2] = _newThresholds[yi][i];
    }
    @Override public void processRow(long gid, final double [] nums, final int ncats, final int [] cats, double [] responses /* time...*/){
      ++_nobs;
      double off = 0;
      for(int i = 1; i <= _noffsets; ++i)
        off += nums[nums.length-i];
      final double y = responses[0];
      assert ((_glm.family != Family.gamma) || y > 0) : "illegal response column, y must be > 0  for family = Gamma.";
      assert ((_glm.family != Family.binomial) || (0 <= y && y <= 1)) : "illegal response column, y must be <0,1>  for family=Binomial. got " + y;
      double w, eta, mu, var, z;
      final int numStart = _dinfo.numStart();
      double d = 1;
      if( _glm.family == Family.gaussian && _glm.link == Link.identity){
        w = 1;
        z = _glm.link(y);
        mu =  off + ((_validate || _computeGradient)?computeEta(ncats,cats,nums.length-_noffsets,nums,_beta):0);
      } else {
        eta = computeEta(ncats, cats,nums.length-_noffsets,nums,_beta);
        mu = _glm.linkInv(eta+off);
        var = _glm.variance(mu);
        if(var < 1e-5) var = 1e-5; // avoid numerical problems with 0 variance
        d = _glm.linkDeriv(mu);
        z = eta + (y-mu)*d;
        w = 1.0/(var*d*d);
      }
      if(_validate) {
        _val.add(y, mu);
        if(_glm.family == Family.binomial) {
          int yi = (int) y;
          if (_ti[yi] == _newThresholds[yi].length)
            sampleThresholds(yi);
          _newThresholds[yi][_ti[yi]++] = (float) mu;
        }
      }
      assert w >= 0|| Double.isNaN(w) : "invalid weight " + w; // allow NaNs - can occur if line-search is needed!
      final double wz = w * z;
      _yy += wz * z;
      if(_computeGradient || _computeGram){
        final double grad = _computeGradient?w*d*(mu-y):0;
        for(int i = 0; i < ncats; ++i){
          final int ii = cats[i];
          if(_computeGradient)_grad[ii] += grad;
          _xy[ii] += wz;
        }
        for(int i = 0; i < nums.length - _noffsets; ++i){
          _xy[numStart+i] += wz*nums[i];
          if(_computeGradient)
            _grad[numStart+i] += grad*nums[i];
        }

        if(_dinfo._hasIntercept){
          _xy[_xy.length-1] += wz;
          if(_computeGradient)
            _grad[numStart + _dinfo._nums - _noffsets] += grad;
        }
        if(_computeGram)_gram.addRow(nums, ncats, cats, w);
      }

    }
    @Override protected void chunkInit(){
      if(_computeGram)_gram = new Gram(_dinfo.fullN()-_noffsets, _dinfo.largestCat(), _dinfo._nums-_noffsets, _dinfo._cats, _dinfo._hasIntercept);
      _xy = MemoryManager.malloc8d(_dinfo.fullN()+(_dinfo._hasIntercept?1:0)-_noffsets); // + 1 is for intercept
      int rank = 0;
      if(_beta != null)for(double d:_beta)if(d != 0)++rank;
      if(_validate){
        _val = new GLMValidation(null, _glm,rank, _thresholds);
        if(_glm.family == Family.binomial){
          _ti = new int[2];
          _newThresholds = new float[2][N_THRESHOLDS << 2];
        }
      }
      if(_computeGradient)
        _grad = MemoryManager.malloc8d(_dinfo.fullN()+ (_dinfo._hasIntercept?1:0) - _noffsets);
      if(_glm.family == Family.binomial && _validate){
        _ti = new int[2];
        _newThresholds = new float[2][4*N_THRESHOLDS];
      }
    }

    @Override protected void chunkDone(long n){
      if(_computeGram)_gram.mul(_reg);
      for(int i = 0; i < _xy.length; ++i)
        _xy[i] *= _reg;
      if(_grad != null)
        for(int i = 0; i < _grad.length; ++i)
          _grad[i] *= _reg;
      _yy *= _reg;
      if(_validate && _glm.family == Family.binomial) {
        _newThresholds[0] = Arrays.copyOf(_newThresholds[0],_ti[0]);
        _newThresholds[1] = Arrays.copyOf(_newThresholds[1],_ti[1]);
        Arrays.sort(_newThresholds[0]);
        Arrays.sort(_newThresholds[1]);
      }
    }

    @Override
    public void reduce(GLMIterationTask git){
      if(_jobKey == null || Job.isRunning(_jobKey)) {
        Utils.add(_xy, git._xy);
        if (_computeGram) _gram.add(git._gram);
        _yy += git._yy;
        _nobs += git._nobs;
        if (_validate) _val.add(git._val);
        if (_computeGradient) Utils.add(_grad, git._grad);
        if(_validate && _glm.family == Family.binomial) {
          _newThresholds[0] = Utils.join(_newThresholds[0], git._newThresholds[0]);
          _newThresholds[1] = Utils.join(_newThresholds[1], git._newThresholds[1]);
          if (_newThresholds[0].length >= 2 * N_THRESHOLDS) {
            for (int i = 0; i < 2 * N_THRESHOLDS; i += 2)
              _newThresholds[0][i >> 1] = _newThresholds[0][i];
          }
          if (_newThresholds[0].length > N_THRESHOLDS)
            _newThresholds[0] = Arrays.copyOf(_newThresholds[0], N_THRESHOLDS);
          if (_newThresholds[1].length >= 2 * N_THRESHOLDS) {
            for (int i = 0; i < 2 * N_THRESHOLDS; i += 2)
              _newThresholds[1][i >> 1] = _newThresholds[1][i];
          }
          if (_newThresholds[1].length > N_THRESHOLDS)
            _newThresholds[1] = Arrays.copyOf(_newThresholds[1], N_THRESHOLDS);
        }
        super.reduce(git);
      }
    }

    @Override public void postGlobal(){
      if(_val != null){
        _val.computeAIC();
        _val.computeAUC();
      }

    }
    public double [] gradient(double alpha, double lambda){
      final double [] res = _grad.clone();
      if(_beta != null)
        for(int i = 0; i < res.length-1; ++i) res[i] += (1-alpha)*lambda*_beta[i];
      return res;
    }
  }
}


text:
By submitting a pull request, you represent that you have the right to license
your contribution to Apple and the community, and agree by submitting the patch
that your contributions are licensed under the Apache 2.0 license (see
`LICENSE.txt`).

## How to submit a bug report

Please ensure to specify the following:

* SwiftNIO commit hash
* Contextual information (e.g. what you were trying to achieve with SwiftNIO)
* Simplest possible steps to reproduce
  * More complex the steps are, lower the priority will be.
  * A pull request with failing test case is preferred, but it's just fine to paste the test case into the issue description.
* Anything that might be relevant in your opinion, such as:
  * Swift version or the output of `swift --version`
  * OS version and the output of `uname -a`
  * Network configuration

### Example

```
SwiftNIO commit hash: 22ec043dc9d24bb011b47ece4f9ee97ee5be2757

Context:
While load testing my HTTP web server written with SwiftNIO, I noticed
that one file descriptor is leaked per request.

Steps to reproduce:
1. ...
2. ...
3. ...
4. ...

$ swift --version
Swift version 4.0.2 (swift-4.0.2-RELEASE)
Target: x86_64-unknown-linux-gnu

Operating system: Ubuntu Linux 16.04 64-bit

$ uname -a
Linux beefy.machine 4.4.0-101-generic #124-Ubuntu SMP Fri Nov 10 18:29:59 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux

My system has IPv6 disabled.
```

## Writing a Patch

A good SwiftNIO patch is:

1. Concise, and contains as few changes as needed to achieve the end result.
2. Tested, ensuring that any tests provided failed before the patch and pass after it.
3. Documented, adding API documentation as needed to cover new functions and properties.
4. Accompanied by a great commit message, using our commit message template.

### Commit Message Template

We require that your commit messages match our template. The easiest way to do that is to get git to help you by explicitly using the template. To do that, `cd` to the root of our repository and run:

    git config commit.template dev/git.commit.template

### Test on Linux

SwiftNIO uses XCTest to run tests on both macOS and Linux. While the macOS version of XCTest is able to use the Objective-C runtime to discover tests at execution time, the Linux version is not. For this reason, whenever you add new tests you will want to run a script that generates the hooks needed to run those tests on Linux, or our CI will complain that the tests are not all present on Linux. To do this, merely execute `ruby scripts/generate_linux_tests.rb` at the root of the package and check the changes it made.

## How to contribute your work

Please open a pull request at https://github.com/apple/swift-nio. Make sure the CI passes, and then wait for code review.