text:
"""C4 dataset based on Common Crawl."""

import collections
import functools
import json
import os
from typing import Optional, Sequence
import uuid

from absl import logging
from etils import epath
from tensorflow_datasets.core.utils import tree_utils
from tensorflow_datasets.core.utils.lazy_imports_utils import tensorflow as tf
import tensorflow_datasets.public_api as tfds
from tensorflow_datasets.text import c4_utils

PageFeatures = c4_utils.PageFeatures

_DESCRIPTION = """\
A colossal, cleaned version of Common Crawl's web crawl corpus.

Based on Common Crawl dataset: https://commoncrawl.org

To generate this dataset, please follow
[the instructions from t5](https://github.com/google-research/text-to-text-transfer-transformer#c4).

Due to the overhead of cleaning the dataset, it is recommend you prepare it with
a distributed service like Cloud Dataflow. More info at
https://www.tensorflow.org/datasets/beam_datasets.
"""
_CITATION = """
@article{2019t5,
  author = {Colin Raffel and Noam Shazeer and Adam Roberts and Katherine Lee and Sharan Narang and Michael Matena and Yanqi Zhou and Wei Li and Peter J. Liu},
  title = {Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer},
  journal = {arXiv e-prints},
  year = {2019},
  archivePrefix = {arXiv},
  eprint = {1910.10683},
}
"""
_VERSION = tfds.core.Version("3.1.0")

# TODO(adarob): Remove supported versions. Starting with 3.0.0, all generated
# datasets are automatically forward compatible. For example,
# tfds.load('c4:3.0.0') works even if the code is at 3.0.1.
_SUPPORTED_VERSIONS = [
    tfds.core.Version("2.3.1"),
    tfds.core.Version("2.3.0"),
    tfds.core.Version("2.2.1"),
    tfds.core.Version("2.2.0"),
]
RELEASE_NOTES = {
    "3.1.0":
        "All: Select newest timestamp when deduping by URL (vs random); escape "
        "badword regexes."
        "Multilingual: Expand complete list of CC dumps (as of Aug 17, 2022); "
        "use soft badword filtering (99.9%); do not require spaces for "
        "Japanese when matching bad words (similar to Thai and Chinese); "
        "up minimum language detection threshold to 0.95 (from 0.7); allow "
        "badwords that filter >10% of documents for a given non-spaced "
        "language due to being common subwords.",
    "3.0.1": "Remove mC4 languages with less than 10k pages.",
    "3.0.0": "Add multilingual version (mC4). Deterministic URL deduplication.",
    "2.3.1": "Hashing change.",
    "2.3.0": "Deduplicate lines within a page.",
    "2.2.1": "Update dataset_info.json",
}

_DOWNLOAD_HOST = "https://data.commoncrawl.org"
_WET_PATH_URL = "https://data.commoncrawl.org/crawl-data/CC-MAIN-{cc_version}/wet.paths.gz"
_REALNEWS_DOMAINS_URL = "https://raw.githubusercontent.com/rowanz/grover/38f7184bd87237ae2d3bc330b99f1e2e246f6d51/realnews/domain_to_allowed_subdomains.json"
_OPENWEBTEXT_URLS_ZIP = "OpenWebText.zip"
_OPENWEBTEXT_URLS_URL = "https://mega.nz/#F!EZZD0YwJ!9_PlEQzdMVLaNdKv_ICNVQ"
_OPENWEBTEXT_URLS_FILE_PATTERN = "OpenWebText/Version 1/URLs/*.txt"
_EN_BADWORDS_URL = "https://raw.githubusercontent.com/LDNOOBW/List-of-Dirty-Naughty-Obscene-and-Otherwise-Bad-Words/25e679f03d96baa721cde20db9944649e8d0a844/en"
_BADWORDS_URL = "https://raw.githubusercontent.com/LDNOOBW/List-of-Dirty-Naughty-Obscene-and-Otherwise-Bad-Words/5faf2ba42d7b1c0977169ec3611df25a3c08eb13/{lang}"
_BADWORDS_LANGS = [
    "ar", "cs", "da", "de", "en", "eo", "es", "fa", "fi", "fil", "fr",
    "fr-CA-u-sd-caqc", "hi", "hu", "it", "ja", "kab", "ko", "nl", "no", "pl",
    "pt", "ru", "sv", "th", "tlh", "tr", "zh"
]
# Words that are allowed since they are common subwords in languages without
# spaces. These each filter >10% of documents of their language when disallowed.
_BADWORDS_ALLOWLIST = {"ja": {"sm", "グロ", "女の子"}, "zh": {"性"}}

DEFAULT_CC_VERSION = "2019-18"

OPENWEBTEXT_CC_VERSIONS = (  # August 2018 - July 2019
    "2019-18",  # Original default for single-crawl dataset (April 2019).
    "2019-30",
    "2019-26",
    "2019-22",
    "2019-13",
    "2019-09",
    "2019-04",
    "2018-51",
    "2018-47",
    "2018-43",
    "2018-39",
    "2018-34")

ALL_CC_VERSIONS = (  # as of August 1, 2022
    "2013-20",
    "2013-48",
    "2014-10",
    "2014-15",
    "2014-23",
    "2014-35",
    "2014-41",
    "2014-42",
    "2014-49",
    "2014-52",
    "2015-06",
    "2015-11",
    "2015-14",
    "2015-18",
    "2015-22",
    "2015-27",
    "2015-32",
    "2015-35",
    "2015-40",
    "2015-48",
    "2016-07",
    "2016-18",
    "2016-22",
    "2016-26",
    "2016-30",
    "2016-36",
    "2016-40",
    "2016-44",
    "2016-50",
    "2017-04",
    "2017-09",
    "2017-13",
    "2017-17",
    "2017-22",
    "2017-26",
    "2017-30",
    "2017-34",
    "2017-39",
    "2017-43",
    "2017-47",
    "2017-51",
    "2018-05",
    "2018-09",
    "2018-13",
    "2018-17",
    "2018-22",
    "2018-26",
    "2018-30",
    "2018-34",
    "2018-39",
    "2018-43",
    "2018-47",
    "2018-51",
    "2019-04",
    "2019-09",
    "2019-13",
    "2019-18",
    "2019-22",
    "2019-26",
    "2019-30",
    "2019-35",
    "2019-39",
    "2019-43",
    "2019-47",
    "2019-51",
    "2020-05",
    "2020-10",
    "2020-16",
    "2020-24",
    "2020-29",
    "2020-34",
    "2020-40",
    "2020-45",
    "2020-50",
    "2021-04",
    "2021-10",
    "2021-17",
    "2021-21",
    "2021-25",
    "2021-31",
    "2021-39",
    "2021-43",
    "2021-49",
    "2022-05",
    "2022-21",
    "2022-27",
)

_KNOWN_CORRUPT_WET_FILES = (  # as of August 12, 2022
    # files that raise UnicodeDecodeError
    "crawl-data/CC-MAIN-2017-13/segments/1490218203536.73/wet/CC-MAIN-20170322213003-00052-ip-10-233-31-227.ec2.internal.warc.wet.gz",
)

# Limited to languages in CLD3 that produce at least 10k pages when using the
# "multilingual" config below.
MC4_LANGUAGES = [
    "af", "am", "ar", "az", "be", "bg", "bg-Latn", "bn", "ca", "ceb", "co",
    "cs", "cy", "da", "de", "el", "el-Latn", "en", "eo", "es", "et", "eu", "fa",
    "fi", "fil", "fr", "fy", "ga", "gd", "gl", "gu", "ha", "haw", "hi",
    "hi-Latn", "hmn", "ht", "hu", "hy", "id", "ig", "is", "it", "iw", "ja",
    "ja-Latn", "jv", "ka", "kk", "km", "kn", "ko", "ku", "ky", "la", "lb", "lo",
    "lt", "lv", "mg", "mi", "mk", "ml", "mn", "mr", "ms", "mt", "my", "ne",
    "nl", "no", "ny", "pa", "pl", "ps", "pt", "ro", "ru", "ru-Latn", "sd", "si",
    "sk", "sl", "sm", "sn", "so", "sq", "sr", "st", "su", "sv", "sw", "ta",
    "te", "tg", "th", "tr", "uk", "ur", "uz", "vi", "xh", "yi", "yo", "zh",
    "zh-Latn", "zu"
]

class C4Config(tfds.core.BuilderConfig):
  """BuilderConfig for C4 dataset."""

  def __init__(self,
               name: str,
               languages: Sequence[str],
               cc_versions: Optional[Sequence[str]] = None,
               clean: bool = False,
               badwords_filter_fraction: float = 0.0,
               paragraph_filter: bool = False,
               dedupe: bool = True,
               realnewslike: bool = False,
               webtextlike: bool = False,
               **kwargs):
    """BuilderConfig for C4.

    Args:
      name: string, the name for the config.
      languages: list(string), the language code(s) to include.
      cc_versions: tuple(string), a collection of versions of Common Crawl to
        use as the raw source text. Set to None to use default.
      clean: bool, whether to heuristically filter out lines and pages
        considered low quality. Note: only expected to work reliably for English
        pages.
      badwords_filter_fraction: float, what fraction of pages to filter out that
        contain "bad words".
      paragraph_filter: bool, whether to filter out pages with too few or too
        short paragraphs.
      dedupe: bool, whether to deduplicate the dataset by paragraphs.
      realnewslike: bool, whether to limit to news domains as compiled by
        RealNews.
      webtextlike: bool, whether to limit to WebText-like URLs.
      **kwargs: keyword arguments forwarded to super.
    """
    super(C4Config, self).__init__(
        name=name,
        version=_VERSION,
        supported_versions=_SUPPORTED_VERSIONS,
        **kwargs)

    if clean and tuple(languages) != ("en",):
      logging.warning(
          "C4 cleaning is only expected to work reliably for English pages.")

    if not 0.0 <= badwords_filter_fraction <= 1.0:
      raise ValueError(
          "`badwords_filter_fraction` must be between 0.0 and 1.0.")

    self.languages = languages
    self.cc_versions = cc_versions or (DEFAULT_CC_VERSION,)
    self.clean = clean
    self.badwords_filter_fraction = badwords_filter_fraction
    self.paragraph_filter = paragraph_filter
    self.dedupe = dedupe
    self.realnewslike = realnewslike
    self.webtextlike = webtextlike

