text:
"""Tokenization classes for GPTNeoXJapanese."""
import collections
import json
import os
import re
from typing import TYPE_CHECKING, List, Optional, Tuple

import numpy as np

from ...tokenization_utils_fast import PreTrainedTokenizer
from ...utils import logging

if TYPE_CHECKING:
    from transformers.pipelines.conversational import Conversation

logger = logging.get_logger(__name__)

VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt", "emoji_file": "emoji.json"}

PRETRAINED_VOCAB_FILES_MAP = {
    "vocab_file": {
        "abeja/gpt-neox-japanese-2.7b": "https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/vocab.txt",
    },
    "emoji_file": {
        "abeja/gpt-neox-japanese-2.7b": "https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/emoji.json",
    },
}

PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
    "abeja/gpt-neox-japanese-2.7b": 2048,
}

def load_vocab_and_emoji(vocab_file, emoji_file):
    """Loads a vocabulary file and emoji file into a dictionary."""
    with open(emoji_file, "r", encoding="utf-8") as f:
        emoji = json.loads(f.read())

    vocab = collections.OrderedDict()
    raw_vocab = collections.OrderedDict()
    ids_to_tokens = collections.OrderedDict()
    with open(vocab_file, "r", encoding="utf-8") as f:
        token = f.readlines()
    token = [[t.rstrip("\n")] if (t == "," or "," not in t) else t.rstrip("\n").split(",") for t in token]
    for idx, b in enumerate(token):
        ids_to_tokens[idx] = b
        raw_vocab[",".join(b)] = idx
        for wd in b:
            vocab[wd] = idx

    return vocab, raw_vocab, ids_to_tokens, emoji

class GPTNeoXJapaneseTokenizer(PreTrainedTokenizer):
    """
    This tokenizer inherits from [`PreTrainedTokenizer`] and is based on Japanese special Sub-Word-Encoding that is
    used in this repository (https://github.com/tanreinama/Japanese-BPEEncoder_V2). Check the repository for details.
    Japanese has a relatively large vocabulary and there is no separation between words. Furthermore, the language is a
    combination of hiragana, katakana, and kanji, and variants such as "1" and "①" are often used. In order to cope
    with these, this tokenizer has the following features
    - Subword-by-subword segmentation, which is intermediate between byte strings and morphological analysis.
    - BPEs are created for each Kanji, Hiragana, and Katakana character, and there are no BPEs that cross character
        types, such as Kanji + Hiragana or Hiragana + Katakana.
    - All-byte encoding that does not require <unk>.
    - Independent of UTF codes such as 2-byte and 3-byte characters
    - Conversion of heterographs to the same token_id
    - Emoji and Emoticon are grouped into 12 types as special tags.

    Example:

    ```python
    >>> from transformers import GPTNeoXJapaneseTokenizer

    >>> tokenizer = GPTNeoXJapaneseTokenizer.from_pretrained("abeja/gpt-neox-japanese-2.7b")
    >>> # You can confirm both 慶応 and 慶應 are encoded to 17749
    >>> tokenizer("吾輩は猫である🐯。実は慶応(慶應)大学出身")["input_ids"]
    [30014, 26883, 26638, 27228, 25, 26650, 31732, 31679, 27809, 26638, 17749, 31592, 17749, 31593, 321, 1281]

    >>> # Both 慶応 and 慶應 are decoded to 慶応
    >>> tokenizer.decode(tokenizer("吾輩は猫である🐯。実は慶応(慶應)大学出身")["input_ids"])
    '吾輩は猫である🐯。実は慶応(慶応)大学出身'
    ```

    Args:
        vocab_file (`str`):
            File containing the vocabulary.
        emoji_file (`str`):
            File containing the emoji.
        unk_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
            The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
            token instead.
        pad_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
            The token used for padding
        bos_token (`str`, *optional*, defaults to `"<|startoftext|>"`):
            The beginning of sequence token.
        eos_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
            The end of sequence token.
        do_clean_text (`bool`, *optional*, defaults to `False`):
            Whether or not to clean text for URL, EMAIL, TEL, Japanese DATE and Japanese PRICE.
    """

    vocab_files_names = VOCAB_FILES_NAMES
    pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
    max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
    model_input_names = ["input_ids", "attention_mask"]

    def __init__(
        self,
        vocab_file,
        emoji_file,
        unk_token="<|endoftext|>",
        pad_token="<|endoftext|>",
        bos_token="<|startoftext|>",
        eos_token="<|endoftext|>",
        do_clean_text=False,
        **kwargs
    ):
        super().__init__(
            unk_token=unk_token,
            pad_token=pad_token,
            bos_token=bos_token,
            eos_token=eos_token,
            do_clean_text=do_clean_text,
            **kwargs,
        )
        if not os.path.isfile(vocab_file):
            raise ValueError(
                f"Can't find a vocabulary file at path '{vocab_file}'. To load the vocabulary from a Google pretrained"
                " model use `tokenizer = GPTNeoXJapaneseokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`"
            )
        if not os.path.isfile(emoji_file):
            raise ValueError(
                f"Can't find a emoji file at path '{emoji_file}'. To load the emoji information from a Google"
                " pretrained model use `tokenizer = GPTNeoXJapaneseokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`"
            )
        self.do_clean_text = do_clean_text
        self.vocab, self.raw_vocab, self.ids_to_tokens, self.emoji = load_vocab_and_emoji(vocab_file, emoji_file)
        self.subword_tokenizer = SubWordJapaneseTokenizer(
            vocab=self.vocab, ids_to_tokens=self.ids_to_tokens, emoji=self.emoji
        )

    @property
    def vocab_size(self):
        # self.vocab contains support for character fluctuation unique to Japanese, and has a large number of vocab
        return len(self.raw_vocab)

    def get_vocab(self):
        return dict(self.raw_vocab, **self.added_tokens_encoder)

    def _tokenize(self, text):
        return self.subword_tokenizer.tokenize(text, clean=self.do_clean_text)

    def _convert_token_to_id(self, token):
        """Converts a token (str) in an id using the vocab."""
        return self.vocab.get(token, self.vocab.get(self.unk_token))

    def _convert_id_to_token(self, index):
        """Converts an index (integer) in a token (str) using the vocab."""
        return self.subword_tokenizer.convert_id_to_token(index)

    def convert_tokens_to_string(self, tokens):
        """Converts a sequence of tokens (string) in a single string."""
        out_string = "".join(tokens).strip()
        return out_string

    def _build_conversation_input_ids(self, conversation: "Conversation") -> List[int]:
        """This corresponds to DialoGPT variants of models."""
        input_ids = []
        for is_user, text in conversation.iter_texts():
            input_ids.extend(self.encode(text, add_special_tokens=False) + [self.eos_token_id])

        if len(input_ids) > self.model_max_length:
            input_ids = input_ids[-self.model_max_length :]
        return input_ids

    def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
        index = 0
        if os.path.isdir(save_directory):
            vocab_file = os.path.join(
                save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
            )
            emoji_file = os.path.join(
                save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["emoji_file"]
            )
        else:
            vocab_file = (
                (filename_prefix + "-" if filename_prefix else "") + save_directory + VOCAB_FILES_NAMES["vocab_file"]
            )
            emoji_file = (
                (filename_prefix + "-" if filename_prefix else "") + save_directory + VOCAB_FILES_NAMES["emoji_file"]
            )
        with open(vocab_file, "w", encoding="utf-8") as writer:
            for token_index, token in self.ids_to_tokens.items():
                if index != token_index:
                    logger.warning(
                        f"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive."
                        " Please check that the vocabulary is not corrupted!"
                    )
                    index = token_index
                writer.write(",".join(token) + "\n")
                index += 1
        with open(emoji_file, "w", encoding="utf-8") as writer:
            json.dump(self.emoji, writer)
        return vocab_file, emoji_file

