text:
<?php

namespace FreeAgent\Bitter;

use \DateTime;
use \Exception;
use FreeAgent\Bitter\Aggregation\Aggregation;
use FreeAgent\Bitter\Aggregation\AggregationKey;
use FreeAgent\Bitter\Aggregation\AggregationKeyInterface;
use FreeAgent\Bitter\Date\DatePeriod;
use FreeAgent\Bitter\UnitOfTime\Year;
use FreeAgent\Bitter\UnitOfTime\Month;
use FreeAgent\Bitter\UnitOfTime\Week;
use FreeAgent\Bitter\UnitOfTime\Day;
use FreeAgent\Bitter\UnitOfTime\Hour;
use FreeAgent\Bitter\UnitOfTime\UnitOfTimeInterface;

/**
 * @author Jérémy Romey <jeremy@free-agent.fr>
 */
class Bitter
{
    private $redisClient;
    private $prefixKey;
    private $prefixTempKey;
    private $expireTimeout;

    public function __construct(
        $redisClient,
        $prefixKey = 'bitter:',
        $prefixTempKey = 'bitter_temp:',
        $expireTimeout = 60
    ) {
        $this->setRedisClient($redisClient);
        $this->prefixKey = $prefixKey;
        $this->prefixTempKey = $prefixTempKey;
        $this->expireTimeout = $expireTimeout;
    }

    /**
     * Get the Redis client
     *
     * @param null $client
     * @return mixed
     */
    public function getRedisClient($client = null)
    {
        if ($client) {
            return $client;
        }

        return $this->redisClient;
    }

    /**
     * Set the Redis client
     *
     * @param $redisClient
     * @return $this
     */
    public function setRedisClient($redisClient)
    {
        $this->redisClient = $redisClient;

        return $this;
    }

    /**
     * Marks an event for hours, days, weeks and months
     *
     * @param $event
     * @param integer $id An unique id, typically user id. The id should not be huge, read Redis documentation why (bitmaps)
     * @param DateTime $dateTime Which date should be used as a reference point, default is now
     * @return $this
     */
    public function mark($event, $id, DateTime $dateTime = null)
    {
        $dateTime = is_null($dateTime) ? new DateTime : $dateTime;

        $event = $event instanceof EventInterface ? $event : new Event($event, $dateTime);

        $this->getRedisClient()->pipeline(
            function ($pipe) use ($event, $id, $dateTime) {

                $now = new \DateTime();

                foreach ($event->getUnitsOfTime($dateTime) as $unit) {

                    $expires = $unit->getExpires();

                    //key will be removed immediately in such case, so why not stop it from write?
                    if ($expires && $expires instanceof DateTime && $now > $expires) {
                        continue;
                    }

                    $key = $this->hash($unit);

                    //set bit or increment score on time unit's key
                    if ($unit instanceof AggregationKeyInterface) {
                        $pipe->zincrby($key, 1.0, $id);
                    } elseif ($unit instanceof KeyInterface) {
                        $pipe->setbit($key, $id, 1);
                    } else {
                        throw new \Exception('Aggregation or Bit keys only');
                    }

                    //set expires for time unit's key, if provided
                    if ($expires) {
                        if ($expires instanceof DateTime) {
                            $pipe->expireat($key, $expires->getTimestamp());
                        } else {
                            $pipe->expire($key, $expires);
                        }
                    }

                    $pipe->sadd($this->prefixKey . 'keys', $key);
                }
            }
        );

        return $this;
    }

    /**
     * Makes it possible to see if an id has been marked
     *
     * @param  integer $id An unique id
     * @param  mixed $key The key or the event
     * @throws \Exception
     * @return boolean True if the id has been marked
     */
    public function in($id, KeyInterface $key)
    {
        if ($key instanceof AggregationKeyInterface) {
            return (bool)$this->getRedisClient()->zscore($this->hash($key), $id);
        }

        return (bool)$this->getRedisClient()->getbit($this->hash($key), $id);

    }

    /**
     * Counts the number of marks
     *
     * @param  mixed $key The key or the event
     * @param null $id
     * @throws \Exception
     * @return integer The value of the count result
     */
    public function count(KeyInterface $key, $id = null)
    {
        if ($key instanceof AggregationKeyInterface) {

            if ($id) {
                return (int)$this->getRedisClient()->zscore($this->hash($key), $id);
            }

            $aggregation = 0;
            foreach ($this->getRedisClient()->zrange($this->hash($key), 0, -1, 'WITHSCORES') as $score) {
                $aggregation += (int)$score;
            }

            return $aggregation;
        }

        return (int)$this->getRedisClient()->bitcount($this->hash($key));
    }

    private function bitOp($op, $destKey, $keyOne, $keyTwo)
    {
        $destKey = $this->hash($destKey);
        $keyOne = $this->hash($keyOne);
        $keyTwo = $this->hash($keyTwo);

        $this->getRedisClient()->bitop($op, $destKey, $keyOne, $keyTwo);
        $this->getRedisClient()->sadd($this->prefixTempKey . 'keys', $destKey);
        $this->getRedisClient()->expire($destKey, $this->expireTimeout);

        return $this;
    }

    public function bitOpAnd($destKey, $keyOne, $keyTwo)
    {
        return $this->bitOp('AND', $destKey, $keyOne, $keyTwo);
    }

    public function bitOpOr($destKey, $keyOne, $keyTwo)
    {
        return $this->bitOp('OR', $destKey, $keyOne, $keyTwo);
    }

    public function bitOpXor($destKey, $keyOne, $keyTwo)
    {
        return $this->bitOp('XOR', $destKey, $keyOne, $keyTwo);
    }

    /**
     * @param $event
     * @param Key $destKey
     * @param DateTime $from
     * @param DateTime $to
     * @return $this
     * @throws \Exception
     */
    public function bitDateRange(EventInterface $event, Key $destKey, DateTime $from, DateTime $to)
    {
        if ($from > $to) {
            throw new Exception("DateTime from (" . $from->format(
                'Y-m-d H:i:s'
            ) . ") must be anterior to DateTime to (" . $to->format('Y-m-d H:i:s') . ").");
        }

        $this->getRedisClient()->del($this->hash($destKey));

        // Hours
        $hoursFrom = DatePeriod::createForHour($from, $to, DatePeriod::CREATE_FROM);
        foreach ($hoursFrom as $date) {
            $this->bitOpOr($destKey, Hour::create($event, $date), $destKey);
        }
        $hoursTo = DatePeriod::createForHour($from, $to, DatePeriod::CREATE_TO);
        if (array_diff($hoursTo->toArray(true), $hoursFrom->toArray(true)) !== array_diff(
                $hoursFrom->toArray(true),
                $hoursTo->toArray(true)
            )
        ) {
            foreach ($hoursTo as $date) {
                $this->bitOpOr($destKey, Hour::create($event, $date), $destKey);
            }
        }

        // Days
        $daysFrom = DatePeriod::createForDay($from, $to, DatePeriod::CREATE_FROM);
        foreach ($daysFrom as $date) {
            $this->bitOpOr($destKey, Day::create($event, $date), $destKey);
        }
        $daysTo = DatePeriod::createForDay($from, $to, DatePeriod::CREATE_TO);
        if (array_diff($daysTo->toArray(true), $daysFrom->toArray(true)) !== array_diff(
                $daysFrom->toArray(true),
                $daysTo->toArray(true)
            )
        ) {
            foreach ($daysTo as $date) {
                $this->bitOpOr($destKey, Day::create($event, $date), $destKey);
            }
        }

        // Months
        $monthsFrom = DatePeriod::createForMonth($from, $to, DatePeriod::CREATE_FROM);
        foreach ($monthsFrom as $date) {
            $this->bitOpOr($destKey, Month::create($event, $date), $destKey);
        }
        $monthsTo = DatePeriod::createForMonth($from, $to, DatePeriod::CREATE_TO);
        if (array_diff($monthsTo->toArray(true), $monthsFrom->toArray(true)) !== array_diff(
                $monthsFrom->toArray(true),
                $monthsTo->toArray(true)
            )
        ) {
            foreach ($monthsTo as $date) {
                $this->bitOpOr($destKey, Month::create($event, $date), $destKey);
            }
        }

        // Years
        $years = DatePeriod::createForYear($from, $to);
        foreach ($years as $date) {
            $this->bitOpOr($destKey, Year::create($event, $date), $destKey);
        }

        $this->getRedisClient()->sadd($this->prefixTempKey . 'keys', $this->hash($destKey));
        $this->getRedisClient()->expire($this->hash($destKey), $this->expireTimeout);

        return $this;
    }

    public function aggregationDateRange($event, AggregationKey $destKey, DateTime $from, DateTime $to = null)
    {
        if (!$to) {
            $to = new DateTime();
        }
        if ($from > $to) {
            throw new Exception("DateTime from (" . $from->format(
                'Y-m-d H:i:s'
            ) . ") must be anterior to DateTime to (" . $to->format('Y-m-d H:i:s') . ").");
        }
        $rc = $this->getRedisClient();

        $rc->del($this->hash($destKey));

        $aggregation_keys = array();

        // Hours
        $hoursFrom = DatePeriod::createForHour($from, $to, DatePeriod::CREATE_FROM);
        foreach ($hoursFrom as $date) {
            $aggregation_keys[] = Aggregation::create(Hour::create($event, $date));
        }
        $hoursTo = DatePeriod::createForHour($from, $to, DatePeriod::CREATE_TO);
        if (array_diff($hoursTo->toArray(true), $hoursFrom->toArray(true)) !== array_diff(
                $hoursFrom->toArray(true),
                $hoursTo->toArray(true)
            )
        ) {
            foreach ($hoursTo as $date) {
                $aggregation_keys[] = Aggregation::create(Hour::create($event, $date));
            }
        }

        // Days
        $daysFrom = DatePeriod::createForDay($from, $to, DatePeriod::CREATE_FROM);
        foreach ($daysFrom as $date) {
            $aggregation_keys[] = Aggregation::create(Day::create($event, $date));
        }
        $daysTo = DatePeriod::createForDay($from, $to, DatePeriod::CREATE_TO);
        if (array_diff($daysTo->toArray(true), $daysFrom->toArray(true)) !== array_diff(
                $daysFrom->toArray(true),
                $daysTo->toArray(true)
            )
        ) {
            foreach ($daysTo as $date) {
                $aggregation_keys[] = Aggregation::create(Day::create($event, $date));
            }
        }

        // Months
        $monthsFrom = DatePeriod::createForMonth($from, $to, DatePeriod::CREATE_FROM);
        foreach ($monthsFrom as $date) {
            $aggregation_keys[] = Aggregation::create(Month::create($event, $date));
        }
        $monthsTo = DatePeriod::createForMonth($from, $to, DatePeriod::CREATE_TO);
        if (array_diff($monthsTo->toArray(true), $monthsFrom->toArray(true)) !== array_diff(
                $monthsFrom->toArray(true),
                $monthsTo->toArray(true)
            )
        ) {
            foreach ($monthsTo as $date) {
                $aggregation_keys[] = Aggregation::create(Month::create($event, $date));
            }
        }

        // Years
        $years = DatePeriod::createForYear($from, $to);
        foreach ($years as $date) {
            $aggregation_keys[] = Aggregation::create(Year::create($event, $date));
        }

        $arguments = array($this->hash($destKey), count($aggregation_keys));

        foreach ($aggregation_keys as $k) {
            array_push($arguments, $this->hash($k));
        }

        call_user_func_array(array($rc, 'zunionstore'), $arguments);

        $this->getRedisClient()->sadd($this->prefixTempKey . 'keys', $this->hash($destKey));
        $this->getRedisClient()->expire($this->hash($destKey), $this->expireTimeout);

        return $this;
    }

