text:
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * Overrided metadata worker's path.
 * @type {string}
 */
ContentMetadataProvider.WORKER_SCRIPT = '/js/metadata_worker.js';

/**
 * @param {Element} container Container element.
 * @constructor
 */
function AudioPlayer(container) {
  this.container_ = container;
  this.volumeManager_ = new VolumeManagerWrapper(
      VolumeManagerWrapper.NonNativeVolumeStatus.ENABLED);
  this.metadataModel_ = MetadataModel.create(this.volumeManager_);
  this.selectedEntry_ = null;
  this.invalidTracks_ = {};

  this.model_ = new AudioPlayerModel();
  Object.observe(this.model_, function(changes) {
    for (var i = 0; i < changes.length; i++) {
      var change = changes[i];
      if (change.name == 'expanded' &&
          (change.type == 'add' || change.type == 'update')) {
        this.onModelExpandedChanged(change.oldValue, change.object.expanded);
        break;
      }
    }
  }.bind(this));

  this.entries_ = [];
  this.currentTrackIndex_ = -1;
  this.playlistGeneration_ = 0;

  /**
   * Whether if the playlist is expanded or not. This value is changed by
   * this.syncExpanded().
   * True: expanded, false: collapsed, null: unset.
   *
   * @type {?boolean}
   * @private
   */
  this.isExpanded_ = null;  // Initial value is null. It'll be set in load().

  this.player_ =
    /** @type {AudioPlayerElement} */ (document.querySelector('audio-player'));
  // TODO(yoshiki): Move tracks into the model.
  this.player_.tracks = [];
  this.model_.initialize(function() {
    this.player_.model = this.model_;
  }.bind(this));

  // Run asynchronously after an event of model change is delivered.
  setTimeout(function() {
    this.errorString_ = '';
    this.offlineString_ = '';
    chrome.fileManagerPrivate.getStrings(function(strings) {
      container.ownerDocument.title = strings['AUDIO_PLAYER_TITLE'];
      this.errorString_ = strings['AUDIO_ERROR'];
      this.offlineString_ = strings['AUDIO_OFFLINE'];
      AudioPlayer.TrackInfo.DEFAULT_ARTIST =
          strings['AUDIO_PLAYER_DEFAULT_ARTIST'];
      // Pass translated labels to the AudioPlayerElement.
      this.player_.ariaLabels = {
        volumeSlider: strings['AUDIO_PLAYER_OPEN_VOLUME_SLIDER_BUTTON_LABEL'],
        shuffle: strings['AUDIO_PLAYER_SHUFFLE_BUTTON_LABEL'],
        repeat: strings['AUDIO_PLAYER_REPEAT_BUTTON_LABEL'],
        previous: strings['MEDIA_PLAYER_PREVIOUS_BUTTON_LABEL'],
        play: strings['MEDIA_PLAYER_PLAY_BUTTON_LABEL'],
        pause: strings['MEDIA_PLAYER_PAUSE_BUTTON_LABEL'],
        next: strings['MEDIA_PLAYER_NEXT_BUTTON_LABEL'],
        volume: strings['AUDIO_PLAYER_OPEN_VOLUME_SLIDER_BUTTON_LABEL'],
        playList: strings['AUDIO_PLAYER_OPEN_PLAY_LIST_BUTTON_LABEL'],
        seekSlider: strings['MEDIA_PLAYER_SEEK_SLIDER_LABEL']
      };
    }.bind(this));

    this.volumeManager_.addEventListener('externally-unmounted',
        this.onExternallyUnmounted_.bind(this));

    window.addEventListener('resize', this.onResize_.bind(this));
    document.addEventListener('keydown', this.onKeyDown_.bind(this));

    // Show the window after DOM is processed.
    var currentWindow = chrome.app.window.current();
    if (currentWindow)
      setTimeout(currentWindow.show.bind(currentWindow), 0);
  }.bind(this), 0);
}

/**
 * Initial load method (static).
 */
AudioPlayer.load = function() {
  document.ondragstart = function(e) { e.preventDefault(); };

  AudioPlayer.instance =
      new AudioPlayer(document.querySelector('.audio-player'));

  reload();
};

/**
 * Unloads the player.
 */
function unload() {
  if (AudioPlayer.instance)
    AudioPlayer.instance.onUnload();
}

/**
 * Reloads the player.
 */
function reload() {
  AudioPlayer.instance.load(/** @type {Playlist} */ (window.appState));
}

/**
 * Loads a new playlist.
 * @param {Playlist} playlist Playlist object passed via mediaPlayerPrivate.
 */
AudioPlayer.prototype.load = function(playlist) {
  this.playlistGeneration_++;
  this.currentTrackIndex_ = -1;

  // Save the app state, in case of restart. Make a copy of the object, so the
  // playlist member is not changed after entries are resolved.
  window.appState = /** @type {Playlist} */ (
      JSON.parse(JSON.stringify(playlist)));  // cloning
  util.saveAppState();

  this.isExpanded_ = this.player_.expanded;

  // Resolving entries has to be done after the volume manager is initialized.
  this.volumeManager_.ensureInitialized(function() {
    util.URLsToEntries(playlist.items || [], function(entries) {
      this.entries_ = entries;

      var position = playlist.position || 0;
      var time = playlist.time || 0;

      if (this.entries_.length == 0)
        return;

      var newTracks = [];
      var currentTracks = this.player_.tracks;
      var unchanged = (currentTracks.length === this.entries_.length);

      for (var i = 0; i != this.entries_.length; i++) {
        var entry = this.entries_[i];
        newTracks.push(new AudioPlayer.TrackInfo(entry));

        if (unchanged && entry.toURL() !== currentTracks[i].url)
          unchanged = false;
      }

      if (!unchanged)
        this.player_.tracks = newTracks;

      // Run asynchronously, to makes it sure that the handler of the track list
      // is called, before the handler of the track index.
      setTimeout(function() {
        this.select_(position);

        // Load the selected track metadata first, then load the rest.
        this.loadMetadata_(position);
        for (i = 0; i != this.entries_.length; i++) {
          if (i != position)
            this.loadMetadata_(i);
        }
      }.bind(this), 0);
    }.bind(this));
  }.bind(this));
};

/**
 * Loads metadata for a track.
 * @param {number} track Track number.
 * @private
 */
AudioPlayer.prototype.loadMetadata_ = function(track) {
  this.fetchMetadata_(
      this.entries_[track], this.displayMetadata_.bind(this, track));
};

/**
 * Displays track's metadata.
 * @param {number} track Track number.
 * @param {Object} metadata Metadata object.
 * @param {string=} opt_error Error message.
 * @private
 */
AudioPlayer.prototype.displayMetadata_ = function(track, metadata, opt_error) {
  this.player_.tracks[track].setMetadata(metadata, opt_error);
};

/**
 * Closes audio player when a volume containing the selected item is unmounted.
 * @param {Event} event The unmount event.
 * @private
 */
AudioPlayer.prototype.onExternallyUnmounted_ = function(event) {
  if (!this.selectedEntry_)
    return;

  if (this.volumeManager_.getVolumeInfo(this.selectedEntry_) ===
      event.volumeInfo)
    window.close();
};

/**
 * Called on window is being unloaded.
 */
AudioPlayer.prototype.onUnload = function() {
  if (this.player_)
    this.player_.onPageUnload();

  if (this.volumeManager_)
    this.volumeManager_.dispose();
};

/**
 * Selects a new track to play.
 * @param {number} newTrack New track number.
 * @private
 */
AudioPlayer.prototype.select_ = function(newTrack) {
  if (this.currentTrackIndex_ == newTrack) return;

  this.currentTrackIndex_ = newTrack;
  this.player_.currentTrackIndex = this.currentTrackIndex_;
  this.player_.time = 0;

  // Run asynchronously after an event of current track change is delivered.
  setTimeout(function() {
    if (!window.appReopen)
      this.player_.$.audio.play();

    window.appState.position = this.currentTrackIndex_;
    window.appState.time = 0;
    util.saveAppState();

    var entry = this.entries_[this.currentTrackIndex_];

    this.fetchMetadata_(entry, function(metadata) {
      if (this.currentTrackIndex_ != newTrack)
        return;

      this.selectedEntry_ = entry;
    }.bind(this));
  }.bind(this), 0);
};