class C4(tfds.core.BeamBasedBuilder):
  """C4 dataset based on Common Crawl."""

  MANUAL_DOWNLOAD_INSTRUCTIONS = f"""
  You are using a C4 config that requires some files to be manually downloaded.
  For `c4/webtextlike`, download {_OPENWEBTEXT_URLS_ZIP} from
  {_OPENWEBTEXT_URLS_URL}.
  """

  BUILDER_CONFIGS = [
      C4Config(
          "en",
          languages=["en"],
          clean=True,
          dedupe=True,
          badwords_filter_fraction=1.0,
          description="English C4 dataset."),
      C4Config(
          "en.noclean",
          languages=["en"],
          clean=False,
          dedupe=False,
          badwords_filter_fraction=0.0,
          description="Disables all cleaning (deduplication, removal based on bad words, "
          "etc.)"),
      C4Config(
          "realnewslike",
          languages=["en"],
          realnewslike=True,
          clean=True,
          dedupe=True,
          badwords_filter_fraction=1.0,
          description="Filters from the default config to only include content from the "
          "domains used in the 'RealNews' dataset (Zellers et al., 2019)."),
      C4Config(
          "webtextlike",
          languages=["en"],
          cc_versions=OPENWEBTEXT_CC_VERSIONS,
          webtextlike=True,
          clean=True,
          dedupe=True,
          badwords_filter_fraction=1.0,
          description="Filters from the default config to only include content from the "
          "URLs in OpenWebText (https://github.com/jcpeterson/openwebtext)."),
      C4Config(
          "multilingual",
          languages=MC4_LANGUAGES,
          cc_versions=ALL_CC_VERSIONS,
          clean=False,
          paragraph_filter=True,
          dedupe=True,
          badwords_filter_fraction=0.999,
          description="Multilingual C4 (mC4) has 101 languages and is generated from 86 "
          "Common Crawl dumps."),
  ]

  def _info(self):
    features = {
        "text": tfds.features.Text(),
        "url": tfds.features.Text(),
        "content-type": tfds.features.Text(),
        "content-length": tfds.features.Text(),
        "timestamp": tfds.features.Text(),
    }
    return tfds.core.DatasetInfo(
        builder=self,
        description=_DESCRIPTION,
        features=tfds.features.FeaturesDict(features),
        citation=_CITATION,
        homepage="https://github.com/google-research/text-to-text-transfer-transformer#datasets",
    )

  def _split_generators(self, dl_manager, pipeline):
    # We will automatically download the first default CC version, but others
    # need to be manually downloaded.
    cc_versions = set(self.builder_config.cc_versions)
    files_to_download = {}
    files_to_download["wet_path_urls"] = [
        _WET_PATH_URL.format(cc_version=cc_version)
        for cc_version in cc_versions
    ]
    if self.builder_config.badwords_filter_fraction > 0.0:
      files_to_download["badwords"] = {
          lang: _BADWORDS_URL.format(lang=lang)
          for lang in _BADWORDS_LANGS
          if lang != "en"
      }
      # Use older "en" file for reproducibility of the original C4.
      files_to_download["badwords"]["en"] = _EN_BADWORDS_URL
    if self.builder_config.realnewslike:
      files_to_download["realnews_domains"] = _REALNEWS_DOMAINS_URL
    file_paths = dl_manager.download_and_extract(files_to_download)

    if self.builder_config.webtextlike:
      owt_path = os.path.join(dl_manager.manual_dir, _OPENWEBTEXT_URLS_ZIP)
      if not tf.io.gfile.exists(owt_path):
        raise AssertionError(
            "For the WebText-like config, you must manually download the "
            "following file from {0} and place it in {1}: {2}".format(
                _OPENWEBTEXT_URLS_URL, dl_manager.manual_dir,
                _OPENWEBTEXT_URLS_ZIP))
      file_paths["openwebtext_urls_zip"] = dl_manager.extract(owt_path)

    file_paths = tree_utils.map_structure(os.fspath, file_paths)

    pages_pcollection = self._get_pages_pcollection(pipeline, file_paths,
                                                    dl_manager)

    def _filter(page, lang, predicate_fn):
      return (page.language == lang and
              c4_utils.get_hashed_url_filter_fn(predicate_fn)(page))

    train_predicate_fn = lambda x: x % 1000 != 0  # 99.9%
    validation_predicate_fn = lambda x: x % 1000 == 0  # 00.1%

    if len(self.builder_config.languages) == 1:
      # Single-language version.
      return [
          tfds.core.SplitGenerator(
              name=tfds.Split.TRAIN,
              gen_kwargs=dict(
                  split="train",
                  pages=pages_pcollection,
                  split_filter_fn=c4_utils.get_hashed_url_filter_fn(
                      predicate_fn=train_predicate_fn)),
          ),
          tfds.core.SplitGenerator(
              name=tfds.Split.VALIDATION,
              gen_kwargs=dict(
                  split="validation",
                  pages=pages_pcollection,
                  split_filter_fn=c4_utils.get_hashed_url_filter_fn(
                      predicate_fn=validation_predicate_fn)),
          ),
      ]

    splits = []
    for lang in self.builder_config.languages + [c4_utils.UNKNOWN_LANGUAGE]:
      splits.extend([
          tfds.core.SplitGenerator(
              name=lang,
              gen_kwargs=dict(
                  split=lang,
                  pages=pages_pcollection,
                  split_filter_fn=functools.partial(
                      _filter, lang=lang, predicate_fn=train_predicate_fn),
              )),
          tfds.core.SplitGenerator(
              name=f"{lang}-validation",
              gen_kwargs=dict(
                  split=f"{lang}-validation",
                  pages=pages_pcollection,
                  split_filter_fn=functools.partial(
                      _filter, lang=lang, predicate_fn=validation_predicate_fn),
              ))
      ])
    return splits

  def _get_pages_pcollection(self, pipeline, file_paths, dl_manager):
    """Build PCollection of un-split page content."""
    beam = tfds.core.lazy_imports.apache_beam

    def download_wet_file(path, dl_dir):
      url = f"{_DOWNLOAD_HOST}/{path}"
      out_path = f"{dl_dir}/{path}"

      if tf.io.gfile.exists(out_path):
        c4_utils.get_counter_inc_fn("download_wet_url")("exists")
        return out_path

      tmp_dir = f"{out_path}.incomplete{uuid.uuid4().hex}"
      try:
        tf.io.gfile.makedirs(tmp_dir)
        downloader = tfds.download.download_manager.get_downloader()
        with downloader.tqdm():
          # TODO(slebedev): Investigate why pytype infers Promise[Future[...]].
          dl_path = downloader.download(url, tmp_dir).get().path  # type: ignore
        tf.io.gfile.rename(os.fspath(dl_path), out_path, overwrite=True)
      finally:
        if tf.io.gfile.exists(tmp_dir):
          tf.io.gfile.rmtree(tmp_dir)

        c4_utils.get_counter_inc_fn("download_wet_url")("downloaded")
      return out_path

    wet_file_paths = (
        pipeline
        | "create_wet_path_urls" >> beam.Create(file_paths["wet_path_urls"])
        | beam.io.ReadAllFromText(
            compression_type=beam.io.filesystem.CompressionTypes.UNCOMPRESSED)
        # Increase parallelism.
        | beam.Reshuffle()
        | "filter_corrupt_wet_files" >>
        beam.Filter(lambda p: p not in _KNOWN_CORRUPT_WET_FILES)
        | beam.Map(
            download_wet_file,
            dl_dir=os.path.join(dl_manager.download_dir, "c4_wet_files")))

    # Parse WET files and filter by length.
    # Output: [PageFeatures]
    pages = (
        wet_file_paths
        | beam.FlatMap(c4_utils.split_wet_file)
        | beam.Filter(c4_utils.is_valid_length))

    # Optionally filter for RealNews domains.
    # Output: [PageFeatures]
    if self.builder_config.realnewslike:
      with tf.io.gfile.GFile(file_paths["realnews_domains"]) as f:
        realnews_domains = json.load(f)
      pages |= beam.Filter(c4_utils.is_realnews_domain, realnews_domains)

    # Normalize and deduplicate by URL.
    # Output: [PageFeatures]
    pages = (
        pages
        | "normalize_url" >> beam.Map(lambda p: (p.normalized_url, p))
        | "select_newest" >> beam.CombinePerKey(c4_utils.select_newest_page)
        | beam.Values())

    # Optionally filter for WebText-like URLs.
    # Output: [PageFeatures]
    if self.builder_config.webtextlike:
      webtextlike_urls = (
          pipeline
          | "read_webtextlike_urls" >> beam.io.ReadFromText(
              os.path.join(file_paths["openwebtext_urls_zip"],
                           _OPENWEBTEXT_URLS_FILE_PATTERN))
          | "add_dummy_page" >>
          beam.Map(lambda url: (c4_utils.normalize_url(url), PageFeatures())))
      pages = ({
          "pages": pages | beam.Map(lambda p: (p.normalized_url, p)),
          "webtextlike_urls": webtextlike_urls
      }
               | "group_webtextlike_urls" >> beam.CoGroupByKey()
               | beam.FlatMap(c4_utils.filter_by_webtextlike))

    if self.builder_config.paragraph_filter:
      pages |= beam.Filter(c4_utils.paragraph_filter)

    if self.builder_config.clean:
      pages |= ("clean_pages" >> beam.FlatMap(c4_utils.get_clean_page_fn()))

    if self.builder_config.dedupe:
      pages = (
          # Also removes documents with too few sentences after deduplication.
          c4_utils.remove_duplicate_text(pages)  # pylint:disable=g-long-ternary
          if self.builder_config.clean else
          # If we are not cleaning, do not remove too-few-sentence documents.
          c4_utils.remove_duplicate_text(pages, min_num_sentences=0))

    # Add detected language.
    if self.builder_config.languages == ["en"]:
      # Use langdetect for reproducibility of the original C4.
      pages |= beam.FlatMap(c4_utils.detect_english)
    else:
      pages = c4_utils.detect_languages(
          pages, valid_languages=self.builder_config.languages)

    if self.builder_config.badwords_filter_fraction > 0.0:
      # Create dictionary of badwords regex for each available language.
      badwords = collections.defaultdict(set)
      for lang, path in file_paths["badwords"].items():
        lang = lang.split("-")[0]  # remove suffix if present
        with epath.Path(path).open() as f:
          badwords[lang].update(l.strip() for l in f)

      for lang, allowlist in _BADWORDS_ALLOWLIST.items():
        badwords[lang] -= allowlist

      pages |= beam.Filter(
          c4_utils.get_badwords_filter_fn(
              badwords,
              filter_fraction=self.builder_config.badwords_filter_fraction))

    return pages

  def _build_pcollection(self, unused_pipeline, split, pages, split_filter_fn):
    beam = tfds.core.lazy_imports.apache_beam

    def _emit_examples(page: PageFeatures):
      c4_utils.get_counter_inc_fn(split)("examples")
      return page.url, {
          "url": page.url,
          "text": page.text,
          "content-type": page.content_type,
          "content-length": page.content_length,
          "timestamp": page.timestamp
      }

    return (pages | beam.Filter(split_filter_fn) | beam.Map(_emit_examples))


text:
class NetworkManager;
class Settings;

class CLIENT_API ConfigController : public Controller
{
    Q_OBJECT

public:
    explicit ConfigController(QObject *parent = 0);
    ~ConfigController();

    // Controller interface
    Status status() const;
    QString errorString() const;

    bool init(NetworkManager *networkManager, Settings *settings);

public slots:
    void update();

protected:
    class Private;
    Private *d;
};

#endif // CONFIGCONTROLLER_H

redpajama_set_name: RedPajamaGithub


text:
package com.jdiazcano.modulartd.lwjgl3;

import com.badlogic.gdx.backends.lwjgl3.Lwjgl3Application;
import com.badlogic.gdx.backends.lwjgl3.Lwjgl3ApplicationConfiguration;
import com.jdiazcano.modulartd.ModularTD;

/** Launches the desktop (LWJGL3) application. */
public class Lwjgl3Launcher {
    public static void main(String[] args) {
        createApplication();
    }

    private static Lwjgl3Application createApplication() {
        return new Lwjgl3Application(new ModularTD(), getDefaultConfiguration());
    }

    private static Lwjgl3ApplicationConfiguration getDefaultConfiguration() {
        Lwjgl3ApplicationConfiguration configuration = new Lwjgl3ApplicationConfiguration();
        configuration.setTitle("ModularTD");
        configuration.setWindowedMode(640, 480);
        return configuration;
    }
}