    /**
     * Returns the ids of an key or event
     *
     * @param  KeyInterface $key The key or the event
     * @param null $with_scores
     * @throws \Exception
     * @return array   The ids array
     */
    public function getIds(KeyInterface $key, $with_scores = null)
    {
        if ($key instanceof AggregationKeyInterface) {
            if (!$with_scores) {
                return $this->getRedisClient()->zrange($this->hash($key), 0, -1);
            }
            $result = array();
            foreach ($this->getRedisClient()->zrange($this->hash($key), 0, -1, 'WITHSCORES') as $member => $score) {
                $result[] = array($member,$score);
            }
            return $result;
        }

        $string = $this->getRedisClient()->get($this->hash($key));

        $data = $this->bitsetToString($string);

        $ids = array();
        while (false !== ($pos = strpos($data, '1'))) {
            $data[$pos] = 0;
            $ids[] = (int)($pos / 8) * 8 + abs(7 - ($pos % 8));
        }

        sort($ids);

        return $ids;

    }

    /**
     * Returns key's string representation
     * If $key is instance of UnitOfTimeInterface then default key prefix used,
     * otherwise temporary key prefix
     * @param KeyInterface $key
     * @return string
     */
    public function hash(KeyInterface $key)
    {
        if ($key instanceof UnitOfTimeInterface) {
            return $this->prefixKey . $key;
        }

        return $this->prefixTempKey . $key;

    }

    protected function bitsetToString($bitset = '')
    {
        return bitset_to_string($bitset);
    }

    /**
     * Removes all Bitter keys
     */
    public function removeAll()
    {
        $keys_chunk = array_chunk($this->getRedisClient()->smembers($this->prefixKey . 'keys'), 100);

        foreach ($keys_chunk as $keys) {
            $this->getRedisClient()->del($keys);
        }

        return $this;
    }

    /**
     * Removes all Bitter temp keys
     */
    public function removeTemp()
    {
        $keys_chunk = array_chunk($this->getRedisClient()->smembers($this->prefixTempKey . 'keys'), 100);

        foreach ($keys_chunk as $keys) {
            $this->getRedisClient()->del($keys);
        }

        return $this;
    }
}


text:
<!doctype html>

        <meta charset="utf-8">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <title>angular-safeguard documentation</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="icon" type="image/x-icon" href="./images/favicon.ico">
	    <link rel="stylesheet" href="./styles/style.css">

            angular-safeguard documentation
            <button type="button" class="btn btn-default btn-menu fa fa-bars" id="btn-menu"></button>

                <input type="text" placeholder="Type to search">

                        angular-safeguard documentation

                        Getting started

                                        Overview

                                  README

                                        LICENSE

                                Modules

                                    LockerModule

                            Classes

                                    Cookie

                                    CookieStorage

                                    Driver

                                    MemoryStorage

                                    PollyfillDriver

                            Injectables

                                    Locker

                                    LockerConfig

                            Interfaces

                                    ICustomStorage

                                    IDriverType

                                    IExpiryData

                                    ILockerConfig

                                    IStorage

                                    IStorageSetConfig

                                    IWebStorage

                            Miscellaneous

                                  Enums

                                  Functions

                                  Variables

                            Documentation generated using

                               angular-safeguard documentation

                                   <input type="text" placeholder="Type to search">

                               Getting started

                                               Overview

                                         README

                                               LICENSE

                                       Modules

                                           LockerModule

                                   Classes

                                           Cookie

                                           CookieStorage

                                           Driver

                                           MemoryStorage

                                           PollyfillDriver

                                   Injectables

                                           Locker

                                           LockerConfig

                                   Interfaces

                                           ICustomStorage

                                           IDriverType

                                           IExpiryData

                                           ILockerConfig

                                           IStorage

                                           IStorageSetConfig

                                           IWebStorage

                                   Miscellaneous

                                         Enums

                                         Functions

                                         Variables

                                   Documentation generated using

The MIT License (MIT)

Copyright (c) 2016-2017 Mika Kalathil

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

 results matching ""

No results matching ""

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<level-list
  xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/auto_ic_status_bar_mobile_strengh_1_night" android:maxLevel="0" />
    <item android:drawable="@drawable/auto_ic_status_bar_mobile_strengh_1_night" android:maxLevel="1" />
    <item android:drawable="@drawable/auto_ic_status_bar_mobile_strengh_2_night" android:maxLevel="2" />
    <item android:drawable="@drawable/auto_ic_status_bar_mobile_strengh_3_night" android:maxLevel="3" />
    <item android:drawable="@drawable/auto_ic_status_bar_mobile_strengh_4_night" android:maxLevel="4" />
</level-list>


text:
package connection_test

import (
	"bytes"
	"errors"
	"net"
	"net/url"

	"code.cloudfoundry.org/garden/client/connection"
	"code.cloudfoundry.org/garden/routes"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/tedsuo/rata"
)

var _ = Describe("ConnectionHijacker", func() {
	Describe("constructing hijacker with a dialer", func() {
		var hijackStreamer connection.HijackStreamer

		BeforeEach(func() {
			dialer := func(string, string) (net.Conn, error) {
				return nil, errors.New("oh no I am hijacked")
			}
			hijackStreamer = connection.NewHijackStreamerWithDialer(dialer)
		})

		Context("when Hijack is called", func() {
			It("should use the dialer", func() {
				_, _, err := hijackStreamer.Hijack(
					routes.Run,
					new(bytes.Buffer),
					rata.Params{
						"handle": "some-test-handle",
					},
					nil,
					"application/json",
				)
				Expect(err).To(MatchError("oh no I am hijacked"))
			})
		})

		Context("when Stream is called", func() {
			It("should use the dialer", func() {
				_, err := hijackStreamer.Stream(
					routes.Run,
					new(bytes.Buffer),
					rata.Params{
						"handle": "some-test-handle",
					},
					nil,
					"application/json",
				)

				pathError, ok := err.(*url.Error)
				Expect(ok).To(BeTrue())
				Expect(pathError.Err).To(MatchError("oh no I am hijacked"))
			})
		})
	})

})


text:
A dark syntax theme inspired by Xcode's Dusk theme for Atom.

# Syntax Preview

The screenshot preview also includes the following theme and packages:

- [Minimap](https://atom.io/packages/minimap)
- [File Icons](https://atom.io/packages/file-icons)
- [Spacegray Dark](https://atom.io/themes/spacegray-dark-ui)

![A preview of Dusk Syntax](https://raw.github.com/jamesejr/dusk-syntax/master/screenshots/preview.png)

# Installation

From the command line:

```
$ apm install dusk-syntax
```

Alternatively, open Atom Preferences (`cmd + ,`), select `Themes`, and search for `dusk`, then install.

Activate the theme by selecting `Dusk Syntax` from the Syntax Theme drop-down menu in the `Themes` section.

# Acknowledgments

Thanks to the following people for their hard work and contributions to the packages mentioned above.

- @cannikin
- @fundon
- @danbrooker


text:
SHARE Markov Description Generator and Tweeter
=============

Generate random bits of science text from descriptions in the SHARE notification service!

This little thing goes to the beta SHARE API endpoint located at:
https://share-dev.osf.io/api/v1/app/6qajn/

Then, gathers some descriptions...

And spits out a line of text!

Guidance from [This Article](https://realpython.com/blog/python/lyricize-a-flask-app-to-create-lyrics-using-markov-chains/) along with [this example code](https://github.com/ketaro/markov-cranberries/blob/master/markov.py) from the article.


text:
package org.apache.hadoop.hdfs.web.resources;

import com.sun.jersey.api.core.HttpContext;
import com.sun.jersey.core.spi.component.ComponentContext;
import com.sun.jersey.core.spi.component.ComponentScope;
import com.sun.jersey.server.impl.inject.AbstractHttpContextInjectable;
import com.sun.jersey.spi.inject.Injectable;
import com.sun.jersey.spi.inject.InjectableProvider;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hdfs.server.common.JspHelper;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.UserGroupInformation.AuthenticationMethod;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.core.Context;
import javax.ws.rs.ext.Provider;
import java.io.IOException;
import java.lang.reflect.Type;
import org.apache.hadoop.security.SecurityUtil;

/**
 * Inject user information to http operations.
 */
@Provider
public class UserProvider
    extends AbstractHttpContextInjectable<UserGroupInformation>
    implements InjectableProvider<Context, Type> {
  @Context
  HttpServletRequest request;
  @Context
  ServletContext servletcontext;

  @Override
  public UserGroupInformation getValue(final HttpContext context) {
    final Configuration conf =
        (Configuration) servletcontext.getAttribute(JspHelper.CURRENT_CONF);
    try {
      return JspHelper
          .getUGI(servletcontext, request, conf, AuthenticationMethod.KERBEROS,
              false);
    } catch (IOException e) {
      throw new SecurityException(
          SecurityUtil.FAILED_TO_GET_UGI_MSG_HEADER + " " + e, e);
    }
  }

  @Override
  public ComponentScope getScope() {
    return ComponentScope.PerRequest;
  }

  @Override
  public Injectable<UserGroupInformation> getInjectable(
      final ComponentContext componentContext, final Context context,
      final Type type) {
    return type.equals(UserGroupInformation.class) ? this : null;
  }
}


text:
<?php

namespace PayPal\Api;

use PayPal\Common\PayPalModel;

/**
 * End-User's preferred address.
 */
class OpenIdAddress extends PayPalModel
{

    /**
     * Full street address component, which may include house number, street name.
     *
     * @param string $street_address
     * @return self
     */
    public function setStreetAddress($street_address)
    {
        $this->street_address = $street_address;
        return $this;
    }

    /**
     * Full street address component, which may include house number, street name.
     *
     * @return string
     */
    public function getStreetAddress()
    {
        return $this->street_address;
    }

    /**
     * City or locality component.
     *
     * @param string $locality
     * @return self
     */
    public function setLocality($locality)
    {
        $this->locality = $locality;
        return $this;
    }

    /**
     * City or locality component.
     *
     * @return string
     */
    public function getLocality()
    {
        return $this->locality;
    }

    /**
     * State, province, prefecture or region component.
     *
     * @param string $region
     * @return self
     */
    public function setRegion($region)
    {
        $this->region = $region;
        return $this;
    }

    /**
     * State, province, prefecture or region component.
     *
     * @return string
     */
    public function getRegion()
    {
        return $this->region;
    }

    /**
     * Zip code or postal code component.
     *
     * @param string $postal_code
     * @return self
     */
    public function setPostalCode($postal_code)
    {
        $this->postal_code = $postal_code;
        return $this;
    }

    /**
     * Zip code or postal code component.
     *
     * @return string
     */
    public function getPostalCode()
    {
        return $this->postal_code;
    }

    /**
     * Country name component.
     *
     * @param string $country
     * @return self
     */
    public function setCountry($country)
    {
        $this->country = $country;
        return $this;
    }

    /**
     * Country name component.
     *
     * @return string
     */
    public function getCountry()
    {
        return $this->country;
    }

}


text:
local st = require"util.stanza";
local new_ip = require"util.ip".new_ip;
local new_outgoing = require"core.s2smanager".new_outgoing;
local bounce_sendq = module:depends"s2s".route_to_new_session.bounce_sendq;
local s2sout = module:depends"s2s".route_to_new_session.s2sout;

local injected = module:get_option("s2s_connect_overrides");

local function isip(addr)
	return not not (addr and addr:match("^%d+%.%d+%.%d+%.%d+$") or addr:match("^[%x:]*:[%x:]-:[%x:]*$"));
end

module:hook("route/remote", function(event)
	local from_host, to_host, stanza = event.from_host, event.to_host, event.stanza;
	local inject = injected and injected[to_host];
	if not inject then return end
	log("debug", "opening a new outgoing connection for this stanza");
	local host_session = new_outgoing(from_host, to_host);

	-- Store in buffer
	host_session.bounce_sendq = bounce_sendq;
	host_session.sendq = { {tostring(stanza), stanza.attr.type ~= "error" and stanza.attr.type ~= "result" and st.reply(stanza)} };
	log("debug", "stanza [%s] queued until connection complete", tostring(stanza.name));

	local ip_hosts, srv_hosts = {}, {};
	host_session.srv_hosts = srv_hosts;
	host_session.srv_choice = 0;

	if type(inject) == "string" then inject = { inject } end

	for _, item in ipairs(inject) do
		local host, port = item[1] or item, tonumber(item[2]) or 5269;
		if isip(host) then
			ip_hosts[#ip_hosts+1] = { ip = new_ip(host), port = port }
		else
			srv_hosts[#srv_hosts+1] = { target = host, port = port }
		end
	end
	if #ip_hosts > 0 then
		host_session.ip_hosts = ip_hosts;
		host_session.ip_choice = 0; -- Incremented by try_next_ip
		s2sout.try_next_ip(host_session);
		return true;
	end

	return s2sout.try_connect(host_session, host_session.srv_hosts[1].target, host_session.srv_hosts[1].port);
end, -2);


text:
var gulp          = require('gulp-help')(require('gulp')), // http://gulpjs.com/
    help          = require('./help.js'),
    paths         = require('./paths.js'),
    git           = require('gulp-git'),                   // https://www.npmjs.com/package/gulp-git
    runSequence   = require('run-sequence'),               // https://www.npmjs.com/package/run-sequence

    currentTime = new Date();

// Tasks ----------------------------------------------------------------------
// Add
gulp.task('git-add', help.git.add, function() {
    return gulp.src('./docs/*')
        .pipe(git.add());
});

// Commit
gulp.task('git-commit', help.git.commit, function() {
    return gulp.src('./docs/*')
        .pipe(git.commit('Deployed site on ' + currentTime));
});

// Push
gulp.task('git-push', help.git.push, function() {
    git.push('origin', 'master', function (err) {
        if (err) throw err;
    });
});

// Parent
gulp.task('git', help.git.parent, function() {
    runSequence(
        'git-add',
        'git-commit',
        'git-push'
    );
});


text:
import React, { Component, PropTypes } from 'react';
import { Grid, Button, ButtonToolbar, DropdownButton, MenuItem } from 'react-bootstrap';

import { setUrl } from '../../config/urlTools';

import {
  countryNamesMap, multiplierTextMap, layoutTextMap,
}
  from '../../config/globals';

export default class SettingsComponentComponent extends Component {
  setCircles(x) {
    const { setObject, setFilter, setRegExp, app } = this.props;
    const { filterObject, advancedMode, regExp } = app;
    setObject({ radiusMultiplier: x });
    if (advancedMode) {
      setRegExp(regExp);
    } else {
      setFilter(filterObject);
    }
  }

  changeMode(advancedMode) {
    const { setObject, setFilter, app } = this.props;
    const { country, filterObject, filterLink } = app;

    const emptyRE = new RegExp('.*', 'i');

    setObject({
      advancedMode,
      regExp: emptyRE,
    });

    // set new url
    if (this.context.router) {
      setUrl(this.context.router, country, {
        pre: Array.from(filterObject.start),
        inf: Array.from(filterObject.any),
        suf: Array.from(filterObject.end),
        lin: filterLink,
        mod: advancedMode,
        reg: emptyRE,
      });
    }

    setFilter({
      start: new Set(),
      end: new Set(),
      any: new Set(),
    });
  }

  changeWeight(circleWeighted) {
    const { setObject } = this.props;
    setObject({
      circleWeighted,
    });
  }

  chooseSource(ctry, src) {
    const { getRaw, setRaw, app, setObject } = this.props;
    const { cacheData, filterObject, filterLink, advancedMode, regExp } = app;

    // set loading state
    setObject({ country: false });

    // set new url
    if (this.context.router) {
      setUrl(this.context.router, ctry, {
        pre: Array.from(filterObject.start),
        inf: Array.from(filterObject.any),
        suf: Array.from(filterObject.end),
        lin: filterLink,
        mod: advancedMode,
        reg: regExp,
      });
    }

    // set/get new data
    if (cacheData[ctry + src]) {
      setRaw(cacheData[ctry + src], ctry, src);
    } else {
      getRaw(ctry, src);
    }
  }

  render() {
    const { app, setObject } = this.props;
    const { country, source, advancedMode, radiusMultiplier, circleWeighted, layout } = app;

    const sourceMap = new Map([
      ['OSM2', 'Stage 1 - Filtered Inhabited Places (Smallest)'],
      ['OSM1', 'Stage 2 - Inhabited Places (Large)'],
      ['OSM0', 'Stage 3 - All Places (HUGE)'],
    ]);

    const sources = [
      {
        key: 'OSM2',
        style: 'primary',
      },
      {
        key: 'OSM1',
        style: 'warning',
      },
      {
        key: 'OSM0',
        style: 'danger',
      },
    ];

    const srcbtns = [];
    sources.map(s => {
      const style = (s.key === source ? s.style : 'default');
      srcbtns.push(<MenuItem
        bsStyle={style}
        key={s.key}
        disabled={s.key === source}
        onClick={() => this.chooseSource(country, s.key)}
      >
        {sourceMap.get(s.key)}
      </MenuItem>);
      return true;
    });

    srcbtns.splice(1, 0, <MenuItem
      divider
      key={'divider'}
    />);
    srcbtns.splice(2, 0,
      <MenuItem header key={'warn'}>Note: Stage 2 & 3 can be large files</MenuItem>);

    const countries = Array.from(countryNamesMap.keys());
    const btns = [];
    countries.map(c => {
      const style = (c === country ? 'primary' : 'default');
      btns.push(<MenuItem
        bsStyle={style}
        key={c}
        disabled={country === c}
        onClick={() => this.chooseSource(c, source)}
      >
        {countryNamesMap.get(c)}
      </MenuItem>);
      return true;
    });

    const layouts = [
      ['auto'],
      [3, 9],
      [6, 6],
      [9, 3],
      [12, 12],
    ];
    const layoutBtns = [];
    layouts.map(l => {
      const lString = l.join(',');
      const layoutString = layout.join(',');
      layoutBtns.push(<MenuItem
        key={lString}
        disabled={lString === layoutString}
        onClick={() => setObject({ layout: l })}
      >
        {layoutTextMap.get(l.join(','))}
      </MenuItem>);
      return true;
    });

    let sourceStyle;
    switch (source) {
      case 'OSM2':
        sourceStyle = 'default';
        break;
      case 'OSM1':
        sourceStyle = 'warning';
        break;
      default:
        sourceStyle = 'danger';
    }

    return (
      <Grid fluid>

Settings

Data

        <ButtonToolbar>
          <DropdownButton
            id={'sb1'}
            bsStyle={'primary'}
            title={country ? `Country: ${countryNamesMap.get(country)}` :
               Loading...}
          >
            {btns}
          </DropdownButton>
          <DropdownButton
            id={'sb2'}
            bsStyle={sourceStyle}
            title={`Data: ${sourceMap.get(source)}`}
          >
            {srcbtns}
          </DropdownButton>
          <Button
            id={'sb3'}
            bsStyle={advancedMode ? 'danger' : 'default'}
            onClick={() => { this.changeMode(!advancedMode); }}
          >
            {`Mode: ${(advancedMode ? 'Advanced' : 'Standard')}`}
          </Button>
        </ButtonToolbar>

Layout

        <ButtonToolbar>
          <DropdownButton
            id={'sb4'}
            title={`Circle Size: ${multiplierTextMap.get(radiusMultiplier)}`}
            bsStyle={radiusMultiplier === 1 / 2 ? 'danger' : 'default'}
          >
            <MenuItem
              bsSize={'xsmall'}
              disabled={radiusMultiplier === 1 / 2}
              onClick={() => { this.setCircles(1 / 2); }}
            >
              S (can be slow)
            </MenuItem>
            <MenuItem
              bsSize={'xsmall'}
              disabled={radiusMultiplier === 1}
              onClick={() => { this.setCircles(1); }}
            >
              M
            </MenuItem>
            <MenuItem
              bsSize={'xsmall'}
              disabled={radiusMultiplier === 2}
              onClick={() => { this.setCircles(2); }}
            >
              L
            </MenuItem>
            <MenuItem
              bsSize={'xsmall'}
              disabled={radiusMultiplier === 4}
              onClick={() => { this.setCircles(4); }}
            >
              XL
            </MenuItem>
          </DropdownButton>
          <Button
            id={'sb6'}
            bsStyle={circleWeighted ? 'primary' : 'default'}
            onClick={() => { this.changeWeight(!circleWeighted); }}
          >
            {`Circle Size: ${(circleWeighted ? 'Weighted by Number of Places' :
              'Equally large Circles')}`}
          </Button>
          <DropdownButton
            id={'sb7'}
            title={`Layout: ${layoutTextMap.get(layout.join(','))}`}
            bsStyle={layout.join(',') !== 'auto' ? 'warning' : 'default'}
          >
            {layoutBtns}
          </DropdownButton>
        </ButtonToolbar>
      </Grid>
    );
  }
}

SettingsComponentComponent.propTypes = {
  app: PropTypes.object,
  getRaw: PropTypes.func.isRequired,
  setFilter: PropTypes.func.isRequired,
  setObject: PropTypes.func.isRequired,
  setRaw: PropTypes.func.isRequired,
  setRegExp: PropTypes.func.isRequired,
};

SettingsComponentComponent.contextTypes = {
  router: PropTypes.object,
};


text:
package org.apache.flink.connector.kafka.source.enumerator.initializer;

import org.apache.flink.annotation.Internal;

import java.util.Properties;

/**
 * Interface for validating {@link OffsetsInitializer} with properties from {@link
 * org.apache.flink.connector.kafka.source.KafkaSource}.
 */
@Internal
public interface OffsetsInitializerValidator {

    /**
     * Validate offsets initializer with properties of Kafka source.
     *
     * @param kafkaSourceProperties Properties of Kafka source
     * @throws IllegalStateException if validation fails
     */
    void validate(Properties kafkaSourceProperties) throws IllegalStateException;
}


text:
package proguard.optimize.evaluation;

import proguard.classfile.Clazz;
import proguard.classfile.attribute.CodeAttribute;
import proguard.evaluation.BasicBranchUnit;
import proguard.evaluation.value.Value;

/**
 * This BranchUnit remembers the branch unit commands that are invoked on it.
 *
 * @author Eric Lafortune
 */
class   TracedBranchUnit
extends BasicBranchUnit
{
    // Implementations for BranchUnit.

    public void branchConditionally(Clazz         clazz,
                                    CodeAttribute codeAttribute,
                                    int           offset,
                                    int           branchTarget,
                                    int           conditional)
    {
        if      (conditional == Value.ALWAYS)
        {
            // Always branch.
            super.branch(clazz, codeAttribute, offset, branchTarget);
        }
        else if (conditional != Value.NEVER)
        {
            // Maybe branch.
            super.branchConditionally(clazz, codeAttribute, offset, branchTarget, conditional);
        }
        else
        {
            super.setCalled();
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<PurchaseOrder PurchaseOrderNumber="99503" OrderDate="1999-10-20">
  <Address Type="Shipping">
    <Name>Ellen Adams</Name>
    <Street>123 Maple Street</Street>
    <City>Mill Valley</City>
    <State>CA</State>
    <Zip>10999</Zip>
    <Country>USA</Country>
  </Address>
  <Address Type="Billing">
    <Name>Tai Yee</Name>
    <Street>8 Oak Avenue</Street>
    <City>Old Town</City>
    <State>PA</State>
    <Zip>95819</Zip>
    <Country>USA</Country>
  </Address>
  <DeliveryNotes>Please leave packages in shed by driveway.</DeliveryNotes>
  <Items>
    <Item PartNumber="872-AA">
      <ProductName>Lawnmower</ProductName>
      <Quantity>1</Quantity>
      <USPrice>148.95</USPrice>
      <Comment>Confirm this is electric</Comment>
    </Item>
    <Item PartNumber="926-AA">
      <ProductName>Baby Monitor</ProductName>
      <Quantity>2</Quantity>
      <USPrice>39.98</USPrice>
      <ShipDate>1999-05-21</ShipDate>
    </Item>
  </Items>
</PurchaseOrder>


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

	<!-- 文件输出日志(DEBUG) -->
	<appender name="debug-file" class="ch.qos.logback.core.rolling.RollingFileAppender">
		<File>../logs/auth-admin/auth-admin-debug.log</File>
	    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
	      <fileNamePattern>../logs/auth-admin//history/auth-admin-debug-%d{yyyy-MM-dd}.log</fileNamePattern>
	      <maxHistory>60</maxHistory>
	    </rollingPolicy>
		<encoder charset="UTF-8">
			<Pattern>[%d{HH:mm:ss}] [%thread] |%level| %marker %logger{50} -> %X{rpid} %msg %n%ex</Pattern>
		</encoder>
	</appender>

	<!-- 文件输出日志(ERROR) -->
	<appender name="error-file" class="ch.qos.logback.core.rolling.RollingFileAppender">
		<File>../logs/auth-admin/auth-admin-error.log</File>
		<filter class="ch.qos.logback.classic.filter.LevelFilter">
	      <level>error</level>
	      <onMatch>ACCEPT</onMatch>
	      <onMismatch>DENY</onMismatch>
	    </filter>
	    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
	      <fileNamePattern>../logs/auth-admin//history/auth-admin-error-%d{yyyy-MM}.log</fileNamePattern>
	      <maxHistory>12</maxHistory>
	    </rollingPolicy>
		<encoder charset="UTF-8">
			<Pattern>[%d{dd|HH:mm:ss}] [%thread] |%level| %marker %logger{50} -> %X{rpid} %msg %n%ex</Pattern>
		</encoder>
	</appender>

	<!-- 异步输出 -->
	<appender name="async-debug-file" class="ch.qos.logback.classic.AsyncAppender">
		<discardingThreshold>0</discardingThreshold>
		<queueSize>1000</queueSize>
		<appender-ref ref="debug-file" />
	</appender>
	<appender name="async-error-file" class="ch.qos.logback.classic.AsyncAppender">
		<discardingThreshold>0</discardingThreshold>
		<queueSize>1000</queueSize>
		<appender-ref ref="error-file" />
	</appender>

	<root level="info">
		<appender-ref ref="async-debug-file" />
		<appender-ref ref="async-error-file"/>
	</root>

    <logger name="com.generic.support" level="debug" additivity="false">
		<appender-ref ref="async-debug-file" />
	</logger>

</configuration>


text:
<?php

use yii\helpers\Html;
use yii\grid\GridView;
use common\models\ThemeMenu;
/* @var $this yii\web\View */
/* @var $searchModel common\models\ThemeSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = 'Тема';
$this->params['breadcrumbs'][] = $this->title;
?>

    <?php // echo $this->render('_search', ['model' => $searchModel]);?>

        <?= Html::a('Создать тему', ['create'], ['class' => 'btn btn-success']) ?>

    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],

            'id',
            'name',
            'active',
            // 'font_size_menu',
            // 'background_color_menu',
            // 'background_color_gradient_menu_position',
            // 'background_color_gradient_menu_1',
            // 'background_color_gradient_menu_2',
            // 'background_image_menu_url:url',
            // 'opacity_background_image_menu',
            // 'border_width_menu',
            // 'border_radius_menu',
            // 'border_color_menu',
            // 'font_color_brand',
            // 'font_size_brand',
            // 'brand_url:url',
            // 'font_color_brand_focus',
            // 'font_color_brand_hover',
            // 'font_color_key_menu',
            // 'background_color_key_menu',
            // 'background_color_gradient_key_menu_position',
            // 'background_color_gradient_key_menu_1',
            // 'background_color_gradient_key_menu_2',
            // 'border_radius_key_menu',
            // 'font_color_key_menu_hover',
            // 'background_color_key_menu_hover',
            // 'background_color_gradient_key_menu_position_hover',
            // 'background_color_gradient_key_menu_1_hover',
            // 'background_color_gradient_key_menu_2_hover',
            // 'font_color_key_menu_focus',
            // 'background_color_key_menu_focus',
            // 'background_color_gradient_key_menu_position_focus',
            // 'background_color_gradient_key_menu_1_focus',
            // 'background_color_gradient_key_menu_2_focus',
            // 'font_color_key_menu_active',
            // 'background_color_key_menu_active',
            // 'background_color_gradient_key_menu_position_active',
            // 'background_color_gradient_key_menu_1_active',
            // 'background_color_gradient_key_menu_2_active',
            // 'border_color_key_toggle_menu',
            // 'border_width_key_toggle_menu',
            // 'background_color_key_toggle_menu_hover',
            // 'background_color_gradient_key_toggle_menu_position_hover',
            // 'background_color_gradient_key_toggle_menu_1_hover',
            // 'background_color_gradient_key_toggle_menu_2_hover',
            // 'background_color_key_toggle_menu_focus',
            // 'background_color_gradient_key_toggle_menu_position_focus',
            // 'background_color_gradient_key_toggle_menu_1_focus',
            // 'background_color_gradient_key_toggle_menu_2_focus',
            // 'background_color_icon_bar_key_toggle_menu',
            // 'background_color_icon_bar_key_toggle_menu_hover',
            // 'background_color_icon_bar_key_toggle_menu_focus',

            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>


text:
import { WebXRFeaturesManager, WebXRFeatureName } from "../webXRFeaturesManager";
import type { WebXRControllerPointerSelection } from "./WebXRControllerPointerSelection";
import type { WebXRSessionManager } from "../webXRSessionManager";
import type { AbstractMesh } from "../../Meshes/abstractMesh";
import { CreateSphere } from "../../Meshes/Builders/sphereBuilder";
import type { Observer } from "../../Misc/observable";
import type { WebXRInput } from "../webXRInput";
import type { WebXRInputSource } from "../webXRInputSource";
import type { Scene } from "../../scene";
import type { WebXRControllerComponent } from "../motionController/webXRControllerComponent";
import type { IndicesArray, Nullable } from "../../types";
import { Vector3, Quaternion, TmpVectors } from "../../Maths/math.vector";
import { Ray } from "../../Culling/ray";
import { PickingInfo } from "../../Collisions/pickingInfo";
import { WebXRAbstractFeature } from "./WebXRAbstractFeature";
import { UtilityLayerRenderer } from "../../Rendering/utilityLayerRenderer";
import type { WebXRAbstractMotionController } from "../motionController/webXRAbstractMotionController";
import { BoundingSphere } from "../../Culling/boundingSphere";
import type { TransformNode } from "../../Meshes/transformNode";
import { StandardMaterial } from "../../Materials/standardMaterial";
import { Color3 } from "../../Maths/math.color";
import { NodeMaterial } from "../../Materials/Node/nodeMaterial";
import type { Material } from "../../Materials/material";
import { Animation } from "../../Animations/animation";
import { QuadraticEase, EasingFunction } from "../../Animations/easing";
// side effects
import "../../Meshes/subMesh.project";

type ControllerData = {
    xrController?: WebXRInputSource;
    squeezeComponent?: WebXRControllerComponent;
    selectionComponent?: WebXRControllerComponent;
    onButtonChangedObserver?: Nullable<Observer<WebXRControllerComponent>>;
    onSqueezeButtonChangedObserver?: Nullable<Observer<WebXRControllerComponent>>;
    onFrameObserver?: Nullable<Observer<XRFrame>>;
    meshUnderPointer: Nullable<AbstractMesh>;
    nearInteractionTargetMesh: Nullable<AbstractMesh>;
    pick: Nullable<PickingInfo>;
    stalePick: Nullable<PickingInfo>;
    id: number;
    touchCollisionMesh: AbstractMesh;
    touchCollisionMeshFunction: (isTouch: boolean) => void;
    hydrateCollisionMeshFunction: (isHydration: boolean) => void;
    currentAnimationState: ControllerOrbAnimationState;
    grabRay: Ray;
    nearInteraction: boolean;
    hoverInteraction: boolean;
    grabInteraction: boolean;
    // event support
    eventListeners?: { [event in XREventType]?: (event: XRInputSourceEvent) => void };
    pickedPointVisualCue: AbstractMesh;
};

// Tracks the interaction animation state when using a motion controller with a near interaction orb
enum ControllerOrbAnimationState {
    /**
     * Orb is invisible
     */
    DEHYDRATED,
    /**
     * Orb is visible and inside the hover range
     */
    HOVER,
    /**
     * Orb is visible and touching a near interaction target
     */
    TOUCH,
}

/**
 * Where should the near interaction mesh be attached to when using a motion controller for near interaction
 */
export enum WebXRNearControllerMode {
    /**
     * Motion controllers will not support near interaction
     */
    DISABLED = 0,
    /**
     * The interaction point for motion controllers will be inside of them
     */
    CENTERED_ON_CONTROLLER = 1,
    /**
     * The interaction point for motion controllers will be in front of the controller
     */
    CENTERED_IN_FRONT = 2,
}

/**
 * Options interface for the near interaction module
 */
export interface IWebXRNearInteractionOptions {
    /**
     * If provided, this scene will be used to render meshes.
     */
    customUtilityLayerScene?: Scene;
    /**
     * Should meshes created here be added to a utility layer or the main scene
     */
    useUtilityLayer?: boolean;
    /**
     * The xr input to use with this near interaction
     */
    xrInput: WebXRInput;
    /**
     * Enable near interaction on all controllers instead of switching between them
     */
    enableNearInteractionOnAllControllers?: boolean;
    /**
     * The preferred hand to give the near interaction to. This will be prioritized when the controller initialize.
     * If switch is enabled, it will still allow the user to switch between the different controllers
     */
    preferredHandedness?: XRHandedness;
    /**
     * Disable switching the near interaction from one controller to the other.
     * If the preferred hand is set it will be fixed on this hand, and if not it will be fixed on the first controller added to the scene
     */
    disableSwitchOnClick?: boolean;

    /**
     * Far interaction feature to toggle when near interaction takes precedence
     */
    farInteractionFeature?: WebXRControllerPointerSelection;

    /**
     * Near interaction mode for motion controllers
     */
    nearInteractionControllerMode?: WebXRNearControllerMode;

    /**
     * Optional material for the motion controller orb, if enabled
     */
    motionControllerOrbMaterial?: Material;
}

/**
 * A module that will enable near interaction near interaction for hands and motion controllers of XR Input Sources
 */
export class WebXRNearInteraction extends WebXRAbstractFeature {
    private static _IdCounter = 200;

    private _tmpRay: Ray = new Ray(new Vector3(), new Vector3());

    private _attachController = (xrController: WebXRInputSource) => {
        if (this._controllers[xrController.uniqueId]) {
            // already attached
            return;
        }
        // get two new meshes
        const { touchCollisionMesh, touchCollisionMeshFunction, hydrateCollisionMeshFunction } = this._generateNewTouchPointMesh();
        const selectionMesh = this._generateVisualCue();

        this._controllers[xrController.uniqueId] = {
            xrController,
            meshUnderPointer: null,
            nearInteractionTargetMesh: null,
            pick: null,
            stalePick: null,
            touchCollisionMesh,
            touchCollisionMeshFunction: touchCollisionMeshFunction,
            hydrateCollisionMeshFunction: hydrateCollisionMeshFunction,
            currentAnimationState: ControllerOrbAnimationState.DEHYDRATED,
            grabRay: new Ray(new Vector3(), new Vector3()),
            hoverInteraction: false,
            nearInteraction: false,
            grabInteraction: false,
            id: WebXRNearInteraction._IdCounter++,
            pickedPointVisualCue: selectionMesh,
        };

        if (this._attachedController) {
            if (
                !this._options.enableNearInteractionOnAllControllers &&
                this._options.preferredHandedness &&
                xrController.inputSource.handedness === this._options.preferredHandedness
            ) {
                this._attachedController = xrController.uniqueId;
            }
        } else {
            if (!this._options.enableNearInteractionOnAllControllers) {
                this._attachedController = xrController.uniqueId;
            }
        }
        switch (xrController.inputSource.targetRayMode) {
            case "tracked-pointer":
                return this._attachNearInteractionMode(xrController);
            case "gaze":
                return null;
            case "screen":
                return null;
        }
    };

    private _controllers: {
        [controllerUniqueId: string]: ControllerData;
    } = {};
    private _scene: Scene;

    private _attachedController: string;

    private _farInteractionFeature: Nullable<WebXRControllerPointerSelection> = null;

    /**
     * The module's name
     */
    public static readonly Name = WebXRFeatureName.NEAR_INTERACTION;
    /**
     * The (Babylon) version of this module.
     * This is an integer representing the implementation version.
     * This number does not correspond to the WebXR specs version
     */
    public static readonly Version = 1;

    /**
     * default color of the selection ring
     */
    public selectionMeshDefaultColor: Color3 = new Color3(0.8, 0.8, 0.8);
    /**
     * This color will be applied to the selection ring when selection is triggered
     */
    public selectionMeshPickedColor: Color3 = new Color3(0.3, 0.3, 1.0);

    /**
     * constructs a new background remover module
     * @param _xrSessionManager the session manager for this module
     * @param _options read-only options to be used in this module
     */
    constructor(_xrSessionManager: WebXRSessionManager, private readonly _options: IWebXRNearInteractionOptions) {
        super(_xrSessionManager);
        this._scene = this._xrSessionManager.scene;
        if (this._options.nearInteractionControllerMode === undefined) {
            this._options.nearInteractionControllerMode = WebXRNearControllerMode.CENTERED_IN_FRONT;
        }

        if (this._options.farInteractionFeature) {
            this._farInteractionFeature = this._options.farInteractionFeature;
        }
    }

    /**
     * Attach this feature
     * Will usually be called by the features manager
     *
     * @returns true if successful.
     */
    public attach(): boolean {
        if (!super.attach()) {
            return false;
        }

        this._options.xrInput.controllers.forEach(this._attachController);
        this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable, this._attachController);
        this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable, (controller) => {
            // REMOVE the controller
            this._detachController(controller.uniqueId);
        });

        this._scene.constantlyUpdateMeshUnderPointer = true;
        return true;
    }

    /**
     * Detach this feature.
     * Will usually be called by the features manager
     *
     * @returns true if successful.
     */
    public detach(): boolean {
        if (!super.detach()) {
            return false;
        }

        Object.keys(this._controllers).forEach((controllerId) => {
            this._detachController(controllerId);
        });

        return true;
    }

    /**
     * Will get the mesh under a specific pointer.
     * `scene.meshUnderPointer` will only return one mesh - either left or right.
     * @param controllerId the controllerId to check
     * @returns The mesh under pointer or null if no mesh is under the pointer
     */
    public getMeshUnderPointer(controllerId: string): Nullable<AbstractMesh> {
        if (this._controllers[controllerId]) {
            return this._controllers[controllerId].meshUnderPointer;
        } else {
            return null;
        }
    }

    /**
     * Get the xr controller that correlates to the pointer id in the pointer event
     *
     * @param id the pointer id to search for
     * @returns the controller that correlates to this id or null if not found
     */
    public getXRControllerByPointerId(id: number): Nullable<WebXRInputSource> {
        const keys = Object.keys(this._controllers);

        for (let i = 0; i < keys.length; ++i) {
            if (this._controllers[keys[i]].id === id) {
                return this._controllers[keys[i]].xrController || null;
            }
        }
        return null;
    }

    /**
     * This function sets webXRControllerPointerSelection feature that will be disabled when
     * the hover range is reached for a mesh and will be reattached when not in hover range.
     * This is used to remove the selection rays when moving.
     * @param farInteractionFeature the feature to disable when finger is in hover range for a mesh
     */
    public setFarInteractionFeature(farInteractionFeature: Nullable<WebXRControllerPointerSelection>) {
        this._farInteractionFeature = farInteractionFeature;
    }

    /**
     * Filter used for near interaction pick and hover
     * @param mesh
     */
    private _nearPickPredicate(mesh: AbstractMesh): boolean {
        return mesh.isEnabled() && mesh.isVisible && mesh.isPickable && mesh.isNearPickable;
    }

    /**
     * Filter used for near interaction grab
     * @param mesh
     */
    private _nearGrabPredicate(mesh: AbstractMesh): boolean {
        return mesh.isEnabled() && mesh.isVisible && mesh.isPickable && mesh.isNearGrabbable;
    }

    /**
     * Filter used for any near interaction
     * @param mesh
     */
    private _nearInteractionPredicate(mesh: AbstractMesh): boolean {
        return mesh.isEnabled() && mesh.isVisible && mesh.isPickable && (mesh.isNearPickable || mesh.isNearGrabbable);
    }

    private _controllerAvailablePredicate(mesh: AbstractMesh, controllerId: string): boolean {
        let parent: TransformNode = mesh;

        while (parent) {
            if (parent.reservedDataStore && parent.reservedDataStore.nearInteraction && parent.reservedDataStore.nearInteraction.excludedControllerId === controllerId) {
                return false;
            }
            parent = parent.parent as TransformNode;
        }

        return true;
    }

    private _handleTransitionAnimation(controllerData: ControllerData, newState: ControllerOrbAnimationState) {
        if (
            controllerData.currentAnimationState === newState ||
            this._options.nearInteractionControllerMode !== WebXRNearControllerMode.CENTERED_IN_FRONT ||
            !!controllerData.xrController?.inputSource.hand
        ) {
            return;
        }

        // Don't always break to allow for animation fallthrough on rare cases of multi-transitions
        if (newState > controllerData.currentAnimationState) {
            switch (controllerData.currentAnimationState) {
                case ControllerOrbAnimationState.DEHYDRATED: {
                    controllerData.hydrateCollisionMeshFunction(true);
                    if (newState === ControllerOrbAnimationState.HOVER) {
                        break;
                    }
                }
                // eslint-disable-next-line no-fallthrough
                case ControllerOrbAnimationState.HOVER: {
                    controllerData.touchCollisionMeshFunction(true);
                    if (newState === ControllerOrbAnimationState.TOUCH) {
                        break;
                    }
                }
            }
        } else {
            switch (controllerData.currentAnimationState) {
                case ControllerOrbAnimationState.TOUCH: {
                    controllerData.touchCollisionMeshFunction(false);
                    if (newState === ControllerOrbAnimationState.HOVER) {
                        break;
                    }
                }
                // eslint-disable-next-line no-fallthrough
                case ControllerOrbAnimationState.HOVER: {
                    controllerData.hydrateCollisionMeshFunction(false);
                    if (newState === ControllerOrbAnimationState.DEHYDRATED) {
                        break;
                    }
                }
            }
        }

        controllerData.currentAnimationState = newState;
    }

    private readonly _hoverRadius = 0.1;
    private readonly _pickRadius = 0.02;
    private readonly _controllerPickRadius = 0.03; // The radius is slightly larger here to make it easier to manipulate since it's not tied to the hand position
    private readonly _nearGrabLengthScale = 5;

    private _processTouchPoint(id: string, position: Vector3, orientation: Quaternion) {
        const controllerData = this._controllers[id];

        // Position and orientation could be temporary values, se we take care of them before calling any functions that use temporary vectors/quaternions
        controllerData.grabRay.origin.copyFrom(position);
        orientation.toEulerAnglesToRef(TmpVectors.Vector3[0]);
        controllerData.grabRay.direction.copyFrom(TmpVectors.Vector3[0]);

        if (this._options.nearInteractionControllerMode === WebXRNearControllerMode.CENTERED_IN_FRONT && !controllerData.xrController?.inputSource.hand) {
            // offset the touch point in the direction the transform is facing
            controllerData.xrController!.getWorldPointerRayToRef(this._tmpRay);
            controllerData.grabRay.origin.addInPlace(this._tmpRay.direction.scale(0.05));
        }

        controllerData.grabRay.length = this._nearGrabLengthScale * this._hoverRadius;
        controllerData.touchCollisionMesh.position.copyFrom(controllerData.grabRay.origin);
    }

    protected _onXRFrame(_xrFrame: XRFrame) {
        Object.keys(this._controllers).forEach((id) => {
            // only do this for the selected pointer
            const controllerData = this._controllers[id];
            const handData = controllerData.xrController?.inputSource.hand;
            // If near interaction is not enabled/available for this controller, return early
            if (
                (!this._options.enableNearInteractionOnAllControllers && id !== this._attachedController) ||
                !controllerData.xrController ||
                (!handData && (!this._options.nearInteractionControllerMode || !controllerData.xrController.inputSource.gamepad))
            ) {
                controllerData.pick = null;
                return;
            }
            controllerData.hoverInteraction = false;
            controllerData.nearInteraction = false;

            // Every frame check collisions/input
            if (controllerData.xrController) {
                if (handData) {
                    const xrIndexTip = handData.get("index-finger-tip");
                    if (xrIndexTip) {
                        const indexTipPose = _xrFrame.getJointPose!(xrIndexTip, this._xrSessionManager.referenceSpace);
                        if (indexTipPose && indexTipPose.transform) {
                            const axisRHSMultiplier = this._scene.useRightHandedSystem ? 1 : -1;
                            TmpVectors.Vector3[0].set(indexTipPose.transform.position.x, indexTipPose.transform.position.y, indexTipPose.transform.position.z * axisRHSMultiplier);
                            TmpVectors.Quaternion[0].set(
                                indexTipPose.transform.orientation.x,
                                indexTipPose.transform.orientation.y,
                                indexTipPose.transform.orientation.z * axisRHSMultiplier,
                                indexTipPose.transform.orientation.w * axisRHSMultiplier
                            );

                            this._processTouchPoint(id, TmpVectors.Vector3[0], TmpVectors.Quaternion[0]);
                        }
                    }
                } else if (controllerData.xrController.inputSource.gamepad && this._options.nearInteractionControllerMode !== WebXRNearControllerMode.DISABLED) {
                    let controllerPose = controllerData.xrController.pointer;
                    if (controllerData.xrController.grip && this._options.nearInteractionControllerMode === WebXRNearControllerMode.CENTERED_ON_CONTROLLER) {
                        controllerPose = controllerData.xrController.grip;
                    }

                    this._processTouchPoint(id, controllerPose.position, controllerPose.rotationQuaternion!);
                }
            } else {
                return;
            }

            const accuratePickInfo = (originalScenePick: Nullable<PickingInfo>, utilityScenePick: Nullable<PickingInfo>): Nullable<PickingInfo> => {
                let pick = null;
                if (!utilityScenePick || !utilityScenePick.hit) {
                    // No hit in utility scene
                    pick = originalScenePick;
                } else if (!originalScenePick || !originalScenePick.hit) {
                    // No hit in original scene
                    pick = utilityScenePick;
                } else if (utilityScenePick.distance < originalScenePick.distance) {
                    // Hit is closer in utility scene
                    pick = utilityScenePick;
                } else {
                    // Hit is closer in original scene
                    pick = originalScenePick;
                }
                return pick;
            };
            const populateNearInteractionInfo = (nearInteractionInfo: Nullable<PickingInfo>): PickingInfo => {
                let result = new PickingInfo();

                let nearInteractionAtOrigin = false;
                const nearInteraction = nearInteractionInfo && nearInteractionInfo.pickedPoint && nearInteractionInfo.hit;
                if (nearInteractionInfo?.pickedPoint) {
                    nearInteractionAtOrigin = nearInteractionInfo.pickedPoint.x === 0 && nearInteractionInfo.pickedPoint.y === 0 && nearInteractionInfo.pickedPoint.z === 0;
                }
                if (nearInteraction && !nearInteractionAtOrigin) {
                    result = nearInteractionInfo!;
                }
                return result;
            };

            // Don't perform touch logic while grabbing, to prevent triggering touch interactions while in the middle of a grab interaction
            // Dont update cursor logic either - the cursor should already be visible for the grab to be in range,
            // and in order to maintain its position on the target mesh it is parented for the duration of the grab.
            if (!controllerData.grabInteraction) {
                let pick = null;

                // near interaction hover
                let utilitySceneHoverPick = null;
                if (this._options.useUtilityLayer && this._utilityLayerScene) {
                    utilitySceneHoverPick = this._pickWithSphere(controllerData, this._hoverRadius, this._utilityLayerScene, (mesh: AbstractMesh) =>
                        this._nearInteractionPredicate(mesh)
                    );
                }
                const originalSceneHoverPick = this._pickWithSphere(controllerData, this._hoverRadius, this._scene, (mesh: AbstractMesh) => this._nearInteractionPredicate(mesh));

                const hoverPickInfo = accuratePickInfo(originalSceneHoverPick, utilitySceneHoverPick);
                if (hoverPickInfo && hoverPickInfo.hit) {
                    pick = populateNearInteractionInfo(hoverPickInfo);
                    if (pick.hit) {
                        controllerData.hoverInteraction = true;
                    }
                }

                // near interaction pick
                if (controllerData.hoverInteraction) {
                    let utilitySceneNearPick = null;
                    const radius = handData ? this._pickRadius : this._controllerPickRadius;
                    if (this._options.useUtilityLayer && this._utilityLayerScene) {
                        utilitySceneNearPick = this._pickWithSphere(controllerData, radius, this._utilityLayerScene, (mesh: AbstractMesh) => this._nearPickPredicate(mesh));
                    }
                    const originalSceneNearPick = this._pickWithSphere(controllerData, radius, this._scene, (mesh: AbstractMesh) => this._nearPickPredicate(mesh));
                    const pickInfo = accuratePickInfo(originalSceneNearPick, utilitySceneNearPick);
                    const nearPick = populateNearInteractionInfo(pickInfo);
                    if (nearPick.hit) {
                        // Near pick takes precedence over hover interaction
                        pick = nearPick;
                        controllerData.nearInteraction = true;
                    }
                }

                controllerData.stalePick = controllerData.pick;
                controllerData.pick = pick;

                // Update mesh under pointer
                if (controllerData.pick && controllerData.pick.pickedPoint && controllerData.pick.hit) {
                    controllerData.meshUnderPointer = controllerData.pick.pickedMesh;
                    controllerData.pickedPointVisualCue.position.copyFrom(controllerData.pick.pickedPoint);
                    controllerData.pickedPointVisualCue.isVisible = true;

                    if (this._farInteractionFeature && this._farInteractionFeature.attached) {
                        this._farInteractionFeature._setPointerSelectionDisabledByPointerId(controllerData.id, true);
                    }
                } else {
                    controllerData.meshUnderPointer = null;
                    controllerData.pickedPointVisualCue.isVisible = false;

                    if (this._farInteractionFeature && this._farInteractionFeature.attached) {
                        this._farInteractionFeature._setPointerSelectionDisabledByPointerId(controllerData.id, false);
                    }
                }
            }

            // Update the interaction animation. Only updates if the visible touch mesh is active
            let state = ControllerOrbAnimationState.DEHYDRATED;
            if (controllerData.grabInteraction || controllerData.nearInteraction) {
                state = ControllerOrbAnimationState.TOUCH;
            } else if (controllerData.hoverInteraction) {
                state = ControllerOrbAnimationState.HOVER;
            }
            this._handleTransitionAnimation(controllerData, state);
        });
    }

    private get _utilityLayerScene() {
        return this._options.customUtilityLayerScene || UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene;
    }

    private _generateVisualCue() {
        const sceneToRenderTo = this._options.useUtilityLayer ? this._options.customUtilityLayerScene || UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene : this._scene;
        const selectionMesh = CreateSphere(
            "nearInteraction",
            {
                diameter: 0.0035 * 3,
            },
            sceneToRenderTo
        );
        selectionMesh.bakeCurrentTransformIntoVertices();
        selectionMesh.isPickable = false;
        selectionMesh.isVisible = false;
        selectionMesh.rotationQuaternion = Quaternion.Identity();
        const targetMat = new StandardMaterial("targetMat", sceneToRenderTo);
        targetMat.specularColor = Color3.Black();
        targetMat.emissiveColor = this.selectionMeshDefaultColor;
        targetMat.backFaceCulling = false;
        selectionMesh.material = targetMat;

        return selectionMesh;
    }

    private _isControllerReadyForNearInteraction(id: number) {
        if (this._farInteractionFeature) {
            return this._farInteractionFeature._getPointerSelectionDisabledByPointerId(id);
        }

        return true;
    }

    private _attachNearInteractionMode(xrController: WebXRInputSource) {
        const controllerData = this._controllers[xrController.uniqueId];
        const pointerEventInit: PointerEventInit = {
            pointerId: controllerData.id,
            pointerType: "xr-near",
        };
        controllerData.onFrameObserver = this._xrSessionManager.onXRFrameObservable.add(() => {
            if (
                (!this._options.enableNearInteractionOnAllControllers && xrController.uniqueId !== this._attachedController) ||
                !controllerData.xrController ||
                (!controllerData.xrController.inputSource.hand && (!this._options.nearInteractionControllerMode || !controllerData.xrController.inputSource.gamepad))
            ) {
                return;
            }
            if (controllerData.pick) {
                controllerData.pick.ray = controllerData.grabRay;
            }

            if (controllerData.pick && this._isControllerReadyForNearInteraction(controllerData.id)) {
                this._scene.simulatePointerMove(controllerData.pick, pointerEventInit);
            }

            // Near pick pointer event
            if (controllerData.nearInteraction && controllerData.pick && controllerData.pick.hit) {
                if (!controllerData.nearInteractionTargetMesh) {
                    this._scene.simulatePointerDown(controllerData.pick, pointerEventInit);
                    controllerData.nearInteractionTargetMesh = controllerData.meshUnderPointer;
                }
            } else if (controllerData.nearInteractionTargetMesh && controllerData.stalePick) {
                this._scene.simulatePointerUp(controllerData.stalePick, pointerEventInit);
                controllerData.nearInteractionTargetMesh = null;
            }
        });

        const grabCheck = (pressed: boolean) => {
            if (
                this._options.enableNearInteractionOnAllControllers ||
                (xrController.uniqueId === this._attachedController && this._isControllerReadyForNearInteraction(controllerData.id))
            ) {
                if (controllerData.pick) {
                    controllerData.pick.ray = controllerData.grabRay;
                }
                if (pressed && controllerData.pick && controllerData.meshUnderPointer && this._nearGrabPredicate(controllerData.meshUnderPointer)) {
                    controllerData.grabInteraction = true;
                    controllerData.pickedPointVisualCue.isVisible = false;
                    this._scene.simulatePointerDown(controllerData.pick, pointerEventInit);
                } else if (!pressed && controllerData.pick && controllerData.grabInteraction) {
                    this._scene.simulatePointerUp(controllerData.pick, pointerEventInit);
                    controllerData.grabInteraction = false;
                    controllerData.pickedPointVisualCue.isVisible = true;
                }
            } else {
                if (pressed && !this._options.enableNearInteractionOnAllControllers && !this._options.disableSwitchOnClick) {
                    this._attachedController = xrController.uniqueId;
                }
            }
        };

        if (xrController.inputSource.gamepad) {
            const init = (motionController: WebXRAbstractMotionController) => {
                controllerData.squeezeComponent = motionController.getComponent("grasp");
                if (controllerData.squeezeComponent) {
                    controllerData.onSqueezeButtonChangedObserver = controllerData.squeezeComponent.onButtonStateChangedObservable.add((component) => {
                        if (component.changes.pressed) {
                            const pressed = component.changes.pressed.current;
                            grabCheck(pressed);
                        }
                    });
                } else {
                    controllerData.selectionComponent = motionController.getMainComponent();
                    controllerData.onButtonChangedObserver = controllerData.selectionComponent.onButtonStateChangedObservable.add((component) => {
                        if (component.changes.pressed) {
                            const pressed = component.changes.pressed.current;
                            grabCheck(pressed);
                        }
                    });
                }
            };
            if (xrController.motionController) {
                init(xrController.motionController);
            } else {
                xrController.onMotionControllerInitObservable.add(init);
            }
        } else {
            // use the select and squeeze events
            const selectStartListener = (event: XRInputSourceEvent) => {
                if (
                    controllerData.xrController &&
                    event.inputSource === controllerData.xrController.inputSource &&
                    controllerData.pick &&
                    this._isControllerReadyForNearInteraction(controllerData.id) &&
                    controllerData.meshUnderPointer &&
                    this._nearGrabPredicate(controllerData.meshUnderPointer)
                ) {
                    controllerData.grabInteraction = true;
                    controllerData.pickedPointVisualCue.isVisible = false;
                    this._scene.simulatePointerDown(controllerData.pick, pointerEventInit);
                }
            };

            const selectEndListener = (event: XRInputSourceEvent) => {
                if (
                    controllerData.xrController &&
                    event.inputSource === controllerData.xrController.inputSource &&
                    controllerData.pick &&
                    this._isControllerReadyForNearInteraction(controllerData.id)
                ) {
                    this._scene.simulatePointerUp(controllerData.pick, pointerEventInit);
                    controllerData.grabInteraction = false;
                    controllerData.pickedPointVisualCue.isVisible = true;
                }
            };

            controllerData.eventListeners = {
                selectend: selectEndListener,
                selectstart: selectStartListener,
            };

            this._xrSessionManager.session.addEventListener("selectstart", selectStartListener);
            this._xrSessionManager.session.addEventListener("selectend", selectEndListener);
        }
    }

    private _detachController(xrControllerUniqueId: string) {
        const controllerData = this._controllers[xrControllerUniqueId];
        if (!controllerData) {
            return;
        }
        if (controllerData.squeezeComponent) {
            if (controllerData.onSqueezeButtonChangedObserver) {
                controllerData.squeezeComponent.onButtonStateChangedObservable.remove(controllerData.onSqueezeButtonChangedObserver);
            }
        }
        if (controllerData.selectionComponent) {
            if (controllerData.onButtonChangedObserver) {
                controllerData.selectionComponent.onButtonStateChangedObservable.remove(controllerData.onButtonChangedObserver);
            }
        }
        if (controllerData.onFrameObserver) {
            this._xrSessionManager.onXRFrameObservable.remove(controllerData.onFrameObserver);
        }
        if (controllerData.eventListeners) {
            Object.keys(controllerData.eventListeners).forEach((eventName: string) => {
                const func = controllerData.eventListeners && controllerData.eventListeners[eventName as XREventType];
                if (func) {
                    this._xrSessionManager.session.removeEventListener(eventName as XREventType, func as any);
                }
            });
        }
        controllerData.touchCollisionMesh.dispose();
        controllerData.pickedPointVisualCue.dispose();

        this._xrSessionManager.runInXRFrame(() => {
            // Fire a pointerup
            const pointerEventInit: PointerEventInit = {
                pointerId: controllerData.id,
                pointerType: "xr-near",
            };
            this._scene.simulatePointerUp(new PickingInfo(), pointerEventInit);
        });

        // remove from the map
        delete this._controllers[xrControllerUniqueId];
        if (this._attachedController === xrControllerUniqueId) {
            // check for other controllers
            const keys = Object.keys(this._controllers);
            if (keys.length) {
                this._attachedController = keys[0];
            } else {
                this._attachedController = "";
            }
        }
    }

    private _generateNewTouchPointMesh() {
        // populate information for near hover, pick and pinch
        const meshCreationScene = this._options.useUtilityLayer ? this._options.customUtilityLayerScene || UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene : this._scene;

        const touchCollisionMesh = CreateSphere("PickSphere", { diameter: 1 }, meshCreationScene);
        touchCollisionMesh.isVisible = false;

        // Generate the material for the touch mesh visuals
        if (this._options.motionControllerOrbMaterial) {
            touchCollisionMesh.material = this._options.motionControllerOrbMaterial;
        } else {
            NodeMaterial.ParseFromSnippetAsync("8RUNKL#3", meshCreationScene).then((nodeMaterial) => {
                touchCollisionMesh.material = nodeMaterial;
            });
        }

        const easingFunction = new QuadraticEase();
        easingFunction.setEasingMode(EasingFunction.EASINGMODE_EASEINOUT);

        // Adjust the visual size based off of the size of the touch collision orb.
        // Having the size perfectly match for hover gives a more accurate tell for when the user will start interacting with the target
        // Sizes for other states are somewhat arbitrary, as they are based on what feels nice during an interaction
        const hoverSizeVec = new Vector3(this._controllerPickRadius, this._controllerPickRadius, this._controllerPickRadius);
        const touchSize = this._controllerPickRadius * (4 / 3);
        const touchSizeVec = new Vector3(touchSize, touchSize, touchSize);
        const hydrateTransitionSize = this._controllerPickRadius * (7 / 6);
        const hydrateTransitionSizeVec = new Vector3(hydrateTransitionSize, hydrateTransitionSize, hydrateTransitionSize);
        const touchHoverTransitionSize = this._controllerPickRadius * (4 / 5);
        const touchHoverTransitionSizeVec = new Vector3(touchHoverTransitionSize, touchHoverTransitionSize, touchHoverTransitionSize);
        const hoverTouchTransitionSize = this._controllerPickRadius * (3 / 2);
        const hoverTouchTransitionSizeVec = new Vector3(hoverTouchTransitionSize, hoverTouchTransitionSize, hoverTouchTransitionSize);

        const touchKeys = [
            { frame: 0, value: hoverSizeVec },
            { frame: 10, value: hoverTouchTransitionSizeVec },
            { frame: 18, value: touchSizeVec },
        ];
        const releaseKeys = [
            { frame: 0, value: touchSizeVec },
            { frame: 10, value: touchHoverTransitionSizeVec },
            { frame: 18, value: hoverSizeVec },
        ];
        const hydrateKeys = [
            { frame: 0, value: Vector3.ZeroReadOnly },
            { frame: 12, value: hydrateTransitionSizeVec },
            { frame: 15, value: hoverSizeVec },
        ];
        const dehydrateKeys = [
            { frame: 0, value: hoverSizeVec },
            { frame: 10, value: Vector3.ZeroReadOnly },
            { frame: 15, value: Vector3.ZeroReadOnly },
        ];

        const touchAction = new Animation("touch", "scaling", 60, Animation.ANIMATIONTYPE_VECTOR3, Animation.ANIMATIONLOOPMODE_CONSTANT);
        const releaseAction = new Animation("release", "scaling", 60, Animation.ANIMATIONTYPE_VECTOR3, Animation.ANIMATIONLOOPMODE_CONSTANT);
        const hydrateAction = new Animation("hydrate", "scaling", 60, Animation.ANIMATIONTYPE_VECTOR3, Animation.ANIMATIONLOOPMODE_CONSTANT);
        const dehydrateAction = new Animation("dehydrate", "scaling", 60, Animation.ANIMATIONTYPE_VECTOR3, Animation.ANIMATIONLOOPMODE_CONSTANT);

        touchAction.setEasingFunction(easingFunction);
        releaseAction.setEasingFunction(easingFunction);
        hydrateAction.setEasingFunction(easingFunction);
        dehydrateAction.setEasingFunction(easingFunction);

        touchAction.setKeys(touchKeys);
        releaseAction.setKeys(releaseKeys);
        hydrateAction.setKeys(hydrateKeys);
        dehydrateAction.setKeys(dehydrateKeys);

        const touchCollisionMeshFunction = (isTouch: boolean) => {
            const action = isTouch ? touchAction : releaseAction;
            meshCreationScene.beginDirectAnimation(touchCollisionMesh, [action], 0, 18, false, 1);
        };

        const hydrateCollisionMeshFunction = (isHydration: boolean) => {
            const action = isHydration ? hydrateAction : dehydrateAction;
            if (isHydration) {
                touchCollisionMesh.isVisible = true;
            }
            meshCreationScene.beginDirectAnimation(touchCollisionMesh, [action], 0, 15, false, 1, () => {
                if (!isHydration) {
                    touchCollisionMesh.isVisible = false;
                }
            });
        };

        return { touchCollisionMesh, touchCollisionMeshFunction, hydrateCollisionMeshFunction };
    }

    private _pickWithSphere(controllerData: ControllerData, radius: number, sceneToUse: Scene, predicate: (mesh: AbstractMesh) => boolean): Nullable<PickingInfo> {
        const pickingInfo = new PickingInfo();
        pickingInfo.distance = +Infinity;

        if (controllerData.touchCollisionMesh && controllerData.xrController) {
            const position = controllerData.touchCollisionMesh.position;
            const sphere = BoundingSphere.CreateFromCenterAndRadius(position, radius);

            for (let meshIndex = 0; meshIndex < sceneToUse.meshes.length; meshIndex++) {
                const mesh = sceneToUse.meshes[meshIndex];
                if (!predicate(mesh) || !this._controllerAvailablePredicate(mesh, controllerData.xrController.uniqueId)) {
                    continue;
                }
                const result = WebXRNearInteraction.PickMeshWithSphere(mesh, sphere);

                if (result && result.hit && result.distance < pickingInfo.distance) {
                    pickingInfo.hit = result.hit;
                    pickingInfo.pickedMesh = mesh;
                    pickingInfo.pickedPoint = result.pickedPoint;
                    pickingInfo.aimTransform = controllerData.xrController.pointer;
                    pickingInfo.gripTransform = controllerData.xrController.grip || null;
                    pickingInfo.originMesh = controllerData.touchCollisionMesh;
                    pickingInfo.distance = result.distance;
                }
            }
        }
        return pickingInfo;
    }

    /**
     * Picks a mesh with a sphere
     * @param mesh the mesh to pick
     * @param sphere picking sphere in world coordinates
     * @param skipBoundingInfo a boolean indicating if we should skip the bounding info check
     * @returns the picking info
     */
    public static PickMeshWithSphere(mesh: AbstractMesh, sphere: BoundingSphere, skipBoundingInfo = false): PickingInfo {
        const subMeshes = mesh.subMeshes;
        const pi = new PickingInfo();
        const boundingInfo = mesh.getBoundingInfo();

        if (!mesh._generatePointsArray()) {
            return pi;
        }

        if (!mesh.subMeshes || !boundingInfo) {
            return pi;
        }

        if (!skipBoundingInfo && !BoundingSphere.Intersects(boundingInfo.boundingSphere, sphere)) {
            return pi;
        }

        const result = TmpVectors.Vector3[0];
        const tmpVec = TmpVectors.Vector3[1];

        let distance = +Infinity;
        let tmp, tmpDistanceSphereToCenter, tmpDistanceSurfaceToCenter;
        const center = TmpVectors.Vector3[2];
        const worldToMesh = TmpVectors.Matrix[0];
        worldToMesh.copyFrom(mesh.getWorldMatrix());
        worldToMesh.invert();
        Vector3.TransformCoordinatesToRef(sphere.center, worldToMesh, center);

        for (let index = 0; index < subMeshes.length; index++) {
            const subMesh = subMeshes[index];

            subMesh.projectToRef(center, <Vector3[]>mesh._positions, <IndicesArray>mesh.getIndices(), tmpVec);

            Vector3.TransformCoordinatesToRef(tmpVec, mesh.getWorldMatrix(), tmpVec);
            tmp = Vector3.Distance(tmpVec, sphere.center);

            // Check for finger inside of mesh
            tmpDistanceSurfaceToCenter = Vector3.Distance(tmpVec, mesh.getAbsolutePosition());
            tmpDistanceSphereToCenter = Vector3.Distance(sphere.center, mesh.getAbsolutePosition());
            if (tmpDistanceSphereToCenter !== -1 && tmpDistanceSurfaceToCenter !== -1 && tmpDistanceSurfaceToCenter > tmpDistanceSphereToCenter) {
                tmp = 0;
                tmpVec.copyFrom(sphere.center);
            }

            if (tmp !== -1 && tmp < distance) {
                distance = tmp;
                result.copyFrom(tmpVec);
            }
        }

        if (distance < sphere.radius) {
            pi.hit = true;
            pi.distance = distance;
            pi.pickedMesh = mesh;
            pi.pickedPoint = result.clone();
        }

        return pi;
    }
}

//Register the plugin
WebXRFeaturesManager.AddWebXRFeature(
    WebXRNearInteraction.Name,
    (xrSessionManager, options) => {
        return () => new WebXRNearInteraction(xrSessionManager, options);
    },
    WebXRNearInteraction.Version,
    true
);


text:
<?php

namespace G4\Runner\Exception;

use G4\Runner\Route\ErrorCodes;

class InvalidServiceException extends \Exception
{
    const MESSAGE = 'Service is not valid: %s';

    public function __construct($service)
    {
        parent::__construct(sprintf(self::MESSAGE, $service), ErrorCodes::INVALID_SERVICE);
    }
}


text:
console.log('--> navigation.js');

// Vars
var ww = window.innerWidth;

var desktopNav = $('#main-nav');
var hamburger = $('#mobile-menu');
var mobileNavWrap = $('#mobile-menu-wrap');
var mobileNav = $('#mobile-nav');
var mobileNavLi = $('#mobile-nav li');
var mobileNavBounds = $('#mobile-nav-bounds');
var mobileNavOverlap = $('#mobile-nav-overlap');

var liFlyaway = $('li.flyaway');
var liFlyawayLink = $('li.flyaway>a');

var liMobileSubmenu = $('#mobile-menu-wrap li[data-opens]');
var mobileSubmenus = $('[data-submenu]')

// Resize Function
$(window).resize(function() {

  ww = window.innerWidth;

  if(ww < 768) {
    desktopNav.attr("aria-hidden","true");
    closeNav();
    mobileNavWrap.show();
  } else {
    desktopNav.attr("aria-hidden","false");
  }

});

// Document Ready
$(document).ready(function() {
  closeNav();
  $(window).trigger('resize');
});

// Window Scroll
$(window).on('scroll', function() {

    if(hamburger.hasClass('active')) {
      closeNav();
    }

});

// Mobile Nav Menu - Global Functions
// -----------------------------------

// Close Mobile Nav
function closeNav() {

  //default
  TweenLite.to(mobileNav, .25, { x: "-270px", autoAlpha:0, ease: Power1.easeOut })
  hamburger.removeClass('active');
  hamburger.attr("aria-expanded","false");
  mobileNav.attr("aria-hidden","true");
  //close submenus
  TweenLite.to(mobileSubmenus, .2, { x: "270px", ease: Power1.easeOut });
  liMobileSubmenu.removeClass('active');
  liMobileSubmenu.find('a').attr('aria-expanded', 'false');
}

// Open Mobile Nav
function openNav() {

  TweenLite.to(mobileNav, .25, { x: 0, autoAlpha:1, ease: Power1.easeOut })
  hamburger.addClass('active');
  hamburger.attr("aria-expanded","true");
  mobileNav.attr("aria-hidden","false");
  mobileNavWrap.show();

}

// Toggle Mobile Nav (calls openNav() or closeNav()
function toggleNav() {

  // Default Action
  if(! hamburger.hasClass('active')) {
    openNav();
  } else {
    closeNav();
  }

  // Close on Document Click
  $(document).on('click', function(event) {
    if(!$(event.target).closest(hamburger).length && !$(event.target).closest(mobileNav).length && hamburger.hasClass('active')) {
      closeNav();
    }
  });

  // Close with Escape key
  $(document).keyup(function(e) {
    if (e.which === 27 && hamburger.hasClass('active')) {
      closeNav();
    }
  });

}

// Default Mobile Nav Trigger
hamburger.on('click', function() {

  toggleNav();

});

// Emulate Hover on Mobile Nav Links
mobileNavLi.mouseenter(function() {

  TweenLite.to($(this), 0.25, { background:"rgba(0,0,0,0.1)", ease: Power1.easeInOut });
  mobileNav.css('cursor','pointer');

}).mouseleave(function() {

  TweenLite.to($(this), 0.25, { background:"rgba(255,255,255,0)", ease: Power1.easeInOut });
  mobileNav.css('cursor','move');

});

// Drag Nav to Close
Draggable.create(mobileNav, {

  type:"x",
  bounds: mobileNavBounds,
  minimumMovement:5,
  throwProps:true,

    // Allow both clicking and dragging on links (<a> needs z-index:-1)
    onClick:function(e) {

      var jqueryEvent = $(e.target);
      if(jqueryEvent.is('li')) {
        var link = jqueryEvent.find('a')[0];

        link.click();

      }

    },

    onDragEnd:function() {
      if (Draggable.hitTest(mobileNav,mobileNavOverlap, 120)) {
        closeNav();
      } else {
        openNav();
      }
    }

});

// LI Flyaways (Desktop)
liFlyawayLink.each(function() {

  var self = $(this).parent();
  var linkTrigger = $(this);
  var childMenu = self.find('ul').first();

  $(this).on('click', function(e) {

     e.preventDefault();

    if(!self.hasClass('active')) {

      self.addClass('active');
      linkTrigger.attr('aria-expanded','true');

    } else {

      self.removeClass('active');
      linkTrigger.attr('aria-expanded','false');

    }

  });

});

// Mobile Submenus
liMobileSubmenu.each(function() {

  var self = $(this);
  var menuLink = self.attr('data-opens');
  var link = $(this).find('[aria-expanded]').first();
  var menu = $('[data-submenu="' + menuLink + '"]');
  var backLink = menu.find('li.back a');

  link.on('click', function() {
    if(!self.hasClass('active')) {
      TweenLite.to(menu, 0.25, { x:0, ease: Power1.easeInOut,onComplete:addClass });
      link.attr('aria-expanded', 'true');
    }
  });
  backLink.on('click', function() {
    TweenLite.to(menu, 0.25, { x:270, ease: Power1.easeInOut,onComplete:removeClass });
    link.attr('aria-expanded', 'false');
  });

  function addClass() {
    self.addClass('active');
    menu.find('.back a').focus();
  };
  function removeClass() {
    self.removeClass('active');
    link.focus();
  };
});

// Close on Document Click
$(document).on('click', function(event) {

  var linkTrigger = liFlyaway.find('a');
  var childMenu = liFlyaway.find('ul');

  if(!$(event.target).closest(liFlyaway).length) {
    liFlyaway.removeClass('active');
    linkTrigger.attr('aria-expanded','false');
  }

});


text:
package exti

const (
	RTCALR  Lines = 1 << 17 // Real Time Clock Alarm event.
	OTGFS   Lines = 1 << 18 // USB OTG FS Wakeup event.
	Ether   Lines = 1 << 19 // Ethernet Wakeup event.
	OTGHS   Lines = 1 << 20 // USB OTG HS Wakeup event.
	RTCTTS  Lines = 1 << 21 // RTC Tamper and TimeStamp events.
	RTCWKUP Lines = 1 << 22 // RTC Wakeup event.
	LPTIM1  Lines = 1 << 23 // LPTIM1 asynchronous event.
)


text:
@interface GRMustacheScopedExpression()
@property (nonatomic, retain) GRMustacheExpression *baseExpression;
@property (nonatomic, copy) NSString *scopeIdentifier;

- (id)initWithBaseExpression:(GRMustacheExpression *)baseExpression scopeIdentifier:(NSString *)scopeIdentifier;
@end

@implementation GRMustacheScopedExpression
@synthesize baseExpression=_baseExpression;
@synthesize scopeIdentifier=_scopeIdentifier;

+ (instancetype)expressionWithBaseExpression:(GRMustacheExpression *)baseExpression scopeIdentifier:(NSString *)scopeIdentifier
{
    return [[[self alloc] initWithBaseExpression:baseExpression scopeIdentifier:scopeIdentifier] autorelease];
}

- (id)initWithBaseExpression:(GRMustacheExpression *)baseExpression scopeIdentifier:(NSString *)scopeIdentifier
{
    self = [super init];
    if (self) {
        self.baseExpression = baseExpression;
        self.scopeIdentifier = scopeIdentifier;
    }
    return self;
}

- (void)dealloc
{
    [_baseExpression release];
    [_scopeIdentifier release];
    [super dealloc];
}

- (void)setToken:(GRMustacheToken *)token
{
    [super setToken:token];
    _baseExpression.token = token;
}

- (BOOL)isEqual:(id)expression
{
    if (![expression isKindOfClass:[GRMustacheScopedExpression class]]) {
        return NO;
    }
    if (![_baseExpression isEqual:((GRMustacheScopedExpression *)expression).baseExpression]) {
        return NO;
    }
    return [_scopeIdentifier isEqual:((GRMustacheScopedExpression *)expression).scopeIdentifier];
}

#pragma mark - GRMustacheExpression

- (BOOL)hasValue:(id *)value withContext:(GRMustacheContext *)context protected:(BOOL *)protected error:(NSError **)error
{
    id scopedValue;
    if (![_baseExpression hasValue:&scopedValue withContext:context protected:NULL error:error]) {
        return NO;
    }

    if (protected != NULL) {
        *protected = NO;
    }
    if (value) {
        *value = [GRMustacheContext valueForKey:_scopeIdentifier inObject:scopedValue];
    }
    return YES;
}

@end


text:
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class OptimizationTests_AutoFastJNIDetection_FunctionPointerCall_Main */

#ifndef _Included_OptimizationTests_AutoFastJNIDetection_FunctionPointerCall_Main
#define _Included_OptimizationTests_AutoFastJNIDetection_FunctionPointerCall_Main
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     OptimizationTests_AutoFastJNIDetection_FunctionPointerCall_Main
 * Method:    nativeFunctionPointerCall
 * Signature: (III)I
 */
JNIEXPORT jint JNICALL Java_OptimizationTests_AutoFastJNIDetection_FunctionPointerCall_Main_nativeFunctionPointerCall
  (JNIEnv *, jobject, jint, jint, jint);
int addInt(int, int, int);

#ifdef __cplusplus
}
#endif
#endif