/**
 * @param {FileEntry} entry Track file entry.
 * @param {function(Object)} callback Callback.
 * @private
 */
AudioPlayer.prototype.fetchMetadata_ = function(entry, callback) {
  this.metadataModel_.get(
      [entry], ['mediaTitle', 'mediaArtist', 'present']).then(
      function(generation, metadata) {
        // Do nothing if another load happened since the metadata request.
        if (this.playlistGeneration_ == generation)
          callback(metadata[0]);
      }.bind(this, this.playlistGeneration_));
};

/**
 * Media error handler.
 * @private
 */
AudioPlayer.prototype.onError_ = function() {
  var track = this.currentTrackIndex_;

  this.invalidTracks_[track] = true;

  this.fetchMetadata_(
      this.entries_[track],
      function(metadata) {
        var error = (!navigator.onLine && !metadata.present) ?
            this.offlineString_ : this.errorString_;
        this.displayMetadata_(track, metadata, error);
        this.player_.onAudioError();
      }.bind(this));
};

/**
 * Toggles the expanded mode when resizing.
 *
 * @param {Event} event Resize event.
 * @private
 */
AudioPlayer.prototype.onResize_ = function(event) {
  if (!this.isExpanded_ &&
      window.innerHeight >= AudioPlayer.EXPANDED_MODE_MIN_HEIGHT) {
    this.isExpanded_ = true;
    this.player_.expanded = true;
  } else if (this.isExpanded_ &&
             window.innerHeight < AudioPlayer.EXPANDED_MODE_MIN_HEIGHT) {
    this.isExpanded_ = false;
    this.player_.expanded = false;
  }
};

/**
 * Handles keydown event to open inspector with shortcut keys.
 *
 * @param {Event} event KeyDown event.
 * @private
 */
AudioPlayer.prototype.onKeyDown_ = function(event) {
  switch (util.getKeyModifiers(event) + event.keyIdentifier) {
    // Handle debug shortcut keys.
    case 'Ctrl-Shift-U+0049': // Ctrl+Shift+I
      chrome.fileManagerPrivate.openInspector('normal');
      break;
    case 'Ctrl-Shift-U+004A': // Ctrl+Shift+J
      chrome.fileManagerPrivate.openInspector('console');
      break;
    case 'Ctrl-Shift-U+0043': // Ctrl+Shift+C
      chrome.fileManagerPrivate.openInspector('element');
      break;
    case 'Ctrl-Shift-U+0042': // Ctrl+Shift+B
      chrome.fileManagerPrivate.openInspector('background');
      break;
  }
};

/* Keep the below constants in sync with the CSS. */

/**
 * Window header size in pixels.
 * @type {number}
 * @const
 */
AudioPlayer.HEADER_HEIGHT = 36;  // 32px + border 4px

/**
 * Track height in pixels.
 * @type {number}
 * @const
 */
AudioPlayer.TRACK_HEIGHT = 48;

/**
 * Controls bar height in pixels.
 * @type {number}
 * @const
 */
AudioPlayer.CONTROLS_HEIGHT = 96;

/**
 * Default number of items in the expanded mode.
 * @type {number}
 * @const
 */
AudioPlayer.DEFAULT_EXPANDED_ITEMS = 5;

/**
 * Minimum size of the window in the expanded mode in pixels.
 * @type {number}
 * @const
 */
AudioPlayer.EXPANDED_MODE_MIN_HEIGHT = AudioPlayer.CONTROLS_HEIGHT +
                                       AudioPlayer.TRACK_HEIGHT * 2;

/**
 * Invoked when the 'expanded' property in the model is changed.
 * @param {boolean} oldValue Old value.
 * @param {boolean} newValue New value.
 */
AudioPlayer.prototype.onModelExpandedChanged = function(oldValue, newValue) {
  if (this.isExpanded_ !== null &&
      this.isExpanded_ === newValue)
    return;

  if (this.isExpanded_ && !newValue)
    this.lastExpandedHeight_ = window.innerHeight;

  if (this.isExpanded_ !== newValue) {
    this.isExpanded_ = newValue;
    this.syncHeight_();

    // Saves new state.
    window.appState.expanded = newValue;
    util.saveAppState();
  }
};

/**
 * @private
 */
AudioPlayer.prototype.syncHeight_ = function() {
  var targetHeight;

  if (this.player_.expanded) {
    // Expanded.
    if (!this.lastExpandedHeight_ ||
        this.lastExpandedHeight_ < AudioPlayer.EXPANDED_MODE_MIN_HEIGHT) {
      var expandedListHeight =
          Math.min(this.entries_.length, AudioPlayer.DEFAULT_EXPANDED_ITEMS) *
              AudioPlayer.TRACK_HEIGHT;
      targetHeight = AudioPlayer.CONTROLS_HEIGHT + expandedListHeight;
      this.lastExpandedHeight_ = targetHeight;
    } else {
      targetHeight = this.lastExpandedHeight_;
    }
  } else {
    // Not expanded.
    targetHeight = AudioPlayer.CONTROLS_HEIGHT + AudioPlayer.TRACK_HEIGHT;
  }

  window.resizeTo(window.innerWidth, targetHeight + AudioPlayer.HEADER_HEIGHT);
};

/**
 * Create a TrackInfo object encapsulating the information about one track.
 *
 * @param {FileEntry} entry FileEntry to be retrieved the track info from.
 * @constructor
 */
AudioPlayer.TrackInfo = function(entry) {
  this.url = entry.toURL();
  this.title = this.getDefaultTitle();
  this.artist = this.getDefaultArtist();

  // TODO(yoshiki): implement artwork.
  this.artwork = null;
  this.active = false;
};

/**
 * @return {string} Default track title (file name extracted from the url).
 */
AudioPlayer.TrackInfo.prototype.getDefaultTitle = function() {
  var title = this.url.split('/').pop();
  var dotIndex = title.lastIndexOf('.');
  if (dotIndex >= 0) title = title.substr(0, dotIndex);
  title = decodeURIComponent(title);
  return title;
};

/**
 * TODO(kaznacheev): Localize.
 */
AudioPlayer.TrackInfo.DEFAULT_ARTIST = 'Unknown Artist';

/**
 * @return {string} 'Unknown artist' string.
 */
AudioPlayer.TrackInfo.prototype.getDefaultArtist = function() {
  return AudioPlayer.TrackInfo.DEFAULT_ARTIST;
};

/**
 * @param {Object} metadata The metadata object.
 * @param {string} error Error string.
 */
AudioPlayer.TrackInfo.prototype.setMetadata = function(
    metadata, error) {
  // TODO(yoshiki): Handle error in better way.
  // TODO(yoshiki): implement artwork (metadata.thumbnail)
  this.title = metadata.mediaTitle || this.getDefaultTitle();
  this.artist = error || metadata.mediaArtist || this.getDefaultArtist();
};

// Starts loading the audio player.
window.addEventListener('DOMContentLoaded', function(e) {
  AudioPlayer.load();
});


text:
<?xml version="1.0" encoding="UTF-8" ?>
<routes xmlns="http://symfony.com/schema/routing"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://symfony.com/schema/routing
        http://symfony.com/schema/routing/routing-1.0.xsd">
    <route id="sulu_comment.comment_template.details" path="/comment-template/details.html">
        <default key="_controller">SuluCommentBundle:CommentTemplate:details</default>
    </route>
    <route id="sulu_comment.thread_template.details" path="/thread-template/details.html">
        <default key="_controller">SuluCommentBundle:ThreadTemplate:details</default>
    </route>
</routes>

redpajama_set_name: RedPajamaGithub


text:
clear all;
clc;

%% Params
sub_list = cellstr(['01';'02';'03';'04';'05';'06';'07';'08';'10';'11';'12';'13';'14';'16';'17';'18']);
trial_list = cellstr(['01';'02';'03']);
sampling_rate = 100;

lag = zeros(1,1); %47