text:
- Initialize repo
- Add `Number/Match Integer`


text:
(() => {
  'use strict';

  // The name used by this script to send alerts to the GM in the chat.
  const CHAT_NAME = 'ItsATrap-PF-Simple';

  // A mapping of saving throw short names to their attribute names.
  const SAVE_NAMES = {
    'fort': 'fort',
    'ref': 'ref',
    'will': 'will'
  };

  // Register the theme with ItsATrap.
  on('ready', () => {

    // Initialize state
    if(!state.TrapThemePFSimple)
      state.TrapThemePFSimple = {
        trapSpotterAttempts: {}
      };

    /**
     * A theme for the Pathfinder (Simple) OGL character sheet by Stephen L..
     */
    class TrapThemePFSimple extends D20TrapTheme {
      /**
       * @inheritdoc
       */
      get name() {
        return 'PF-Simple';
      }

      /**
       * @inheritdoc
       */
      getAC(character) {
        return TrapTheme.getSheetAttr(character, 'ac');
      }

      /**
       * @inheritdoc
       */
      getPassivePerception(character) {
        return TrapTheme.getSheetAttr(character, 'perception')
        .then(perception => {
          return perception + 10;
        });
      }

      /**
       * @inheritdoc
       */
      getSaveBonus(character, saveName) {
        return TrapTheme.getSheetAttr(character, SAVE_NAMES[saveName]);
      }

      /**
       * @inheritdoc
       */
      getThemeProperties(trapToken) {
        let result = super.getThemeProperties(trapToken);
        let save = _.find(result, item => {
          return item.id === 'save';
        });
        save.options = [ 'none', 'fort', 'ref', 'will' ];
        return result;
      }

      /**
       * @inheritdoc
       * Also supports the Trap Spotter ability.
       */
      passiveSearch(trap, charToken) {
        super.passiveSearch(trap, charToken);

        let character = getObj('character', charToken.get('represents'));
        let effect = (new TrapEffect(trap, charToken)).json;

        // Perform automated behavior for Trap Spotter.
        if((effect.type === 'trap' || _.isUndefined(effect.type)) && effect.spotDC && character) {
          TrapTheme.getSheetRepeatingRow(character, 'classabilities', rowAttrs => {
            if(!rowAttrs.name)
              return false;

            let abilityName = rowAttrs.name.get('current');
            return abilityName.toLowerCase().includes('trap spotter');
          })
          .then(trapSpotter => {
            let dist = ItsATrap.getSearchDistance(trap, charToken);
            if(trapSpotter && dist <= 10)
              this._trapSpotter(character, trap, effect);
          })
          .catch(err => {
            sendChat('Trap theme: ' + this.name, '/w gm ' + err.message);
            log(err.stack);
          });
        }
      }

      /**
       * Trap Spotter behavior.
       * @private
       */
      _trapSpotter(character, trap, effect) {
        // Quit early if this character has already attempted to trap-spot
        // this trap.
        let trapId = trap.get('_id');
        let charId = trap.get('_id');
        if(!state.TrapThemePFSimple.trapSpotterAttempts[trapId])
          state.TrapThemePFSimple.trapSpotterAttempts[trapId] = {};
        if(state.TrapThemePFSimple.trapSpotterAttempts[trapId][charId])
          return;
        else
          state.TrapThemePFSimple.trapSpotterAttempts[trapId][charId] = true;

        // Make a hidden Perception check to try to notice the trap.
        TrapTheme.getSheetAttr(character, 'perception')
        .then(perception => {
          if(_.isNumber(perception)) {
            return TrapTheme.rollAsync(`1d20 + ${perception}`);
          }
          else
            throw new Error('Trap Spotter: Could not get Perception value for Character ' + charToken.get('_id') + '.');
        })
        .then(searchResult => {
          // Inform the GM about the Trap Spotter attempt.
          sendChat('Trap theme: ' + this.name, `/w gm ${character.get('name')} attempted to notice trap "${trap.get('name')}" with Trap Spotter ability. Perception ${searchResult.total} vs DC ${effect.spotDC}`);

          // Resolve whether the trap was spotted or not.
          if(searchResult.total >= effect.spotDC) {
            let html = TrapTheme.htmlNoticeTrap(character, trap);
            ItsATrap.noticeTrap(trap, html.toString(TrapTheme.css));
          }
        })
        .catch(err => {
          sendChat('Trap theme: ' + this.name, '/w gm ' + err.message);
          log(err.stack);
        });
      }
    }

    ItsATrap.registerTheme(new TrapThemePFSimple());
  });
})();


text:
#include "data/hdf/HDFCmpFile.h"
#include "data/hdf/HDFBasReader.h"
#include "CommandLineParser.h"
#include "datastructures/alignment/ByteAlignment.h"
#include "datastructures/alignment/Alignment.h"
#include "algorithms/alignment/AlignmentPrinter.h"

int main(int argc, char* argv[]) {

	CommandLineParser clp;
	string cmpFileName;
	vector<int> holeNumbers;
	vector<string> patterns, refGroups;
  bool printAll = false;
	clp.RegisterStringOption("cmph5filename", &cmpFileName, "input cmp h5", false);
	clp.RegisterPreviousFlagsAsHidden();
	clp.RegisterIntListOption("holeNumbers", &holeNumbers, "hole numbers to print alignments", false);
	clp.RegisterStringListOption("pattern", &patterns, "patterns to search read names to print alignments", false);
  clp.RegisterFlagOption("all", &printAll, "Just print all alignments.", false);
  clp.RegisterStringListOption("refgroups", &refGroups, "Reference groups to print.", false);
	clp.ParseCommandLine(argc, argv);

	CmpFile cmpFile;

	/*
	 * These readers pull information from the same pls file.
	 */
	HDFCmpFile<CmpAlignment> hdfcmpFile;

	if (hdfcmpFile.Initialize(cmpFileName) == 0) {
		cout << "ERROR, could not open the cmp file." << endl;
		exit(0);
	}

	hdfcmpFile.Read(cmpFile);

	int alignmentIndex;
	for (alignmentIndex = 0; alignmentIndex < cmpFile.alnInfo.alignments.size(); alignmentIndex++) {
		int alnHoleNumber;
		alnHoleNumber = cmpFile.alnInfo.alignments[alignmentIndex].GetHoleNumber();
		int hi;
    bool printThisAlignment = false;

    //
    // Read the alignment string.  All alignments
    //
    int refGroupId = cmpFile.alnInfo.alignments[alignmentIndex].GetRefGroupId();
    int movieId    = cmpFile.alnInfo.alignments[alignmentIndex].GetMovieId();

    int refGroupIndex = hdfcmpFile.refGroupIdToArrayIndex[refGroupId];
    int readGroupIndex = hdfcmpFile.refAlignGroups[refGroupIndex]->movieIdToIndex[movieId];
    string refGroupPath = cmpFile.refGroup.path[refGroupIndex];

		for (hi = 0; hi < holeNumbers.size(); hi++) {
			if (alnHoleNumber == holeNumbers[hi]) {
        printThisAlignment = true;
        break;
      }
    }
    int ri;
    for (ri = 0; ri < refGroups.size(); ri++) {
      if (refGroups[ri] == refGroupPath) {
        printThisAlignment = true;
        break;
      }
    }

    if (printThisAlignment or printAll) {
      unsigned int alignStartIndex, alignEndIndex;
      UInt offsetBegin, offsetEnd;

      string   refSequence;
      string   readSequence;
      vector<unsigned char> byteAlignment;

      offsetBegin = cmpFile.alnInfo.alignments[alignmentIndex].GetOffsetBegin();
      offsetEnd   = cmpFile.alnInfo.alignments[alignmentIndex].GetOffsetEnd();
      int alignedSequenceLength = offsetEnd - offsetBegin;
      if (alignedSequenceLength >= 0) {
        refSequence.resize(alignedSequenceLength);
        byteAlignment.resize(alignedSequenceLength);
      }

      hdfcmpFile.refAlignGroups[refGroupIndex]->readGroups[readGroupIndex]->alignmentArray.Read(offsetBegin,
                                                                                offsetEnd,
                                                                                &byteAlignment[0]);

      readSequence.resize(byteAlignment.size());
      refSequence.resize(byteAlignment.size());

      ByteAlignmentToQueryString(&byteAlignment[0], byteAlignment.size(), &readSequence[0]);
      ByteAlignmentToRefString(&byteAlignment[0], byteAlignment.size(), &refSequence[0]);
      string ungappedRead, ungappedRef;
      RemoveGaps(readSequence, ungappedRead);
      RemoveGaps(refSequence, ungappedRef);
      Alignment alignment;
      GappedStringsToAlignment(readSequence, refSequence, alignment);
      DNASequence qAlignedSeq, rAlignedSeq;
      qAlignedSeq.seq = (Nucleotide*) &ungappedRead[0];
      qAlignedSeq.length = ungappedRead.size();
      rAlignedSeq.seq = (Nucleotide*) &ungappedRef[0];
      rAlignedSeq.length = ungappedRef.size();

      int qStart = cmpFile.alnInfo.alignments[alignmentIndex].GetQueryStart();
      int tStart = cmpFile.alnInfo.alignments[alignmentIndex].GetRefStart();
      stringstream sstrm;
      sstrm << alnHoleNumber << "/" << qStart << "_" << cmpFile.alnInfo.alignments[alignmentIndex].GetQueryEnd();
      alignment.qName = sstrm.str();
      StickPrintAlignment(alignment, qAlignedSeq, rAlignedSeq, cout, qStart, tStart);

    }
  }
}


text:
package com.blankj.utilcode.util;

import android.os.Build;
import android.util.SparseArray;
import android.util.SparseBooleanArray;
import android.util.SparseIntArray;
import android.util.SparseLongArray;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.Map;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.collection.LongSparseArray;
import androidx.collection.SimpleArrayMap;

/**
 *

 *     author: Blankj
 *     blog  : http://blankj.com
 *     time  : 2017/12/24
 *     desc  : utils about object
 *

 */
public final class ObjectUtils {

    private ObjectUtils() {
        throw new UnsupportedOperationException("u can't instantiate me...");
    }

    /**
     * Return whether object is empty.
     *
     * @param obj The object.
     * @return {@code true}: yes
{@code false}: no
     */
    public static boolean isEmpty(final Object obj) {
        if (obj == null) {
            return true;
        }
        if (obj.getClass().isArray() && Array.getLength(obj) == 0) {
            return true;
        }
        if (obj instanceof CharSequence && obj.toString().length() == 0) {
            return true;
        }
        if (obj instanceof Collection && ((Collection) obj).isEmpty()) {
            return true;
        }
        if (obj instanceof Map && ((Map) obj).isEmpty()) {
            return true;
        }
        if (obj instanceof SimpleArrayMap && ((SimpleArrayMap) obj).isEmpty()) {
            return true;
        }
        if (obj instanceof SparseArray && ((SparseArray) obj).size() == 0) {
            return true;
        }
        if (obj instanceof SparseBooleanArray && ((SparseBooleanArray) obj).size() == 0) {
            return true;
        }
        if (obj instanceof SparseIntArray && ((SparseIntArray) obj).size() == 0) {
            return true;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            if (obj instanceof SparseLongArray && ((SparseLongArray) obj).size() == 0) {
                return true;
            }
        }
        if (obj instanceof LongSparseArray && ((LongSparseArray) obj).size() == 0) {
            return true;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            if (obj instanceof android.util.LongSparseArray
                    && ((android.util.LongSparseArray) obj).size() == 0) {
                return true;
            }
        }
        return false;
    }