class SubWordJapaneseTokenizer(object):
    """
    https://github.com/tanreinama/Japanese-BPEEncoder_V2 This tokenizer class is under MIT Lisence according to the
    original repository.

    MIT License

    Copyright (c) 2020 tanreinama

    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.
    """

    def __init__(self, vocab, ids_to_tokens, emoji):
        self.vocab = vocab  # same as swe
        self.ids_to_tokens = ids_to_tokens  # same as bpe
        self.emoji = emoji
        self.maxlen = np.max([len(w) for w in self.vocab.keys()])
        self.content_repatter1 = re.compile(r"(https?|ftp)(:\/\/[-_\.!~*\'()a-zA-Z0-9;\/?:\@&=\+$,%#]+)")
        self.content_repatter2 = re.compile(r"[A-Za-z0-9\._+]*@[\-_0-9A-Za-z]+(\.[A-Za-z]+)*")
        self.content_repatter3 = re.compile(r"[\(]{0,1}[0-9]{2,4}[\)\-\(]{0,1}[0-9]{2,4}[\)\-]{0,1}[0-9]{3,4}")
        self.content_repatter4 = re.compile(
            r"([12]\d{3}[/\-年])*(0?[1-9]|1[0-2])[/\-月]((0?[1-9]|[12][0-9]|3[01])日?)*(\d{1,2}|:|\d{1,2}時|\d{1,2}分|\(日\)|\(月\)|\(火\)|\(水\)|\(木\)|\(金\)|\(土\)|㈰|㈪|㈫|㈬|㈭|㈮|㈯)*"
        )
        self.content_repatter5 = re.compile(
            r"(明治|大正|昭和|平成|令和|㍾|㍽|㍼|㍻|\u32ff)\d{1,2}年(0?[1-9]|1[0-2])月(0?[1-9]|[12][0-9]|3[01])日(\d{1,2}|:|\d{1,2}時|\d{1,2}分|\(日\)|\(月\)|\(火\)|\(水\)|\(木\)|\(金\)|\(土\)|㈰|㈪|㈫|㈬|㈭|㈮|㈯)*"
        )
        self.content_repatter6 = re.compile(
            r"((0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*億)*((0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*万)*((0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*千)*(0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*(千円|万円|千万円|円|千ドル|万ドル|千万ドル|ドル|千ユーロ|万ユーロ|千万ユーロ|ユーロ)+(\(税込\)|\(税抜\)|\+tax)*"
        )
        keisen = "─━│┃┄┅┆┇┈┉┊┋┌┍┎┏┐┑┒┓└┕┖┗┘┙┚┛├┝┞┟┠┡┢┣┤┥┦┧┨┩┪┫┬┭┮┯┰┱┲┳┴┵┶┷┸┹┺┻┼┽┾┿╀╁╂╃╄╅╆╇╈╉╊╋╌╍╎╏═║╒╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡╢╣╤╥╦╧╨╩╪╫╬╭╮╯╰╱╲╳╴╵╶╷╸╹╺╻╼╽╾╿"
        blocks = "▀▁▂▃▄▅▆▇█▉▊▋▌▍▎▏▐░▒▓▔▕▖▗▘▙▚▛▜▝▞▟"
        self.content_trans1 = str.maketrans({k: "<BLOCK>" for k in keisen + blocks})

    def __len__(self):
        return len(self.ids_to_tokens)

    def clean_text(self, content):
        content = self.content_repatter1.sub("<URL>", content)
        content = self.content_repatter2.sub("<EMAIL>", content)
        content = self.content_repatter3.sub("<TEL>", content)
        content = self.content_repatter4.sub("<DATE>", content)
        content = self.content_repatter5.sub("<DATE>", content)
        content = self.content_repatter6.sub("<PRICE>", content)
        content = content.translate(self.content_trans1)
        while "<BLOCK><BLOCK>" in content:
            content = content.replace("<BLOCK><BLOCK>", "<BLOCK>")
        return content

    def tokenize(self, text, clean=False):
        text = text.replace(" ", "<SP>")
        text = text.replace(" ", "<SP>")
        text = text.replace("\r\n", "
")
        text = text.replace("\n", "
")
        text = text.replace("\r", "
")
        text = text.replace("\t", "<TAB>")
        text = text.replace("—", "ー")
        text = text.replace("−", "ー")
        for k, v in self.emoji["emoji"].items():
            if k in text:
                text = text.replace(k, v)
        if clean:
            text = self.clean_text(text)

        def check_simbol(x):
            e = x.encode()
            if len(x) == 1 and len(e) == 2:
                c = (int(e[0]) << 8) + int(e[1])
                if (
                    (c >= 0xC2A1 and c <= 0xC2BF)
                    or (c >= 0xC780 and c <= 0xC783)
                    or (c >= 0xCAB9 and c <= 0xCBBF)
                    or (c >= 0xCC80 and c <= 0xCDA2)
                ):
                    return True
            return False

        def checku2e(x):
            e = x.encode()
            if len(x) == 1 and len(e) == 3:
                c = (int(e[0]) << 16) + (int(e[1]) << 8) + int(e[2])
                if c >= 0xE28080 and c <= 0xE2B07F:
                    return True
            return False

        pos = 0
        result = []
        while pos < len(text):
            end = min(len(text), pos + self.maxlen + 1) if text[pos] == "<" else pos + 3
            candidates = []  # (token_id, token, pos)
            for e in range(end, pos, -1):
                wd = text[pos:e]
                if wd in self.vocab:
                    if wd[0] == "<" and len(wd) > 2:
                        candidates = [(self.vocab[wd], wd, e)]
                        break
                    else:
                        candidates.append((self.vocab[wd], wd, e))
            if len(candidates) > 0:
                # the smallest token_id is adopted
                _, wd, e = sorted(candidates, key=lambda x: x[0])[0]
                result.append(wd)
                pos = e
            else:
                end = pos + 1
                wd = text[pos:end]
                if check_simbol(wd):
                    result.append("<KIGOU>")
                elif checku2e(wd):
                    result.append("<U2000U2BFF>")
                else:
                    for i in wd.encode("utf-8"):
                        result.append("<|byte%d|>" % i)
                pos = end
        return result

    def convert_id_to_token(self, index, breakline="\n"):
        words = []
        byte_tokens = []
        word = self.ids_to_tokens[index][0]
        if word[:6] == "<|byte" and word[-2:] == "|>":
            byte_tokens.append(int(word[6:-2]))
        else:
            if len(byte_tokens) > 0:
                words.append(bytearray(byte_tokens).decode("utf-8", errors="replace"))
                byte_tokens = []
            if word[:7] == "<|emoji" and word[-2:] == "|>":
                words.append(self.emoji["emoji_inv"][word])
            elif word == "<SP>":
                words.append(" ")
            elif word == "
":
                words.append(breakline)
            elif word == "<TAB>":
                words.append("\t")
            elif word == "<BLOCK>":
                words.append("▀")
            elif word == "<KIGOU>":
                words.append("ǀ")
            elif word == "<U2000U2BFF>":
                words.append("‖")
            else:
                words.append(word)
        if len(byte_tokens) > 0:
            words.append(bytearray(byte_tokens).decode("utf-8", errors="replace"))
        text = "".join(words)
        return text


text:
'use strict';
/* eslint-disable
  no-unused-vars
*/

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

module.exports = /*#__PURE__*/function () {
  function BaseClient() {
    _classCallCheck(this, BaseClient);
  }

  _createClass(BaseClient, null, [{
    key: "getClientPath",
    value: function getClientPath(options) {
      throw new Error('Client needs implementation');
    }
  }]);

  return BaseClient;
}();

redpajama_set_name: RedPajamaGithub


text:
Currently, only Ubuntu 14.04+ is officially supported as primary development environment.

There are several dependencies, that should be installed manually. The following list is the absolute minimum for building:

- `gcc` or any C99-compliant compiler (native or cross, e.g., arm-none-eabi)
- `cmake` >= `2.8.12.2`

Several scripts and tools help the building and development process, thus it is recommended to have the following installed as well:

- `bash` >= `4.3.11`
- `cppcheck` >= `1.61`
- `vera++` >= `1.2.1`
- `python` >= `2.7.6`

```bash
sudo apt-get install gcc gcc-arm-none-eabi cmake cppcheck vera++ python
```

To make our scripts run correctly, several shell utilities should be available on the system:

- `awk`
- `bc`
- `find`
- `sed`

## Building JerryScript

**To build debug version for Linux**

```bash
python tools/build.py --debug
```

**To build debug version for Linux without LTO (Link Time Optimization)**

```bash
python tools/build.py --debug --lto=off
```

**Add custom arguments to CMake**

```bash
python tools/build.py --cmake-param=CMAKE_PARAM
```

**Set a profile mode (full, minimal)**

```bash
python tools/build.py --feature=full|minimal
```

**Use (jerry, compiler-default, external) libc**

The default libc is jerry-libc, but you can use compiler-default libc or an external libc:

- compiler-default libc:

```bash
python tools/build.py --jerry-libc=off
```

- external libc:

```bash
python tools/build.py --jerry-libc=off --compile-flag="-nostdlib -I/path/to/ext-libc/include" --link-lib="ext-c"
```

**Add toolchain file**

The ```cmake``` dir already contains some usable toolchain files, which you can use in the following format:

```bash
python tools/build.py --toolchain=TOOLCHAIN
```

For example the cross-compile to RaspberryPi 2 is something like this:

```bash
python tools/build.py --toolchain=cmake/toolchain_linux_armv7l.cmake
```

**To get a list of all the available buildoptions for Linux**

```bash
python tools/build.py --help
```

## Checking patch

```bash
python tools/run-tests.py --precommit
```

### Running only one type of test

**To run build option tests**

```bash
python tools/run-tests.py --buildoption-test
```

**To run unittests**

```bash
python tools/run-tests.py --unittests
```

**To run jerry-tests**

```bash
python tools/run-tests.py --jerry-tests
```

**To run jerry-test-suite**

```bash
python tools/run-tests.py --jerry-test-suite
```

**To run signed-off check**

```bash
python tools/run-tests.py --check-signed-off
```

**To run cppcheck**

```bash
python tools/run-tests.py --check-cppcheck
```

**To run vera check**

```bash
python tools/run-tests.py --check-vera
```

**To get a list of all the available test options**

```bash
python tools/run-tests.py --help
```


text:
require 'active_support/configurable'

module Shim
  class Configuration
    include ActiveSupport::Configurable
    config_accessor :active_nav_class
  end
end


text:
## NOTE: GradleRIO-C is now a part of GradleRIO
GradleRIO now has both Java and Native (C,C++) support in the [root repository](https://github.com/Open-RIO/GradleRIO). This repository is discontinued.

------
Managing FRC C++ Projects, the Gradle way. Build, Develop and Deploy your FRC Code on any system, without the need for eclipse or administrative priviledges.

Unlike the standard FRC Development Tools, GradleRIO-C can be run on any system, even if they're locked down (like school PCs). This includes installing
the C++ toolchain (with the exception of debian linux, which requires sudo and/or `apt` access). The only requirement is the Java Virtual Machine to run Gradle itself, a Command Line, and an Internet Connection.

## Commands
_Replace `gradlew` with `./gradlew` if you're on Mac or Linux_
`gradlew install_frc_toolchain` will install the FRC C++ Toolchain, allowing you to build for the RoboRIO (note: while this is available on linux, it is best to install it yourself with the instructions [here](http://first.wpi.edu/FRC/roborio/toolchains/FRCLinuxToolchain2016.txt) as it requires sudo access)
`gradlew build` will build your FRC Code
`gradlew build deploy` will build and deploy your FRC Code. Can also be run without build as `gradlew deploy`
`gradlew restart_rio_code` will restart user code running on the RoboRIO

`gradlew clion` will generate a CMakeLists.txt file for the Clion IDE. CLion w/ GradleRIO info can be found [here](https://github.com/Open-RIO/GradleRIO-C/wiki/Using-CLion-IDE).
`gradlew cleanClion` will delete all Clion associated files (e.g. CMakeLists.txt, .idea and cmake-build-debug)

Run `gradlew tasks --all` for more information.

GradleRIO will deploy to the RoboRIO through the following preference list:
1: mDNS (`roborio-TEAM-frc.local`)
2: USB (`172.22.11.2`)
3: Static IP (`10.TE.AM.20`)
The addresses for mDNS and Static IP can be changed in the buildscript.

## Quick Start
Download the [Quick Start Sample Project](Quickstart.zip) and edit it to your own accord.
You can get examples [here](examples/). Feel free to download them into your own project.

## Custom Implementation
Put the following at the top of your `build.gradle` file
```
plugins {
    // Replace latest-version with the latest version available.
    id "jaci.openrio.cpp.gradle.GradleRIO-C" version "latest-version"
}

apply plugin: "cpp"
```
You can copy-paste this [install instruction from here](https://plugins.gradle.org/plugin/jaci.openrio.cpp.gradle.GradleRIO-C)

You can now setup your project just like any other Gradle C++ project.
You can get examples [here](examples/). Feel free to download them into your own project.

Example (barebones) `build.gradle` below.

```gradle
plugins {
    id "jaci.openrio.cpp.gradle.GradleRIO-C" version "latest-version"
}
apply plugin: "cpp"

model {
    frc {
        team = "5333"
    }
    components {
        my_program(FRCUserProgram) {                        // This is your program, my_program
            targetPlatform "roborio-arm"                    // Build on the RoboRIO
            sources.cpp {
                source.srcDirs "src"                        // Where your .cpp files are stored
                exportedHeaders.srcDirs "include"           // Where your .h / .hpp files are stored
                lib library: "wpilib", linkage: "static"    // Compile with WPILib
                lib library: "talonSrx", linkage: "static"  // Compile with TalonSrx (CTRLib)
                lib library: "navx", linkage: "static"      // Compile with NavX
            }
        }
    }
}
```

Full GradleRIO-C Spec
```gradle
plugins {
    id "jaci.openrio.cpp.gradle.GradleRIO-C" version "latest-version"
}

apply plugin: "cpp"
// You can use Visual Studio for development and Gradle for building if you so desire.
// my_programVisualStudio to generate the Visual Studio 2010+ solution file
apply plugin: "visual-studio"

model {
    frc {
        team = "5333"
        // The below options are optional. Values are the defaults
        deployTimeout = 3                   // Timeout (in seconds) when trying to find the RoboRIO on the network
        deployDirectory = "/home/lvuser"    // Directory to deploy to on the RoboRIO
        rioIP = "10.53.33.20"               // IP Address of the RoboRIO. This is automatically calculated from team number
        rioHost = "roborio-5333-frc.local"  // Hostname of the RoboRIO. This is automatically calculated from team number
        robotCommand = "./my_program"       // Script to run when booting the RoboRIO. This is automatically calculated based on the components below
        runArguments = ""                   // Arguments to add to robotCommand. No effect if robotCommand is manually set
    }

    // This block is entirely optional. If not specified, it will use the WPILib from the WPILib Maven Repository and the default options
    // NOTE: If you plan to use WPI from a Git repo, the FRC Toolchain Bin directory must be on your System PATH. If you installed
    // on linux (or without GradleRIO), this is already done. If you installed on Windows or Mac with gradlew install_frc_toolchain,
    // you must set your path before building, as WPILib's Git Repo does not look in ~/.gradle/gradlerioc/toolchain/<platform>/bin
    // for the cross-compiling toolchain
    wpi {
        git = true                          // Set to true to use Git instead of the WPI Maven (github/wpilibsuite/allwpilib)
        gitVersion = "3784b66"              // Commit, Branch or Tag to checkout before building

        eclipsePlugins = true               // Set to true to use Local WPILib instead of the WPI Maven

        local = true                        // Set to true if you want to use the WPILib libraries from a local path on your filesystem
        localDirectory = file('libs/wpi')   // Set this to where you have extracted the WPILibC Zip file (subdirs: lib, include). Must be set if local is true

        // Maven is the default provider for the WPILib library
        mavenBranch = "development"         // Set which branch of the WPILib Maven to use. By default, this is 'release'
        wpilibVersion = "2017.1.1-beta-3"     // Set which version of WPILib to use from the Maven. By default, this is '+' (latest release)
        halVersion    = "2017.1.1-beta-3"     // Set which version of the HAL to use from the Maven. By default, this is the same as mavenWpilib
        wpiutilVersion = "1.0.2"              // Set which version of WPIUtil to use from the Maven. By default, this is '+' (latest release)
        ntcoreVersion = "3.1.2"               // Set which version of NTCore to use from the Maven. By default, this is '+' (latest release)
        cscoreVersion = "0.9.1-beta-3"        // Set which version of CSCore to use from the Maven. By default, this is '+' (latest release)

        talonSrxVersion = "4.4.1.9"         // Set which version of CTRLib (Talon SRX) to use from the maven. By default, this is '+' (latest release)
        navxVersion = "3.0.323"             // Set which version of NavX to use from the maven. By default, this is '+' (latest version)
    }

    // Use this block to add libraries that have been prebuilt (i.e. device libraries, or other code)
    // If you're building a library from source, it is better to add that as a dependency or as another component.
    // If the library uses GradleRIO, use the multi_project example. If it doesn't, you can add the sources as shown
    // in the custom_library example.
    // This block is optional.
    libraries {
        some_lib(LibraryPrebuilt) {
            headers "some_lib/include"
            staticFile "some_lib/some_lib.a"
            sharedFile "some_lib/some_lib.so"
        }
    }

    components {
        // This is where you define your actual C++ binary
        my_program(FRCUserProgram) {
            targetPlatform "roborio-arm"        // Build using the RoboRIO Toolchain
            sources.cpp {
                source {
                    srcDirs "src"               // Where your .cpp files are stored
                }
                exportedHeaders {
                    srcDirs "include"           // Where your .h/.hpp files are stored
                }
                lib library: "wpilib", linkage: "static"    // Compile with WPILib
                lib library: "talonSrx", linkage: "static"  // Compile with TalonSrx
                lib library: "navx", linkage: "static"      // Compile with NavX

                lib library: "some_lib", linkage: "static"  // From our libraries {} block
            }
        }
    }
}
```

## The Windows Subsystem For Linux
GradleRIO-C supports the Windows Subsystem for Linux, a Beta feature that can be run with Windows 10. For this to work, however, you need the following requirements:
- Windows Build 14986+ (Windows Creator Update, Available now with the Windows Insider Program)
- 4GB+ Physical Memory, 4GB - 8GB Windows Pagefile

The following packages are required to be installed on WSL assuming a clean image:
- `sudo apt-get install git build-essential`
- `sudo apt-get install gcc-multilib g++-multilib`
- Java 8 update 6+ (you can get the instructions [here, just ignore the gradle part if you want to use the gradle wrapper provided](https://github.com/Microsoft/BashOnWindows/issues/196#issuecomment-225305971))

Please note that, as of current, the Windows Subsystem for Linux does **NOT** support the FRC Toolchain. This may change for the 2017 season, however using the 2016 branch is not possible. Sorry.


text:
set -ex

export NYC_TREES_TEST_DB_NAME="test_nyc_trees_$(bash -c 'echo $RANDOM')"

if [ "$SELENIUM_PLATFORM$SELENIUM_BROWSER$SELENIUM_VERSION" = "Linuxfirefox34" ]
then
  # Touchstone
  vagrant up --provision
else
  # Matrix
  vagrant up app --provision
fi

./scripts/manage.sh selenium $@


text:
#include <ros/ros.h>
#include <tf/transform_listener.h>
#include <tf/message_filter.h>
#include <message_filters/subscriber.h>
#include <tf/transform_broadcaster.h>

class HeadTransformer {

  message_filters::Subscriber<geometry_msgs::PoseStamped> point_sub_;
  tf::TransformListener tf_;
  tf::MessageFilter<geometry_msgs::PoseStamped> * tf_filter_;
  ros::NodeHandle n_;
  std::string target_frame_;

public:

  HeadTransformer() : tf_(),  target_frame_("head") {
    point_sub_.subscribe(n_, "/head/pose", 10);
    tf_filter_ = new tf::MessageFilter<geometry_msgs::PoseStamped>(point_sub_, tf_, target_frame_, 10);
    tf_filter_->registerCallback( boost::bind( &HeadTransformer::msgCallback, this, _1) );
  } ;

  //  Callback to register with tf::MessageFilter to be called when transforms are available
  void msgCallback(const boost::shared_ptr<const geometry_msgs::PoseStamped>& pose_ptr) {
    //geometry_msgs::PoseStamped pose_out;
    tf::TransformBroadcaster br;
    tf::Transform transform;

    try {
      transform.setOrigin( tf::Vector3( pose_ptr->pose.position.x, pose_ptr->pose.position.y, pose_ptr->pose.position.z) );
      transform.setRotation( tf::Quaternion( pose_ptr->pose.orientation.x, pose_ptr->pose.orientation.y, pose_ptr->pose.orientation.z, pose_ptr->pose.orientation.w) );
      //transform.setRotation( tf::Quaternion() );
      //tf_.transformPose(target_frame_, *pose_ptr, pose_out);

      /*
	printf("point of turtle 3 in frame of turtle 1 Position(x:%f y:%f z:%f)\n",
	       pose_out.pose.position.x,
	       pose_out.pose.position.y,
	       pose_out.pose.position.z);
      */
      br.sendTransform(tf::StampedTransform(transform, ros::Time::now(), "base_link", "head") );

    }
    catch (tf::TransformException &ex) {
      printf ("Failure %s\n", ex.what()); //Print exception which was caught
    }
  };

};

int main(int argc, char ** argv) {
  ros::init(argc, argv, "qbo_head_transform_node"); //Init ROS
  HeadTransformer ht; // Construct class
  ros::spin(); // Run until interupted
};


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>EnumValuesTest xref</title>
<link type="text/css" rel="stylesheet" href="../../../stylesheet.css" />

View Javadoc

1   package ml.alternet.scan;
2
3   import java.io.IOException;
4
5   import org.assertj.core.api.Assertions;
6   import org.testng.annotations.Test;
7
8   @Test
9   public class EnumValuesTest {
10
11      enum Function {
12          sin, cos, exp, ln, sqrt;
13      }
14
15      enum Argon2 {
16          argon2d, argon2i, argon2id;
17      }
18
19      enum Single {
20          justOne;
21      }
22
23      public void enumValue_Should_beScanned() throws IOException {
24          EnumValues<Function> f = EnumValues.from(Function.class);
25          System.out.println("Function = " + f);
26          Function fun =  f.nextValue(Scanner.of("cos")).get();
27
28          Assertions.assertThat(fun).isSameAs(Function.cos);
29      }
30
31      public void singleRootedEnumValue_Should_beScanned() throws IOException {
32          EnumValues<Argon2> a = EnumValues.from(Argon2.class);
33          System.out.println("Argon2 = " + a);
34          Argon2 arg =  a.nextValue(Scanner.of("argon2d")).get();
35
36          Assertions.assertThat(arg).isSameAs(Argon2.argon2d);
37      }
38
39      public void singleEnumValue_Should_beScanned() throws IOException {
40          EnumValues<Single> s = EnumValues.from(Single.class);
41          System.out.println("Single = " + s);
42          Single sin =  s.nextValue(Scanner.of("justOne")).get();
43
44          Assertions.assertThat(sin).isSameAs(Single.justOne);
45      }
46
47  }

Copyright © 2020 Alternet. All rights reserved.


text:
You can use the [environment markers](https://www.python.org/dev/peps/pep-0496/)
to achieve this in `requirements.txt` since `pip` 6.0:

```python
SomeProject==5.4; python_version < '2.7'
SomeProject; sys.platform == 'win32'
```

See also [requirement specifiers](https://pip.readthedocs.io/en/stable/reference/pip_install/#requirement-specifiers)
.

Via [StackOverflow.com](http://stackoverflow.com/a/33451105/1257318).


text:
import React from 'react';
import { Helmet } from 'react-helmet';
import { hot } from 'react-hot-loader';
import { BaseStyles } from '@primer/components';

import { PreferencesForm } from '@renderer/components';

const App = (): JSX.Element => {
  return (
    <BaseStyles>
      <Helmet title="Streaker - Preferences" />
      <PreferencesForm />
      <style
        dangerouslySetInnerHTML={{
          __html: `
            body {
              overflow: hidden;
            }
            input[type="time"]::-webkit-calendar-picker-indicator {
              display: none;
            }
          `,
        }}
      />
    </BaseStyles>
  );
};

export default hot(module)(App);


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Code Coverage for /Users/stanislavmenshykh/phalcon.local/vendor/stanislav-web/phalcon-sms-factory/src/SMSFactory/Aware/Provider.php</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="../css/bootstrap.min.css" rel="stylesheet">
  <link href="../css/style.css" rel="stylesheet">

/Users/stanislavmenshykh/phalcon.local/vendor/stanislav-web/phalcon-sms-factory/src/SMSFactory

Aware

Provider.php

Code Coverage

Classes and Traits

Functions and Methods

Lines

      Total

           100.00% covered (success)

100.00%

1 / 1

      CRAP

      Provider

           100.00% covered (success)

100.00%

1 / 1

           100.00% covered (success)

100.00%

1 / 1

      1

       call($provider)

           100.00% covered (success)

100.00%

1 / 1

      1

1
	<?php

2
	namespace SMSFactory\Aware;

3

4
	use SMSFactory\Providers;

5

6

16
	abstract class Provider

17
	{

18

19
	    /**

20
	     * Global app config container

21
	     *

22
	     * @var \Phalcon\Config $config

23
	     */

24
	    protected $config;

25

26
	    /**

27
	     * Call provider interface

28
	     *

29
	     * @param $provider

30
	     * @return mixed

31
	     */

32
	    abstract protected function call($provider);

33
	}

Legend

     Executed
     Not Executed
     Dead Code

     Generated by PHP_CodeCoverage 2.0.16 using PHP 5.5.20 and PHPUnit 4.6.4 at Wed Apr 15 9:58:11 UTC 2015.


text:
#ifndef InjectedBundleHitTestResultMediaType_h
#define InjectedBundleHitTestResultMediaType_h

namespace WebKit {

enum BundleHitTestResultMediaType {
    BundleHitTestResultMediaTypeNone,
    BundleHitTestResultMediaTypeAudio,
    BundleHitTestResultMediaTypeVideo
};

} // namespace WebKit

#endif // InjectedBundleHitTestResultMediaType_h


text:
package com.google.gwt.user.cellview.client;

import com.google.gwt.aria.client.Roles;
import com.google.gwt.cell.client.Cell;
import com.google.gwt.cell.client.Cell.Context;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.dom.client.AnchorElement;
import com.google.gwt.dom.client.BrowserEvents;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.dom.client.Style.Display;
import com.google.gwt.dom.client.Style.Overflow;
import com.google.gwt.event.logical.shared.CloseEvent;
import com.google.gwt.event.logical.shared.OpenEvent;
import com.google.gwt.event.shared.EventHandler;
import com.google.gwt.event.shared.GwtEvent;
import com.google.gwt.event.shared.GwtEvent.Type;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.i18n.client.LocaleInfo;
import com.google.gwt.safecss.shared.SafeStyles;
import com.google.gwt.safecss.shared.SafeStylesUtils;
import com.google.gwt.safehtml.client.SafeHtmlTemplates;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.user.cellview.client.CellTree.CellTreeMessages;
import com.google.gwt.user.cellview.client.HasKeyboardSelectionPolicy.KeyboardSelectionPolicy;
import com.google.gwt.user.cellview.client.LoadingStateChangeEvent.LoadingState;
import com.google.gwt.user.client.ui.UIObject;
import com.google.gwt.user.client.ui.impl.FocusImpl;
import com.google.gwt.view.client.CellPreviewEvent;
import com.google.gwt.view.client.CellPreviewEvent.Handler;
import com.google.gwt.view.client.HasData;
import com.google.gwt.view.client.ProvidesKey;
import com.google.gwt.view.client.Range;
import com.google.gwt.view.client.RangeChangeEvent;
import com.google.gwt.view.client.RowCountChangeEvent;
import com.google.gwt.view.client.SelectionModel;
import com.google.gwt.view.client.TreeViewModel;
import com.google.gwt.view.client.TreeViewModel.NodeInfo;
import com.google.gwt.aria.client.ExpandedValue;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * A view of a tree node.
 *
 * last revision : r9976
 */
// TODO(jlabanca): Convert this to be the type of the child and create lazily.
public class CellTreeNodeView<T> extends UIObject {

  interface Template extends SafeHtmlTemplates {
    @Template("
{2}
{4}

")
    SafeHtml innerDiv(SafeStyles cssString, String classes, SafeHtml image, String itemValueStyle,
        SafeHtml cellContents);

    @Template("
"
        + "
{2}

")
    SafeHtml outerDiv(SafeStyles cssString, String classes, SafeHtml content, String ariaSelected);
  }

  /**
   * The {@link com.google.gwt.view.client.HasData} used to show children. This
   * class is intentionally static because we might move it to a new
   * {@link CellTreeNodeView}, and we don't want non-static references to the
   * old {@link CellTreeNodeView}.
   *
   * @param <C> the child item type
   */
  protected static class NodeCellList<C> implements HasData<C> {

    /**
     * The view used by the NodeCellList.
     */
    protected class View implements HasDataPresenter.View<C> {

      private final Element childContainer;

      public View(Element childContainer) {
        this.childContainer = childContainer;
      }

      @Override
      public <H extends EventHandler> HandlerRegistration addHandler(H handler, Type<H> type) {
        return handlerManger.addHandler(type, handler);
      }

      public void render(SafeHtmlBuilder sb, List<C> values, int start,
          SelectionModel<? super C> selectionModel) {
        // Cache the style names that will be used for each child.
        CellTree.Style style = nodeView.tree.getStyle();
        String itemValueStyle = style.cellTreeItemValue();
        String selectedStyle = " " + style.cellTreeSelectedItem();
        String itemStyle = style.cellTreeItem();
        String itemImageValueStyle = " " + style.cellTreeItemImageValue();
        String openStyle = " " + style.cellTreeOpenItem();
        String topStyle = " " + style.cellTreeTopItem();
        String topImageValueStyle = " " + style.cellTreeTopItemImageValue();
        boolean isRootNode = nodeView.isRootNode();
        SafeHtml openImage = nodeView.tree.getOpenImageHtml(isRootNode);
        SafeHtml closedImage = nodeView.tree.getClosedImageHtml(isRootNode);
        int imageWidth = nodeView.tree.getImageWidth();
        String paddingDirection = LocaleInfo.getCurrentLocale().isRTL() ? "right" : "left";
        int paddingAmount = imageWidth * nodeView.depth;

        // Create a set of currently open nodes.
        Set<Object> openNodes = new HashSet<Object>();
        int childCount = nodeView.getChildCount();
        int end = start + values.size();
        for (int i = start; i < end && i < childCount; i++) {
          CellTreeNodeView<?> child = nodeView.getChildNode(i);
          // Ignore child nodes that are closed.
          if (child.isOpen()) {
            openNodes.add(child.getValueKey());
          }
        }

        // Render the child nodes.
        ProvidesKey<C> keyProvider = nodeInfo.getProvidesKey();
        TreeViewModel model = nodeView.tree.getTreeViewModel();
        for (int i = start; i < end; i++) {
          C value = values.get(i - start);
          Object key = keyProvider.getKey(value);
          boolean isOpen = openNodes.contains(key);

          // Outer div contains image, value, and children (when open)
          StringBuilder outerClasses = new StringBuilder(itemStyle);
          if (isOpen) {
            outerClasses.append(openStyle);
          }
          if (isRootNode) {
            outerClasses.append(topStyle);
          }
          boolean isSelected = (selectionModel != null && selectionModel.isSelected(value));
          String ariaSelected = String.valueOf(isSelected);
          if (isSelected) {
            outerClasses.append(selectedStyle);
          }

          // Inner div contains image and value
          StringBuilder innerClasses = new StringBuilder(itemStyle);
          innerClasses.append(itemImageValueStyle);
          if (isRootNode) {
            innerClasses.append(topImageValueStyle);
          }
          // Add the open/close icon.
          SafeHtml image;
          if (isOpen) {
            image = openImage;
          } else if (model.isLeaf(value)) {
            image = LEAF_IMAGE;
          } else {
            image = closedImage;
          }
          // Render cell contents
          SafeHtmlBuilder cellBuilder = new SafeHtmlBuilder();
          Context context = new Context(i, 0, key);
          cell.render(context, value, cellBuilder);
          SafeStyles innerPadding =
              SafeStylesUtils.fromTrustedString("padding-" + paddingDirection + ": " + imageWidth
                  + "px;");
          SafeHtml innerDiv =
              template.innerDiv(innerPadding, innerClasses.toString(), image, itemValueStyle,
                  cellBuilder.toSafeHtml());
          SafeStyles outerPadding =
              SafeStylesUtils.fromTrustedString("padding-" + paddingDirection + ": "
                  + paddingAmount + "px;");
          sb.append(template.outerDiv(outerPadding, outerClasses.toString(), innerDiv,
              ariaSelected));
        }
      }

      @Override
      public void replaceAllChildren(List<C> values, SelectionModel<? super C> selectionModel,
          boolean stealFocus) {
        // Render the children.
        SafeHtmlBuilder sb = new SafeHtmlBuilder();
        render(sb, values, 0, selectionModel);

        // Hide the child container so we can animate it.
        if (nodeView.tree.isAnimationEnabled()) {
          nodeView.ensureAnimationFrame().getStyle().setDisplay(Display.NONE);
        }

        // Replace the child nodes.
        nodeView.tree.isRefreshing = true;
        Map<Object, CellTreeNodeView<?>> savedViews = saveChildState(values, 0);
        AbstractHasData.replaceAllChildren(nodeView.tree, childContainer, sb.toSafeHtml());
        nodeView.tree.isRefreshing = false;

        // Trim the list of children.
        int size = values.size();
        int childCount = nodeView.children.size();
        while (childCount > size) {
          childCount--;
          CellTreeNodeView<?> deleted = nodeView.children.remove(childCount);
          deleted.cleanup(true);
        }

        // Reattach the open nodes.
        loadChildState(values, 0, savedViews);

        // If this is the root node, move keyboard focus to the first child.
        if (nodeView.isRootNode() && nodeView.tree.getKeyboardSelectedNode() == nodeView
            && values.size() > 0) {
          nodeView.tree.keyboardSelect(nodeView.children.get(0), false);
        }

        // Animate the child container open.
        if (nodeView.tree.isAnimationEnabled()) {
          nodeView.tree.maybeAnimateTreeNode(nodeView);
        }
      }

      @Override
      public void replaceChildren(List<C> values, int start,
          SelectionModel<? super C> selectionModel, boolean stealFocus) {
        // Render the children.
        SafeHtmlBuilder sb = new SafeHtmlBuilder();
        render(sb, values, 0, selectionModel);

        Map<Object, CellTreeNodeView<?>> savedViews = saveChildState(values, start);

        nodeView.tree.isRefreshing = true;
        SafeHtml html = sb.toSafeHtml();
        Element newChildren = AbstractHasData.convertToElements(nodeView.tree, getTmpElem(), html);
        AbstractHasData
            .replaceChildren(nodeView.tree, childContainer, newChildren, start, html);
        nodeView.tree.isRefreshing = false;

        loadChildState(values, start, savedViews);
      }

      @Override
      public void resetFocus() {
        nodeView.tree.resetFocus();
      }

      @Override
      public void setKeyboardSelected(int index, boolean selected, boolean stealFocus) {
        // Keyboard selection is handled by CellTree.
        Element elem = childContainer.getChild(index).cast();
        setStyleName(getSelectionElement(elem), nodeView.tree.getStyle()
            .cellTreeKeyboardSelectedItem(), selected);
      }

      @Override
      public void setLoadingState(LoadingState state) {
        nodeView.updateImage(state == LoadingState.LOADING);
        showOrHide(nodeView.emptyMessageElem, state == LoadingState.LOADED && presenter.isEmpty());
      }

      /**
       * Reload the open children after rendering new items in this node.
       *
       * @param values the values being replaced
       * @param start the start index
       * @param savedViews the open nodes
       */
      private void loadChildState(List<C> values, int start,
          Map<Object, CellTreeNodeView<?>> savedViews) {
        int len = values.size();
        int end = start + len;
        int childCount = nodeView.getChildCount();
        int setSize = (childCount > len) ? childCount : end;
        ProvidesKey<C> keyProvider = nodeInfo.getProvidesKey();

        Element container = nodeView.ensureChildContainer();
        Element childElem = (values.size() == 0) ? null : Element.as(container.getChild(start));
        CellTreeNodeView<?> keyboardSelected = nodeView.tree.getKeyboardSelectedNode();
        for (int i = start; i < end; i++) {
          C childValue = values.get(i - start);
          CellTreeNodeView<C> child =
              nodeView.createTreeNodeView(nodeInfo, childElem, childValue, null);
          CellTreeNodeView<?> savedChild = savedViews.remove(keyProvider.getKey(childValue));
          // Copy the saved child's state into the new child
          if (savedChild != null) {
            child.animationFrame = savedChild.animationFrame;
            child.contentContainer = savedChild.contentContainer;
            child.childContainer = savedChild.childContainer;
            child.children = savedChild.children;
            child.emptyMessageElem = savedChild.emptyMessageElem;
            child.nodeInfo = savedChild.nodeInfo;
            child.nodeInfoLoaded = savedChild.nodeInfoLoaded;
            child.open = savedChild.open;
            child.showMoreElem = savedChild.showMoreElem;

            // Transfer the tree node so that if the user has a handle to it, it
            // won't be destroyed.
            child.treeNode = savedChild.treeNode;
            if (child.treeNode != null) {
              child.treeNode.nodeView = child;
            }

            // Swap the node view in the child. We reuse the same NodeListView
            // so that we don't have to unset and register a new view with the
            // NodeInfo, which would inevitably cause the NodeInfo to push
            // new data.
            child.listView = savedChild.listView;
            if (child.listView != null) {
              child.listView.nodeView = child;
            }

            // Set the new parent of the grandchildren.
            if (child.children != null) {
              for (CellTreeNodeView<?> grandchild : child.children) {
                grandchild.parentNode = child;
              }
            }

            // Transfer the keyboard selected node.
            if (keyboardSelected == savedChild) {
              keyboardSelected = child;
            }

            // Copy the child container element to the new child
            child.getElement().appendChild(savedChild.ensureAnimationFrame());

            // Mark the old child as destroy without actually destroying it.
            savedChild.isDestroyed = true;
          }

          if (childCount > i) {
            nodeView.children.set(i, child);
          } else {
            nodeView.children.add(child);
          }
          child.updateAriaAttributes(setSize);
          childElem = childElem.getNextSiblingElement();
        }

        // Move the keyboard selected node if it is this node or a child of this
        // node.
        CellTreeNodeView<?> curNode = keyboardSelected;
        while (curNode != null) {
          if (curNode == nodeView) {
            nodeView.tree.keyboardSelect(keyboardSelected, false);
            break;
          }
          curNode = curNode.parentNode;
        }
      }

      /**
       * Save the state of the open child nodes within the range of the
       * specified values. Use {@link #loadChildState(List, int, Map)} to
       * re-attach the open nodes after they have been replaced.
       *
       * @param values the values being replaced
       * @param start the start index
       * @return the map of open nodes
       */
      private Map<Object, CellTreeNodeView<?>> saveChildState(List<C> values, int start) {
        // Ensure that we have a children array.
        if (nodeView.children == null) {
          nodeView.children = new ArrayList<CellTreeNodeView<?>>();
        }

        // Construct a map of former child views based on their value keys.
        int len = values.size();
        int end = start + len;
        int childCount = nodeView.getChildCount();
        CellTreeNodeView<?> keyboardSelected = nodeView.tree.getKeyboardSelectedNode();
        Map<Object, CellTreeNodeView<?>> openNodes = new HashMap<Object, CellTreeNodeView<?>>();
        for (int i = start; i < end && i < childCount; i++) {
          CellTreeNodeView<?> child = nodeView.getChildNode(i);
          if (child.isOpen() || child == keyboardSelected) {
            // Save child nodes that are open or keyboard selected.
            openNodes.put(child.getValueKey(), child);
          } else {
            // Cleanup child nodes that are closed.
            child.cleanup(true);
          }
        }

        // Trim the saved views down to the children that still exists.
        ProvidesKey<C> keyProvider = nodeInfo.getProvidesKey();
        Map<Object, CellTreeNodeView<?>> savedViews = new HashMap<Object, CellTreeNodeView<?>>();
        for (C childValue : values) {
          // Remove any child elements that correspond to prior children
          // so the call to setInnerHtml will not destroy them
          Object key = keyProvider.getKey(childValue);
          CellTreeNodeView<?> savedView = openNodes.remove(key);
          if (savedView != null) {
            savedView.ensureAnimationFrame().removeFromParent();
            savedViews.put(key, savedView);
          }
        }

        // Cleanup the remaining open nodes that are not in the new data set.
        for (CellTreeNodeView<?> lostNode : openNodes.values()) {
          lostNode.cleanup(true);
        }

        return savedViews;
      }
    }

    final HasDataPresenter<C> presenter;
    private final Cell<C> cell;
    private final int defaultPageSize;
    private HandlerManager handlerManger = new HandlerManager(this);
    private final NodeInfo<C> nodeInfo;
    private CellTreeNodeView<?> nodeView;

    public NodeCellList(final NodeInfo<C> nodeInfo, final CellTreeNodeView<?> nodeView, int pageSize) {
      this.defaultPageSize = pageSize;
      this.nodeInfo = nodeInfo;
      this.nodeView = nodeView;
      cell = nodeInfo.getCell();

      // Create a presenter.
      presenter =
          new HasDataPresenter<C>(this, createView(), pageSize,
              nodeInfo.getProvidesKey());

      // Disable keyboard selection because it is handled by CellTree.
      presenter.setKeyboardSelectionPolicy(KeyboardSelectionPolicy.DISABLED);

      // Use a pager to update buttons.
      presenter.addRowCountChangeHandler(new RowCountChangeEvent.Handler() {
        @Override
        public void onRowCountChange(RowCountChangeEvent event) {
          int rowCount = event.getNewRowCount();
          boolean isExact = event.isNewRowCountExact();
          int pageSize = getVisibleRange().getLength();
          showOrHide(nodeView.showMoreElem, isExact && rowCount > pageSize);
        }
      });
    }

    @Override
    public HandlerRegistration addCellPreviewHandler(Handler<C> handler) {
      return presenter.addCellPreviewHandler(handler);
    }

    @Override
    public HandlerRegistration addRangeChangeHandler(RangeChangeEvent.Handler handler) {
      return presenter.addRangeChangeHandler(handler);
    }

    @Override
    public HandlerRegistration addRowCountChangeHandler(RowCountChangeEvent.Handler handler) {
      return presenter.addRowCountChangeHandler(handler);
    }

    /**
     * Cleanup this node view.
     */
    public void cleanup() {
      presenter.clearSelectionModel();
    }

    @Override
    public void fireEvent(GwtEvent<?> event) {
      handlerManger.fireEvent(event);
    }

    public int getDefaultPageSize() {
      return defaultPageSize;
    }

    @Override
    public int getRowCount() {
      return presenter.getRowCount();
    }

    @Override
    public SelectionModel<? super C> getSelectionModel() {
      return presenter.getSelectionModel();
    }

    @Override
    public C getVisibleItem(int indexOnPage) {
      return presenter.getVisibleItem(indexOnPage);
    }

    @Override
    public int getVisibleItemCount() {
      return presenter.getVisibleItemCount();
    }

    @Override
    public List<C> getVisibleItems() {
      return presenter.getVisibleItems();
    }

    @Override
    public Range getVisibleRange() {
      return presenter.getVisibleRange();
    }

    @Override
    public boolean isRowCountExact() {
      return presenter.isRowCountExact();
    }

    @Override
    public final void setRowCount(int count) {
      setRowCount(count, true);
    }

    @Override
    public void setRowCount(int size, boolean isExact) {
      presenter.setRowCount(size, isExact);
    }

    @Override
    public void setRowData(int start, List<? extends C> values) {
      presenter.setRowData(start, values);
    }

    @Override
    public void setSelectionModel(final SelectionModel<? super C> selectionModel) {
      presenter.setSelectionModel(selectionModel);
    }

    @Override
    public final void setVisibleRange(int start, int length) {
      setVisibleRange(new Range(start, length));
    }

    @Override
    public void setVisibleRange(Range range) {
      presenter.setVisibleRange(range);
    }

    @Override
    public void setVisibleRangeAndClearData(Range range, boolean forceRangeChangeEvent) {
      presenter.setVisibleRangeAndClearData(range, forceRangeChangeEvent);
    }

    /*Open API for drag and drop support
     */
    protected View createView(){
      return new View(nodeView.ensureChildContainer());
    }

    protected NodeInfo<C> getNodeInfo() {
      return nodeInfo;
    }

    protected CellTreeNodeView<?> getNodeView() {
      return nodeView;
    }
  }

  /**
   * An implementation of {@link TreeNode} that delegates to a
   * {@link CellTreeNodeView}. This class is intentionally static because we
   * might move it to a new {@link CellTreeNodeView}, and we don't want
   * non-static references to the old {@link CellTreeNodeView}.
   */
  private static class TreeNodeImpl implements TreeNode {

    private CellTreeNodeView<?> nodeView;

    public TreeNodeImpl(CellTreeNodeView<?> nodeView) {
      this.nodeView = nodeView;
    }

    @Override
    public int getChildCount() {
      assertNotDestroyed();
      flush();
      return nodeView.getChildCount();
    }

    @Override
    public Object getChildValue(int index) {
      assertNotDestroyed();
      checkChildBounds(index);
      flush();
      return nodeView.getChildNode(index).value;
    }

    @Override
    public int getIndex() {
      assertNotDestroyed();
      return (nodeView.parentNode == null) ? 0 : nodeView.parentNode.children.indexOf(nodeView);
    }

    @Override
    public TreeNode getParent() {
      assertNotDestroyed();
      return getParentImpl();
    }

    @Override
    public Object getValue() {
      return nodeView.value;
    }

    @Override
    public boolean isChildLeaf(int index) {
      assertNotDestroyed();
      checkChildBounds(index);
      flush();
      return nodeView.getChildNode(index).isLeaf();
    }

    @Override
    public boolean isChildOpen(int index) {
      assertNotDestroyed();
      checkChildBounds(index);
      flush();
      return nodeView.getChildNode(index).isOpen();
    }

    @Override
    public boolean isDestroyed() {
      if (!nodeView.isDestroyed) {
        /*
         * Flush the parent display because the user may have replaced this
         * node, which would destroy it.
         */
        TreeNodeImpl parent = getParentImpl();
        if (parent != null && !parent.isDestroyed()) {
          parent.flush();
        }
      }
      return nodeView.isDestroyed || !nodeView.isOpen();
    }

    @Override
    public TreeNode setChildOpen(int index, boolean open) {
      return setChildOpen(index, open, true);
    }

    @Override
    public TreeNode setChildOpen(int index, boolean open, boolean fireEvents) {
      assertNotDestroyed();
      checkChildBounds(index);
      CellTreeNodeView<?> child = nodeView.getChildNode(index);
      return child.setOpen(open, fireEvents) ? child.treeNode : null;
    }

    /**
     * Assert that the node has not been destroyed.
     */
    private void assertNotDestroyed() {
      if (isDestroyed()) {
        throw new IllegalStateException("TreeNode no longer exists.");
      }
    }

    /**
     * Check the child bounds.
     *
     * @param index the index of the child
     * @throws IndexOutOfBoundsException if the child is not in range
     */
    private void checkChildBounds(int index) {
      if ((index < 0) || (index >= getChildCount())) {
        throw new IndexOutOfBoundsException();
      }
    }

    /**
     * Flush pending changes in the view.
     */
    private void flush() {
      if (nodeView.listView != null) {
        nodeView.listView.presenter.flush();
      }
    }

    /**
     * Get the parent node without checking if this node is destroyed.
     *
     * @return the parent node, or null if the node has no parent
     */
    private TreeNodeImpl getParentImpl() {
      return nodeView.isRootNode() ? null : nodeView.parentNode.treeNode;
    }
  }

  /**
   * The element used in place of an image when a node has no children.
   */
  private static final SafeHtml LEAF_IMAGE = SafeHtmlUtils
      .fromSafeConstant("

");

  private static final Template template = GWT.create(Template.class);

  /**
   * The temporary element used to render child items.
   */
  private static com.google.gwt.user.client.Element tmpElem;

  /**
   * Returns the element that parents the cell contents of the node.
   *
   * @param nodeElem the element that represents the node
   * @return the cell parent within the node
   */
  private static Element getCellParent(Element nodeElem) {
    return getSelectionElement(nodeElem).getFirstChildElement().getChild(1).cast();
  }

  /**
   * Returns the element that selection is applied to.
   *
   * @param nodeElem the element that represents the node
   * @return the cell parent within the node
   */
  private static Element getImageElement(Element nodeElem) {
    return getSelectionElement(nodeElem).getFirstChildElement().getFirstChildElement();
  }

  /**
   * Returns the element that selection is applied to.
   *
   * @param nodeElem the element that represents the node
   * @return the cell parent within the node
   */
  private static Element getSelectionElement(Element nodeElem) {
    return nodeElem.getFirstChildElement();
  }

  /**
   * Return the temporary element used to create elements.
   */
  private static com.google.gwt.user.client.Element getTmpElem() {
    if (tmpElem == null) {
      tmpElem = Document.get().createDivElement().cast();
    }
    return tmpElem;
  }

  /**
   * Show or hide an element.
   *
   * @param element the element to show or hide
   * @param show true to show, false to hide
   */
  private static void showOrHide(Element element, boolean show) {
    if (show) {
      element.getStyle().clearDisplay();
    } else {
      element.getStyle().setDisplay(Display.NONE);
    }
  }

  /**
   * The list view used to display the nodes.
   */
  NodeCellList<?> listView;

  /**
   * True during the time a node should be animated.
   */
  private boolean animate;

  /**
   * A reference to the element that is used to animate nodes. Parent of the
   * contentContainer.
   */
  private Element animationFrame;

  /**
   * A reference to the element that contains the children. Parent to the actual
   * child nodes.
   */
  private Element childContainer;

  /**
   * A list of child views.
   */
  private List<CellTreeNodeView<?>> children;

  /**
   * A reference to the element that contains all content. Parent of the
   * childContainer and the show/hide elements.
   */
  private Element contentContainer;

  /**
   * The depth of this node in the tree.
   */
  private final int depth;

  /**
   * The element used when there are no children to display.
   */
  private Element emptyMessageElem;

  /**
   * Set to true when the node is destroyed.
   */
  private boolean isDestroyed;

  /**
   * Messages used for translation.
   */
  private final CellTreeMessages messages;

  /**
   * The info about children of this node.
   */
  private NodeInfo<?> nodeInfo;

  /**
   * Indicates whether or not we've loaded the node info.
   */
  private boolean nodeInfoLoaded;

  /**
   * Indicates whether or not this node is open.
   */
  private boolean open;

  /**
   * The parent {@link CellTreeNodeView}.
   */
  private CellTreeNodeView<?> parentNode;

  /**
   * The {@link NodeInfo} of the parent node.
   */
  private final NodeInfo<T> parentNodeInfo;

  /**
   * The element used to display more children.
   */
  private AnchorElement showMoreElem;

  /**
   * The {@link CellTree} that this node belongs to.
   */
  private final CellTree tree;

  /**
   * The publicly visible tree node. The {@link CellTreeNodeView} doesn't
   * implement {@link TreeNode} directly because we want to transfer the user's
   * handle to the {@link TreeNode} to the new {@link CellTreeNodeView}.
   */
  private TreeNodeImpl treeNode;

  /**
   * This node's value.
   */
  private T value;

  /**
   * Construct a {@link CellTreeNodeView}.
   *
   * @param tree the parent {@link CellTreeNodeView}
   * @param parent the parent {@link CellTreeNodeView}
   * @param parentNodeInfo the {@link NodeInfo} of the parent
   * @param elem the outer element of this {@link CellTreeNodeView}
   * @param value the value of this node
   * @param messages tranlation messages
   */
  protected CellTreeNodeView(final CellTree tree, final CellTreeNodeView<?> parent,
      NodeInfo<T> parentNodeInfo, Element elem, T value, CellTreeMessages messages) {
    this.tree = tree;
    this.parentNode = parent;
    this.parentNodeInfo = parentNodeInfo;
    this.depth = parentNode == null ? 0 : parentNode.depth + 1;
    this.value = value;
    this.messages = messages;
    setElement(elem);

    Roles.getTreeitemRole().set(getElement());
  }

  public int getChildCount() {
    return children == null ? 0 : children.size();
  }

  public CellTreeNodeView<?> getChildNode(int childIndex) {
    return children.get(childIndex);
  }

  public boolean isLeaf() {
    return tree.isLeaf(value);
  }

  /**
   * Check whether or not this node is open.
   *
   * @return true if open, false if closed
   */
  public boolean isOpen() {
    return open;
  }

  /**
   * Sets whether this item's children are displayed.
   *
   * @param open whether the item is open
   * @param fireEvents true to fire events if the state changes
   * @return true if successfully opened, false otherwise.
   */
  public boolean setOpen(boolean open, boolean fireEvents) {
    // Early out.
    if (this.open == open) {
      return this.open;
    }

    // If this node is a leaf node, do not call TreeViewModel.getNodeInfo().
    if (open && isLeaf()) {
      return false;
    }

    // The animation clears the innerHtml of the childContainer. If we reopen a
    // node as its closing, it is possible that the new data will be set
    // synchronously, so we have to cancel the animation before attaching the
    // data display to the node info.
    tree.cancelTreeNodeAnimation();
    this.animate = true;
    this.open = open;
    if (open) {
      if (!nodeInfoLoaded) {
        nodeInfoLoaded = true;
        nodeInfo = tree.getNodeInfo(value);

        // Sink events for the new node.
        if (nodeInfo != null) {
          Set<String> eventsToSink = new HashSet<String>();
          // Listen for focus and blur for keyboard navigation
          eventsToSink.add(BrowserEvents.FOCUS);
          eventsToSink.add(BrowserEvents.BLUR);

          Set<String> consumedEvents = nodeInfo.getCell().getConsumedEvents();
          if (consumedEvents != null) {
            eventsToSink.addAll(consumedEvents);
          }
          CellBasedWidgetImpl.get().sinkEvents(tree, eventsToSink);
        }
      }

      // If we don't have any nodeInfo, we must be a leaf node.
      if (nodeInfo != null) {
        // Add a loading message.
        ensureChildContainer();
        showOrHide(showMoreElem, false);
        showOrHide(emptyMessageElem, false);
        if (!isRootNode()) {
          setStyleName(getCellParent(), tree.getStyle().cellTreeOpenItem(), true);
        }
        ensureAnimationFrame().getStyle().setProperty("display", "");
        onOpen(nodeInfo);

        // Fire an event.
        if (fireEvents) {
          OpenEvent.fire(tree, getTreeNode());
        }
      } else {
        this.open = false;
      }
    } else {
      if (!isRootNode()) {
        setStyleName(getCellParent(), tree.getStyle().cellTreeOpenItem(), false);
      }
      cleanup(false);
      tree.maybeAnimateTreeNode(this);
      updateImage(false);

      // Keyboard select this node if the open node was a child.
      CellTreeNodeView<?> keySelected = tree.getKeyboardSelectedNode();
      while (keySelected != null) {
        if (keySelected == this) {
          tree.keyboardSelect(this, true);
          break;
        }
        keySelected = keySelected.getParentNode();
      }

      // Fire an event.
      if (fireEvents) {
        CloseEvent.fire(tree, getTreeNode());
      }
    }

    return this.open;
  }

  /**
   * Unregister the list handler and destroy all child nodes.
   *
   * @param destroy true to destroy this node
   */
  protected void cleanup(boolean destroy) {
    // Unregister the list handler.
    if (listView != null) {
      listView.cleanup();
      nodeInfo.unsetDataDisplay();
      listView = null;
    }

    // Recursively destroy children.
    if (children != null) {
      for (CellTreeNodeView<?> child : children) {
        child.cleanup(true);
      }
      children = null;
    }

    // Destroy this node.
    if (destroy) {
      isDestroyed = true;

      // If this is the keyboard selected node, select the parent. The children
      // have already been cleaned, so the selected node cannot be under this
      // node.
      if (this == tree.getKeyboardSelectedNode()) {
        tree.keyboardSelect(parentNode, false);
      }
    }
  }

  protected boolean consumeAnimate() {
    boolean hasAnimate = animate;
    animate = false;
    return hasAnimate;
  }

  /**
   * Returns an instance of TreeNodeView of the same subclass as the calling
   * object.
   *
   * @param <C> the data type of the node's children
   * @param nodeInfo a NodeInfo object describing the child nodes
   * @param childElem the DOM element used to parent the new TreeNodeView
   * @param childValue the child's value
   * @param viewData view data associated with the node
   * @return a TreeNodeView of suitable type
   */
  protected <C> CellTreeNodeView<C> createTreeNodeView(NodeInfo<C> nodeInfo, Element childElem,
      C childValue, Object viewData) {
    return new CellTreeNodeView<C>(tree, this, nodeInfo, childElem, childValue, messages);
  }

  /**
   * Fire an event to the {@link com.google.gwt.cell.client.AbstractCell}.
   *
   * @param event the native event
   */
  @SuppressWarnings("unchecked")
  protected void fireEventToCell(NativeEvent event) {
    if (parentNodeInfo == null) {
      return;
    }

    Cell<T> parentCell = parentNodeInfo.getCell();
    String eventType = event.getType();
    Element cellParent = getCellParent();
    Object key = getValueKey();
    Context context = new Context(getIndex(), 0, key);
    boolean cellWasEditing = parentCell.isEditing(context, cellParent, value);

    // Update selection.
    boolean isSelectionHandled =
        parentCell.handlesSelection()
            || KeyboardSelectionPolicy.BOUND_TO_SELECTION == tree.getKeyboardSelectionPolicy();
    HasData<T> display = (HasData<T>) parentNode.listView;
    CellPreviewEvent<T> previewEvent =
        CellPreviewEvent.fire(display, event, display, context, value, cellWasEditing,
            isSelectionHandled);

    // Forward the event to the cell.
    if (previewEvent.isCanceled() || !cellParent.isOrHasChild(Element.as(event.getEventTarget()))) {
      return;
    }
    Set<String> consumedEvents = parentCell.getConsumedEvents();
    if (consumedEvents != null && consumedEvents.contains(eventType)) {
      parentCell
          .onBrowserEvent(context, cellParent, value, event, parentNodeInfo.getValueUpdater());
      tree.cellIsEditing = parentCell.isEditing(context, cellParent, value);
      if (cellWasEditing && !tree.cellIsEditing) {
        CellBasedWidgetImpl.get().resetFocus(new Scheduler.ScheduledCommand() {
          @Override
          public void execute() {
            tree.setFocus(true);
          }
        });
      }
    }
  }

  /**
   * Returns the element that parents the cell contents of this node.
   */
  protected Element getCellParent() {
    return getCellParent(getElement());
  }

  /**
   * Returns the element corresponding to the open/close image.
   *
   * @return the open/close image element
   */
  protected Element getImageElement() {
    return getImageElement(getElement());
  }

  /**
   * Returns the element that selection styles are applied to. The element
   * includes the open/close image and the rendered value and spans the width of
   * the tree.
   *
   * @return the selection element
   */
  protected Element getSelectionElement() {
    return getSelectionElement(getElement());
  }

  /**
   * Returns the key for the value of this node using the parent's
   * implementation of NodeInfo.getKey().
   */
  protected Object getValueKey() {
    return parentNodeInfo.getProvidesKey().getKey(value);
  }

  /**
   * Set up the node when it is opened.
   *
   * @param nodeInfo the {@link NodeInfo} that provides information about the
   *          child values
   * @param <C> the child data type of the node
   */
  protected <C> void onOpen(final NodeInfo<C> nodeInfo) {
    NodeCellList<C> view = createNodeCellList(nodeInfo);
    listView = view;
    view.setSelectionModel(nodeInfo.getSelectionModel());
    nodeInfo.setDataDisplay(view);
  }

  /**
   * Ensure that the animation frame exists and return it.
   *
   * @return the animation frame
   */
  Element ensureAnimationFrame() {
    if (animationFrame == null) {
      animationFrame = Document.get().createDivElement();
      animationFrame.getStyle().setOverflow(Overflow.HIDDEN);
      animationFrame.getStyle().setDisplay(Display.NONE);
      getElement().appendChild(animationFrame);
    }
    return animationFrame;
  }

  /**
   * Ensure that the child container exists and return it.
   *
   * @return the child container
   */
  public Element ensureChildContainer() {
    if (childContainer == null) {
      childContainer = Document.get().createDivElement();
      ensureContentContainer().insertFirst(childContainer);
    }
    return childContainer;
  }

  /**
   * Ensure that the content container exists and return it.
   *
   * @return the content container
   */
  Element ensureContentContainer() {
    if (contentContainer == null) {
      contentContainer = Document.get().createDivElement();
      ensureAnimationFrame().appendChild(contentContainer);

      emptyMessageElem = Document.get().createDivElement();
      emptyMessageElem.setInnerHTML(messages.emptyTree());
      setStyleName(emptyMessageElem, tree.getStyle().cellTreeEmptyMessage(), true);
      showOrHide(emptyMessageElem, false);
      contentContainer.appendChild(emptyMessageElem);

      showMoreElem = Document.get().createAnchorElement();
      showMoreElem.setHref("javascript:;");
      showMoreElem.setInnerText(messages.showMore());
      setStyleName(showMoreElem, tree.getStyle().cellTreeShowMoreButton(), true);
      showOrHide(showMoreElem, false);
      contentContainer.appendChild(showMoreElem);
    }
    return contentContainer;
  }

  /**
   * Return the index of this node in its parent.
   */
  int getIndex() {
    return parentNode == null ? 0 : parentNode.indexOf(this);
  }

  /**
   * Return the parent node, or null if this node is the root.
   */
  CellTreeNodeView<?> getParentNode() {
    return parentNode;
  }

  Element getShowMoreElement() {
    return showMoreElem;
  }

  /**
   * Get a {@link TreeNode} with a public API for this node view.
   *
   * @return the {@link TreeNode}
   */
  TreeNode getTreeNode() {
    if (treeNode == null) {
      treeNode = new TreeNodeImpl(this);
    }
    return treeNode;
  }

  int indexOf(CellTreeNodeView<?> child) {
    return children.indexOf(child);
  }

  boolean isDestroyed() {
    return isDestroyed;
  }

  /**
   * Check if this node is a root node.
   *
   * @return true if a root node
   */
  boolean isRootNode() {
    return parentNode == null;
  }

  /**
   * Check if the value of this node is selected.
   *
   * @return true if selected, false if not
   */
  boolean isSelected() {
    if (parentNodeInfo != null) {
      SelectionModel<? super T> selectionModel = parentNodeInfo.getSelectionModel();
      if (selectionModel != null) {
        return selectionModel.isSelected(value);
      }
    }
    return false;
  }

  /**
   * Reset focus on this node.
   *
   * @return true of the cell takes focus, false if not
   */
  boolean resetFocusOnCell() {
    if (parentNodeInfo != null) {
      Context context = new Context(getIndex(), 0, getValueKey());
      Cell<T> cell = parentNodeInfo.getCell();
      return cell.resetFocus(context, getCellParent(), value);
    }
    return false;
  }

  /**
   * Select or deselect this node with the keyboard.
   *
   * @param selected true if selected, false if not
   * @param stealFocus true to steal focus
   */
  void setKeyboardSelected(boolean selected, boolean stealFocus) {
    if (tree.isKeyboardSelectionDisabled()) {
      return;
    }

    // Apply the selected style.
    if (!selected || tree.isFocused || stealFocus) {
      setKeyboardSelectedStyle(selected);
    }

    // Make the node focusable or not.
    Element cellParent = getCellParent();
    if (!selected) {
      // Chrome: Elements remain focusable after removing the tabIndex, so set
      // it to -1 first.
      cellParent.setTabIndex(-1);
      cellParent.removeAttribute("tabIndex");
      cellParent.removeAttribute("accessKey");
    } else {
      FocusImpl focusImpl = FocusImpl.getFocusImplForWidget();
      com.google.gwt.user.client.Element cellElem = cellParent.cast();
      focusImpl.setTabIndex(cellElem, tree.getTabIndex());
      char accessKey = tree.getAccessKey();
      if (accessKey != 0) {
        focusImpl.setAccessKey(cellElem, accessKey);
      }
      if (stealFocus && !tree.cellIsEditing) {
        cellElem.focus();
      }
    }

    // Update the selection model.
    if (KeyboardSelectionPolicy.BOUND_TO_SELECTION == tree.getKeyboardSelectionPolicy()) {
      setSelected(selected);
    }
  }

  /**
   * Add or remove the keyboard selected style.
   *
   * @param selected true if selected, false if not
   */
  void setKeyboardSelectedStyle(boolean selected) {
    if (!isRootNode()) {
      Element selectionElem = getSelectionElement(getElement());
      if (selectionElem != null) {
        setStyleName(selectionElem, tree.getStyle().cellTreeKeyboardSelectedItem(), selected);
      }
    }
  }

  /**
   * Select or deselect this node.
   *
   * @param selected true to select, false to deselect
   */
  void setSelected(boolean selected) {
    if (parentNodeInfo != null) {
      SelectionModel<? super T> selectionModel = parentNodeInfo.getSelectionModel();
      if (selectionModel != null) {
        selectionModel.setSelected(value, selected);
      }
    }
  }

  void showFewer() {
    Range range = listView.getVisibleRange();
    int defaultPageSize = listView.getDefaultPageSize();
    int maxSize = Math.max(defaultPageSize, range.getLength() - defaultPageSize);
    listView.setVisibleRange(range.getStart(), maxSize);
  }

  void showMore() {
    Range range = listView.getVisibleRange();
    int pageSize = range.getLength() + listView.getDefaultPageSize();
    listView.setVisibleRange(range.getStart(), pageSize);
  }

  private void updateAriaAttributes(int setSize) {
    // Early out if this is a root node.
    if (isRootNode()) {
      return;
    }

    Roles.getTreeitemRole().setAriaSetsizeProperty(getElement(), setSize);
    int selectionIndex = parentNode.indexOf(this);
    Roles.getTreeitemRole().setAriaPosinsetProperty(getElement(), selectionIndex + 1);
    // Set 'aria-expanded' state
    // don't set aria-expanded on the leaf nodes
    if (isLeaf()) {
      Roles.getTreeitemRole().removeAriaExpandedState(getElement());
    } else {
      Roles.getTreeitemRole().setAriaExpandedState(getElement(),
          ExpandedValue.of(open));
    }
    Roles.getTreeitemRole().setAriaLevelProperty(getElement(), this.depth);
  }

  /**
   * Update the image based on the current state.
   *
   * @param isLoading true if still loading data
   */
  private void updateImage(boolean isLoading) {
    // Early out if this is a root node.
    if (isRootNode()) {
      return;
    }

    // Replace the image element with a new one.
    boolean isTopLevel = parentNode.isRootNode();
    SafeHtml html = tree.getClosedImageHtml(isTopLevel);
    if (open) {
      html = isLoading ? tree.getLoadingImageHtml() : tree.getOpenImageHtml(isTopLevel);
    }
    if (nodeInfoLoaded && nodeInfo == null) {
      html = LEAF_IMAGE;
    }
    Element tmp = Document.get().createDivElement();
    tmp.setInnerHTML(html.asString());
    Element imageElem = tmp.getFirstChildElement();

    Element oldImg = getImageElement();
    oldImg.getParentElement().replaceChild(imageElem, oldImg);

    // Set 'aria-expanded' state
    // don't set aria-expanded on the leaf nodes
    if (isLeaf()) {
      Roles.getTreeitemRole().removeAriaExpandedState(getElement());
    } else {
      Roles.getTreeitemRole().setAriaExpandedState(getElement(),
          ExpandedValue.of(open));
    }
  }

  /* for drag and drop support */
  protected <C> NodeCellList<C> createNodeCellList(NodeInfo<C> nodeInfo){
    return new NodeCellList<C>(nodeInfo, this,
        tree.getDefaultNodeSize());

  }

}


text:
package org.railwaystations.rsapi.adapter.in.web.writer;

import org.junit.jupiter.api.Test;
import org.railwaystations.rsapi.adapter.in.web.model.StationDto;
import org.springframework.mock.http.MockHttpOutputMessage;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;

import static org.assertj.core.api.Assertions.assertThat;

public class StationsGpxWriterTest {

	@Test
	public void testWriteTo() throws IOException {
		final var stations = new ArrayList<StationDto>();
		stations.add(new StationDto().country("de").idStr("4711").title("Test").lat(50d).lon(9d));
		stations.add(new StationDto().country("de").idStr("4712").title("Foo").lat(51d).lon(8d));

		final var outputMessage = new MockHttpOutputMessage();
		new StationsGpxWriter().writeInternal(stations, outputMessage);

		final var gpx = outputMessage.getBodyAsString(StandardCharsets.UTF_8);
		assertThat(gpx)
				.isEqualTo("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<gpx xmlns=\"http://www.topografix.com/GPX/1/1\" version=\"1.1\">\n<wpt lat=\"50.0\" lon=\"9.0\"><name>Test</name></wpt>\n<wpt lat=\"51.0\" lon=\"8.0\"><name>Foo</name></wpt>\n</gpx>");
	}

}


text:
import express from 'express';
import url from 'url';
import path from 'path';
// eslint-disable-next-line
import proxy from 'express-http-proxy';

const prjRoot = p => path.resolve(__dirname, '../', p);

const main = async () => {
  const app = express();
  /* app routes */
  app.use('/api', proxy(
    'localhost:5000',
    {
      forwardPath: (req) => {
        const reqUrl = url.parse(req.url).path;
        // eslint-disable-next-line
        console.log('reqUrl =', reqUrl);
        return `/api${reqUrl}`;
      },
    },
  ));
  app.use('/static', express.static(prjRoot('./dist/')));
  app.get('/*', (req, res) => {
    res.sendFile('index.html', { root: prjRoot('./dist/') });
  });

  app.listen(4001, () => {
    // eslint-disable-next-line no-console
    console.log('Webpack dev server listening on port 4001...');
  });
};

// eslint-disable-next-line no-console
main().catch(err => console.error(err));


text:
$(document).ready(function() {
  // Links don't behave like links.
  $('tr.accordion-toggle').css('cursor', 'pointer').find('a span.glyphicon').on('click', function(event) {
    event.preventDefault();
  });
  // Expand collapsed table row content.
  $('[id^="logRecordDetail"] tr.accordion-toggle').trigger('click');
});


text:
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "privacy/net/krypton/jni/vpn_service.h"

#include <jni.h>
#include <jni_md.h>

#include <memory>
#include <optional>
#include <string>

#include "base/logging.h"
#include "privacy/net/krypton/datapath/android_ipsec/ipsec_datapath.h"

#include "privacy/net/krypton/fd_packet_pipe.h"
#include "privacy/net/krypton/jni/jni_cache.h"
#include "privacy/net/krypton/jni/jni_utils.h"
#include "privacy/net/krypton/proto/network_info.proto.h"
#include "privacy/net/krypton/proto/tun_fd_data.proto.h"
#include "third_party/absl/status/status.h"
#include "third_party/absl/status/statusor.h"
#include "third_party/absl/strings/str_cat.h"

namespace privacy {
namespace krypton {
namespace jni {

DatapathInterface* VpnService::BuildDatapath(const KryptonConfig& config,
                                             utils::LooperThread* looper,
                                             TimerManager* /*timer_manager*/) {
  if (config.datapath_protocol() == KryptonConfig::IPSEC) {
    return new datapath::android::IpSecDatapath(looper, this);
  }
}

absl::Status VpnService::CreateTunnel(const TunFdData& tun_fd_data) {
  LOG(INFO) << "Requesting TUN fd from Java with tun data "
            << tun_fd_data.DebugString();

  auto jni_cache = JniCache::Get();
  auto env = jni_cache->GetJavaEnv();
  if (!env) {
    LOG(ERROR) << "Cannot find JavaEnv to request TUN fd";
    return absl::Status(absl::StatusCode::kInternal, "Unable to get Java Env");
  }

  std::string tun_fd_bytes;
  tun_fd_data.SerializeToString(&tun_fd_bytes);

  jint fd = env.value()->CallIntMethod(
      krypton_instance_->get(), jni_cache->GetKryptonCreateTunFdMethod(),
      JavaByteArray(env.value(), tun_fd_bytes).get());

  if (fd < 0) {
    return absl::Status(absl::StatusCode::kUnavailable,
                        absl::StrCat("Unable to create TUN fd: ", fd));
  }

  absl::MutexLock l(&mutex_);
  if (tunnel_ != nullptr) {
    LOG(WARNING) << "Old tunnel was still open. Closing now.";
    tunnel_->Close();
  }
  tunnel_ = std::make_unique<FdPacketPipe>(fd);
  return absl::OkStatus();
}

PacketPipe* VpnService::GetTunnel() {
  absl::MutexLock l(&mutex_);
  return tunnel_.get();
}

absl::StatusOr<int> VpnService::GetTunnelFd() {
  auto tunnel = GetTunnel();
  if (tunnel == nullptr) {
    return absl::InternalError("tunnel is null");
  }
  return tunnel->GetFd();
}

void VpnService::CloseTunnel() {
  absl::MutexLock l(&mutex_);
  if (tunnel_ == nullptr) {
    return;
  }
  tunnel_->Close();
  tunnel_.reset();
}

absl::StatusOr<int> VpnService::CreateProtectedNetworkSocket(
    const NetworkInfo& network_info) {
  LOG(INFO) << "Requesting network fd from Java with network info "
            << network_info.DebugString();

  auto jni_cache = JniCache::Get();
  auto env = jni_cache->GetJavaEnv();
  if (!env) {
    LOG(ERROR) << "Cannot find JavaEnv to request network fd";
    return absl::Status(absl::StatusCode::kInternal, "Unable to get Java Env");
  }

  std::string network_info_bytes;
  network_info.SerializeToString(&network_info_bytes);

  jint fd = env.value()->CallIntMethod(
      krypton_instance_->get(), jni_cache->GetKryptonCreateNetworkFdMethod(),
      JavaByteArray(env.value(), network_info_bytes).get());

  if (fd < 0) {
    return absl::Status(absl::StatusCode::kUnavailable,
                        absl::StrCat("Unable to create network fd: ", fd));
  }

  return fd;
}

absl::StatusOr<std::unique_ptr<PacketPipe>> VpnService::CreateNetworkPipe(
    const NetworkInfo& network_info, const Endpoint& endpoint) {
  PPN_ASSIGN_OR_RETURN(int fd, CreateProtectedNetworkSocket(network_info));

  auto pipe = std::make_unique<FdPacketPipe>(fd);
  auto status = pipe->Connect(endpoint);
  if (!status.ok()) {
    pipe->Close();
    return status;
  }
  return pipe;
}

absl::Status VpnService::ConfigureIpSec(const IpSecTransformParams& params) {
  LOG(INFO) << "Configuring IPSec for fd: " << params.network_fd();

  auto jni_cache = JniCache::Get();
  auto env = jni_cache->GetJavaEnv();
  if (!env) {
    LOG(ERROR) << "Cannot find JavaEnv to configure IPSec.";
    return absl::Status(absl::StatusCode::kInternal, "Unable to get Java Env");
  }

  std::string transform_params_bytes;
  params.SerializeToString(&transform_params_bytes);
  jboolean status = env.value()->CallBooleanMethod(
      krypton_instance_->get(), jni_cache->GetKryptonConfigureIpSecMethod(),
      JavaByteArray(env.value(), transform_params_bytes).get());
  if (static_cast<bool>(status)) {
    return absl::OkStatus();
  }
  return absl::Status(
      absl::StatusCode::kUnavailable,
      absl::StrCat("Error encountered when applying transform to fd: ",
                   params.network_fd()));
}

}  // namespace jni
}  // namespace krypton
}  // namespace privacy


text:
package org.optaplanner.core.impl.localsearch.event;

import org.optaplanner.core.impl.localsearch.scope.LocalSearchPhaseScope;
import org.optaplanner.core.impl.localsearch.scope.LocalSearchStepScope;
import org.optaplanner.core.impl.solver.event.SolverLifecycleListenerAdapter;

public abstract class LocalSearchPhaseLifecycleListenerAdapter extends SolverLifecycleListenerAdapter
        implements LocalSearchPhaseLifecycleListener {

    public void phaseStarted(LocalSearchPhaseScope phaseScope) {
        // Hook method
    }

    public void stepStarted(LocalSearchStepScope stepScope) {
        // Hook method
    }

    public void stepEnded(LocalSearchStepScope stepScope) {
        // Hook method
    }

    public void phaseEnded(LocalSearchPhaseScope phaseScope) {
        // Hook method
    }

}


text:
<?php

namespace Elcodi\Component\Product\StockValidator\Traits;

use Elcodi\Component\Product\Entity\Interfaces\PurchasableInterface;

/**
 * Trait SimplePurchasableStockValidatorTrait.
 */
trait SimplePurchasableStockValidatorTrait {
	/**
	 * Make a simple validation of a Purchasable instance.
	 *
	 * @param PurchasableInterface $purchasable   Purchasable
	 * @param int                  $stockRequired Stock required
	 * @param bool                 $useStock      Use stock
	 *
	 * @return bool|int Is valid or the number of elements that can be used
	 */
	public function isValidUsingSimplePurchasableValidation(
		PurchasableInterface $purchasable,
		$stockRequired,
		$useStock
	) {

		if ($useStock) {
			if (!$purchasable->isEnabled() || $stockRequired <= 0 || ($useStock && $purchasable->getStock() <= 0)) {
				return false;
			}

			if ($purchasable->getStock() < $stockRequired) {
				return $purchasable->getStock();
			}
		}
		return true;
	}
}


text:
package com.androidbase.interfaces;

public interface ICopiable {

	public void copy(Object value);

}


text:
[![Build Status][travis_badge]][travis]

This is a Debian container packed with much bitwise surgical kapow for you to operate with.

Currently works with `docker-machine` only.

## Usage

Change your current host working directory to the path of interest. Use the Force:

```
$ room
```

By default, you start in a ZSH prompt. Additionally, you can provide commands that will be passed to the container:

```
$ room npm install
```

## Installation

To make available system-wide Install in your host environment via `curl`:

```
curl -sL https://git.io/v69Xg | sh -
```

Alternatively, you clone the repository and run [`room.sh`](room.sh) directly:

```
git clone https://github.com/langri-sha/room.git
./room/room.sh
```

## Thanks!

If you sift through the list of goodies and feel like it's missing some :lollipop: pizzazz, please throw me a PR. I :heart: adding shiny new tools to the collection!

[travis_badge]: https://travis-ci.org/langri-sha/room.svg?branch=master
[travis]: https://travis-ci.org/langri-sha/room
[room.sh]: https://raw.githubusercontent.com/langri-sha/room/master/room.sh


text:
"use strict";
var Dog_1 = require("../classes/Dog");
var DogFactory = (function () {
    function DogFactory() {
    }
    DogFactory.prototype.make = function () {
        var constructorArguments = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            constructorArguments[_i - 0] = arguments[_i];
        }
        var object = Object.create(Dog_1["default"].prototype);
        Dog_1["default"].apply(object, constructorArguments);
        return object;
    };
    return DogFactory;
}());
module.exports = DogFactory;


text:
"""Tests for the run_experiment function."""

from acme.agents.jax import sac
from acme.jax import experiments
from acme.jax.experiments import test_utils as experiment_test_utils
from acme.testing import fakes
from acme.testing import test_utils
import dm_env
from absl.testing import absltest
from absl.testing import parameterized

class RunExperimentTest(test_utils.TestCase):

  @parameterized.named_parameters(
      dict(testcase_name='noeval', num_eval_episodes=0),
      dict(testcase_name='eval', num_eval_episodes=1))
  def test_checkpointing(self, num_eval_episodes: int):
    num_train_steps = 100
    experiment_config = self._get_experiment_config(
        num_train_steps=num_train_steps)

    experiments.run_experiment(
        experiment_config, eval_every=10, num_eval_episodes=num_eval_episodes)

    checkpoint_counter = experiment_test_utils.restore_counter(
        experiment_config.checkpointing)
    self.assertIn('actor_steps', checkpoint_counter.get_counts())
    self.assertGreater(checkpoint_counter.get_counts()['actor_steps'], 0)

    # Run the second experiment with the same checkpointing config to verify
    # that it restores from the latest saved checkpoint.
    experiments.run_experiment(
        experiment_config, eval_every=50, num_eval_episodes=num_eval_episodes)

    checkpoint_counter = experiment_test_utils.restore_counter(
        experiment_config.checkpointing)
    self.assertIn('actor_steps', checkpoint_counter.get_counts())
    # Verify that the steps done in the first run are taken into account.
    self.assertLessEqual(checkpoint_counter.get_counts()['actor_steps'],
                         num_train_steps)

  def test_eval_every(self):
    num_train_steps = 100
    experiment_config = self._get_experiment_config(
        num_train_steps=num_train_steps)

    experiments.run_experiment(
        experiment_config, eval_every=70, num_eval_episodes=1)

    checkpoint_counter = experiment_test_utils.restore_counter(
        experiment_config.checkpointing)
    self.assertIn('actor_steps', checkpoint_counter.get_counts())
    self.assertGreater(checkpoint_counter.get_counts()['actor_steps'], 0)
    self.assertLessEqual(checkpoint_counter.get_counts()['actor_steps'],
                         num_train_steps)

  def _get_experiment_config(
      self, *, num_train_steps: int) -> experiments.ExperimentConfig:
    """Returns a config for a test experiment with the given number of steps."""

    def environment_factory(seed: int) -> dm_env.Environment:
      del seed
      return fakes.ContinuousEnvironment(
          episode_length=10, action_dim=3, observation_dim=5)

    num_train_steps = 100

    sac_config = sac.SACConfig()
    checkpointing_config = experiments.CheckpointingConfig(
        directory=self.get_tempdir(), time_delta_minutes=0)
    return experiments.ExperimentConfig(
        builder=sac.SACBuilder(sac_config),
        environment_factory=environment_factory,
        network_factory=sac.make_networks,
        seed=0,
        max_num_actor_steps=num_train_steps,
        checkpointing=checkpointing_config)

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