%% Body
k=0;
for i=4%1:length(sub_list)
    sub_num = char(sub_list(i));
    for j=2%1:length(trial_list)
        trial_num = char(trial_list(j));
        if (strcmpi(sub_num,'18') + strcmpi(trial_num,'02')<2)
            k=k+1;
            resultfile = strcat('E:\PhD ResearchWork\NSF_EFRI\Older_Adults_Acceptance_Study\data\processed_combined\sub',sub_num,'_trial',trial_num,'.mat');
            result = load(resultfile);

            % Calculate lag
            robot_pos = (result.robot_front_com_pos_interp - mean(result.robot_front_com_pos_interp))/std(result.robot_front_com_pos_interp);
            human_pos = (result.human_left_shoulder_pos_interp - mean(result.human_left_shoulder_pos_interp))/std(result.human_left_shoulder_pos_interp);
            [C,trial_lags] = xcorr(robot_pos, human_pos);
            zero_index = find((trial_lags >=0),1,'first');%limit lag to positive values
            C_pos = C(zero_index:end);
            trial_lags_pos = trial_lags(zero_index:end);
            [max_C,max_i] = max(C_pos); %find index with max correlation

            %corrLength=length(result.robot_front_com_pos_interp)+length(result.human_left_shoulder_pos_interp)-1;
            %c=fftshift(ifft(fft(result.robot_front_com_pos_interp,corrLength).*conj(fft(result.human_left_shoulder_pos_interp,corrLength))));

            %finddelay(result.robot_front_com_pos_interp, result.human_left_shoulder_pos_interp)/100;

            % Calculate values
            lag(k) = trial_lags_pos(max_i) / sampling_rate; %find lag value at that index, convert into seconds using 100Hz sampling rate

            % Plot
%             figure(1);
%             plot(result.time,result.human_left_shoulder_pos_interp);
%             hold on;
%             plot(result.time + lag(k), result.robot_front_com_pos_interp + (result.robot_front_com_pos_interp-result.robot_front_com_pos_interp),'r');
%             title(['Subject ' sub_num ' , Lag: ' num2str(lag(k)) ' (sec)']);
%             ylabel('pos (m)');
%             legend('human','robot');
%             xlabel('Time (sec)');
        end
    end
end


text:
package org.http4s

import cats.{Eq, Monoid}
import cats.data.Chain
import cats.effect.Sync
import cats.implicits._
import org.http4s.headers._
import org.http4s.internal.CollectionCompat
import org.http4s.parser._
import scala.io.Codec

class UrlForm private (val values: Map[String, Chain[String]]) extends AnyVal {
  override def toString: String = values.toString()

  def get(key: String): Chain[String] =
    this.getOrElse(key, Chain.empty[String])

  def getOrElse(key: String, default: => Chain[String]): Chain[String] =
    values.getOrElse(key, default)

  def getFirst(key: String): Option[String] =
    values.get(key).flatMap(_.uncons).map { case (s, _) => s }

  def getFirstOrElse(key: String, default: => String): String =
    this.getFirst(key).getOrElse(default)

  def +(kv: (String, String)): UrlForm = {
    val newValues = values.get(kv._1).fold(Chain(kv._2))(_ :+ kv._2)
    UrlForm(values.updated(kv._1, newValues))
  }

  /**
    * @param key name of the field
    * @param value value of the field
    * @param ev evidence of the existence of `QueryParamEncoder[T]`
    * @return `UrlForm` updated with `key` and `value` pair if key does not exist in `values`. Otherwise `value` will be added to the existing entry.
    */
  def updateFormField[T](key: String, value: T)(implicit ev: QueryParamEncoder[T]): UrlForm =
    this + (key -> ev.encode(value).value)

  /**
    * @param key name of the field
    * @param value optional value of the field
    * @param ev evidence of the existence of `QueryParamEncoder[T]`
    * @return `UrlForm` updated as it is updated with `updateFormField(key, v)` if `value` is `Some(v)`, otherwise it is unaltered
    */
  def updateFormField[T](key: String, value: Option[T])(
      implicit ev: QueryParamEncoder[T]): UrlForm =
    value.fold(this)(updateFormField(key, _))

  /**
    * @param key name of the field
    * @param vals a Chain of values for the field
    * @param ev evidence of the existence of `QueryParamEncoder[T]`
    * @return `UrlForm` updated with `key` and `vals` if key does not exist in `values`, otherwise `vals` will be appended to the existing entry. If `vals` is empty, `UrlForm` will remain as is
    */
  def updateFormFields[T](key: String, vals: Chain[T])(implicit ev: QueryParamEncoder[T]): UrlForm =
    vals.foldLeft(this)(_.updateFormField(key, _)(ev))

  /* same as `updateFormField(key, value)` */
  def +?[T: QueryParamEncoder](key: String, value: T): UrlForm =
    updateFormField(key, value)

  /* same as `updateParamEncoder`(key, value) */
  def +?[T: QueryParamEncoder](key: String, value: Option[T]): UrlForm =
    updateFormField(key, value)

  /* same as `updatedParamEncoders`(key, vals) */
  def ++?[T: QueryParamEncoder](key: String, vals: Chain[T]): UrlForm =
    updateFormFields(key, vals)
}

object UrlForm {

  val empty: UrlForm = new UrlForm(Map.empty)

  def apply(values: Map[String, Chain[String]]): UrlForm =
    // value "" -> Chain() is just noise and it is not maintain during encoding round trip
    if (values.get("").fold(false)(_.isEmpty)) new UrlForm(values - "")
    else new UrlForm(values)

  def apply(values: (String, String)*): UrlForm =
    values.foldLeft(empty)(_ + _)

  def fromChain(values: Chain[(String, String)]): UrlForm =
    apply(values.toList: _*)

  implicit def entityEncoder[F[_]](
      implicit charset: Charset = DefaultCharset): EntityEncoder[F, UrlForm] =
    EntityEncoder
      .stringEncoder[F]
      .contramap[UrlForm](encodeString(charset))
      .withContentType(`Content-Type`(MediaType.application.`x-www-form-urlencoded`, charset))

  implicit def entityDecoder[F[_]](
      implicit F: Sync[F],
      defaultCharset: Charset = DefaultCharset): EntityDecoder[F, UrlForm] =
    EntityDecoder.decodeBy(MediaType.application.`x-www-form-urlencoded`) { m =>
      DecodeResult(
        EntityDecoder
          .decodeString(m)
          .map(decodeString(m.charset.getOrElse(defaultCharset)))
      )
    }

  implicit val eqInstance: Eq[UrlForm] = Eq.instance { (x: UrlForm, y: UrlForm) =>
    x.values === y.values
  }

  implicit val monoidInstance: Monoid[UrlForm] = new Monoid[UrlForm] {
    override def empty: UrlForm = UrlForm.empty

    override def combine(x: UrlForm, y: UrlForm): UrlForm =
      UrlForm(x.values |+| y.values)
  }

  /** Attempt to decode the `String` to a [[UrlForm]] */
  def decodeString(charset: Charset)(
      urlForm: String): Either[MalformedMessageBodyFailure, UrlForm] =
    QueryParser
      .parseQueryString(urlForm.replace("+", "%20"), new Codec(charset.nioCharset))
      .map(q => UrlForm(CollectionCompat.mapValues(q.multiParams)(Chain.fromSeq)))
      .leftMap { parseFailure =>
        MalformedMessageBodyFailure(parseFailure.message, None)
      }

  /** Encode the [[UrlForm]] into a `String` using the provided `Charset` */
  def encodeString(charset: Charset)(urlForm: UrlForm): String = {
    def encode(s: String): String =
      Uri.encode(s, charset.nioCharset, spaceIsPlus = true, toSkip = Uri.Unreserved)

    val sb = new StringBuilder(urlForm.values.size * 20)
    urlForm.values.foreach {
      case (k, vs) =>
        if (sb.nonEmpty) sb.append('&')
        val encodedKey = encode(k)
        if (vs.isEmpty) sb.append(encodedKey)
        else {
          var first = true
          vs.map { v =>
            if (!first) sb.append('&')
            else first = false
            sb.append(encodedKey)
              .append('=')
              .append(encode(v))
          }
        }
    }
    sb.result()
  }
}


text:
package com.cinchapi.runway;

import java.util.concurrent.atomic.AtomicInteger;

import org.junit.Assert;
import org.junit.Test;

import com.cinchapi.common.base.CheckedExceptions;
import com.cinchapi.concourse.lang.Criteria;
import com.cinchapi.concourse.test.ClientServerTest;
import com.cinchapi.concourse.thrift.Operator;
import com.cinchapi.concourse.util.Random;