    public static boolean isEmpty(final CharSequence obj) {
        return obj == null || obj.toString().length() == 0;
    }

    public static boolean isEmpty(final Collection obj) {
        return obj == null || obj.isEmpty();
    }

    public static boolean isEmpty(final Map obj) {
        return obj == null || obj.isEmpty();
    }

    public static boolean isEmpty(final SimpleArrayMap obj) {
        return obj == null || obj.isEmpty();
    }

    public static boolean isEmpty(final SparseArray obj) {
        return obj == null || obj.size() == 0;
    }

    public static boolean isEmpty(final SparseBooleanArray obj) {
        return obj == null || obj.size() == 0;
    }

    public static boolean isEmpty(final SparseIntArray obj) {
        return obj == null || obj.size() == 0;
    }

    public static boolean isEmpty(final LongSparseArray obj) {
        return obj == null || obj.size() == 0;
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    public static boolean isEmpty(final SparseLongArray obj) {
        return obj == null || obj.size() == 0;
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    public static boolean isEmpty(final android.util.LongSparseArray obj) {
        return obj == null || obj.size() == 0;
    }

    /**
     * Return whether object is not empty.
     *
     * @param obj The object.
     * @return {@code true}: yes
{@code false}: no
     */
    public static boolean isNotEmpty(final Object obj) {
        return !isEmpty(obj);
    }

    public static boolean isNotEmpty(final CharSequence obj) {
        return !isEmpty(obj);
    }

    public static boolean isNotEmpty(final Collection obj) {
        return !isEmpty(obj);
    }

    public static boolean isNotEmpty(final Map obj) {
        return !isEmpty(obj);
    }

    public static boolean isNotEmpty(final SimpleArrayMap obj) {
        return !isEmpty(obj);
    }

    public static boolean isNotEmpty(final SparseArray obj) {
        return !isEmpty(obj);
    }

    public static boolean isNotEmpty(final SparseBooleanArray obj) {
        return !isEmpty(obj);
    }

    public static boolean isNotEmpty(final SparseIntArray obj) {
        return !isEmpty(obj);
    }

    public static boolean isNotEmpty(final LongSparseArray obj) {
        return !isEmpty(obj);
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    public static boolean isNotEmpty(final SparseLongArray obj) {
        return !isEmpty(obj);
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    public static boolean isNotEmpty(final android.util.LongSparseArray obj) {
        return !isEmpty(obj);
    }

    /**
     * Return whether object1 is equals to object2.
     *
     * @param o1 The first object.
     * @param o2 The second object.
     * @return {@code true}: yes
{@code false}: no
     */
    public static boolean equals(final Object o1, final Object o2) {
        return o1 == o2 || (o1 != null && o1.equals(o2));
    }

    /**
     * Returns 0 if the arguments are identical and {@code
     * c.compare(a, b)} otherwise.
     * Consequently, if both arguments are {@code null} 0
     * is returned.
     */
    public static <T> int compare(T a, T b, @NonNull Comparator<? super T> c) {
        return (a == b) ? 0 : c.compare(a, b);
    }

    /**
     * Checks that the specified object reference is not {@code null}.
     */
    public static <T> T requireNonNull(T obj) {
        if (obj == null) throw new NullPointerException();
        return obj;
    }

    /**
     * Checks that the specified object reference is not {@code null} and
     * throws a customized {@link NullPointerException} if it is.
     */
    public static <T> T requireNonNull(T obj, String ifNullTip) {
        if (obj == null) throw new NullPointerException(ifNullTip);
        return obj;
    }

    /**
     * Require the objects are not null.
     *
     * @param objects The object.
     * @throws NullPointerException if any object is null in objects
     */
    public static void requireNonNulls(final Object... objects) {
        if (objects == null) throw new NullPointerException();
        for (Object object : objects) {
            if (object == null) throw new NullPointerException();
        }
    }

    /**
     * Return the nonnull object or default object.
     *
     * @param object        The object.
     * @param defaultObject The default object to use with the object is null.
     * @param <T>           The value type.
     * @return the nonnull object or default object
     */
    public static <T> T getOrDefault(final T object, final T defaultObject) {
        if (object == null) {
            return defaultObject;
        }
        return object;
    }

    /**
     * Returns the result of calling {@code toString} for a non-{@code
     * null} argument and {@code "null"} for a {@code null} argument.
     */
    public static String toString(Object obj) {
        return String.valueOf(obj);
    }

    /**
     * Returns the result of calling {@code toString} on the first
     * argument if the first argument is not {@code null} and returns
     * the second argument otherwise.
     */
    public static String toString(Object o, String nullDefault) {
        return (o != null) ? o.toString() : nullDefault;
    }

    /**
     * Return the hash code of object.
     *
     * @param o The object.
     * @return the hash code of object
     */
    public static int hashCode(final Object o) {
        return o != null ? o.hashCode() : 0;
    }

    /**
     * Return the hash code of objects.
     */
    public static int hashCodes(Object... values) {
        return Arrays.hashCode(values);
    }
}


text:
export default class MainCtrl {
    constructor($scope, $window, $timeout) {
        this.timer;
        this.mapSize;

        this.$scope = $scope;
        this.$window = $window;
        this.$timeout = $timeout;

        this.draw = true;

        angular.element($window).bind('resize', this.onResize.bind(this));
    }
    onResize() {
        let value = this.getWindowDimensions();
        this.mapSize = {
            width: value.w + 'px',
            height: value.h + 'px'
        };
        this.timer = this.$timeout(() => {
            this.$scope.$apply(() => {
                this.draw = !this.draw;
                if (this.draw) {
                    this.$timeout.cancel(this.timer);
                }
            });
        })
    }

    getWindowDimensions() {
        return {
            'h': this.$window.innerHeight,
            'w': this.$window.innerWidth
        };
    }
}

MainCtrl.$inject = ['$scope', '$window', '$timeout'];


text:
<?php

namespace Drupal\slick\Form;

use Drupal\Core\Url;
use Drupal\Core\Render\Element;
use Drupal\Component\Utility\Html;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\blazy\Dejavu\BlazyAdminExtended;
use Drupal\slick\SlickManagerInterface;

/**
 * Provides resusable admin functions, or form elements.
 */
class SlickAdmin implements SlickAdminInterface {

  use StringTranslationTrait;

  /**
   * The blazy admin service.
   *
   * @var \Drupal\blazy\Dejavu\BlazyAdminExtended
   */
  protected $blazyAdmin;

  /**
   * The slick manager service.
   *
   * @var \Drupal\slick\SlickManagerInterface
   */
  protected $manager;

  /**
   * Constructs a SlickAdmin object.
   *
   * @param \Drupal\blazy\Dejavu\BlazyAdminExtended $blazy_admin
   *   The blazy admin service.
   * @param \Drupal\slick\SlickManagerInterface $manager
   *   The slick manager service.
   */
  public function __construct(BlazyAdminExtended $blazy_admin, SlickManagerInterface $manager) {
    $this->blazyAdmin = $blazy_admin;
    $this->manager = $manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static (
      $container->get('blazy.admin.extended'),
      $container->get('slick.manager')
    );
  }

  /**
   * Returns the blazy admin formatter.
   */
  public function blazyAdmin() {
    return $this->blazyAdmin;
  }

  /**
   * Returns the slick manager.
   */
  public function manager() {
    return $this->manager;
  }

  /**
   * Returns the main form elements.
   */
  public function buildSettingsForm(array &$form, $definition = []) {
    $definition['caches']           = isset($definition['caches']) ? $definition['caches'] : TRUE;
    $definition['namespace']        = 'slick';
    $definition['optionsets']       = isset($definition['optionsets']) ? $definition['optionsets'] : $this->getOptionsetsByGroupOptions('main');
    $definition['skins']            = isset($definition['skins']) ? $definition['skins'] : $this->getSkinsByGroupOptions('main');
    $definition['responsive_image'] = isset($definition['responsive_image']) ? $definition['responsive_image'] : TRUE;

    foreach (['optionsets', 'skins'] as $key) {
      if (isset($definition[$key]['default'])) {
        ksort($definition[$key]);
        $definition[$key] = ['default' => $definition[$key]['default']] + $definition[$key];
      }
    }

    if (empty($definition['no_layouts'])) {
      $definition['layouts'] = isset($definition['layouts']) ? array_merge($this->getLayoutOptions(), $definition['layouts']) : $this->getLayoutOptions();
    }

    $this->openingForm($form, $definition);

    if (!empty($definition['image_style_form']) && !isset($form['image_style'])) {
      $this->imageStyleForm($form, $definition);
    }

    if (!empty($definition['media_switch_form']) && !isset($form['media_switch'])) {
      $this->mediaSwitchForm($form, $definition);
    }

    if (!empty($definition['grid_form']) && !isset($form['grid'])) {
      $this->gridForm($form, $definition);
    }

    if (!empty($definition['fieldable_form']) && !isset($form['image'])) {
      $this->fieldableForm($form, $definition);
    }

    if (!empty($definition['breakpoints'])) {
      $this->blazyAdmin->breakpointsForm($form, $definition);
    }

    if (!empty($definition['style']) && isset($form['style']['#description'])) {
      $form['style']['#description'] .= ' ' . $this->t('CSS3 Columns is best with adaptiveHeight, non-vertical. Will use regular carousel as default style if left empty. Yet, both CSS3 Columns and Grid Foundation are respected as Grid displays when Grid large option is provided.');
    }

    $this->closingForm($form, $definition);
  }

  /**
   * Returns the opening form elements.
   */
  public function openingForm(array &$form, $definition = []) {
    $path         = drupal_get_path('module', 'slick');
    $readme       = Url::fromUri('base:' . $path . '/README.txt')->toString();
    $readme_field = Url::fromUri('base:' . $path . '/src/Plugin/Field/README.txt')->toString();
    $arrows       = $this->getSkinsByGroupOptions('arrows');
    $dots         = $this->getSkinsByGroupOptions('dots');

    if (!isset($form['optionset'])) {
      $this->blazyAdmin->openingForm($form, $definition);

      $form['optionset']['#title'] = $this->t('Optionset main');

      if ($this->manager()->getModuleHandler()->moduleExists('slick_ui')) {
        $route_name = 'entity.slick.collection';
        $form['optionset']['#description'] = $this->t('Manage optionsets at the optionset admin page.', [':url' => Url::fromRoute($route_name)->toString()]);
      }
    }

    if (!empty($definition['nav']) || !empty($definition['thumbnails'])) {
      $form['optionset_thumbnail'] = [
        '#type'        => 'select',
        '#title'       => $this->t('Optionset thumbnail'),
        '#options'     => $this->getOptionsetsByGroupOptions('thumbnail'),
        '#description' => $this->t('If provided, asNavFor aka thumbnail navigation applies. Leave empty to not use thumbnail navigation.'),
        '#weight'      => -108,
      ];

      $form['skin_thumbnail'] = [
        '#type'        => 'select',
        '#title'       => $this->t('Skin thumbnail'),
        '#options'     => $this->getSkinsByGroupOptions('thumbnail'),
        '#description' => $this->t('Thumbnail navigation skin. See main README for details on Skins. Leave empty to not use thumbnail navigation.', ['@url' => $readme]),
        '#weight'      => -106,
      ];
    }

    if (count($arrows) > 0) {
      $form['skin_arrows'] = [
        '#type'        => 'select',
        '#title'       => $this->t('Skin arrows'),
        '#options'     => $arrows ?: [],
        '#enforced'    => TRUE,
        '#description' => $this->t('Implement \Drupal\slick\SlickSkinInterface::arrows() to add your own arrows skins, in the same format as SlickSkinInterface::skins().'),
        '#weight'      => -105,
      ];
    }

    if (count($dots) > 0) {
      $form['skin_dots'] = [
        '#type'        => 'select',
        '#title'       => $this->t('Skin dots'),
        '#options'     => $dots ?: [],
        '#enforced'    => TRUE,
        '#description' => $this->t('Implement \Drupal\slick\SlickSkinInterface::dots() to add your own dots skins, in the same format as SlickSkinInterface::skins().'),
        '#weight'      => -105,
      ];
    }

    if (!empty($definition['thumb_positions'])) {
      $form['thumbnail_position'] = [
        '#type'        => 'select',
        '#title'       => $this->t('Thumbnail position'),
        '#options' => [
          'left'       => $this->t('Left'),
          'right'      => $this->t('Right'),
          'top'        => $this->t('Top'),
          'over-left'  => $this->t('Overlay left'),
          'over-right' => $this->t('Overlay right'),
          'over-top'   => $this->t('Overlay top'),
        ],
        '#description' => $this->t('By default thumbnail is positioned at bottom. Hence to change the position of thumbnail. Only reasonable with 1 visible main stage at a time. Except any TOP, the rest requires Vertical option enabled for Optionset thumbnail, and a custom CSS height to selector .slick--thumbnail to avoid overflowing tall thumbnails, or adjust slidesToShow to fit the height. Further theming is required as usual. Overlay is absolutely positioned over the stage rather than sharing the space. See skin X VTabs for vertical thumbnail sample.'),
        '#states' => [
          'visible' => [
            'select[name*="[optionset_thumbnail]"]' => ['!value' => ''],
          ],
        ],
        '#weight'      => -99,
      ];
    }

    if (!empty($definition['thumb_captions'])) {
      $form['thumbnail_caption'] = [
        '#type'        => 'select',
        '#title'       => $this->t('Thumbnail caption'),
        '#options'     => $definition['thumb_captions'],
        '#description' => $this->t('Thumbnail caption maybe just title/ plain text. If Thumbnail image style is not provided, the thumbnail pagers will be just text like regular tabs.'),
        '#states' => [
          'visible' => [
            'select[name*="[optionset_thumbnail]"]' => ['!value' => ''],
          ],
        ],
        '#weight'      => 2,
      ];
    }

    if (isset($form['skin'])) {
      $form['skin']['#title'] = $this->t('Skin main');
      $form['skin']['#description'] = $this->t('Skins allow various layouts with just CSS. Some options below depend on a skin. However a combination of skins and options may lead to unpredictable layouts, get yourself dirty. E.g.: Skin Split requires any split layout option. Failing to choose the expected layout makes it useless. See SKINS section at README.txt for details on Skins. Leave empty to DIY. Or use hook_slick_skins_info() and implement \Drupal\slick\SlickSkinInterface to register ones.', [':url' => $readme]);
    }

    if (isset($form['layout'])) {
      $form['layout']['#description'] = $this->t('Requires a skin. The builtin layouts affects the entire slides uniformly. Split half requires any skin Split. See README under "Slide layout" for more info. Leave empty to DIY.', ['@url' => $readme_field]);
    }

    $weight = -99;
    foreach (Element::children($form) as $key) {
      if (!isset($form[$key]['#weight'])) {
        $form[$key]['#weight'] = ++$weight;
      }
    }
  }

  /**
   * Returns the image formatter form elements.
   */
  public function mediaSwitchForm(array &$form, $definition = []) {
    $this->blazyAdmin->mediaSwitchForm($form, $definition);

    if (isset($form['media_switch'])) {
      $form['media_switch']['#description'] = $this->t('Depends on the enabled supported modules, or has known integration with Slick.

Link to content: for aggregated small slicks.

Image to iframe: audio/video is hidden below image until toggled, otherwise iframe is always displayed, and draggable fails. Aspect ratio applies.

Colorbox.

Photobox. Be sure to select "Thumbnail style" for the overlay thumbnails.

Intense: image to fullscreen intense image.
');

      if (!empty($definition['multimedia']) && isset($definition['fieldable_form'])) {
        $form['media_switch']['#description'] .= ' ' . $this->t('
Image rendered by its formatter: image-related settings here will be ignored: breakpoints, image style, CSS background, aspect ratio, lazyload, etc. Only choose if needing a special image formatter such as Image Link Formatter.
');
      }

      $form['media_switch']['#description'] .= ' ' . $this->t('
 Try selecting "- None -" first before changing if trouble with this complex form states.');
    }

    if (isset($form['ratio']['#description'])) {
      $form['ratio']['#description'] .= ' ' . $this->t('Required if using media entity to switch between iframe and overlay image, otherwise DIY.');
    }
  }

  /**
   * Returns the image formatter form elements.
   */
  public function imageStyleForm(array &$form, $definition = []) {
    $definition['thumbnail_style'] = isset($definition['thumbnail_style']) ? $definition['thumbnail_style'] : TRUE;
    $definition['ratios'] = isset($definition['ratios']) ? $definition['ratios'] : TRUE;

    $definition['thumbnail_effect'] = [
      'hover' => $this->t('Hoverable'),
      'grid'  => $this->t('Static grid'),
    ];

    if (!isset($form['image_style'])) {
      $this->blazyAdmin->imageStyleForm($form, $definition);

      $form['image_style']['#description'] = $this->t('The main image style. This will be treated as the fallback image, which is normally smaller, if Breakpoints are provided, and if Use CSS background is disabled. Otherwise this is the only image displayed. Ignored by Responsive image option.');
    }

    if (isset($form['thumbnail_style'])) {
      $form['thumbnail_style']['#description'] = $this->t('Usages:

If Optionset thumbnail provided, it is for asNavFor thumbnail navigation.

For Thumbnail effect.

Photobox thumbnail.

Custom work via the provided data-thumb attributes: arrows with thumbnails, Photoswipe thumbnail, etc.

Leave empty to not use thumbnails.');
    }

    if (isset($form['thumbnail_effect'])) {
      $form['thumbnail_effect']['#description'] = $this->t('Dependent on a Skin, Dots and Thumbnail style options. No asnavfor/ Optionset thumbnail is needed.

Hoverable: Dots pager are kept, and thumbnail will be hidden and only visible on dot mouseover, default to min-width 120px.

Static grid: Dots are hidden, and thumbnails are displayed as a static grid acting like dots pager.

Alternative to asNavFor aka separate thumbnails as slider.');
    }

    if (isset($form['background'])) {
      $form['background']['#description'] .= ' ' . $this->t('Works best with a single visible slide, skins full width/screen.');
    }
  }

  /**
   * Returns re-usable fieldable formatter form elements.
   */
  public function fieldableForm(array &$form, $definition = []) {
    $this->blazyAdmin->fieldableForm($form, $definition);

    if (isset($form['thumbnail'])) {
      $form['thumbnail']['#description'] = $this->t("Only needed if Optionset thumbnail is provided. Maybe the same field as the main image, only different instance and image style. Leave empty to not use thumbnail pager.");
    }

    if (isset($form['overlay'])) {
      $form['overlay']['#title'] = $this->t('Overlay media/slicks');
      $form['overlay']['#description'] = $this->t('For audio/video, be sure the display is not image. For nested slicks, use the Slick carousel formatter for this field. Zebra layout is reasonable for overlay and captions.');
    }
  }

  /**
   * Returns re-usable grid elements across Slick field formatter and Views.
   */
  public function gridForm(array &$form, $definition = []) {
    if (!isset($form['grid'])) {
      $this->blazyAdmin->gridForm($form, $definition);
    }

    $header = $this->t('Group individual item as block grid?An older alternative to core Rows option. Only works if the total items > Visible slides.
block grid != slidesToShow option, yet both can work in tandem.
block grid = Rows option, yet the first is module feature, the later core.');

    $form['grid_header']['#markup'] = '
' . $header . '
';

    $form['grid']['#description'] = $this->t('The amount of block grid columns for large monitors 64.063em - 90em.
Requires:

Visible items,

Skin Grid for starter,

A reasonable amount of contents,

Optionset with Rows and slidesPerRow = 1.

This is module feature, older than core Rows, and offers more flexibility. Leave empty to DIY, or to not build grids.');
  }

  /**
   * Returns the closing ending form elements.
   */
  public function closingForm(array &$form, $definition = []) {
    $form['override'] = [
      '#title'       => $this->t('Override main optionset'),
      '#type'        => 'checkbox',
      '#description' => $this->t('If checked, the following options will override the main optionset. Useful to re-use one optionset for several different displays.'),
      '#weight'      => 112,
      '#enforced'    => TRUE,
    ];

    $form['overridables'] = [
      '#type'        => 'checkboxes',
      '#title'       => $this->t('Overridable options'),
      '#description' => $this->t("Override the main optionset to re-use one. Anything dictated here will override the current main optionset. Unchecked means FALSE"),
      '#options'     => $this->getOverridableOptions(),
      '#weight'      => 113,
      '#enforced'    => TRUE,
      '#states' => [
        'visible' => [
          ':input[name$="[override]"]' => ['checked' => TRUE],
        ],
      ],
    ];

    $this->blazyAdmin->closingForm($form, $definition);
  }

  /**
   * Returns overridable options to re-use one optionset.
   */
  public function getOverridableOptions() {
    $options = [
      'arrows'        => $this->t('Arrows'),
      'autoplay'      => $this->t('Autoplay'),
      'dots'          => $this->t('Dots'),
      'draggable'     => $this->t('Draggable'),
      'infinite'      => $this->t('Infinite'),
      'mouseWheel'    => $this->t('Mousewheel'),
      'randomize'     => $this->t('Randomize'),
      'variableWidth' => $this->t('Variable width'),
    ];

    $this->manager->getModuleHandler()->alter('slick_overridable_options_info', $options);
    return $options;
  }

  /**
   * Returns default layout options for the core Image, or Views.
   */
  public function getLayoutOptions() {
    return [
      'bottom'      => $this->t('Caption bottom'),
      'top'         => $this->t('Caption top'),
      'right'       => $this->t('Caption right'),
      'left'        => $this->t('Caption left'),
      'center'      => $this->t('Caption center'),
      'center-top'  => $this->t('Caption center top'),
      'below'       => $this->t('Caption below the slide'),
      'stage-right' => $this->t('Caption left, stage right'),
      'stage-left'  => $this->t('Caption right, stage left'),
      'split-right' => $this->t('Caption left, stage right, split half'),
      'split-left'  => $this->t('Caption right, stage left, split half'),
      'stage-zebra' => $this->t('Stage zebra'),
      'split-zebra' => $this->t('Split half zebra'),
    ];
  }

  /**
   * Returns available slick optionsets by group.
   */
  public function getOptionsetsByGroupOptions($group = '') {
    $optionsets = $groups = $ungroups = [];
    $slicks = $this->manager->entityLoadMultiple('slick');
    foreach ($slicks as $slick) {
      $name = Html::escape($slick->label());
      $id = $slick->id();
      $current_group = $slick->getGroup();
      if (!empty($group)) {
        if ($current_group) {
          if ($current_group != $group) {
            continue;
          }
          $groups[$id] = $name;
        }
        else {
          $ungroups[$id] = $name;
        }
      }
      $optionsets[$id] = $name;
    }

    return $group ? array_merge($ungroups, $groups) : $optionsets;
  }

  /**
   * Returns available slick skins for select options.
   */
  public function getSkinsByGroupOptions($group = '') {
    return $this->manager->getSkinsByGroup($group, TRUE);
  }

  /**
   * Return the field formatter settings summary.
   *
   * @deprecated: Removed for self::getSettingsSummary().
   */
  public function settingsSummary($plugin, $definition = []) {
    return $this->blazyAdmin->settingsSummary($plugin, $definition);
  }

  /**
   * Return the field formatter settings summary.
   *
   * @todo: Remove second param $plugin for post-release for Blazy RC2+.
   */
  public function getSettingsSummary($definition = [], $plugin = NULL) {
    // @todo: Remove condition for Blazy RC2+.
    if (!method_exists($this->blazyAdmin, 'getSettingsSummary')) {
      return $this->blazyAdmin->settingsSummary($plugin, $definition);
    }

    return $this->blazyAdmin->getSettingsSummary($definition);
  }

  /**
   * Returns available fields for select options.
   */
  public function getFieldOptions($target_bundles = [], $allowed_field_types = [], $entity_type_id = 'media', $target_type = '') {
    return $this->blazyAdmin->getFieldOptions($target_bundles, $allowed_field_types, $entity_type_id, $target_type);
  }

  /**
   * Returns re-usable logic, styling and assets across fields and Views.
   */
  public function finalizeForm(array &$form, $definition = []) {
    $this->blazyAdmin->finalizeForm($form, $definition);
  }

}


text:
<!doctype html>

  <meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1.0, user-scalable=yes">
  <title>flip-card Demo</title>

  <link rel="import" href="flip-card.html">

A `flip-card` looks like this:

  <flip-card>
    <front>Front of card</front>
    <back>Back of card</back>
  </flip-card>

You can also rotate vertically by providing `axis="x"`:

  <flip-card axis="x">
    <front>Front of card</front>
    <back>Back of card</back>
  </flip-card>


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.42000
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace ToyPicsDL_GUI.Properties {

    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "14.0.0.0")]
    internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {

        private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));

        public static Settings Default {
            get {
                return defaultInstance;
            }
        }

        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("C:\\Users\\Public\\Videos\\")]
        public string saveLocation {
            get {
                return ((string)(this["saveLocation"]));
            }
            set {
                this["saveLocation"] = value;
            }
        }

        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.DefaultSettingValueAttribute("0")]
        public ulong timesDownloaded {
            get {
                return ((ulong)(this["timesDownloaded"]));
            }
            set {
                this["timesDownloaded"] = value;
            }
        }

        [global::System.Configuration.UserScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        public global::System.Collections.Specialized.StringCollection history {
            get {
                return ((global::System.Collections.Specialized.StringCollection)(this["history"]));
            }
            set {
                this["history"] = value;
            }
        }
    }
}


text:
<?php
App::uses('RolesUsersController', 'Controller');

/**
 * RolesUsersController Test Case
 *
 */
class RolesUsersControllerTest extends ControllerTestCase {

/**
 * Fixtures
 *
 * @var array
 */
	public $fixtures = array(
		'app.roles_user',
		'app.role',
		'app.user',
		'app.profile',
		'app.enrollment',
		'app.section',
		'app.course',
		'app.term',
		'app.assignment',
		'app.res_folder',
		'app.res_file',
		'app.submission',
		'app.courses_user',
		'app.section_type',
		'app.sections_user',
		'app.grade',
		'app.permission',
		'app.permissions_user'
	);

}


text:
namespace Alphora.Dataphor.Dataphoria.Web.Core.Models
{
	public interface IGenerator
	{
		string NextResourceId(string resource);
		string NextVersionId(string resource);
		bool CustomResourceIdAllowed(string value);
	}
}


text:
<?php
/**
 *
 */

namespace Mvc5\Http;

use Mvc5\Config\Configuration;

interface Headers
    extends Configuration
{
}


text:
import language.experimental.erasedDefinitions
import annotation.experimental

@experimental
erased class Foo

erased class Bar // error

@experimental
erased def foo = 2

erased def bar = 2 // error

@experimental
erased val foo2 = 2

erased val bar2 = 2 // error

@experimental
def foo3(erased a: Int) = 2

def bar3(erased a: Int) = 2 // error


text:
class IThreadControl
{
public:
	virtual void ThreadStartCallback() = 0;
	virtual void ThreadExitCallback() = 0;
};

class SoraThread
{
public:
	SoraThread();

	HRESULT Start(bool sync);
	HRESULT Stop(bool sync);
	HRESULT Suspend();
	HRESULT Resume();

	void SetCallback(IThreadControl * callback);

	virtual void Threadfunc() = 0;
	bool CheckStatus();

	enum STATE {
		RUNNING,
		STOPPED,
		SUSPENDED,
	} state;

	enum STATE GetState();

private:
	static DWORD WINAPI ThreadProc(PVOID);
	HANDLE thread;
	DWORD threadID;

	WaitObj syncStartObj;
	WaitObj syncEndObj;
	WaitObj syncSuspendObj;

	bool flagStop;

	IThreadControl * threadCallback;

	void RunThreadStartCallback();
	void RunThreadEndCallback();
	void RunThreadFunction();

};


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/black"
    >

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="Black fragment"
        android:textColor="@android:color/white"
        style="?android:attr/textAppearanceLarge"
        android:gravity="center"
        />

</RelativeLayout>


text:
<?php

namespace WellCommerce\Bundle\CatalogBundle\Controller\Admin;

use WellCommerce\Bundle\CoreBundle\Controller\Admin\AbstractAdminController;

/**
 * Class AvailabilityController
 *
 * @author  Adam Piotrowski <adam@wellcommerce.org>
 */
class AvailabilityController extends AbstractAdminController
{
}


text:
import { connect } from 'react-redux'
import View from 'app/components/service'

var Container = connect(
  (state) => {
    return {
      location: state.router.location.pathname
    }
  },
  (dispatch) => ({
  })
)(View)

export default Container


text:
package com.mattyork.jarhn.AsyncTasks;

import org.apache.http.client.methods.HttpGet;

import android.content.Context;
import android.os.AsyncTask;

import com.mattyork.jarhn.Dtos.DtoLoginResponse;

public class LoginPart2AsyncTask extends AsyncTask<Void, Void, DtoLoginResponse> {

	Context context;
	String mUsername;
	String mPassword;
	String url;

	public LoginPart2AsyncTask(String username , String password) {
		// TODO Auto-generated constructor stub
		this.mUsername = username;
		this.mPassword = password;
		this.url = "https://news.ycombinator.com/" + "newslogin?whence=%6e%65%77%73";
	}

	@Override
	protected DtoLoginResponse doInBackground(
			Void... arg0) {

		HttpGet httpGet = new HttpGet(url);/*
		try
			//Make the request
			HttpResponse response = Service.client.execute(httpGet);

			//Get cookie
			List<Cookie> cookies = Service.client.getCookieStore().getCookies();
			if (cookies.size() > 0) {
				@SuppressWarnings("unused")
				Cookie cookie = cookies.get(0);
			}
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/

		return null;
	}

}


text:
package org.xcolab.service.contest.domain.proposaltemplatesection;

import org.jooq.DSLContext;
import org.jooq.Record;
import org.jooq.SelectQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import org.xcolab.client.contest.pojo.IProposalTemplateSection;
import org.xcolab.client.contest.pojo.tables.pojos.ProposalTemplateSection;

import java.util.List;

import static org.xcolab.model.Tables.PROPOSAL_TEMPLATE_SECTION;

@Repository
public class ProposalTemplateSectionDaoImpl implements ProposalTemplateSectionDao {

    private final DSLContext dslContext;

    @Autowired
    public ProposalTemplateSectionDaoImpl(DSLContext dslContext) {
        this.dslContext = dslContext;
    }

    @Override
    public List<IProposalTemplateSection> findByGiven(Long proposalTemplateId, Long sectionDefinition) {
        final SelectQuery<Record> query = dslContext.select()
                .from(PROPOSAL_TEMPLATE_SECTION).getQuery();
        if (proposalTemplateId != null) {
            query.addConditions(PROPOSAL_TEMPLATE_SECTION.PROPOSAL_TEMPLATE_ID.eq(proposalTemplateId));
        }

        if (sectionDefinition != null) {
            query.addConditions(PROPOSAL_TEMPLATE_SECTION.SECTION_DEFINITION_ID.eq(sectionDefinition));
        }

        return query.fetchInto(ProposalTemplateSection.class);
    }

    @Override
    public IProposalTemplateSection create(IProposalTemplateSection proposalTemplateSection) {

        this.dslContext.insertInto(PROPOSAL_TEMPLATE_SECTION)
                .set(PROPOSAL_TEMPLATE_SECTION.PROPOSAL_TEMPLATE_ID, proposalTemplateSection.getProposalTemplateId())
                .set(PROPOSAL_TEMPLATE_SECTION.SECTION_DEFINITION_ID, proposalTemplateSection.getSectionDefinitionId())
                .set(PROPOSAL_TEMPLATE_SECTION.WEIGHT, proposalTemplateSection.getWeight())
                .execute();
        return proposalTemplateSection;
    }

    @Override
    public int delete(Long proposalTemplateId, Long sectionDefinitionId) {
        return dslContext.deleteFrom(PROPOSAL_TEMPLATE_SECTION)
                .where(PROPOSAL_TEMPLATE_SECTION.PROPOSAL_TEMPLATE_ID.eq(proposalTemplateId))
                .and(PROPOSAL_TEMPLATE_SECTION.SECTION_DEFINITION_ID.eq(sectionDefinitionId))
                .execute();
    }

    @Override
    public boolean update(IProposalTemplateSection proposalTemplateSection) {
        return dslContext.update(PROPOSAL_TEMPLATE_SECTION)
                .set(PROPOSAL_TEMPLATE_SECTION.WEIGHT, proposalTemplateSection.getWeight())
                .where(PROPOSAL_TEMPLATE_SECTION.PROPOSAL_TEMPLATE_ID.eq(proposalTemplateSection.getProposalTemplateId()))
                .and(PROPOSAL_TEMPLATE_SECTION.SECTION_DEFINITION_ID.eq(proposalTemplateSection.getSectionDefinitionId()))
                .execute() > 0;
    }
}


text:
package com.intellij.plugins.haxe.ide.projectStructure;

import com.intellij.openapi.module.ModuleConfigurationEditor;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.roots.CompilerModuleExtension;
import com.intellij.openapi.roots.ui.configuration.ModuleConfigurationState;
import com.intellij.plugins.haxe.HaxeBundle;
import com.intellij.plugins.haxe.ide.projectStructure.ui.HaxeConfigurationEditor;
import org.jetbrains.annotations.Nls;

import javax.swing.*;

/**
 * @author: Fedor.Korotkov
 */
public class HaxeModuleConfigurationEditor implements ModuleConfigurationEditor {
  private HaxeConfigurationEditor haxeConfigurationEditor;

  public HaxeModuleConfigurationEditor(ModuleConfigurationState state) {
    haxeConfigurationEditor = new HaxeConfigurationEditor(state.getRootModel().getModule(), state.getRootModel().getModuleExtension(
      CompilerModuleExtension.class));
  }

  @Override
  public void saveData() {
  }

  @Override
  public void moduleStateChanged() {
  }

  @Nls
  @Override
  public String getDisplayName() {
    return HaxeBundle.message("haxe.module.editor.haxe");
  }

  @Override
  public String getHelpTopic() {
    return null;
  }

  @Override
  public JComponent createComponent() {
    return haxeConfigurationEditor == null ? null : haxeConfigurationEditor.getMainPanel();
  }

  @Override
  public boolean isModified() {
    return haxeConfigurationEditor != null && haxeConfigurationEditor.isModified();
  }

  @Override
  public void apply() throws ConfigurationException {
    // FIXME: This is hacky workaround - need to investigate the issue https://github.com/HaxeFoundation/intellij-haxe/issues/728
    if (haxeConfigurationEditor != null) {
      haxeConfigurationEditor.apply();
      haxeConfigurationEditor = null;
    }
  }

  @Override
  public void reset() {
    if (haxeConfigurationEditor != null) {
      haxeConfigurationEditor.reset();
    }
  }

  @Override
  public void disposeUIResources() {
  }
}


text:
/**
 * nullOfReturnType allows us to extract the return type of a function; this is
 * necessary because typescript does not currently have a syntax to directly
 * extract the return type of a function.
 *
 * This is needed in cases where:
 * 1. A function returns an object with a complex type which is not explicitly
 * declared. This occurs, for example, when constructing lookup objects that
 * contain many fields: explicitly declaring the return type results in
 * significant boilerplate which is unnecessary, because typescript knows the
 * type of the variable being returned.
 * 2. We need to declare a variable to hold the output of this function, but
 * cannot immediately assign the output of the function to the variable.
 *
 * The output of nullOfReturnType() cannot be directly fed into a typeof
 * statement; instead, its result must be stored in a variable, and in turn
 * that variable can be used with a typeof statement.
 *
 * An example of extracting type information using nullOfReturnType():
 *
 * function fnWithComplicatedResult() {
 *  return {...};
 * }
 *
 * const complicatedReturnType = nullOfReturnType(fnWithComplicatedReturn);
 * let complicatedVariable: typeof complicatedReturnType;
 */
export function nullOfReturnType<R> (_: (...args: any[]) => R): R {
    return null;
}


text:
package org.wtk.util.json;

import net.sf.json.processors.JsonValueProcessorMatcher;

import java.util.Set;

/**
 * Matches value processor by inheritance.
 *
 * @author Yoav Aharoni
 */
public class InheritaceJsonValueProcessorMatcher extends JsonValueProcessorMatcher {
	private static final JsonValueProcessorMatcher INSTANCE = new InheritaceJsonValueProcessorMatcher();

	@SuppressWarnings({"unchecked"})
	@Override
	public Object getMatch(Class target, Set set) {
		for (Class clazz : (Set<Class>) set) {
			if (clazz.isAssignableFrom(target)) {
				return clazz;
			}
		}
		return null;
	}

	public static JsonValueProcessorMatcher getInstance() {
		return INSTANCE;
	}
}


text:
import moment from 'moment'
import textTable from 'text-table'

const find = (apiWrapper) => (search, options) => {
  const {
    startdate,
    enddate,
    businessunitids
  } = options
  return new Promise((resolve, reject) => {
    apiWrapper.getActivities({
      startdate,
      enddate,
      businessunitids
    })
    .then((response) => {
      const searchParam = search.toLowerCase()
      const activities = response.activities.activity
      const foundActivities = activities.filter((activity) => {
        const name = activity.product.name.toLowerCase()
        const bookableSlots = parseInt(activity.bookableslots, 10)

        return name.indexOf(searchParam) !== -1 && bookableSlots > 0
      })
      .map((activity) => {
        const startTime = activity.start.timepoint.datetime
        const dayOfWeek = moment(startTime).format('dddd')
        const time = moment(startTime).format('HH:mm')

        return [
          activity.id,
          dayOfWeek,
          time,
          activity.product.name,
          activity.bookableslots
        ]
      })

      if (foundActivities.length === 0) {
        resolve('No activities found')
      }

      const table = textTable(foundActivities)
      const spacedTable = `\`\`\`${table.toString()}\`\`\``
      resolve(spacedTable)
    })
  })
}

export default find


text:
module Cv

  class Contact < Struct.new(:name, :address, :state, :email)
  end

  class Profile < Struct.new(:items)
  end

  class Project < Struct.new(:name, :technology, :items)
  end

  class Company < Struct.new(:name, :location, :start, :end, :title, :projects)
  end

  class Employment < Struct.new(:companies)
  end

  class TechnicalSkills < Struct.new(:header, :skills)
  end

  class Skill < Struct.new(:name, :items)
  end

  class Education < Struct.new(:periods)
  end

  class Period < Struct.new(:start, :end, :location, :items)
  end

  class OtherSections < Struct.new(:sections)
  end

  class Section < Struct.new(:name, :items)
  end

  class CvDocument < Struct.new(:contact, :profile, :employment, :technical_skills, :education, :other_sections)
  end
end


text:
package playground.spring.cloud.kinesis.springcloudstreamkinesis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import playground.spring.cloud.kinesis.springcloudstreamkinesis.stream.StreamEventProducer;

import java.io.BufferedReader;
import java.io.InputStreamReader;

@Service
public class CommandLineLoop {

    private final BufferedReader br;

    private StreamEventProducer producer;

    @Autowired
    public CommandLineLoop(StreamEventProducer producer) {

        this.br = new BufferedReader(new InputStreamReader(System.in));
        this.producer = producer;
    }

    void run() throws Exception {

        while(true) {

            System.out.print("> ");

            String line = br.readLine();

            if (line.trim().isEmpty()) {

                continue;
            }

            producer.sendData(line);

            System.out.println(": '" + line + "' sent");
        }

    }
}


text:
/*global define */
(function() {
	"use strict";
	define([
		'jquery',
		'underscore',
		'backbone',
		'views/lists-navigation',
		'views/add-list',
		'views/list',
		'collections/lists'
],
		function($, _, Backbone, ListsNavigationView, ListCreationView, ListView, Lists) {
		var AppRouter = Backbone.Router.extend({

			routes:{
				'list/:id':'showList'
			},

			showList:function(id) {
				console.log('showList:' + id);
				this.listView.selectItem(id);
			},

			initialize: function() {
				var that = this;
				console.log('AppRouter.initialize()');
				this.lists = new Lists();
				this.listsNavigationView = new ListsNavigationView({router:this});
				this.listCreationView = new ListCreationView({router:this});
				this.listView = new ListView();
				this.listCreationView.render();
				this.lists.fetch({
					success:function() {
						that.listsNavigationView.render();
					}
				});
			}
		});

		var initialize = function(options) {
			var router = new AppRouter(options);
		};
		return {
			initialize:initialize
		};
	});
}());


text:
var BIG_STATES = 4;
var BIG_COUNTRIES = 3;

var pkg = require('../package.json'); //Application Settings
var db;
var collection; //Twitter Collection
var summaryLength = 3;
var screenNamePos = 0;
var summaryPos = 0;
var summary = {}; //Tweets by screen name summary
summary.name = "Travel";
summary.time = new Date(); //Track when the report was created
summary.users={};
summary.stateCount = 0;
summary.smallStates = [];
summary.countryCount = 0;
summary.smallCountries = [];

var createSummary = function() {

	for (var x = 0; x < BIG_STATES+100; x++) {
		summary.smallStates[x] = {};
		if(x < BIG_STATES) {
			summary.smallStates[x].name = x+' states/provinces';
		} else if(x == BIG_STATES) {
			summary.smallStates[x].name = BIG_STATES+' - '+(BIG_STATES+9)+' states/provinces';
		} else {
			var start = ((x-BIG_STATES)*10)+BIG_STATES;
			summary.smallStates[x].name = start+' - '+(start+9)+' states/provinces';
		}
		summary.smallStates[x].value=0;
	}
	for (var x = 0; x < BIG_COUNTRIES+100; x++) {
		summary.smallCountries[x] = {};
		if(x < BIG_COUNTRIES) {
			summary.smallCountries[x].name = x+' countries';
		} else if(x == BIG_COUNTRIES) {
			summary.smallCountries[x].name = BIG_COUNTRIES+' - '+(BIG_COUNTRIES+9)+' countries';
		} else {
			var start = ((x-BIG_COUNTRIES)*10)+BIG_COUNTRIES;
			summary.smallCountries[x].name = start+' - '+(start+9)+' countries';
		}
		summary.smallCountries[x].value=0;
	}

	db.command({
			'aggregate': 'twitter',
			'pipeline': [{
				$group: {
					_id: "$properties.country"
				}
			}, {
				$group: {
					_id: 1,
					count: {
						$sum: 1
					}
				}
			}]
		},
		function(err, docs) {
			if (err) {
				console.error("Error - distinct countries: " + err.message);
			} else {
				summary.countryCount = docs.result[0].count;
				console.log('Distinct Countries: ' + summary.countryCount);
			}
			wrapIt();
		}
	);
	db.command({
			'aggregate': 'twitter',
			'pipeline': [{
				$group: {
					_id: "$properties.state"
				}
			}, {
				$group: {
					_id: 1,
					count: {
						$sum: 1
					}
				}
			}]
		},
		function(err, docs) {
			if (err) {
				console.error("Error - distinct states/provinces: " + err.message);
			} else {
				summary.stateCount = docs.result[0].count;
				console.log('Distinct States: ' + summary.stateCount);
			}
			wrapIt();
		}
	);

	collection.find({}, function(err, resultCursor) {
		if (err) {
			console.error('Find Error: ' + err);
		}
		collectUsers(resultCursor);
	});

};

var collectUsers = function(resultCursor) {
	console.log('Collecting user locations. Please wait....This could take a long time.')
	var count = 0;
	resultCursor.each(function(err, result) {
		if (err) {
			console.error(err);
		}
		if (result == null) {
			simplifyUsers();
			return;
		}

		//Ensure user_id has a object
		if (!summary.users[result.properties.user_id]) {
			summary.users[result.properties.user_id] = {};
		}

		//Ensure the user_id has a country object
		if (!summary.users[result.properties.user_id][result.properties.country]) {
			summary.users[result.properties.user_id][result.properties.country] = {};
		}

		//Ensure the user_id country object has this state
		if (!summary.users[result.properties.user_id][result.properties.country].state) {
			summary.users[result.properties.user_id][result.properties.country].state=[];
		}
		if(summary.users[result.properties.user_id][result.properties.country].state.indexOf(result.properties.state) < 0) {
			summary.users[result.properties.user_id][result.properties.country].state.push(result.properties.state);
		}

	});

};

var simplifyUsers = function() {
	console.log('Total user IDs: ' + Object.keys(summary.users).length);
	console.log('Distilling country and state/province counts');
	for (key in summary.users) {

		//Country Count

		var loc= Object.keys(summary.users[key]).length;
		if(loc < BIG_COUNTRIES) {
			//In the little counts
			summary.smallCountries[loc].value++;
		} else {
			//Groups of 10
			summary.smallCountries[Math.floor(BIG_COUNTRIES+(loc/10))].value++;
		}

		//State/province count
		var states=0;
		for(k in summary.users[key]) {
			states += summary.users[key][k].state.length;
		}
		if(states < BIG_STATES) {
			//In the little counts
			summary.smallStates[states].value++;
		} else {
			//Groups of 10
			summary.smallStates[Math.floor(BIG_STATES+(loc/10))].value++;
		}

		//Free up the memory
		delete summary.users[key];

	}

	console.log('Removing ranges with zero users');
	//Remove zero counts
	var ss = [];
	for(var x = 0; x < summary.smallStates.length; x++) {
		if(summary.smallStates[x].value != 0) {
			ss.push(summary.smallStates[x]);
		}
	}
	summary.smallStates = ss;

	var sc = [];
	for(var x = 0; x < summary.smallCountries.length; x++) {
		if(summary.smallCountries[x].value != 0) {
			sc.push(summary.smallCountries[x]);
		}
	}
	summary.smallCountries = sc;

	wrapIt();

};

var wrapIt = function() {
	summaryPos++;
	console.log(summaryPos + "/" + summaryLength);
	if (summaryLength == summaryPos) {
		console.log("Writing Summary");
		//console.log(summary);
		db.collection('summary').update({
			"name": summary.name
		}, summary, {
			upsert: true,
			w: 1,
			safe: true
		}, function(err) {
			if (err) {
				console.error('Update Error: ' + err.message);
			} else {
				console.log('Done');
			}
			db.close();
		});
	}
}

var dbLoaded = function(err, database) {
	if (err) {
		console.error(err.message);
	}
	db = database;
	collection = db.collection('twitter');
	console.log("Database Connected");
	createSummary();
};
require('mongodb').MongoClient.connect(pkg.config.db_url, dbLoaded);


text:
@EverythingIsNonnullByDefault
package com.elixlogic.tifoon.domain.model.object;

import com.elixlogic.tifoon.common.annotation.EverythingIsNonnullByDefault;


text:
package org.apache.druid.indexing.common.task.batch.parallel;

import com.google.common.util.concurrent.ListenableFuture;
import org.apache.druid.client.indexing.NoopIndexingServiceClient;
import org.apache.druid.client.indexing.TaskStatusResponse;
import org.apache.druid.data.input.InputSplit;
import org.apache.druid.indexer.RunnerTaskState;
import org.apache.druid.indexer.TaskLocation;
import org.apache.druid.indexer.TaskState;
import org.apache.druid.indexer.TaskStatus;
import org.apache.druid.indexer.TaskStatusPlus;
import org.apache.druid.indexing.common.TaskToolbox;
import org.apache.druid.indexing.common.task.NoopTask;
import org.apache.druid.indexing.common.task.batch.parallel.TaskMonitor.SubTaskCompleteEvent;
import org.apache.druid.java.util.common.DateTimes;
import org.apache.druid.java.util.common.ISE;
import org.apache.druid.java.util.common.concurrent.Execs;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class TaskMonitorTest
{
  private static final int SPLIT_NUM = 10;

  private final ExecutorService taskRunner = Execs.multiThreaded(5, "task-monitor-test-%d");
  private final ConcurrentMap<String, TaskState> tasks = new ConcurrentHashMap<>();
  private final TaskMonitor<TestTask, SimpleSubTaskReport> monitor = new TaskMonitor<>(
      new TestIndexingServiceClient(),
      3,
      SPLIT_NUM
  );

  @Before
  public void setup()
  {
    tasks.clear();
    monitor.start(100);
  }

  @After
  public void teardown()
  {
    monitor.stop();
    taskRunner.shutdownNow();
  }

  @Test
  public void testBasic() throws InterruptedException, ExecutionException, TimeoutException
  {
    final List<ListenableFuture<SubTaskCompleteEvent<TestTask>>> futures = IntStream
        .range(0, 10)
        .mapToObj(i -> monitor.submit(
            new TestTaskSpec("specId" + i, "groupId", "supervisorId", null, new IntegerInputSplit(i), 100L, 0, false)
        ))
        .collect(Collectors.toList());
    for (int i = 0; i < futures.size(); i++) {
      // # of threads of taskRunner is 5, so the expected max timeout is 2 sec. We additionally wait three more seconds
      // here to make sure the test passes.
      final SubTaskCompleteEvent<TestTask> result = futures.get(i).get(1, TimeUnit.SECONDS);
      Assert.assertEquals("supervisorId", result.getSpec().getSupervisorTaskId());
      Assert.assertEquals("specId" + i, result.getSpec().getId());
      Assert.assertNotNull(result.getLastStatus());
      Assert.assertEquals(TaskState.SUCCESS, result.getLastStatus().getStatusCode());
      Assert.assertEquals(TaskState.SUCCESS, result.getLastState());
    }
  }

  @Test
  public void testRetry() throws InterruptedException, ExecutionException, TimeoutException
  {
    final List<TestTaskSpec> specs = IntStream
        .range(0, 10)
        .mapToObj(
            i -> new TestTaskSpec(
                "specId" + i,
                "groupId",
                "supervisorId",
                null,
                new IntegerInputSplit(i),
                100L,
                2,
                false
            )
        )
        .collect(Collectors.toList());
    final List<ListenableFuture<SubTaskCompleteEvent<TestTask>>> futures = specs
        .stream()
        .map(monitor::submit)
        .collect(Collectors.toList());
    for (int i = 0; i < futures.size(); i++) {
      // # of threads of taskRunner is 5, and each task is expected to be run 3 times (with 2 retries), so the expected
      // max timeout is 6 sec. We additionally wait 4 more seconds here to make sure the test passes.
      final SubTaskCompleteEvent<TestTask> result = futures.get(i).get(2, TimeUnit.SECONDS);
      Assert.assertEquals("supervisorId", result.getSpec().getSupervisorTaskId());
      Assert.assertEquals("specId" + i, result.getSpec().getId());

      Assert.assertNotNull(result.getLastStatus());
      Assert.assertEquals(TaskState.SUCCESS, result.getLastStatus().getStatusCode());
      Assert.assertEquals(TaskState.SUCCESS, result.getLastState());

      final TaskHistory<TestTask> taskHistory = monitor.getCompleteSubTaskSpecHistory(specs.get(i).getId());
      Assert.assertNotNull(taskHistory);

      final List<TaskStatusPlus> attemptHistory = taskHistory.getAttemptHistory();
      Assert.assertNotNull(attemptHistory);
      Assert.assertEquals(3, attemptHistory.size());
      Assert.assertEquals(TaskState.FAILED, attemptHistory.get(0).getStatusCode());
      Assert.assertEquals(TaskState.FAILED, attemptHistory.get(1).getStatusCode());
    }
  }

  @Test
  public void testResubmitWithOldType() throws InterruptedException, ExecutionException, TimeoutException
  {
    final List<TestTaskSpec> specs = IntStream
        .range(0, 10)
        .mapToObj(
            i -> new TestTaskSpec(
                "specId" + i,
                "groupId",
                "supervisorId",
                null,
                new IntegerInputSplit(i),
                100L,
                0,
                true
            )
        )
        .collect(Collectors.toList());
    final List<ListenableFuture<SubTaskCompleteEvent<TestTask>>> futures = specs
        .stream()
        .map(monitor::submit)
        .collect(Collectors.toList());
    for (int i = 0; i < futures.size(); i++) {
      // # of threads of taskRunner is 5, and each task is expected to be run 3 times (with 2 retries), so the expected
      // max timeout is 6 sec. We additionally wait 4 more seconds here to make sure the test passes.
      final SubTaskCompleteEvent<TestTask> result = futures.get(i).get(2, TimeUnit.SECONDS);
      Assert.assertEquals("supervisorId", result.getSpec().getSupervisorTaskId());
      Assert.assertEquals("specId" + i, result.getSpec().getId());

      Assert.assertNotNull(result.getLastStatus());
      Assert.assertEquals(TaskState.SUCCESS, result.getLastStatus().getStatusCode());
      Assert.assertEquals(TaskState.SUCCESS, result.getLastState());

      final TaskHistory<TestTask> taskHistory = monitor.getCompleteSubTaskSpecHistory(specs.get(i).getId());
      Assert.assertNotNull(taskHistory);

      final List<TaskStatusPlus> attemptHistory = taskHistory.getAttemptHistory();
      Assert.assertNotNull(attemptHistory);
      Assert.assertEquals(1, attemptHistory.size());
      Assert.assertEquals(TaskState.SUCCESS, attemptHistory.get(0).getStatusCode());
    }
  }

  private class TestTaskSpec extends SubTaskSpec<TestTask>
  {
    private final long runTime;
    private final int numMaxFails;
    private final boolean throwUnknownTypeIdError;

    private int numFails;

    TestTaskSpec(
        String id,
        String groupId,
        String supervisorTaskId,
        Map<String, Object> context,
        InputSplit inputSplit,
        long runTime,
        int numMaxFails,
        boolean throwUnknownTypeIdError
    )
    {
      super(id, groupId, supervisorTaskId, context, inputSplit);
      this.runTime = runTime;
      this.numMaxFails = numMaxFails;
      this.throwUnknownTypeIdError = throwUnknownTypeIdError;
    }

    @Override
    public TestTask newSubTask(int numAttempts)
    {
      return new TestTask(getId(), runTime, numFails++ < numMaxFails, throwUnknownTypeIdError);
    }

    @Override
    public TestTask newSubTaskWithBackwardCompatibleType(int numAttempts)
    {
      return new TestTask(getId(), runTime, numFails++ < numMaxFails, false);
    }
  }

  private class TestTask extends NoopTask
  {
    private final boolean shouldFail;
    private final boolean throwUnknownTypeIdError;

    TestTask(String id, long runTime, boolean shouldFail, boolean throwUnknownTypeIdError)
    {
      super(id, null, "testDataSource", runTime, 0, null, null, null);
      this.shouldFail = shouldFail;
      this.throwUnknownTypeIdError = throwUnknownTypeIdError;
    }

    @Override
    public TaskStatus run(TaskToolbox toolbox) throws Exception
    {
      monitor.collectReport(new SimpleSubTaskReport(getId()));
      if (shouldFail) {
        Thread.sleep(getRunTime());
        return TaskStatus.failure(getId(), "Dummy task status failure for testing");
      } else {
        return super.run(toolbox);
      }
    }
  }

  private class TestIndexingServiceClient extends NoopIndexingServiceClient
  {
    @Override
    public String runTask(String taskId, Object taskObject)
    {
      final TestTask task = (TestTask) taskObject;
      tasks.put(task.getId(), TaskState.RUNNING);
      if (task.throwUnknownTypeIdError) {
        throw new RuntimeException(new ISE("Could not resolve type id 'test_task_id'"));
      }
      taskRunner.submit(() -> tasks.put(task.getId(), task.run(null).getStatusCode()));
      return task.getId();
    }

    @Override
    public TaskStatusResponse getTaskStatus(String taskId)
    {
      return new TaskStatusResponse(
          taskId,
          new TaskStatusPlus(
              taskId,
              "groupId",
              "testTask",
              DateTimes.EPOCH,
              DateTimes.EPOCH,
              tasks.get(taskId),
              RunnerTaskState.RUNNING,
              -1L,
              TaskLocation.unknown(),
              "testDataSource",
              null
          )
      );
    }
  }

  private static class IntegerInputSplit extends InputSplit<Integer>
  {
    IntegerInputSplit(int split)
    {
      super(split);
    }
  }

  private static class SimpleSubTaskReport implements SubTaskReport
  {
    private final String taskId;

    private SimpleSubTaskReport(String taskId)
    {
      this.taskId = taskId;
    }

    @Override
    public String getTaskId()
    {
      return taskId;
    }
  }
}