/**
 * Unit tests for filtering functionality in {@link Runway}.
 *
 * @author Jeff Nelson
 */
public class RunwayFilterTest extends ClientServerTest {

    @Override
    protected String getServerVersion() {
        return Testing.CONCOURSE_VERSION;
    }

    Runway db;

    @Override
    public void beforeEachTest() {
        db = Runway.builder().port(server.getClientPort()).build();
    }

    @Override
    public void afterEachTest() {
        try {
            db.close();
        }
        catch (Exception e) {
            CheckedExceptions.wrapAsRuntimeException(e);
        }
    }

    @Test
    public void testCountFilter() {
        Writer a = new Writer("a");
        Writer b = new Writer("b");
        Editor c = new Editor("c");
        db.save(a, b);

        int acount = Random.getScaleCount();
        for (int i = 0; i < acount; ++i) {
            Article article = new Article("a" + i, a);
            article.save();
        }

        int bcount = Random.getScaleCount();
        for (int i = 0; i < bcount; ++i) {
            Article article = new Article("b" + i, b);
            article.save();
        }

        Assert.assertEquals(acount,
                db.count(Article.class, article -> article.isVisibleTo(a)));
        Assert.assertEquals(bcount,
                db.count(Article.class, article -> article.isVisibleTo(b)));
        Assert.assertEquals(acount + bcount,
                db.count(Article.class, article -> article.isVisibleTo(c)));
    }

    @Test
    public void testCountAnyFilter() {
        int writers = Random.getScaleCount();
        int editors = Random.getScaleCount();
        int admins = Random.getScaleCount();
        for (int i = 0; i < writers; ++i) {
            Writer writer = new Writer("writer" + i);
            writer.save();
        }
        for (int i = 0; i < editors; ++i) {
            Editor editor = new Editor("writer" + i);
            editor.save();
        }
        for (int i = 0; i < admins; ++i) {
            Admin admin = new Admin("writer" + i);
            admin.save();
        }
        Writer w = new Writer("writer");
        Editor e = new Editor("editor");
        Admin a = new Admin("a");
        db.save(w, e, a);
        Assert.assertEquals(1, db.countAny(User.class, u -> u.isVisibleTo(w)));
        Assert.assertEquals(2 + editors + writers,
                db.countAny(User.class, u -> u.isVisibleTo(e)));
        Assert.assertEquals(3 + admins + editors + writers,
                db.countAny(User.class, u -> u.isVisibleTo(a)));
    }

    @Test
    public void testCountCriteriaFilter() {
        Writer a = new Writer("a");
        Writer b = new Writer("b");
        db.save(a, b);
        AtomicInteger acount = new AtomicInteger(0);
        AtomicInteger bcount = new AtomicInteger(0);
        for (int i = 0; i < Random.getScaleCount(); ++i) {
            String title;
            if(Random.getScaleCount() % 3 == 0) {
                title = "Expected";
                acount.getAndIncrement();
            }
            else {
                title = Random.getSimpleString();
            }
            Article article = new Article(title, a);
            article.save();
        }
        for (int i = 0; i < Random.getScaleCount(); ++i) {
            String title;
            if(Random.getScaleCount() % 3 == 0) {
                title = "Expected";
                bcount.getAndIncrement();
            }
            else {
                title = Random.getSimpleString();
            }
            Article article = new Article(title, b);
            article.save();
        }
        Assert.assertEquals(acount.get(),
                db.count(Article.class,
                        Criteria.where().key("title").operator(Operator.EQUALS)
                                .value("Expected"),
                        article -> article.isVisibleTo(a)));
        Assert.assertEquals(bcount.get(),
                db.count(Article.class,
                        Criteria.where().key("title").operator(Operator.EQUALS)
                                .value("Expected"),
                        article -> article.isVisibleTo(b)));

    }

    abstract class Base extends Record {

        protected abstract boolean isVisibleTo(User user);
    }

    abstract class User extends Base {

        String name;

        public User(String name) {
            this.name = name;
        }

    }

    class Admin extends User {

        /**
         * Construct a new instance.
         *
         * @param name
         */
        public Admin(String name) {
            super(name);
        }

        @Override
        protected boolean isVisibleTo(User user) {
            return this.equals(user) || user instanceof Admin;
        }
    }

    class Editor extends User {

        /**
         * Construct a new instance.
         *
         * @param name
         */
        public Editor(String name) {
            super(name);
        }

        @Override
        protected boolean isVisibleTo(User user) {
            return this.equals(user) || user instanceof Admin
                    || user instanceof Editor;
        }
    }

    class Writer extends User {

        /**
         * Construct a new instance.
         *
         * @param name
         */
        public Writer(String name) {
            super(name);
        }

        @Override
        protected boolean isVisibleTo(User user) {
            return this.equals(user) || user instanceof Admin
                    || user instanceof Editor;
        }
    }

    class Article extends Base {

        public Article(String title, Writer author) {
            this.title = title;
            this.author = author;
        }

        Writer author;
        String title;

        @Override
        protected boolean isVisibleTo(User user) {
            return user instanceof Admin || user instanceof Editor
                    || author.equals(user);
        }
    }

}


text:
package io.prediction.data.storage.jdbc

import java.sql.DriverManager
import java.sql.ResultSet

import com.github.nscala_time.time.Imports._
import io.prediction.data.storage.DataMap
import io.prediction.data.storage.Event
import io.prediction.data.storage.PEvents
import io.prediction.data.storage.StorageClientConfig
import org.apache.spark.SparkContext
import org.apache.spark.rdd.JdbcRDD
import org.apache.spark.rdd.RDD
import org.json4s.JObject
import org.json4s.native.Serialization
import scalikejdbc._

/** JDBC implementation of [[PEvents]] */
class JDBCPEvents(client: String, config: StorageClientConfig, namespace: String) extends PEvents {
  @transient private implicit lazy val formats = org.json4s.DefaultFormats
  def find(
    appId: Int,
    channelId: Option[Int] = None,
    startTime: Option[DateTime] = None,
    untilTime: Option[DateTime] = None,
    entityType: Option[String] = None,
    entityId: Option[String] = None,
    eventNames: Option[Seq[String]] = None,
    targetEntityType: Option[Option[String]] = None,
    targetEntityId: Option[Option[String]] = None)(sc: SparkContext): RDD[Event] = {
    val lower = startTime.map(_.getMillis).getOrElse(0.toLong)
    /** Change the default upper bound from +100 to +1 year because MySQL's
      * FROM_UNIXTIME(t) will return NULL if we use +100 years.
      */
    val upper = untilTime.map(_.getMillis).getOrElse((DateTime.now + 1.years).getMillis)
    val par = scala.math.min(
      new Duration(upper - lower).getStandardDays,
      config.properties.getOrElse("PARTITIONS", "4").toLong).toInt
    val entityTypeClause = entityType.map(x => s"and entityType = '$x'").getOrElse("")
    val entityIdClause = entityId.map(x => s"and entityId = '$x'").getOrElse("")
    val eventNamesClause =
      eventNames.map("and (" + _.map(y => s"event = '$y'").mkString(" or ") + ")").getOrElse("")
    val targetEntityTypeClause = targetEntityType.map(
      _.map(x => s"and targetEntityType = '$x'"
    ).getOrElse("and targetEntityType is null")).getOrElse("")
    val targetEntityIdClause = targetEntityId.map(
      _.map(x => s"and targetEntityId = '$x'"
    ).getOrElse("and targetEntityId is null")).getOrElse("")
    val q = s"""
      select
        id,
        event,
        entityType,
        entityId,
        targetEntityType,
        targetEntityId,
        properties,
        eventTime,
        eventTimeZone,
        tags,
        prId,
        creationTime,
        creationTimeZone
      from ${JDBCUtils.eventTableName(namespace, appId, channelId)}
      where
        eventTime >= ${JDBCUtils.timestampFunction(client)}(?) and
        eventTime < ${JDBCUtils.timestampFunction(client)}(?)
      $entityTypeClause
      $entityIdClause
      $eventNamesClause
      $targetEntityTypeClause
      $targetEntityIdClause
      """.replace("\n", " ")
    new JdbcRDD(
      sc,
      () => {
        DriverManager.getConnection(
          client,
          config.properties("USERNAME"),
          config.properties("PASSWORD"))
      },
      q,
      lower / 1000,
      upper / 1000,
      par,
      (r: ResultSet) => {
        Event(
          eventId = Option(r.getString("id")),
          event = r.getString("event"),
          entityType = r.getString("entityType"),
          entityId = r.getString("entityId"),
          targetEntityType = Option(r.getString("targetEntityType")),
          targetEntityId = Option(r.getString("targetEntityId")),
          properties = Option(r.getString("properties")).map(x =>
            DataMap(Serialization.read[JObject](x))).getOrElse(DataMap()),
          eventTime = new DateTime(r.getTimestamp("eventTime").getTime,
            DateTimeZone.forID(r.getString("eventTimeZone"))),
          tags = Option(r.getString("tags")).map(x =>
            x.split(",").toList).getOrElse(Nil),
          prId = Option(r.getString("prId")),
          creationTime = new DateTime(r.getTimestamp("creationTime").getTime,
            DateTimeZone.forID(r.getString("creationTimeZone"))))
      }).cache()
  }

  def write(events: RDD[Event], appId: Int, channelId: Option[Int])(sc: SparkContext): Unit = {
    @transient lazy val tableName =
      sqls.createUnsafely(JDBCUtils.eventTableName(namespace, appId, channelId))
    events.foreachPartition { events =>
      val batchParams = events.map { event =>
        Seq(
          event.eventId.getOrElse(JDBCUtils.generateId),
          event.event,
          event.entityType,
          event.entityId,
          event.targetEntityType,
          event.targetEntityId,
          Serialization.write(event.properties.toJObject),
          event.eventTime,
          event.eventTime.getZone.getID,
          if (event.tags.nonEmpty) Some(event.tags.mkString(",")) else None,
          event.prId,
          event.creationTime,
          event.creationTime.getZone.getID)
      }.toSeq
      DB localTx { implicit session =>
        @transient lazy val q =
          sql"""
          insert into $tableName values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
          """
        q.batch(batchParams: _*).apply()
      }
    }
  }
}


text:
module Ggg where

import           Data.Char
import           Data.List
import qualified Data.List.Split as L

-- See the challenge on reddit: https://www.reddit.com/r/dailyprogrammer/comments/3x3hqa/20151216_challenge_245_intermediate_ggggggg_gggg/

line1 :: [Char]
line1 = "H GgG d gGg e ggG l GGg o gGG r Ggg w ggg"
line2 :: [Char]
line2 = "GgGggGGGgGGggGG, ggggGGGggGGggGg!"
keys :: [[Char]]
keys = L.splitOn " " line1

buildmapping :: [t] -> [(t, t)]
buildmapping [] = []
buildmapping (a:a':as) = (a', a):buildmapping as
buildmapping ([_]) = error "Number of keys not equal to number of words."

decode :: Eq a => [([a], [a])] -> [a] -> [a]
decode _ [] = []
decode mapping string = go mapping
  where
    go ((from, to):ms)
     | from  `isPrefixOf` string = to ++ decode mapping (drop (length from) string)
     | otherwise = go ms
    -- go [] = maybe (string) (\h -> h:decode mapping (tail string)) (listToMaybe string)
    go [] = head string : (decode mapping $ tail string)

fromIntToGGG :: Int -> String
fromIntToGGG k = 'G' : replicate k 'g'

generateMapping :: Foldable t => t Char -> [Char]
generateMapping string = tail $ concatMap (\k -> ' ' : k : ' ' : (fromIntToGGG $ ord k)) string


text:
package com.ansorgit.plugins.bash.documentation;

import com.ansorgit.plugins.bash.lang.psi.api.DocumentationAwareElement;
import com.ansorgit.plugins.bash.lang.psi.api.command.BashCommand;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiComment;
import com.intellij.psi.PsiElement;

import java.util.List;

/**
 * Provides the comment right before a function definition as documentation for a function call psi element and
 * for the definition itself.
 *

 * User: jansorg
 * Date: Nov 10, 2009
 * Time: 7:12:28 PM
 */
class FunctionPsiCommentSource implements DocumentationSource {
    private static final Logger log = Logger.getInstance("#bash.FunctionPsiCommentSource");

    public String documentation(PsiElement element, PsiElement originalElement) {
        if (element instanceof DocumentationAwareElement) {
            log.debug("Looking for doc for doc aware psi element");
            return psiElementDocumentation((DocumentationAwareElement) element);
        }

        if (element instanceof BashCommand) {
            BashCommand command = (BashCommand) element;
            if (command.isFunctionCall()) {
                log.debug("Looking for doc for function call");

                PsiElement function = command.getReference().resolve();

                if (function instanceof DocumentationAwareElement) {
                    return psiElementDocumentation((DocumentationAwareElement) function);
                }
            }
        }

        return null;
    }

    private String psiElementDocumentation(DocumentationAwareElement element) {
        List<PsiComment> psiComments = element.findAttachedComment();
        return psiComments != null ? cleanupComment(joinComments(psiComments)) : null;
    }

    private String joinComments(List<PsiComment> psiComments) {
        StringBuilder command = new StringBuilder();

        for (PsiComment comment : psiComments) {
            command.append(comment.getText()).append("\n");
        }

        return command.toString();
    }

    private String cleanupComment(String text) {
        List<String> lines = StringUtil.split(text, "\n");

        StringBuilder result = new StringBuilder();
        for (String line : lines) {
            result.append(StringUtil.trimStart(line.substring(1), " "));
            result.append("
\n");
        }

        return result.toString();
    }

    public String documentationUrl(PsiElement element, PsiElement originalElement) {
        return null;
    }
}


text:
using SkidiKit.Core;
using SkidiKit.Core.Signals;

namespace SkidiKit.Components
{
    public abstract class GameScene: DrawNode
    {
        private bool _enabled;
        private bool _active;

        protected GameScene(GameStage stage)
        {
            InternalCascade = true;
            Active = false;
            Enabled = false;
            Visible = false;
        }

        public bool Active
        {
            get { return _active; }
            set
            {
                _active = value;
                this.SendSignal(_active ? CommonSignals.Activate : CommonSignals.Deactivate);
            }
        }

        public bool Enabled
        {
            get
            {
                return _enabled;
            }
            set
            {
                _enabled = value;
                this.SendSignal(_enabled ? CommonSignals.Ui.Enable : CommonSignals.Ui.Disable);
            }
        }
    }
}


text:
package com.dozenx.game.engine.fx;

import cola.machine.game.myblocks.engine.modes.GamingState;
import com.dozenx.game.engine.item.action.ItemManager;
import com.dozenx.game.engine.item.bean.ItemDefinition;
import com.dozenx.util.StringUtil;

import core.log.LogUtil;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.control.Tab;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;

import java.util.HashMap;
import java.util.Iterator;

/**
 * Created by dozen.zhang on 2017/8/14.
 */
public class ItemPanel extends Tab {

    private FlowPane flowPane =new FlowPane();
    public void add(Node node){
        flowPane.getChildren().add(node);
    }

    public ItemPanel(Stage primaryStage) {

        //double width, double height
        this.setContent(flowPane);

        this.setText("物品列表");

        GridPane selectGrid = new GridPane();
        selectGrid.setVgap(5);
        selectGrid.setPadding(new Insets(5, 5, 5, 5));

        //创建列表
        final ListView<String> list = new ListView<String>();
        final ObservableList<String> items = FXCollections.observableArrayList(
        );
        list.setItems(items);//ba

        final HashMap<Integer, ItemDefinition> imageMap = ItemManager.itemType2ItemDefinitionMap; //遍历所有的物品项目

        Iterator it = imageMap.keySet().iterator();
        while (it.hasNext()) {
//			java.util.Map.Entry entry = (java.util.Map.Entry)it.next();
//			request.setAttribute((String)entry.getKey(),entry.getValue());

            Integer id = (Integer) it.next();

            ItemDefinition itemDefinition = ItemManager.getItemDefinition(id);
            if(itemDefinition == null ){
                LogUtil.err("can't find item ");
            }
            items.add(id + "_" + ItemManager.getItemDefinition(id).getName());

        }

        list.setOnMouseClicked(new EventHandler<MouseEvent>() {

            @Override
            public void handle(MouseEvent event) {
                System.out.println("clicked on " + list.getSelectionModel().getSelectedItem());
                String name = list.getSelectionModel().getSelectedItem();
                if(StringUtil.isNotEmpty(name)){
                     //name= name.split("_")[1];
                    int index = name.indexOf("_")+1;// 19_fur_hekmet
                    name= name.substring(index);
                    ItemDefinition item = ItemManager.getItemDefinition(name);
                    if(item!=null ){
                        GamingState.editEngine.readyShootBlock = item.getShape();
                    }

                }

            }
        });

        selectGrid.add(list,0,0);
        //=======刷新按钮

        Button freshBtn = new Button("刷新");

        freshBtn.setOnAction(new EventHandler<ActionEvent>(){

            @Override
            public void handle(ActionEvent event) {
                Iterator it = imageMap.keySet().iterator();
                while (it.hasNext()) {
//			java.util.Map.Entry entry = (java.util.Map.Entry)it.next();
//			request.setAttribute((String)entry.getKey(),entry.getValue());

                    Integer id = (Integer) it.next();
                    items.add(id+"_"+ItemManager.getItemDefinition(id).getName());

                }
            }
        }); selectGrid.add(freshBtn,0,1);

        this.setContent(selectGrid);

    }

}


text:
/*!
 * Snail UI CSS Framework 1.9.2
 * http://www.snailui.com
 * author: roy.lyn
 */
.sn-datepicker { width: 17em; padding: .2em .2em 0; display: none; }
.sn-datepicker .sn-datepicker-header { position:relative; padding:.2em 0; }
.sn-datepicker .sn-datepicker-prev, .sn-datepicker .sn-datepicker-next { position:absolute; top: 2px; width: 1.8em; height: 1.8em; }
.sn-datepicker .sn-datepicker-prev-hover, .sn-datepicker .sn-datepicker-next-hover { top: 1px; }
.sn-datepicker .sn-datepicker-prev { left:2px; }
.sn-datepicker .sn-datepicker-next { right:2px; }
.sn-datepicker .sn-datepicker-prev-hover { left:1px; }
.sn-datepicker .sn-datepicker-next-hover { right:1px; }
.sn-datepicker .sn-datepicker-prev span, .sn-datepicker .sn-datepicker-next span { display: block; position: absolute; left: 50%; margin-left: -8px; top: 50%; margin-top: -8px;  }
.sn-datepicker .sn-datepicker-title { margin: 0 2.3em; line-height: 1.8em; text-align: center; }
.sn-datepicker .sn-datepicker-title select { font-size:1em; margin:1px 0; }
.sn-datepicker select.sn-datepicker-month-year {width: 100%;}
.sn-datepicker select.sn-datepicker-month,
.sn-datepicker select.sn-datepicker-year { width: 49%;}
.sn-datepicker table {width: 100%; font-size: .9em; border-collapse: collapse; margin:0 0 .4em; }
.sn-datepicker th { padding: .7em .3em; text-align: center; font-weight: bold; border: 0;  }
.sn-datepicker td { border: 0; padding: 1px; }
.sn-datepicker td span, .sn-datepicker td a { display: block; padding: .2em; text-align: right; text-decoration: none; }
.sn-datepicker .sn-datepicker-buttonpane { background-image: none; margin: .7em 0 0 0; padding:0 .2em; border-left: 0; border-right: 0; border-bottom: 0; }
.sn-datepicker .sn-datepicker-buttonpane button { float: right; margin: .5em .2em .4em; cursor: pointer; padding: .2em .6em .3em .6em; width:auto; overflow:visible; }
.sn-datepicker .sn-datepicker-buttonpane button.sn-datepicker-current { float:left; }

/* with multiple calendars */
.sn-datepicker.sn-datepicker-multi { width:auto; }
.sn-datepicker-multi .sn-datepicker-group { float:left; }
.sn-datepicker-multi .sn-datepicker-group table { width:95%; margin:0 auto .4em; }
.sn-datepicker-multi-2 .sn-datepicker-group { width:50%; }
.sn-datepicker-multi-3 .sn-datepicker-group { width:33.3%; }
.sn-datepicker-multi-4 .sn-datepicker-group { width:25%; }
.sn-datepicker-multi .sn-datepicker-group-last .sn-datepicker-header { border-left-width:0; }
.sn-datepicker-multi .sn-datepicker-group-middle .sn-datepicker-header { border-left-width:0; }
.sn-datepicker-multi .sn-datepicker-buttonpane { clear:left; }
.sn-datepicker-row-break { clear:both; width:100%; font-size:0em; }

/* RTL support */
.sn-datepicker-rtl { direction: rtl; }
.sn-datepicker-rtl .sn-datepicker-prev { right: 2px; left: auto; }
.sn-datepicker-rtl .sn-datepicker-next { left: 2px; right: auto; }
.sn-datepicker-rtl .sn-datepicker-prev:hover { right: 1px; left: auto; }
.sn-datepicker-rtl .sn-datepicker-next:hover { left: 1px; right: auto; }
.sn-datepicker-rtl .sn-datepicker-buttonpane { clear:right; }
.sn-datepicker-rtl .sn-datepicker-buttonpane button { float: left; }
.sn-datepicker-rtl .sn-datepicker-buttonpane button.sn-datepicker-current { float:right; }
.sn-datepicker-rtl .sn-datepicker-group { float:right; }
.sn-datepicker-rtl .sn-datepicker-group-last .sn-datepicker-header { border-right-width:0; border-left-width:1px; }
.sn-datepicker-rtl .sn-datepicker-group-middle .sn-datepicker-header { border-right-width:0; border-left-width:1px; }

/* IE6 IFRAME FIX (taken from datepicker 1.5.3 */
.sn-datepicker-cover {
    position: absolute; /*must have*/
    z-index: -1; /*must have*/
    filter: mask(); /*must have*/
    top: -4px; /*must have*/
    left: -4px; /*must have*/
    width: 200px; /*must have*/
    height: 200px; /*must have*/
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<parent>
		<artifactId>jaf-examples-parents</artifactId>
		<groupId>com.jaf.examples</groupId>
		<version>1.0.0</version>
		<relativePath>../jaf-examples-parents/pom.xml</relativePath>
	</parent>
	<modelVersion>4.0.0</modelVersion>

	<artifactId>jaf-examples-j2se</artifactId>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.openjdk.jol</groupId>
			<artifactId>jol-core</artifactId>
			<version>0.3.2</version>
		</dependency>

		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>com.google.guava</groupId>
			<artifactId>guava</artifactId>
			<version>19.0</version>
		</dependency>
	</dependencies>
</project>


text:
import {
	TRAM_TAG,
	TRAM_TAG_REACTION,
	TRAM_TAG_NEW_EFFECTS,
	TRAM_TAG_CLEANUP_EFFECTS,
	TRAM_TAG_STORE_KEYS,
} from './node-names';

/* ============= PUBLIC TYPES ========================================
 * A lot of the types here are wrapped using an array / index of 0.
 * This allows us to expose the types as readable on the consumption side.
 * =====================================================================
 */

/**
 * Type for when we can take a CSS Selector, or an HTML Element (mostly mounting).
 */
export type ElementOrSelector = [string | HTMLElement][0];

/**
 * Type for our template renderers (either html or svg).
 * This is not wrapped in an indexed alias, because everything should be provided automatically.
 */
export type DOMTaggedTemplateFunction<TramOneElementType extends TramOneElement> = (
	strings: TemplateStringsArray,
	...elementsAndAttributes: any[]
) => TramOneElementType;

/**
 * Type for custom Tram One Components.
 * They can take in props and children, and return some rendered Element.
 */
export type TramOneComponent<PropsInterface extends Props = Props, ChildrenInterface extends Children = Children> = [
	(props: PropsInterface, children: ChildrenInterface) => TramOneElement
][0];

/**
 * Type for useStore and useGlobalStore hooks.
 * Describes the kinds of values you can store, either an array or an object.
 *
 * Note, for useGlobalStore, you may have an unknown object if you didn't pass in a defaultValue,
 * that is because we can't determine what type it is, and we will rely on you to clarify.
 */
export type StoreObject = [{ [key: string]: any } | any[]][0];

/**
 * Type to describe the output of Effect.
 * Really this is just an annotation to make TramOneElement easier to understand.
 * In reality, this can be a function (to run on removal), or could be nothing.
 */
export type CleanupEffect = [() => unknown][0];

/**
 * Type for the effect function.
 * This is passed into the useEffect hook
 */
export type Effect = [(ref: TramOneHTMLElement | TramOneSVGElement) => unknown][0];

/**
 * The Props interface for custom Tram One Components.
 * These are all user defined, if any
 */
export type Props = [
	{
		[attribute: string]: any;
	}
][0];

/**
 * The Children interface for custom Tram One Components.
 * If the tag is self-closing, it will be `undefined`, otherwise it will
 * be a list of strings and DOM Elements
 */
export type Children = [(Element | string)[] | undefined][0];

/**
 * Type for registering Tram One Components in the template interface.
 * This is used in registerHtml and registerSvg.
 */
export type Registry = [
	{
		// we use <any, any> here since in the Registry we can't be as explicit about the types being provided
		// - for now lean on the end-user to know what types are required and passing them in
		[tag: string]: TramOneComponent<any, any>;
	}
][0];

/**
 * Type for useUrlParams, which contains a `matches` property,
 * and a set of key - value pairs (for query and path parameters)
 */
export type UrlMatchResults = [
	{
		matches: boolean;
		[parameter: string]: string | boolean;
	}
][0];

/**
 * Type for an element that has Tram-One attributes.
 * See `./node-names.ts` for more details
 */
export interface TramOneElement extends Element {
	[TRAM_TAG]: boolean;
	[TRAM_TAG_REACTION]: Reaction;
	[TRAM_TAG_NEW_EFFECTS]: Effect[];
	[TRAM_TAG_CLEANUP_EFFECTS]: CleanupEffect[];
	[TRAM_TAG_STORE_KEYS]: string[];
}

export type TramOneHTMLElement = TramOneElement & HTMLElement;
export type TramOneSVGElement = TramOneElement & SVGElement;

/**
 * Type for the Root TramOneComponent,
 * it can have no props or children, since it is the root element
 */
export type RootTramOneComponent = TramOneComponent<{ [attribute: string]: never }, undefined>;

/* ============= INTERNAL TYPES ========================================
 * These won't be exposed or really visible to end users.
 * =====================================================================
 */

/**
 * Type for the container, which always has a first child to render the app on
 */
export interface Container extends Element {
	firstElementChild: Element;
}

/**
 * Type for internally tracking where we our in the render tree.
 */
export type WorkingkeyObject = {
	branch: string[];
	branchIndices: {
		[branch: string]: number;
	};
};

/**
 * Type for nx-js's observer-util.
 * This is really just an annotation to make TramOneElement easier to understand
 */
export type Reaction = () => void;

/**
 * Type for saving properties of an element that we are removing / replacing
 */
export type RemovedElementDataStore = {
	index: number;
	tagName: string;
	scrollLeft: number;
	scrollTop: number;
	selectionStart: number | null;
	selectionEnd: number | null;
	selectionDirection: 'forward' | 'backward' | 'none' | undefined;
};

/**
 * Type for top-level window state that Tram-One uses
 */
export interface TramWindow extends Window {
	'tram-space': {
		[namespace: string]: any;
	};
}

/**
 * Type for Element that could _potentially_ have selection range
 */
export interface ElementPotentiallyWithSelectionAndFocus extends Element {
	setSelectionRange?: (
		selectionStart: number | null | undefined,
		selectionEnd: number | null | undefined,
		selectionDirection?: 'forward' | 'backward' | 'none'
	) => void;
	focus?: () => void;
}

/**
 * Type for internal storage of effects
 */
export interface EffectStore {
	[callLikeKey: string]: Effect;
}

/**
 * Type for keeping track of the number of observers for a store
 */
export type KeyObservers = {
	[key: string]: number;
};


text:
<?php
/**
 * Created by PhpStorm.
 * User: HAILONG_ICT
 * Date: 12/21/2015
 * Time: 10:01 AM
 */
?>

Quản Lý Tin Tức

                    <a href="<?php echo base_url('admin/index')?>">

Tin Tức

Thêm Mới

Tin Tức Edit

                    <?php if(isset($postData)){?>
                    <form class="form-horizontal form-bordered" id="postForm" action="<?php echo base_url('admin_News/updateNews')?>" method="post" onsubmit="return postForm()" enctype="multipart/form-data">
                        <?php foreach($postData as $row){?>

                                            <input type="hidden" id="news_id" name="news_id" value="<?php echo $row->NEWS_ID?>">
                                            <?php if($this->form_validation->run() == false){echo validation_errors();}?>

                                    Danh Mục

                                        <select data-plugin-selectTwo class="form-control populate" name="drb_category" id="drb_category" required="required">
                                            <optgroup label="Chọn Danh Mục">
                                                <?php if(isset($newsCate)){
                                                    foreach ($newsCate as $rowCate) {
                                                        echo '<option value="'.$rowCate->CATEGORY_ID.'"'.($row->CATEGORY_ID == $rowCate->CATEGORY_ID ? 'selected' : '').'>'.$rowCate->CATEGORY_NM_VI.'</option>';
                                                    }
                                                }
                                                ?>
                                            </optgroup>
                                        </select>

                                    Tiêu Đề

                                        <input type="text" class="form-control" name="vi_title" id="vi_title" value="<?php echo $row->NEWS_TITLE_VI ?>" placeholder="Tiêu đề tiếng Việt" required="required">

                                        <input type="text" class="form-control" name="en_title" id="en_title" value="<?php echo $row->NEWS_TITLE_EN ?>" placeholder="Tiêu đề tiếng Anh" required="required">

                                        Hiển Thị:
                                        <select class="form-control" data-plugin-multiselect id="display_yn" name="display_yn">
                                            <optgroup label="Hiển Thị Bài Đăng">
                                                <option value="1" <?php echo ($row->STATUS == 1 ? 'selected' : '') ?> >Có</option>
                                                <option value="0" <?php echo ($row->STATUS == 0 ? 'selected' : '') ?> >Không</option>
                                            </optgroup>
                                        </select>

                                    Nội Dung Ngắn

                                        <textarea class="form-control" rows="3" id="shrt_cnt_vi" name="shrt_cnt_vi" placeholder="Tiếng Việt" required="required"><?php echo $row->NEWS_SHRT_CNT_VI ?></textarea>

                                        <textarea class="form-control" rows="3" id="shrt_cnt_en" name="shrt_cnt_en" placeholder="Tiếng Anh" required="required"><?php echo $row->NEWS_SHRT_CNT_EN ?></textarea>

                                        <textarea class="summernote" name="content_vi" id="content_vi" data-plugin-summernote data-plugin-options='{ "height": 300, "codemirror": { "theme": "ambiance" } }'><?php echo $row->NEWS_CONTENT_VI ?></textarea>

                                        <textarea class="summernote" name="content_en" id="content_en" data-plugin-summernote data-plugin-options='{ "height": 300, "codemirror": { "theme": "ambiance" } }'><?php echo $row->NEWS_CONTENT_EN ?></textarea>

                                    Hình Đại Diện

                                        <input type="hidden" name="rpv_img_old" id="rpv_img_old" value="<?php echo $row->NEWS_RPV_IMG?>">
                                        <img src="<?php if(strlen($row->NEWS_RPV_IMG)> 0){ echo base_url($row->NEWS_RPV_IMG);}else{echo base_url('resources/images/no-image.jpg');}?>" width="270" height="160">

                                                Change
                                                Select file
                                                <input type="file" name="rpv_img"/>

                                                Remove

                                    Meta Title

                                        <input name="vi_meta_title" id="vi_meta_title" type="text" class="form-control"  value="<?php echo $row->META_TITLE_VI?>" placeholder="Meta Title Vi" required="required"/>

                                        <input name="en_meta_title" id="en_meta_title" type="text" class="form-control"  value="<?php echo $row->META_TITLE_EN?>" placeholder="Meta Title En" required="required"/>

                                    Description

                                        <input name="vi_description" id="vi_description" class="form-control" value="<?php echo $row->META_DESC_VI?>" placeholder="Description Vi" required="required"/>

                                        <input name="en_description" id="en_description" class="form-control" value="<?php echo $row->META_DESC_EN?>" placeholder="Description En" required="required"/>

                                    Từ Khóa VI

                                        <input name="vi_keywords" id="vi_keywords" data-role="tagsinput" data-tag-class="label label-primary" class="form-control" value="<?php echo $row->META_KEYWORD_VI?>" placeholder="Key Words Vi" required="required"/>
                                        <input name="en_keywords" id="en_keywords" data-role="tagsinput" data-tag-class="label label-primary" class="form-control" value="<?php echo $row->META_KEYWORD_EN?>" placeholder="Key Words En" required="required"/>

                                        <button class="btn btn-primary" type="button" onclick="history.go(-1);"> Trở Lại </button>

                                        <button class="btn btn-primary" type="submit"> Cập Nhật </button>

                        <?php }?>
                    </form>
                    <?php }else{?>
                    <form class="form-horizontal form-bordered" id="postForm" action="<?php echo base_url('admin_news/insertNews')?>" method="post" onsubmit="return postForm()" enctype="multipart/form-data">

                                Danh Mục

                                    <select data-plugin-selectTwo class="form-control populate" name="drb_category" id="drb_category" required="required">
                                        <optgroup label="Chọn Danh Mục">
                                            <?php if(isset($newsCate)){
                                                foreach ($newsCate as $row) {
                                                    echo '<option value="'.$row->CATEGORY_ID.'">'.$row->CATEGORY_NM_VI.'</option>';
                                                }
                                            }
                                            ?>
                                        </optgroup>
                                    </select>

                                Tiêu Đề

                                    <input type="text" class="form-control" name="vi_title" id="vi_title" value="" placeholder="Tiêu đề tiếng Việt" required="required">

                                    <input type="text" class="form-control" name="en_title" id="en_title" value="" placeholder="Tiêu đề tiếng Anh" required="required">

                                Nội Dung Ngắn

                                    <textarea class="form-control" rows="3" id="shrt_cnt_vi" name="shrt_cnt_vi" placeholder="Tiếng Việt" required="required"></textarea>

                                    <textarea class="form-control" rows="3" id="shrt_cnt_en" name="shrt_cnt_en" placeholder="Tiếng Anh" required="required"></textarea>

                                    <textarea class="summernote" name="content_vi" id="content_vi" data-plugin-summernote data-plugin-options='{ "height": 300, "codemirror": { "theme": "ambiance" } }'>Nội Dung Tiếng Việt...</textarea>

                                    <textarea class="summernote" name="content_en" id="content_en" data-plugin-summernote data-plugin-options='{ "height": 300, "codemirror": { "theme": "ambiance" } }'>Nội Dung Tiếng Anh...</textarea>

                                Hình Đại Diện

                                                    Change
                                                    Select file
                                                    <input type="file" name="rpv_img"/>

                                            Remove

                                Meta Title

                                    <input name="vi_meta_title" id="vi_meta_title" type="text" class="form-control"  value="" placeholder="Meta Title Vi" required="required"/>

                                    <input name="en_meta_title" id="en_meta_title" type="text" class="form-control"  value="" placeholder="Meta Title En" required="required"/>

                                Description

                                    <input name="vi_description" id="vi_description" class="form-control" value="" placeholder="Description Vi" required="required"/>

                                    <input name="en_description" id="en_description" class="form-control" value="" placeholder="Description En" required="required"/>

                                Từ Khóa VI

                                    <input name="vi_keywords" id="vi_keywords" data-role="tagsinput" data-tag-class="label label-primary" class="form-control" value="" placeholder="Key Words Vi" required="required"/>
                                    <input name="en_keywords" id="en_keywords" data-role="tagsinput" data-tag-class="label label-primary" class="form-control" value="" placeholder="Key Words En" required="required"/>

                                    <button class="btn btn-primary" type="button" onclick="history.go(-1);"> Trở Lại </button>

                                    <button class="btn btn-primary" type="submit"> Cập Nhật </button>

                    </form>
                    <?php }?>


text:
/**
 * @fileoverview Text blocks for Blockly.
 * @author fraser@google.com (Neil Fraser)
 */
'use strict';

goog.provide('Blockly.Blocks.text');

goog.require('Blockly.Blocks');

Blockly.Blocks['text'] = {
  init: function() {
    this.setHelpUrl(Blockly.Msg.TEXT_TEXT_HELPURL);
    this.setColour(160);
    this.appendDummyInput()
        .appendField(this.newQuote_(true))
        .appendField(new Blockly.FieldTextInput(''), 'TEXT')
        .appendField(this.newQuote_(false));
    this.setOutput(true, 'String');
    this.setTooltip(Blockly.Msg.TEXT_TEXT_TOOLTIP);
  },
  newQuote_: function(open) {
    if (open == Blockly.RTL) {
      var file = 'quote1.png';
    } else {
      var file = 'quote0.png';
    }
    return new Blockly.FieldImage(Blockly.pathToBlockly + 'media/' + file,
                                  12, 12, '"');
  }
};

Blockly.Blocks['text_length'] = {
  init: function() {
    this.setHelpUrl(Blockly.Msg.TEXT_LENGTH_HELPURL);
    this.setColour(160);
    this.interpolateMsg(Blockly.Msg.TEXT_LENGTH_TITLE,
                        ['VALUE', ['String', 'Array'], Blockly.ALIGN_RIGHT],
                        Blockly.ALIGN_RIGHT);
    this.setOutput(true, 'Number');
    this.setTooltip(Blockly.Msg.TEXT_LENGTH_TOOLTIP);
  }
};

Blockly.Blocks['text_isEmpty'] = {
  init: function() {
    this.setHelpUrl(Blockly.Msg.TEXT_ISEMPTY_HELPURL);
    this.setColour(160);
    this.interpolateMsg(Blockly.Msg.TEXT_ISEMPTY_TITLE,
                        ['VALUE', ['String', 'Array'], Blockly.ALIGN_RIGHT],
                        Blockly.ALIGN_RIGHT);
    this.setOutput(true, 'Boolean');
    this.setTooltip(Blockly.Msg.TEXT_ISEMPTY_TOOLTIP);
  }
};

Blockly.Blocks['equals_string'] = {
  init: function() {
    this.setColour(160);
    this.appendValueInput("STRING_ONE")
        .setCheck("String");
    this.appendDummyInput()
        .appendField("is equal");
    this.appendValueInput("STRING_TWO")
        .setCheck("String");
    this.setInputsInline(true);
    this.setOutput(true, "Boolean");
    this.setTooltip('');
  }
};


text:
require 'customer_datasource'

describe CustomerDatasource, :skip => true do
  it "returns the first name of a customer" do
    subject.get_first_value(:one).should == "Yukihiro"
  end

  it "returns the datatype for the first name" do
    subject.get_first_datatype(:one).should == :string
  end

  it "returns the last name of a customer" do
    subject.get_last_value(:one).should == "Matsumoto"
  end

  it "returns the datatype for the last name" do
    subject.get_last_datatype(:one).should == :string
  end

  it "returns the email address of a customer" do
    subject.get_email_value(:one).should == "matz@bostonrb.org"
  end

  it "returns the datatype for the email" do
    subject.get_email_datatype(:one).should == :string
  end

  it "returns the age of a customer" do
    subject.get_age_value(:one).should == 48
  end

  it "returns the datatype for the age" do
    subject.get_age_datatype(:one).should == :integer
  end

  it "raises an error if there is no customer record" do
    expect{ subject.get_first_value(:none) }.to raise_error("No customer found matching id: none")
  end
end


text:
using System;

/* Declare an integer variable and assign it with the value 254 in hexadecimal format ( 0x## ).
 * Use Windows Calculator to find its hexadecimal representation.
 * Print the variable and ensure that the result is 254.
*/

class VariableInHexadecimalFormat
    {
        static void Main()
        {
            int hexVar = 0xFE;
            Console.WriteLine("The decimal value of hexadecimal number 0xFE is "+hexVar+"!");
        }
    }


text:
import React from 'react';
import TextInput from 'ps-react/TextInput';

/** Required TextBox with error */
export default class ExampleError extends React.Component {
  render() {
    return (
      <TextInput
        htmlId="example-optional"
        label="First Name"
        name="firstname"
        onChange={() => {}}
        required
        error="First name is required."
       />
    )
  }
}