text:
package org.smblott.intentradio;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.Context;

import android.os.AsyncTask;;

import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.text.Spanned;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuInflater;
import android.widget.Button;
import android.widget.TextView;
import android.widget.PopupMenu;

import android.content.ClipData;
import android.content.ClipboardManager;

public class IntentRadio extends PreferenceActivity
{
   private static Context context = null;

   private AsyncTask<Object, Void, Spanned> draw_task = null;
   private AsyncTask<Void, Void, String> install_task = null;
   private String url = null;

   @Override
   public void onCreate(Bundle savedInstanceState)
   {
      super.onCreate(savedInstanceState);
      context = getApplicationContext();
      Logger.init(context);

      // Handle app activity...
      //
      draw_task = null;
      install_task = null;

      setContentView(R.layout.main);

      TextView view = (TextView) findViewById(R.id.text);
      view.setMovementMethod(LinkMovementMethod.getInstance());
      view.setText("Loading...");

      // Read file contents and build date for main screen asyncronously...
      //
      draw_task = new AsyncTask<Object, Void, Spanned>()
      {
         private TextView view = null;
         private Integer id = null;
         private String url = null;

         @Override
         protected Spanned doInBackground(Object... args)
         {
            view = (TextView) args[0];
            id = (Integer) args[1];
            url = (String) args[2];

            String text = ReadRawTextFile.read(getApplicationContext(),id.intValue());

            if ( url != null )
               text = text.replace("REPLACE_URL", url);
            else
               text +=
                    "\n"
                  + "
\n"
                  + "Distribution: " + getString(R.string.distribution) + "
\n"
                  + "Version: " + Build.version_string(context) + "
\n"
                  + "Build: " + Build.getBuildDate(context) + "\n"
                  + "
\n";

            return Html.fromHtml(text);
         }

         @Override
         protected void onPostExecute(Spanned html)
         {
            if ( ! isCancelled() )
               view.setText(html);
         }

      };

      // Handle intent...
      //
      Intent intent = getIntent();
      String action = intent.getAction();
      if ( action.equals(Intent.ACTION_VIEW) )
      {
         url = intent.getDataString();
         Intent msg = new Intent(context, IntentPlayer.class);
         msg.putExtra("action", getString(R.string.intent_play));
         msg.putExtra("url", url);
         context.startService(msg);
         findViewById(R.id.clip_url).setVisibility(View.VISIBLE);
         draw_task.execute(view, R.raw.playing, url);
         return;
      }

      // Open app...
      //
      findViewById(R.id.clip_buttons).setVisibility(View.VISIBLE);
      findViewById(R.id.install_tasker).setVisibility(View.VISIBLE);
      draw_task.execute(view, R.raw.message, null);
   }

   /* ********************************************************************
    * Destroy activity: clean up any remaining tasks...
    */

   public void onDestroy()
   {
      if ( draw_task != null && draw_task.getStatus() != AsyncTask.Status.FINISHED )
         draw_task.cancel(true);

      if ( install_task != null && install_task.getStatus() != AsyncTask.Status.FINISHED )
         install_task.cancel(true);

      draw_task = null;
      install_task = null;

      super.onDestroy();
   }

   /* ********************************************************************
    * Launch clip buttons...
    */

   public void clip_buttons(View v)
   {
      Intent clipper = new Intent(IntentRadio.this, ClipButtons.class);
      startActivity(clipper);
   }

   /* ********************************************************************
    * Install sample Tasker project...
    *
    * This currently assumes that Tasker *always* stores projects in:
    *
    *    - /sdcard/Tasker/projects
    *
    * Does it?
    *
    * File I/O is more blocking than anything else we're doing, so we'll do it
    * asyncronously.
    */

   private static final String project_file = "Tasker/projects/IntentRadio.prj.xml";

   public void install_tasker(View v)
   {
      if ( install_task != null && install_task.getStatus() != AsyncTask.Status.FINISHED )
         return;

      install_task = new AsyncTask<Void, Void, String>()
      {
         @Override
         protected String doInBackground(Void... unused)
         {
            return CopyResource.copy(context, R.raw.tasker, project_file);
         }

         @Override
         protected void onPostExecute(String error)
         {
            if ( isCancelled() )
               return;

            if ( error == null /* so, success */ )
            {
               toast("Project file installed...\n\n/sdcard/" + project_file);
               toast("Next, import this project into Tasker.");
            }
            else
               toast("Install error:\n" + error + "\n\n/sdcard/" + project_file);
         }

      };
      install_task.execute();
   }

   /* ********************************************************************
    * Clip url...
    */

   public void clip_url(View view)
      { Clipper.clip(context,url); }

   /* ********************************************************************
    * Toasts...
    */

   static private void toast(String msg)
      { Logger.toast_long(msg); }

}


text:
/*!
 * Angular Material Design
 * https://github.com/angular/material
 * @license MIT
 * v1.0.0-rc4-master-4f3c5d9
 */
md-list {
  display: block;
  padding: 8px 0px 8px 0px; }
  md-list .md-subheader {
    font-size: 14px;
    font-weight: 500;
    letter-spacing: 0.01em;
    line-height: 1.2em; }

md-list-item {
  position: relative; }
  md-list-item.md-proxy-focus.md-focused .md-no-style {
    transition: background-color 0.15s linear; }
  md-list-item.md-no-proxy, md-list-item .md-no-style {
    position: relative;
    padding: 0px 16px;
    -webkit-flex: 1 1 auto;
        -ms-flex: 1 1 auto;
            flex: 1 1 auto; }
    md-list-item.md-no-proxy.md-button, md-list-item .md-no-style.md-button {
      font-size: inherit;
      height: inherit;
      text-align: left;
      text-transform: none;
      width: 100%;
      white-space: normal;
      -webkit-flex-direction: inherit;
          -ms-flex-direction: inherit;
              flex-direction: inherit;
      -webkit-align-items: inherit;
          -ms-flex-align: inherit;
              align-items: inherit;
      border-radius: 0; }
      md-list-item.md-no-proxy.md-button > .md-ripple-container, md-list-item .md-no-style.md-button > .md-ripple-container {
        border-radius: 0; }
    md-list-item.md-no-proxy:focus, md-list-item .md-no-style:focus {
      outline: none; }
  md-list-item.md-with-secondary {
    position: relative; }
  md-list-item.md-clickable:hover {
    cursor: pointer; }
  md-list-item md-divider {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%; }
    md-list-item md-divider[md-inset] {
      left: 96px;
      width: calc(100% - 96px);
      margin: 0; }

md-list-item, md-list-item .md-list-item-inner {
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
  -webkit-justify-content: flex-start;
      -ms-flex-pack: start;
          justify-content: flex-start;
  -webkit-align-items: center;
      -ms-flex-align: center;
          align-items: center;
  min-height: 48px;
  height: auto; }
  md-list-item > div.md-primary > md-icon:not(.md-avatar-icon), md-list-item > div.md-secondary > md-icon:not(.md-avatar-icon), md-list-item > md-icon:first-child:not(.md-avatar-icon), md-list-item > md-icon.md-secondary:not(.md-avatar-icon), md-list-item .md-list-item-inner > div.md-primary > md-icon:not(.md-avatar-icon), md-list-item .md-list-item-inner > div.md-secondary > md-icon:not(.md-avatar-icon), md-list-item .md-list-item-inner > md-icon:first-child:not(.md-avatar-icon), md-list-item .md-list-item-inner > md-icon.md-secondary:not(.md-avatar-icon) {
    width: 24px;
    margin-top: 16px;
    margin-bottom: 12px;
    box-sizing: content-box; }
  md-list-item > div.md-primary > md-checkbox, md-list-item > div.md-secondary > md-checkbox, md-list-item > md-checkbox:first-child, md-list-item md-checkbox.md-secondary, md-list-item .md-list-item-inner > div.md-primary > md-checkbox, md-list-item .md-list-item-inner > div.md-secondary > md-checkbox, md-list-item .md-list-item-inner > md-checkbox:first-child, md-list-item .md-list-item-inner md-checkbox.md-secondary {
    -webkit-align-self: center;
        -ms-flex-item-align: center;
            align-self: center; }
    md-list-item > div.md-primary > md-checkbox .md-label, md-list-item > div.md-secondary > md-checkbox .md-label, md-list-item > md-checkbox:first-child .md-label, md-list-item md-checkbox.md-secondary .md-label, md-list-item .md-list-item-inner > div.md-primary > md-checkbox .md-label, md-list-item .md-list-item-inner > div.md-secondary > md-checkbox .md-label, md-list-item .md-list-item-inner > md-checkbox:first-child .md-label, md-list-item .md-list-item-inner md-checkbox.md-secondary .md-label {
      display: none; }
  md-list-item > md-icon:first-child:not(.md-avatar-icon), md-list-item .md-list-item-inner > md-icon:first-child:not(.md-avatar-icon) {
    margin-right: 32px; }
  md-list-item > md-checkbox:first-child, md-list-item .md-list-item-inner > md-checkbox:first-child {
    width: 24px;
    margin-left: 3px;
    margin-right: 29px; }
  md-list-item > .md-avatar, md-list-item .md-avatar-icon, md-list-item .md-list-item-inner > .md-avatar, md-list-item .md-list-item-inner .md-avatar-icon {
    margin-top: 8px;
    margin-bottom: 8px;
    margin-right: 16px;
    border-radius: 50%;
    box-sizing: content-box; }
  md-list-item > .md-avatar, md-list-item .md-list-item-inner > .md-avatar {
    width: 40px;
    height: 40px; }
  md-list-item > .md-avatar-icon, md-list-item .md-list-item-inner > .md-avatar-icon {
    padding: 8px; }
  md-list-item md-checkbox.md-secondary, md-list-item md-switch.md-secondary, md-list-item .md-list-item-inner md-checkbox.md-secondary, md-list-item .md-list-item-inner md-switch.md-secondary {
    margin-top: 0;
    margin-bottom: 0; }
  md-list-item md-checkbox.md-secondary, md-list-item .md-list-item-inner md-checkbox.md-secondary {
    margin-right: 0; }
  md-list-item md-switch.md-secondary, md-list-item .md-list-item-inner md-switch.md-secondary {
    margin-right: -6px; }
  md-list-item button.md-button.md-secondary-container, md-list-item .md-list-item-inner button.md-button.md-secondary-container {
    background-color: transparent;
    -webkit-align-self: center;
        -ms-flex-item-align: center;
            align-self: center;
    border-radius: 50%;
    margin: 0px;
    min-width: 0px; }
    md-list-item button.md-button.md-secondary-container .md-ripple, md-list-item button.md-button.md-secondary-container .md-ripple-container, md-list-item .md-list-item-inner button.md-button.md-secondary-container .md-ripple, md-list-item .md-list-item-inner button.md-button.md-secondary-container .md-ripple-container {
      border-radius: 50%; }
    md-list-item button.md-button.md-secondary-container.md-icon-button, md-list-item .md-list-item-inner button.md-button.md-secondary-container.md-icon-button {
      margin-right: -12px; }
  md-list-item .md-secondary-container, md-list-item .md-secondary, md-list-item .md-list-item-inner .md-secondary-container, md-list-item .md-list-item-inner .md-secondary {
    position: absolute;
    top: 50%;
    right: 16px;
    margin: 0 0 0 16px;
    -webkit-transform: translate3d(0, -50%, 0);
            transform: translate3d(0, -50%, 0); }
  md-list-item > .md-button.md-secondary-container > .md-secondary, md-list-item .md-list-item-inner > .md-button.md-secondary-container > .md-secondary {
    margin-left: 0;
    position: static; }
  md-list-item > p, md-list-item > .md-list-item-inner > p, md-list-item .md-list-item-inner > p, md-list-item .md-list-item-inner > .md-list-item-inner > p {
    -webkit-flex: 1;
        -ms-flex: 1;
            flex: 1;
    margin: 0; }

md-list-item.md-2-line, md-list-item.md-2-line > .md-no-style, md-list-item.md-3-line, md-list-item.md-3-line > .md-no-style {
  -webkit-align-items: flex-start;
      -ms-flex-align: start;
          align-items: flex-start;
  -webkit-justify-content: center;
      -ms-flex-pack: center;
          justify-content: center; }
  md-list-item.md-2-line .md-list-item-text, md-list-item.md-2-line > .md-no-style .md-list-item-text, md-list-item.md-3-line .md-list-item-text, md-list-item.md-3-line > .md-no-style .md-list-item-text {
    -webkit-flex: 1;
        -ms-flex: 1;
            flex: 1;
    margin: auto;
    text-overflow: ellipsis; }
    md-list-item.md-2-line .md-list-item-text.md-offset, md-list-item.md-2-line > .md-no-style .md-list-item-text.md-offset, md-list-item.md-3-line .md-list-item-text.md-offset, md-list-item.md-3-line > .md-no-style .md-list-item-text.md-offset {
      margin-left: 56px; }
    md-list-item.md-2-line .md-list-item-text h3, md-list-item.md-2-line > .md-no-style .md-list-item-text h3, md-list-item.md-3-line .md-list-item-text h3, md-list-item.md-3-line > .md-no-style .md-list-item-text h3 {
      font-size: 16px;
      font-weight: 400;
      letter-spacing: 0.01em;
      margin: 0 0 0px 0;
      line-height: 1.2em;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis; }
    md-list-item.md-2-line .md-list-item-text h4, md-list-item.md-2-line > .md-no-style .md-list-item-text h4, md-list-item.md-3-line .md-list-item-text h4, md-list-item.md-3-line > .md-no-style .md-list-item-text h4 {
      font-size: 14px;
      letter-spacing: 0.01em;
      margin: 3px 0 1px 0;
      font-weight: 400;
      line-height: 1.2em;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis; }
    md-list-item.md-2-line .md-list-item-text p, md-list-item.md-2-line > .md-no-style .md-list-item-text p, md-list-item.md-3-line .md-list-item-text p, md-list-item.md-3-line > .md-no-style .md-list-item-text p {
      font-size: 14px;
      font-weight: 500;
      letter-spacing: 0.01em;
      margin: 0 0 0 0;
      line-height: 1.6em; }

md-list-item.md-2-line, md-list-item.md-2-line > .md-no-style {
  height: auto;
  min-height: 72px; }
  md-list-item.md-2-line.md-long-text, md-list-item.md-2-line > .md-no-style.md-long-text {
    margin: 1.6em; }
  md-list-item.md-2-line > .md-avatar, md-list-item.md-2-line .md-avatar-icon, md-list-item.md-2-line > .md-no-style > .md-avatar, md-list-item.md-2-line > .md-no-style .md-avatar-icon {
    margin-top: 12px; }
  md-list-item.md-2-line > md-icon:first-child, md-list-item.md-2-line > .md-no-style > md-icon:first-child {
    -webkit-align-self: flex-start;
        -ms-flex-item-align: start;
            align-self: flex-start; }
  md-list-item.md-2-line .md-list-item-text, md-list-item.md-2-line > .md-no-style .md-list-item-text {
    -webkit-flex: 1;
        -ms-flex: 1;
            flex: 1; }

md-list-item.md-3-line, md-list-item.md-3-line > .md-no-style {
  height: auto;
  min-height: 88px; }
  md-list-item.md-3-line.md-long-text, md-list-item.md-3-line > .md-no-style.md-long-text {
    margin: 1.6em; }
  md-list-item.md-3-line > md-icon:first-child, md-list-item.md-3-line > .md-avatar, md-list-item.md-3-line > .md-no-style > md-icon:first-child, md-list-item.md-3-line > .md-no-style > .md-avatar {
    margin-top: 16px; }

redpajama_set_name: RedPajamaGithub


text:
namespace flutter {

namespace {
// An arbitrary size for the character cache in bytes.
//
// It should hold a UTF-32 character encoded in UTF-8 as well as the trailing
// '\0'.
constexpr size_t kCharacterCacheSize = 8;

constexpr SHORT kStateMaskToggled = 0x01;
constexpr SHORT kStateMaskPressed = 0x80;

const char* empty_character = "";

// Get some bits of the char, from the start'th bit from the right (excluded)
// to the end'th bit from the right (included).
//
// For example, _GetBit(0x1234, 8, 4) => 0x3.
char _GetBit(char32_t ch, size_t start, size_t end) {
  return (ch >> end) & ((1 << (start - end)) - 1);
}
}  // namespace

std::string ConvertChar32ToUtf8(char32_t ch) {
  std::string result;
  assert(0 <= ch && ch <= 0x10FFFF);
  if (ch <= 0x007F) {
    result.push_back(ch);
  } else if (ch <= 0x07FF) {
    result.push_back(0b11000000 + _GetBit(ch, 11, 6));
    result.push_back(0b10000000 + _GetBit(ch, 6, 0));
  } else if (ch <= 0xFFFF) {
    result.push_back(0b11100000 + _GetBit(ch, 16, 12));
    result.push_back(0b10000000 + _GetBit(ch, 12, 6));
    result.push_back(0b10000000 + _GetBit(ch, 6, 0));
  } else {
    result.push_back(0b11110000 + _GetBit(ch, 21, 18));
    result.push_back(0b10000000 + _GetBit(ch, 18, 12));
    result.push_back(0b10000000 + _GetBit(ch, 12, 6));
    result.push_back(0b10000000 + _GetBit(ch, 6, 0));
  }
  return result;
}

KeyboardKeyEmbedderHandler::KeyboardKeyEmbedderHandler(
    SendEventHandler send_event,
    GetKeyStateHandler get_key_state,
    MapVirtualKeyToScanCode map_virtual_key_to_scan_code)
    : perform_send_event_(send_event),
      get_key_state_(get_key_state),
      response_id_(1) {
  InitCriticalKeys(map_virtual_key_to_scan_code);
}

KeyboardKeyEmbedderHandler::~KeyboardKeyEmbedderHandler() = default;

static bool isEasciiPrintable(int codeUnit) {
  return (codeUnit <= 0x7f && codeUnit >= 0x20) ||
         (codeUnit <= 0xff && codeUnit >= 0x80);
}

// Converts upper letters to lower letters in ASCII and extended ASCII, and
// returns as-is otherwise.
//
// Independent of locale.
static uint64_t toLower(uint64_t n) {
  constexpr uint64_t lower_a = 0x61;
  constexpr uint64_t upper_a = 0x41;
  constexpr uint64_t upper_z = 0x5a;

  constexpr uint64_t lower_a_grave = 0xe0;
  constexpr uint64_t upper_a_grave = 0xc0;
  constexpr uint64_t upper_thorn = 0xde;
  constexpr uint64_t division = 0xf7;

  // ASCII range.
  if (n >= upper_a && n <= upper_z) {
    return n - upper_a + lower_a;
  }

  // EASCII range.
  if (n >= upper_a_grave && n <= upper_thorn && n != division) {
    return n - upper_a_grave + lower_a_grave;
  }

  return n;
}

// Transform scancodes sent by windows to scancodes written in Chromium spec.
static uint16_t normalizeScancode(int windowsScanCode, bool extended) {
  // In Chromium spec the extended bit is shown as 0xe000 bit,
  // e.g. PageUp is represented as 0xe049.
  return (windowsScanCode & 0xff) | (extended ? 0xe000 : 0);
}

uint64_t KeyboardKeyEmbedderHandler::ApplyPlaneToId(uint64_t id,
                                                    uint64_t plane) {
  return (id & valueMask) | plane;
}

uint64_t KeyboardKeyEmbedderHandler::GetPhysicalKey(int scancode,
                                                    bool extended) {
  int chromiumScancode = normalizeScancode(scancode, extended);
  auto resultIt = windowsToPhysicalMap_.find(chromiumScancode);
  if (resultIt != windowsToPhysicalMap_.end())
    return resultIt->second;
  return ApplyPlaneToId(scancode, windowsPlane);
}

uint64_t KeyboardKeyEmbedderHandler::GetLogicalKey(int key,
                                                   bool extended,
                                                   int scancode) {
  if (key == VK_PROCESSKEY) {
    return VK_PROCESSKEY;
  }

  // Normally logical keys should only be derived from key codes, but since some
  // key codes are either 0 or ambiguous (multiple keys using the same key
  // code), these keys are resolved by scan codes.
  auto numpadIter =
      scanCodeToLogicalMap_.find(normalizeScancode(scancode, extended));
  if (numpadIter != scanCodeToLogicalMap_.cend())
    return numpadIter->second;

  // Check if the keyCode is one we know about and have a mapping for.
  auto logicalIt = windowsToLogicalMap_.find(key);
  if (logicalIt != windowsToLogicalMap_.cend())
    return logicalIt->second;

  // Upper case letters should be normalized into lower case letters.
  if (isEasciiPrintable(key)) {
    return ApplyPlaneToId(toLower(key), unicodePlane);
  }

  return ApplyPlaneToId(toLower(key), windowsPlane);
}

void KeyboardKeyEmbedderHandler::KeyboardHookImpl(
    int key,
    int scancode,
    int action,
    char32_t character,
    bool extended,
    bool was_down,
    std::function<void(bool)> callback) {
  const uint64_t physical_key = GetPhysicalKey(scancode, extended);
  const uint64_t logical_key = GetLogicalKey(key, extended, scancode);
  assert(action == WM_KEYDOWN || action == WM_KEYUP ||
         action == WM_SYSKEYDOWN || action == WM_SYSKEYUP);
  const bool is_physical_down = action == WM_KEYDOWN || action == WM_SYSKEYDOWN;

  auto last_logical_record_iter = pressingRecords_.find(physical_key);
  const bool had_record = last_logical_record_iter != pressingRecords_.end();
  const uint64_t last_logical_record =
      had_record ? last_logical_record_iter->second : 0;

  // The resulting event's `type`.
  FlutterKeyEventType type;
  // The resulting event's `logical_key`.
  uint64_t result_logical_key;
  // What pressingRecords_[physical_key] should be after the KeyboardHookImpl
  // returns (0 if the entry should be removed).
  uint64_t eventual_logical_record;
  char character_bytes[kCharacterCacheSize];

  character = UndeadChar(character);

  if (is_physical_down) {
    if (had_record) {
      if (was_down) {
        // A normal repeated key.
        type = kFlutterKeyEventTypeRepeat;
        assert(had_record);
        ConvertUtf32ToUtf8_(character_bytes, character);
        eventual_logical_record = last_logical_record;
        result_logical_key = last_logical_record;
      } else {
        // A non-repeated key has been pressed that has the exact physical key
        // as a currently pressed one, usually indicating multiple keyboards are
        // pressing keys with the same physical key, or the up event was lost
        // during a loss of focus. The down event is ignored.
        callback(true);
        return;
      }
    } else {
      // A normal down event (whether the system event is a repeat or not).
      type = kFlutterKeyEventTypeDown;
      assert(!had_record);
      ConvertUtf32ToUtf8_(character_bytes, character);
      eventual_logical_record = logical_key;
      result_logical_key = logical_key;
    }
  } else {  // isPhysicalDown is false
    if (last_logical_record == 0) {
      // The physical key has been released before. It might indicate a missed
      // event due to loss of focus, or multiple keyboards pressed keys with the
      // same physical key. Ignore the up event.
      callback(true);
      return;
    } else {
      // A normal up event.
      type = kFlutterKeyEventTypeUp;
      assert(had_record);
      // Up events never have character.
      character_bytes[0] = '\0';
      eventual_logical_record = 0;
      result_logical_key = last_logical_record;
    }
  }

  if (result_logical_key == VK_PROCESSKEY) {
    // VK_PROCESSKEY means that the key press is used by an IME. These key
    // presses are considered handled and not sent to Flutter. These events must
    // be filtered by result_logical_key because the key up event of such
    // presses uses the "original" logical key.
    callback(true);
    return;
  }

  UpdateLastSeenCritialKey(key, physical_key, result_logical_key);
  // Synchronize the toggled states of critical keys (such as whether CapsLocks
  // is enabled). Toggled states can only be changed upon a down event, so if
  // the recorded toggled state does not match the true state, this function
  // will synthesize (an up event if the key is recorded pressed, then) a down
  // event.
  //
  // After this function, all critical keys will have their toggled state
  // updated to the true state, while the critical keys whose toggled state have
  // been changed will be pressed regardless of their true pressed state.
  // Updating the pressed state will be done by SynchronizeCritialPressedStates.
  SynchronizeCritialToggledStates(key, type == kFlutterKeyEventTypeDown);
  // Synchronize the pressed states of critical keys (such as whether CapsLocks
  // is pressed).
  //
  // After this function, all critical keys except for the target key will have
  // their toggled state and pressed state matched with their true states. The
  // target key's pressed state will be updated immediately after this.
  SynchronizeCritialPressedStates(key, type != kFlutterKeyEventTypeRepeat);

  if (eventual_logical_record != 0) {
    pressingRecords_[physical_key] = eventual_logical_record;
  } else {
    auto record_iter = pressingRecords_.find(physical_key);
    assert(record_iter != pressingRecords_.end());
    pressingRecords_.erase(record_iter);
  }

  FlutterKeyEvent key_data{
      .struct_size = sizeof(FlutterKeyEvent),
      .timestamp = static_cast<double>(
          std::chrono::duration_cast<std::chrono::microseconds>(
              std::chrono::high_resolution_clock::now().time_since_epoch())
              .count()),
      .type = type,
      .physical = physical_key,
      .logical = result_logical_key,
      .character = character_bytes,
      .synthesized = false,
  };

  response_id_ += 1;
  uint64_t response_id = response_id_;
  PendingResponse pending{
      .callback =
          [this, callback = std::move(callback)](bool handled,
                                                 uint64_t response_id) {
            auto found = pending_responses_.find(response_id);
            if (found != pending_responses_.end()) {
              pending_responses_.erase(found);
            }
            callback(handled);
          },
      .response_id = response_id,
  };
  auto pending_ptr = std::make_unique<PendingResponse>(std::move(pending));
  pending_responses_[response_id] = std::move(pending_ptr);
  SendEvent(key_data, KeyboardKeyEmbedderHandler::HandleResponse,
            reinterpret_cast<void*>(pending_responses_[response_id].get()));
}

void KeyboardKeyEmbedderHandler::KeyboardHook(
    int key,
    int scancode,
    int action,
    char32_t character,
    bool extended,
    bool was_down,
    std::function<void(bool)> callback) {
  sent_any_events = false;
  KeyboardHookImpl(key, scancode, action, character, extended, was_down,
                   std::move(callback));
  if (!sent_any_events) {
    FlutterKeyEvent empty_event{
        .struct_size = sizeof(FlutterKeyEvent),
        .timestamp = static_cast<double>(
            std::chrono::duration_cast<std::chrono::microseconds>(
                std::chrono::high_resolution_clock::now().time_since_epoch())
                .count()),
        .type = kFlutterKeyEventTypeDown,
        .physical = 0,
        .logical = 0,
        .character = empty_character,
        .synthesized = false,
    };
    SendEvent(empty_event, nullptr, nullptr);
  }
}

void KeyboardKeyEmbedderHandler::UpdateLastSeenCritialKey(
    int virtual_key,
    uint64_t physical_key,
    uint64_t logical_key) {
  auto found = critical_keys_.find(virtual_key);
  if (found != critical_keys_.end()) {
    found->second.physical_key = physical_key;
    found->second.logical_key = logical_key;
  }
}

void KeyboardKeyEmbedderHandler::SynchronizeCritialToggledStates(
    int this_virtual_key,
    bool is_down_event) {
  for (auto& kv : critical_keys_) {
    UINT virtual_key = kv.first;
    CriticalKey& key_info = kv.second;
    if (key_info.physical_key == 0) {
      // Never seen this key.
      continue;
    }
    assert(key_info.logical_key != 0);

    // Check toggling state first, because it might alter pressing state.
    if (key_info.check_toggled) {
      // The togglable keys observe a 4-phase cycle:
      //
      //  Phase#   0          1          2         3
      //   Event       Down        Up        Down      Up
      // Pressed   0          1          0         1
      // Toggled   0          1          1         0
      SHORT state = get_key_state_(virtual_key);
      bool should_toggled = state & kStateMaskToggled;
      if (virtual_key == this_virtual_key && is_down_event) {
        key_info.toggled_on = !key_info.toggled_on;
      }
      if (key_info.toggled_on != should_toggled) {
        // If the key is pressed, release it first.
        if (pressingRecords_.find(key_info.physical_key) !=
            pressingRecords_.end()) {
          SendEvent(SynthesizeSimpleEvent(
                        kFlutterKeyEventTypeUp, key_info.physical_key,
                        key_info.logical_key, empty_character),
                    nullptr, nullptr);
        }
        // Synchronizing toggle state always ends with the key being pressed.
        pressingRecords_[key_info.physical_key] = key_info.logical_key;
        SendEvent(SynthesizeSimpleEvent(kFlutterKeyEventTypeDown,
                                        key_info.physical_key,
                                        key_info.logical_key, empty_character),
                  nullptr, nullptr);
      }
      key_info.toggled_on = should_toggled;
    }
  }
}

void KeyboardKeyEmbedderHandler::SynchronizeCritialPressedStates(
    int this_virtual_key,
    bool pressed_state_will_change) {
  for (auto& kv : critical_keys_) {
    UINT virtual_key = kv.first;
    CriticalKey& key_info = kv.second;
    if (key_info.physical_key == 0) {
      // Never seen this key.
      continue;
    }
    assert(key_info.logical_key != 0);
    if (key_info.check_pressed) {
      SHORT state = get_key_state_(virtual_key);
      auto recorded_pressed_iter = pressingRecords_.find(key_info.physical_key);
      bool recorded_pressed = recorded_pressed_iter != pressingRecords_.end();
      bool should_pressed = state & kStateMaskPressed;
      if (virtual_key == this_virtual_key && pressed_state_will_change) {
        should_pressed = !should_pressed;
      }
      if (recorded_pressed != should_pressed) {
        if (recorded_pressed) {
          pressingRecords_.erase(recorded_pressed_iter);
        } else {
          pressingRecords_[key_info.physical_key] = key_info.logical_key;
        }
        const char* empty_character = "";
        SendEvent(
            SynthesizeSimpleEvent(recorded_pressed ? kFlutterKeyEventTypeUp
                                                   : kFlutterKeyEventTypeDown,
                                  key_info.physical_key, key_info.logical_key,
                                  empty_character),
            nullptr, nullptr);
      }
    }
  }
}

void KeyboardKeyEmbedderHandler::HandleResponse(bool handled, void* user_data) {
  PendingResponse* pending = reinterpret_cast<PendingResponse*>(user_data);
  auto callback = std::move(pending->callback);
  callback(handled, pending->response_id);
}

void KeyboardKeyEmbedderHandler::InitCriticalKeys(
    MapVirtualKeyToScanCode map_virtual_key_to_scan_code) {
  auto createCheckedKey = [this, &map_virtual_key_to_scan_code](
                              UINT virtual_key, bool extended,
                              bool check_pressed,
                              bool check_toggled) -> CriticalKey {
    UINT scan_code = map_virtual_key_to_scan_code(virtual_key, extended);
    return CriticalKey{
        .physical_key = GetPhysicalKey(scan_code, extended),
        .logical_key = GetLogicalKey(virtual_key, extended, scan_code),
        .check_pressed = check_pressed || check_toggled,
        .check_toggled = check_toggled,
        .toggled_on = check_toggled
                          ? !!(get_key_state_(virtual_key) & kStateMaskToggled)
                          : false,
    };
  };

  // TODO(dkwingsmt): Consider adding more critical keys here.
  // https://github.com/flutter/flutter/issues/76736
  critical_keys_.emplace(VK_LSHIFT,
                         createCheckedKey(VK_LSHIFT, false, true, false));
  critical_keys_.emplace(VK_RSHIFT,
                         createCheckedKey(VK_RSHIFT, false, true, false));
  critical_keys_.emplace(VK_LCONTROL,
                         createCheckedKey(VK_LCONTROL, false, true, false));
  critical_keys_.emplace(VK_RCONTROL,
                         createCheckedKey(VK_RCONTROL, true, true, false));
  critical_keys_.emplace(VK_LMENU,
                         createCheckedKey(VK_LMENU, false, true, false));
  critical_keys_.emplace(VK_RMENU,
                         createCheckedKey(VK_RMENU, true, true, false));
  critical_keys_.emplace(VK_LWIN, createCheckedKey(VK_LWIN, true, true, false));
  critical_keys_.emplace(VK_RWIN, createCheckedKey(VK_RWIN, true, true, false));

  critical_keys_.emplace(VK_CAPITAL,
                         createCheckedKey(VK_CAPITAL, false, true, true));
  critical_keys_.emplace(VK_SCROLL,
                         createCheckedKey(VK_SCROLL, false, true, true));
  critical_keys_.emplace(VK_NUMLOCK,
                         createCheckedKey(VK_NUMLOCK, true, true, true));
}

void KeyboardKeyEmbedderHandler::ConvertUtf32ToUtf8_(char* out, char32_t ch) {
  if (ch == 0) {
    out[0] = '\0';
    return;
  }
  std::string result = ConvertChar32ToUtf8(ch);
  strcpy_s(out, kCharacterCacheSize, result.c_str());
}

FlutterKeyEvent KeyboardKeyEmbedderHandler::SynthesizeSimpleEvent(
    FlutterKeyEventType type,
    uint64_t physical,
    uint64_t logical,
    const char* character) {
  return FlutterKeyEvent{
      .struct_size = sizeof(FlutterKeyEvent),
      .timestamp = static_cast<double>(
          std::chrono::duration_cast<std::chrono::microseconds>(
              std::chrono::high_resolution_clock::now().time_since_epoch())
              .count()),
      .type = type,
      .physical = physical,
      .logical = logical,
      .character = character,
      .synthesized = true,
  };
}

void KeyboardKeyEmbedderHandler::SendEvent(const FlutterKeyEvent& event,
                                           FlutterKeyEventCallback callback,
                                           void* user_data) {
  sent_any_events = true;
  perform_send_event_(event, callback, user_data);
}

}  // namespace flutter


text:
import sys
sys.path[0:0] = [""]

import os
import os.path
import socket

import six

# websocket-client
import websocket as ws
from websocket._handshake import _create_sec_websocket_key, \
    _validate as _validate_header
from websocket._http import read_headers
from websocket._url import get_proxy_info, parse_url
from websocket._utils import validate_utf8

if six.PY3:
    from base64 import decodebytes as base64decode
else:
    from base64 import decodestring as base64decode

if sys.version_info[0] == 2 and sys.version_info[1] < 7:
    import unittest2 as unittest
else:
    import unittest

try:
    from ssl import SSLError
except ImportError:
    # dummy class of SSLError for ssl none-support environment.
    class SSLError(Exception):
        pass

# Skip test to access the internet.
TEST_WITH_INTERNET = os.environ.get('TEST_WITH_INTERNET', '0') == '1'

# Skip Secure WebSocket test.
TEST_SECURE_WS = True
TRACEABLE = False

def create_mask_key(_):
    return "abcd"

class SockMock(object):
    def __init__(self):
        self.data = []
        self.sent = []

    def add_packet(self, data):
        self.data.append(data)

    def recv(self, bufsize):
        if self.data:
            e = self.data.pop(0)
            if isinstance(e, Exception):
                raise e
            if len(e) > bufsize:
                self.data.insert(0, e[bufsize:])
            return e[:bufsize]

    def send(self, data):
        self.sent.append(data)
        return len(data)

    def close(self):
        pass

class HeaderSockMock(SockMock):

    def __init__(self, fname):
        SockMock.__init__(self)
        path = os.path.join(os.path.dirname(__file__), fname)
        with open(path, "rb") as f:
            self.add_packet(f.read())

class WebSocketTest(unittest.TestCase):
    def setUp(self):
        ws.enableTrace(TRACEABLE)

    def tearDown(self):
        pass

    def testDefaultTimeout(self):
        self.assertEqual(ws.getdefaulttimeout(), None)
        ws.setdefaulttimeout(10)
        self.assertEqual(ws.getdefaulttimeout(), 10)
        ws.setdefaulttimeout(None)

    def testParseUrl(self):
        p = parse_url("ws://www.example.com/r")
        self.assertEqual(p[0], "www.example.com")
        self.assertEqual(p[1], 80)
        self.assertEqual(p[2], "/r")
        self.assertEqual(p[3], False)

        p = parse_url("ws://www.example.com/r/")
        self.assertEqual(p[0], "www.example.com")
        self.assertEqual(p[1], 80)
        self.assertEqual(p[2], "/r/")
        self.assertEqual(p[3], False)

        p = parse_url("ws://www.example.com/")
        self.assertEqual(p[0], "www.example.com")
        self.assertEqual(p[1], 80)
        self.assertEqual(p[2], "/")
        self.assertEqual(p[3], False)

        p = parse_url("ws://www.example.com")
        self.assertEqual(p[0], "www.example.com")
        self.assertEqual(p[1], 80)
        self.assertEqual(p[2], "/")
        self.assertEqual(p[3], False)

        p = parse_url("ws://www.example.com:8080/r")
        self.assertEqual(p[0], "www.example.com")
        self.assertEqual(p[1], 8080)
        self.assertEqual(p[2], "/r")
        self.assertEqual(p[3], False)

        p = parse_url("ws://www.example.com:8080/")
        self.assertEqual(p[0], "www.example.com")
        self.assertEqual(p[1], 8080)
        self.assertEqual(p[2], "/")
        self.assertEqual(p[3], False)

        p = parse_url("ws://www.example.com:8080")
        self.assertEqual(p[0], "www.example.com")
        self.assertEqual(p[1], 8080)
        self.assertEqual(p[2], "/")
        self.assertEqual(p[3], False)

        p = parse_url("wss://www.example.com:8080/r")
        self.assertEqual(p[0], "www.example.com")
        self.assertEqual(p[1], 8080)
        self.assertEqual(p[2], "/r")
        self.assertEqual(p[3], True)

        p = parse_url("wss://www.example.com:8080/r?key=value")
        self.assertEqual(p[0], "www.example.com")
        self.assertEqual(p[1], 8080)
        self.assertEqual(p[2], "/r?key=value")
        self.assertEqual(p[3], True)

        self.assertRaises(ValueError, parse_url, "http://www.example.com/r")

        if sys.version_info[0] == 2 and sys.version_info[1] < 7:
            return

        p = parse_url("ws://[2a03:4000:123:83::3]/r")
        self.assertEqual(p[0], "2a03:4000:123:83::3")
        self.assertEqual(p[1], 80)
        self.assertEqual(p[2], "/r")
        self.assertEqual(p[3], False)

        p = parse_url("ws://[2a03:4000:123:83::3]:8080/r")
        self.assertEqual(p[0], "2a03:4000:123:83::3")
        self.assertEqual(p[1], 8080)
        self.assertEqual(p[2], "/r")
        self.assertEqual(p[3], False)

        p = parse_url("wss://[2a03:4000:123:83::3]/r")
        self.assertEqual(p[0], "2a03:4000:123:83::3")
        self.assertEqual(p[1], 443)
        self.assertEqual(p[2], "/r")
        self.assertEqual(p[3], True)

        p = parse_url("wss://[2a03:4000:123:83::3]:8080/r")
        self.assertEqual(p[0], "2a03:4000:123:83::3")
        self.assertEqual(p[1], 8080)
        self.assertEqual(p[2], "/r")
        self.assertEqual(p[3], True)

    def testWSKey(self):
        key = _create_sec_websocket_key()
        self.assertTrue(key != 24)
        self.assertTrue(six.u("¥n") not in key)

    def testWsUtils(self):
        key = "c6b8hTg4EeGb2gQMztV1/g=="
        required_header = {
            "upgrade": "websocket",
            "connection": "upgrade",
            "sec-websocket-accept": "Kxep+hNu9n51529fGidYu7a3wO0=",
            }
        self.assertEqual(_validate_header(required_header, key, None), (True, None))

        header = required_header.copy()
        header["upgrade"] = "http"
        self.assertEqual(_validate_header(header, key, None), (False, None))
        del header["upgrade"]
        self.assertEqual(_validate_header(header, key, None), (False, None))

        header = required_header.copy()
        header["connection"] = "something"
        self.assertEqual(_validate_header(header, key, None), (False, None))
        del header["connection"]
        self.assertEqual(_validate_header(header, key, None), (False, None))

        header = required_header.copy()
        header["sec-websocket-accept"] = "something"
        self.assertEqual(_validate_header(header, key, None), (False, None))
        del header["sec-websocket-accept"]
        self.assertEqual(_validate_header(header, key, None), (False, None))

        header = required_header.copy()
        header["sec-websocket-protocol"] = "sub1"
        self.assertEqual(_validate_header(header, key, ["sub1", "sub2"]), (True, "sub1"))
        self.assertEqual(_validate_header(header, key, ["sub2", "sub3"]), (False, None))

        header = required_header.copy()
        header["sec-websocket-protocol"] = "sUb1"
        self.assertEqual(_validate_header(header, key, ["Sub1", "suB2"]), (True, "sub1"))

    def testReadHeader(self):
        status, header = read_headers(HeaderSockMock("data/header01.txt"))
        self.assertEqual(status, 101)
        self.assertEqual(header["connection"], "Upgrade")

        HeaderSockMock("data/header02.txt")
        self.assertRaises(ws.WebSocketException, read_headers, HeaderSockMock("data/header02.txt"))

    def testSend(self):
        # TODO: add longer frame data
        sock = ws.WebSocket()
        sock.set_mask_key(create_mask_key)
        s = sock.sock = HeaderSockMock("data/header01.txt")
        sock.send("Hello")
        self.assertEqual(s.sent[0], six.b("\x81\x85abcd)\x07\x0f\x08\x0e"))

        sock.send("こんにちは")
        self.assertEqual(s.sent[1], six.b("\x81\x8fabcd\x82\xe3\xf0\x87\xe3\xf1\x80\xe5\xca\x81\xe2\xc5\x82\xe3\xcc"))

        sock.send(u"こんにちは")
        self.assertEqual(s.sent[1], six.b("\x81\x8fabcd\x82\xe3\xf0\x87\xe3\xf1\x80\xe5\xca\x81\xe2\xc5\x82\xe3\xcc"))

        sock.send("x" * 127)

    def testRecv(self):
        # TODO: add longer frame data
        sock = ws.WebSocket()
        s = sock.sock = SockMock()
        something = six.b("\x81\x8fabcd\x82\xe3\xf0\x87\xe3\xf1\x80\xe5\xca\x81\xe2\xc5\x82\xe3\xcc")
        s.add_packet(something)
        data = sock.recv()
        self.assertEqual(data, "こんにちは")

        s.add_packet(six.b("\x81\x85abcd)\x07\x0f\x08\x0e"))
        data = sock.recv()
        self.assertEqual(data, "Hello")

    @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled")
    def testIter(self):
        count = 2
        for _ in ws.create_connection('ws://stream.meetup.com/2/rsvps'):
            count -= 1
            if count == 0:
                break

    @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled")
    def testNext(self):
        sock = ws.create_connection('ws://stream.meetup.com/2/rsvps')
        self.assertEqual(str, type(next(sock)))

    def testInternalRecvStrict(self):
        sock = ws.WebSocket()
        s = sock.sock = SockMock()
        s.add_packet(six.b("foo"))
        s.add_packet(socket.timeout())
        s.add_packet(six.b("bar"))
        # s.add_packet(SSLError("The read operation timed out"))
        s.add_packet(six.b("baz"))
        with self.assertRaises(ws.WebSocketTimeoutException):
            sock.frame_buffer.recv_strict(9)
        # if six.PY2:
        #     with self.assertRaises(ws.WebSocketTimeoutException):
        #         data = sock._recv_strict(9)
        # else:
        #     with self.assertRaises(SSLError):
        #         data = sock._recv_strict(9)
        data = sock.frame_buffer.recv_strict(9)
        self.assertEqual(data, six.b("foobarbaz"))
        with self.assertRaises(ws.WebSocketConnectionClosedException):
            sock.frame_buffer.recv_strict(1)

    def testRecvTimeout(self):
        sock = ws.WebSocket()
        s = sock.sock = SockMock()
        s.add_packet(six.b("\x81"))
        s.add_packet(socket.timeout())
        s.add_packet(six.b("\x8dabcd\x29\x07\x0f\x08\x0e"))
        s.add_packet(socket.timeout())
        s.add_packet(six.b("\x4e\x43\x33\x0e\x10\x0f\x00\x40"))
        with self.assertRaises(ws.WebSocketTimeoutException):
            sock.recv()
        with self.assertRaises(ws.WebSocketTimeoutException):
            sock.recv()
        data = sock.recv()
        self.assertEqual(data, "Hello, World!")
        with self.assertRaises(ws.WebSocketConnectionClosedException):
            sock.recv()

    def testRecvWithSimpleFragmentation(self):
        sock = ws.WebSocket()
        s = sock.sock = SockMock()
        # OPCODE=TEXT, FIN=0, MSG="Brevity is "
        s.add_packet(six.b("\x01\x8babcd#\x10\x06\x12\x08\x16\x1aD\x08\x11C"))
        # OPCODE=CONT, FIN=1, MSG="the soul of wit"
        s.add_packet(six.b("\x80\x8fabcd\x15\n\x06D\x12\r\x16\x08A\r\x05D\x16\x0b\x17"))
        data = sock.recv()
        self.assertEqual(data, "Brevity is the soul of wit")
        with self.assertRaises(ws.WebSocketConnectionClosedException):
            sock.recv()

    def testRecvWithFireEventOfFragmentation(self):
        sock = ws.WebSocket(fire_cont_frame=True)
        s = sock.sock = SockMock()
        # OPCODE=TEXT, FIN=0, MSG="Brevity is "
        s.add_packet(six.b("\x01\x8babcd#\x10\x06\x12\x08\x16\x1aD\x08\x11C"))
        # OPCODE=CONT, FIN=0, MSG="Brevity is "
        s.add_packet(six.b("\x00\x8babcd#\x10\x06\x12\x08\x16\x1aD\x08\x11C"))
        # OPCODE=CONT, FIN=1, MSG="the soul of wit"
        s.add_packet(six.b("\x80\x8fabcd\x15\n\x06D\x12\r\x16\x08A\r\x05D\x16\x0b\x17"))

        _, data = sock.recv_data()
        self.assertEqual(data, six.b("Brevity is "))
        _, data = sock.recv_data()
        self.assertEqual(data, six.b("Brevity is "))
        _, data = sock.recv_data()
        self.assertEqual(data, six.b("the soul of wit"))

        # OPCODE=CONT, FIN=0, MSG="Brevity is "
        s.add_packet(six.b("\x80\x8babcd#\x10\x06\x12\x08\x16\x1aD\x08\x11C"))

        with self.assertRaises(ws.WebSocketException):
            sock.recv_data()

        with self.assertRaises(ws.WebSocketConnectionClosedException):
            sock.recv()

    def testClose(self):
        sock = ws.WebSocket()
        sock.sock = SockMock()
        sock.connected = True
        sock.close()
        self.assertEqual(sock.connected, False)

        sock = ws.WebSocket()
        s = sock.sock = SockMock()
        sock.connected = True
        s.add_packet(six.b('\x88\x80\x17\x98p\x84'))
        sock.recv()
        self.assertEqual(sock.connected, False)

    def testRecvContFragmentation(self):
        sock = ws.WebSocket()
        s = sock.sock = SockMock()
        # OPCODE=CONT, FIN=1, MSG="the soul of wit"
        s.add_packet(six.b("\x80\x8fabcd\x15\n\x06D\x12\r\x16\x08A\r\x05D\x16\x0b\x17"))
        self.assertRaises(ws.WebSocketException, sock.recv)

    def testRecvWithProlongedFragmentation(self):
        sock = ws.WebSocket()
        s = sock.sock = SockMock()
        # OPCODE=TEXT, FIN=0, MSG="Once more unto the breach, "
        s.add_packet(six.b("\x01\x9babcd.\x0c\x00\x01A\x0f\x0c\x16\x04B\x16\n\x15"
                           "\rC\x10\t\x07C\x06\x13\x07\x02\x07\tNC"))
        # OPCODE=CONT, FIN=0, MSG="dear friends, "
        s.add_packet(six.b("\x00\x8eabcd\x05\x07\x02\x16A\x04\x11\r\x04\x0c\x07"
                           "\x17MB"))
        # OPCODE=CONT, FIN=1, MSG="once more"
        s.add_packet(six.b("\x80\x89abcd\x0e\x0c\x00\x01A\x0f\x0c\x16\x04"))
        data = sock.recv()
        self.assertEqual(
            data,
            "Once more unto the breach, dear friends, once more")
        with self.assertRaises(ws.WebSocketConnectionClosedException):
            sock.recv()

    def testRecvWithFragmentationAndControlFrame(self):
        sock = ws.WebSocket()
        sock.set_mask_key(create_mask_key)
        s = sock.sock = SockMock()
        # OPCODE=TEXT, FIN=0, MSG="Too much "
        s.add_packet(six.b("\x01\x89abcd5\r\x0cD\x0c\x17\x00\x0cA"))
        # OPCODE=PING, FIN=1, MSG="Please PONG this"
        s.add_packet(six.b("\x89\x90abcd1\x0e\x06\x05\x12\x07C4.,$D\x15\n\n\x17"))
        # OPCODE=CONT, FIN=1, MSG="of a good thing"
        s.add_packet(six.b("\x80\x8fabcd\x0e\x04C\x05A\x05\x0c\x0b\x05B\x17\x0c"
                           "\x08\x0c\x04"))
        data = sock.recv()
        self.assertEqual(data, "Too much of a good thing")
        with self.assertRaises(ws.WebSocketConnectionClosedException):
            sock.recv()
        self.assertEqual(
            s.sent[0],
            six.b("\x8a\x90abcd1\x0e\x06\x05\x12\x07C4.,$D\x15\n\n\x17"))

    @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled")
    def testWebSocket(self):
        s = ws.create_connection("ws://echo.websocket.org/")
        self.assertNotEqual(s, None)
        s.send("Hello, World")
        result = s.recv()
        self.assertEqual(result, "Hello, World")

        s.send(u"こにゃにゃちは、世界")
        result = s.recv()
        self.assertEqual(result, "こにゃにゃちは、世界")
        s.close()

    @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled")
    def testPingPong(self):
        s = ws.create_connection("ws://echo.websocket.org/")
        self.assertNotEqual(s, None)
        s.ping("Hello")
        s.pong("Hi")
        s.close()

    @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled")
    @unittest.skipUnless(TEST_SECURE_WS, "wss://echo.websocket.org doesn't work well.")
    def testSecureWebSocket(self):
        if 1:
            import ssl
            s = ws.create_connection("wss://echo.websocket.org/")
            self.assertNotEqual(s, None)
            self.assertTrue(isinstance(s.sock, ssl.SSLSocket))
            s.send("Hello, World")
            result = s.recv()
            self.assertEqual(result, "Hello, World")
            s.send(u"こにゃにゃちは、世界")
            result = s.recv()
            self.assertEqual(result, "こにゃにゃちは、世界")
            s.close()
        #except:
        #    pass

    @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled")
    def testWebSocketWihtCustomHeader(self):
        s = ws.create_connection("ws://echo.websocket.org/",
                                 headers={"User-Agent": "PythonWebsocketClient"})
        self.assertNotEqual(s, None)
        s.send("Hello, World")
        result = s.recv()
        self.assertEqual(result, "Hello, World")
        s.close()

    @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled")
    def testAfterClose(self):
        s = ws.create_connection("ws://echo.websocket.org/")
        self.assertNotEqual(s, None)
        s.close()
        self.assertRaises(ws.WebSocketConnectionClosedException, s.send, "Hello")
        self.assertRaises(ws.WebSocketConnectionClosedException, s.recv)

    def testNonce(self):
        """ WebSocket key should be a random 16-byte nonce.
        """
        key = _create_sec_websocket_key()
        nonce = base64decode(key.encode("utf-8"))
        self.assertEqual(16, len(nonce))

class WebSocketAppTest(unittest.TestCase):

    class NotSetYet(object):
        """ A marker class for signalling that a value hasn't been set yet.
        """

    def setUp(self):
        ws.enableTrace(TRACEABLE)

        WebSocketAppTest.keep_running_open = WebSocketAppTest.NotSetYet()
        WebSocketAppTest.keep_running_close = WebSocketAppTest.NotSetYet()
        WebSocketAppTest.get_mask_key_id = WebSocketAppTest.NotSetYet()

    def tearDown(self):
        WebSocketAppTest.keep_running_open = WebSocketAppTest.NotSetYet()
        WebSocketAppTest.keep_running_close = WebSocketAppTest.NotSetYet()
        WebSocketAppTest.get_mask_key_id = WebSocketAppTest.NotSetYet()

    @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled")
    def testKeepRunning(self):
        """ A WebSocketApp should keep running as long as its self.keep_running
        is not False (in the boolean context).
        """

        def on_open(self, *args, **kwargs):
            """ Set the keep_running flag for later inspection and immediately
            close the connection.
            """
            WebSocketAppTest.keep_running_open = self.keep_running

            self.close()

        def on_close(self, *args, **kwargs):
            """ Set the keep_running flag for the test to use.
            """
            WebSocketAppTest.keep_running_close = self.keep_running

        app = ws.WebSocketApp('ws://echo.websocket.org/', on_open=on_open, on_close=on_close)
        app.run_forever()

        self.assertFalse(isinstance(WebSocketAppTest.keep_running_open,
                                    WebSocketAppTest.NotSetYet))

        self.assertFalse(isinstance(WebSocketAppTest.keep_running_close,
                                    WebSocketAppTest.NotSetYet))

        self.assertEqual(True, WebSocketAppTest.keep_running_open)
        self.assertEqual(False, WebSocketAppTest.keep_running_close)

    @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled")
    def testSockMaskKey(self):
        """ A WebSocketApp should forward the received mask_key function down
        to the actual socket.
        """

        def my_mask_key_func():
            pass

        def on_open(self, *args, **kwargs):
            """ Set the value so the test can use it later on and immediately
            close the connection.
            """
            WebSocketAppTest.get_mask_key_id = id(self.get_mask_key)
            self.close()

        app = ws.WebSocketApp('ws://echo.websocket.org/', on_open=on_open, get_mask_key=my_mask_key_func)
        app.run_forever()

        # Note: We can't use 'is' for comparing the functions directly, need to use 'id'.
        self.assertEqual(WebSocketAppTest.get_mask_key_id, id(my_mask_key_func))

class SockOptTest(unittest.TestCase):
    @unittest.skipUnless(TEST_WITH_INTERNET, "Internet-requiring tests are disabled")
    def testSockOpt(self):
        sockopt = ((socket.IPPROTO_TCP, socket.TCP_NODELAY, 1),)
        s = ws.create_connection("ws://echo.websocket.org", sockopt=sockopt)
        self.assertNotEqual(s.sock.getsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY), 0)
        s.close()

class UtilsTest(unittest.TestCase):
    def testUtf8Validator(self):
        state = validate_utf8(six.b('\xf0\x90\x80\x80'))
        self.assertEqual(state, True)
        state = validate_utf8(six.b('\xce\xba\xe1\xbd\xb9\xcf\x83\xce\xbc\xce\xb5\xed\xa0\x80edited'))
        self.assertEqual(state, False)
        state = validate_utf8(six.b(''))
        self.assertEqual(state, True)

class ProxyInfoTest(unittest.TestCase):
    def setUp(self):
        self.http_proxy = os.environ.get("http_proxy", None)
        self.https_proxy = os.environ.get("https_proxy", None)
        if "http_proxy" in os.environ:
            del os.environ["http_proxy"]
        if "https_proxy" in os.environ:
            del os.environ["https_proxy"]

    def tearDown(self):
        if self.http_proxy:
            os.environ["http_proxy"] = self.http_proxy
        elif "http_proxy" in os.environ:
            del os.environ["http_proxy"]

        if self.https_proxy:
            os.environ["https_proxy"] = self.https_proxy
        elif "https_proxy" in os.environ:
            del os.environ["https_proxy"]

    def testProxyFromArgs(self):
        self.assertEqual(get_proxy_info("echo.websocket.org", False, proxy_host="localhost"), ("localhost", 0, None))
        self.assertEqual(get_proxy_info("echo.websocket.org", False, proxy_host="localhost", proxy_port=3128), ("localhost", 3128, None))
        self.assertEqual(get_proxy_info("echo.websocket.org", True, proxy_host="localhost"), ("localhost", 0, None))
        self.assertEqual(get_proxy_info("echo.websocket.org", True, proxy_host="localhost", proxy_port=3128), ("localhost", 3128, None))

        self.assertEqual(get_proxy_info("echo.websocket.org", False, proxy_host="localhost", proxy_auth=("a", "b")),
            ("localhost", 0, ("a", "b")))
        self.assertEqual(get_proxy_info("echo.websocket.org", False, proxy_host="localhost", proxy_port=3128, proxy_auth=("a", "b")),
            ("localhost", 3128, ("a", "b")))
        self.assertEqual(get_proxy_info("echo.websocket.org", True, proxy_host="localhost", proxy_auth=("a", "b")),
            ("localhost", 0, ("a", "b")))
        self.assertEqual(get_proxy_info("echo.websocket.org", True, proxy_host="localhost", proxy_port=3128, proxy_auth=("a", "b")),
            ("localhost", 3128, ("a", "b")))

        self.assertEqual(get_proxy_info("echo.websocket.org", True, proxy_host="localhost", proxy_port=3128, no_proxy=["example.com"], proxy_auth=("a", "b")),
            ("localhost", 3128, ("a", "b")))
        self.assertEqual(get_proxy_info("echo.websocket.org", True, proxy_host="localhost", proxy_port=3128, no_proxy=["echo.websocket.org"], proxy_auth=("a", "b")),
            (None, 0, None))

    def testProxyFromEnv(self):
        os.environ["http_proxy"] = "http://localhost/"
        self.assertEqual(get_proxy_info("echo.websocket.org", False), ("localhost", None, None))
        os.environ["http_proxy"] = "http://localhost:3128/"
        self.assertEqual(get_proxy_info("echo.websocket.org", False), ("localhost", 3128, None))

        os.environ["http_proxy"] = "http://localhost/"
        os.environ["https_proxy"] = "http://localhost2/"
        self.assertEqual(get_proxy_info("echo.websocket.org", False), ("localhost", None, None))
        os.environ["http_proxy"] = "http://localhost:3128/"
        os.environ["https_proxy"] = "http://localhost2:3128/"
        self.assertEqual(get_proxy_info("echo.websocket.org", False), ("localhost", 3128, None))

        os.environ["http_proxy"] = "http://localhost/"
        os.environ["https_proxy"] = "http://localhost2/"
        self.assertEqual(get_proxy_info("echo.websocket.org", True), ("localhost2", None, None))
        os.environ["http_proxy"] = "http://localhost:3128/"
        os.environ["https_proxy"] = "http://localhost2:3128/"
        self.assertEqual(get_proxy_info("echo.websocket.org", True), ("localhost2", 3128, None))

        os.environ["http_proxy"] = "http://a:b@localhost/"
        self.assertEqual(get_proxy_info("echo.websocket.org", False), ("localhost", None, ("a", "b")))
        os.environ["http_proxy"] = "http://a:b@localhost:3128/"
        self.assertEqual(get_proxy_info("echo.websocket.org", False), ("localhost", 3128, ("a", "b")))

        os.environ["http_proxy"] = "http://a:b@localhost/"
        os.environ["https_proxy"] = "http://a:b@localhost2/"
        self.assertEqual(get_proxy_info("echo.websocket.org", False), ("localhost", None, ("a", "b")))
        os.environ["http_proxy"] = "http://a:b@localhost:3128/"
        os.environ["https_proxy"] = "http://a:b@localhost2:3128/"
        self.assertEqual(get_proxy_info("echo.websocket.org", False), ("localhost", 3128, ("a", "b")))

        os.environ["http_proxy"] = "http://a:b@localhost/"
        os.environ["https_proxy"] = "http://a:b@localhost2/"
        self.assertEqual(get_proxy_info("echo.websocket.org", True), ("localhost2", None, ("a", "b")))
        os.environ["http_proxy"] = "http://a:b@localhost:3128/"
        os.environ["https_proxy"] = "http://a:b@localhost2:3128/"
        self.assertEqual(get_proxy_info("echo.websocket.org", True), ("localhost2", 3128, ("a", "b")))

        os.environ["http_proxy"] = "http://a:b@localhost/"
        os.environ["https_proxy"] = "http://a:b@localhost2/"
        os.environ["no_proxy"] = "example1.com,example2.com"
        self.assertEqual(get_proxy_info("example.1.com", True), ("localhost2", None, ("a", "b")))
        os.environ["http_proxy"] = "http://a:b@localhost:3128/"
        os.environ["https_proxy"] = "http://a:b@localhost2:3128/"
        os.environ["no_proxy"] = "example1.com,example2.com, echo.websocket.org"
        self.assertEqual(get_proxy_info("echo.websocket.org", True), (None, 0, None))

        os.environ["http_proxy"] = "http://a:b@localhost:3128/"
        os.environ["https_proxy"] = "http://a:b@localhost2:3128/"
        os.environ["no_proxy"] = "127.0.0.0/8, 192.168.0.0/16"
        self.assertEqual(get_proxy_info("127.0.0.1", False), (None, 0, None))
        self.assertEqual(get_proxy_info("192.168.1.1", False), (None, 0, None))

if __name__ == "__main__":
    unittest.main()


text:
#ifndef SRC_COMPONENTS_UTILS_INCLUDE_UTILS_LOG_MESSAGE_LOOP_THREAD_H_
#define SRC_COMPONENTS_UTILS_INCLUDE_UTILS_LOG_MESSAGE_LOOP_THREAD_H_

#include <string>
#include <queue>
//#include <log4cxx/logger.h>

#include "utils/macro.h"
#include "utils/threads/message_loop_thread.h"

namespace logger {

typedef struct {
  //log4cxx::LoggerPtr logger;
  //log4cxx::LevelPtr level;
  std::string entry;
  //log4cxx_time_t timeStamp;
  //log4cxx::spi::LocationInfo location;
  //log4cxx::LogString threadName;
} LogMessage;

typedef std::queue<LogMessage> LogMessageQueue;

typedef threads::MessageLoopThread<LogMessageQueue>
    LogMessageLoopThreadTemplate;

class LogMessageHandler : public LogMessageLoopThreadTemplate::Handler {
 public:
  virtual void Handle(const LogMessage message) OVERRIDE;
};

class LogMessageLoopThread : public LogMessageLoopThreadTemplate {
 public:
  LogMessageLoopThread();
  ~LogMessageLoopThread();

  DISALLOW_COPY_AND_ASSIGN(LogMessageLoopThread);
};

}  // namespace logger

#endif  // SRC_COMPONENTS_UTILS_INCLUDE_UTILS_LOG_MESSAGE_LOOP_THREAD_H_


text:
class Question():
    def __len__(self):
        return len(self.distractors)

    def iter_distractors(self):
        return iter(self.distractors)

    def to_string(self, formatter=None):
        if formatter is None:
            formatter = self._default_formatter
        s = formatter.to_string(self)
        return s

class Quiz():
    @classmethod
    def join(cls, lst_quiz):
        quiz_result = cls()
        for quiz in lst_quiz:
            for question in quiz.iter_questions():
                quiz_result.append(question)
        return quiz_result


text:
import logging

from datehelper import DateHelper

logger = logging.getLogger(__name__)

class InvalidDockerEventError(Exception):
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return repr(self.value)

class DockerEvent:
    def __init__(self, details, event_type, event_time, container_id, container_name, service_name):
        self.details = details
        self.type = event_type
        self.container_id = container_id
        self.container_name = container_name
        self.time = event_time
        self.service_name = service_name
        self.formatted_time = DateHelper.format_timestamp(event_time)

    def __str__(self):
        return "type: %s, container_id: %s, container_name: %s, service_name: %s, time: %s" \
               % (self.type, self.container_id, self.container_name, self.service_name, self.formatted_time)

    @classmethod
    def from_dict(cls, data):
        if data.get('status'):
            event_type = data['status']
            container_id = data['id']
            event_time = data['time']
            container_name = data['Actor']['Attributes']['name']
            # key is different in compose vs swarm / stack
            if data['Actor']['Attributes'].get("com.docker.compose.service"):
                service_name = data['Actor']['Attributes']["com.docker.compose.service"]
            elif data['Actor']['Attributes'].get("com.docker.swarm.service.name"):
                service_name = data['Actor']['Attributes']["com.docker.swarm.service.name"]
            else:
                raise InvalidDockerEventError(data)
        else:
            # if we don't have status, it could be any other not container related event
            # e.g. network disconnect
            event_type = None
            container_id = None
            container_name = None
            service_name = None
            event_time = data['time']

        return cls(data, event_type, event_time, container_id, container_name, service_name)


text:
class Outer {
  protected record Foo() {
    <caret>protected Foo {}
  }
}


text:
package cloudformation

// AWSS3Bucket_LambdaConfiguration AWS CloudFormation Resource (AWS::S3::Bucket.LambdaConfiguration)
// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-notificationconfig-lambdaconfig.html
type AWSS3Bucket_LambdaConfiguration struct {

	// Event AWS CloudFormation Property
	// Required: true
	// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-notificationconfig-lambdaconfig.html#cfn-s3-bucket-notificationconfig-lambdaconfig-event
	Event string `json:"Event,omitempty"`

	// Filter AWS CloudFormation Property
	// Required: false
	// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-notificationconfig-lambdaconfig.html#cfn-s3-bucket-notificationconfig-lambdaconfig-filter
	Filter *AWSS3Bucket_NotificationFilter `json:"Filter,omitempty"`

	// Function AWS CloudFormation Property
	// Required: true
	// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-notificationconfig-lambdaconfig.html#cfn-s3-bucket-notificationconfig-lambdaconfig-function
	Function string `json:"Function,omitempty"`
}

// AWSCloudFormationType returns the AWS CloudFormation resource type
func (r *AWSS3Bucket_LambdaConfiguration) AWSCloudFormationType() string {
	return "AWS::S3::Bucket.LambdaConfiguration"
}


text:
/*
 * @name Interactivity 2
 * @arialabel Dark grey background with a colored circle in the middle that changes color as the user drags a slider on the bottom
 * @frame 720,425
 * @description The circle changes color when you move the slider.
 */

// A HTML range slider
let slider;

function setup() {
  createCanvas(720, 400);
  // hue, saturation, and brightness
  colorMode(HSB, 255);
  // slider has a range between 0 and 255 with a starting value of 127
  slider = createSlider(0, 255, 127);
}

function draw() {
  background(127);
  strokeWeight(2);

  // Set the hue according to the slider
  stroke(slider.value(), 255, 255);
  fill(slider.value(), 255, 255, 127);
  ellipse(360, 200, 200, 200);
}


text:
package org.pentaho.di.trans.steps.ldapinput;

import org.pentaho.di.trans.step.StepMetaInterface;

public interface LdapMeta extends StepMetaInterface {
  String getProtocol();

  String getHost();

  String getPort();

  String getDerefAliases();

  String getReferrals();

  boolean isUseCertificate();

  String getTrustStorePath();

  String getTrustStorePassword();

  boolean isTrustAllCertificates();
}


text:
package com.wordnik.swagger.sample.model;

import java.util.Date;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

import com.wordnik.swagger.annotations.ApiModelProperty;

@XmlRootElement(name = "Order")
public class Order {
	private long id;
	private long petId;
	private int quantity;
	private Date shipDate;
	private String status;
    private boolean complete;

	@XmlElement(name = "id")
	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

    public boolean isComplete() {
        return complete;
    }

    public void setComplete(boolean complete) {
        this.complete = complete;
    }

	@XmlElement(name = "petId")
	public long getPetId() {
		return petId;
	}

	public void setPetId(long petId) {
		this.petId = petId;
	}

	@XmlElement(name = "quantity")
	public int getQuantity() {
		return quantity;
	}

	public void setQuantity(int quantity) {
		this.quantity = quantity;
	}

	@XmlElement(name = "status")
	@ApiModelProperty(value = "Order Status", allowableValues = "placed, approved, delivered")
	public String getStatus() {
		return status;
	}

	public void setStatus(String status) {
		this.status = status;
	}

	@XmlElement(name = "shipDate")
	public Date getShipDate() {
		return shipDate;
	}

	public void setShipDate(Date shipDate) {
		this.shipDate = shipDate;
	}
}


text:
Rbtclk.configure do |c|
  # clock, countup and countdown are available.
  c.mode = "clock"

  # Font setting depends on Artii library.
  # https://github.com/miketierney/artii/tree/master/lib/figlet/fonts
  # You can use a lot of font types.
  c.font = "clb8x8"

  # You can use Ruby's Date#strftime style.
  # It is compatible with strftime(3) of standard C library.
  c.format = "%X"

  # black, red, green, yellow, blue, magenta, cyan and white are available.
  c.color = "black"

  # You can specify limit time as seconds in countdown timer.
  c.time = "180"

  # The alarm sound is suppressed if no_alarm is true.
  c.no_alarm = false
end


text:
<?php

defined( 'ABSPATH' ) || die();

class Debug_This {
	protected $buffer;
	protected $debug;
	protected $description;
	public static $mode;
	public static $query_var = 'debug-this';
	public static $no_pre = false;
	protected $default_mode = 'wp_query';
	protected $original_template;
	public static $execution_time;
	public static $queries;
	protected $nonce_action = 'dEbUg-ThIs';
	public static $debug_header;
	public static $template_included;

	public function __construct() {
		if (
			$this->is_user_permitted()
			&& ! is_admin()
		) {
			include_once dirname( __FILE__ ) . '/inc/extensions.php';
			add_filter( 'query_vars', array( $this, 'add_query_var' ), 90210 );
			add_action( 'wp_enqueue_scripts', array( $this, 'enqueue' ), 90210 );
			add_action( 'admin_bar_menu', array( $this, 'admin_bar' ), 90210 );
			add_action( 'shutdown', array( $this, 'render_fetch_data' ), 90210 );

			add_filter( 'template_include', array( $this, 'template_include_filter' ), 1000 );
		}

		if (
			$this->is_user_permitted()
			&& $this->is_debug()
			&& ! is_admin()
		) {
			add_action( 'all', array( $this, 'log_current_filters_and_actions' ) );
			add_filter( 'template_include', array( $this, 'template_include' ), 90210, 1 );
			add_filter( 'template_redirect', array( $this, 'buffer_page' ), 90210 );
			add_action( 'debug_this', array( $this, 'debug' ), self::$mode, 5 );
		}
	}

	public function enqueue() {
		if ( $this->is_debug() ) {
			wp_enqueue_style( 'debug-this', plugins_url( 'inc/css/debug-this.css', __FILE__ ) );
		}
		wp_enqueue_script( 'jquery' );
		wp_enqueue_script( 'debug-this', plugins_url( 'inc/js/debug-this.js', __FILE__ ), array( 'jquery' ) );
		$l10n = array(
			'mode'        => self::$mode,
			'defaultMode' => $this->default_mode,
			'template'    => $this->original_template,
			'queryVar'    => self::$query_var
		);
		wp_localize_script( 'debug-this', 'debugThis', $l10n );
		wp_enqueue_script( 'debug-this-trigger', plugins_url( 'inc/js/debug-this-trigger.js', __FILE__ ), array( 'debug-this' ), '', true );
	}

	public function add_query_var( $vars ) {
		$vars[] = self::$query_var;
		$vars[] = self::$query_var . "-fetch";
		$vars[] = self::$query_var . "-key";
		$vars[] = self::$query_var . "-ts";
		$vars[] = self::$query_var . "-nonce";

		return $vars;
	}

	public function template_include( $template ) {
		$this->original_template = $template;
		$template                = dirname( __FILE__ ) . '/inc/debug-template.php';
		$template                = apply_filters( 'debug_this_template', $template );

		return $template;
	}

	protected function is_fetch() {
		if (
			get_query_var( self::$query_var . "-fetch" ) &&
			get_query_var( self::$query_var . "-ts" ) &&
			get_query_var( self::$query_var . "-key" ) &&
			get_query_var( self::$query_var . "-nonce" )
		) {
			$time  = get_query_var( self::$query_var . "-ts" );
			$nonce = get_query_var( self::$query_var . "-nonce" );
			$key   = get_query_var( self::$query_var . "-key" );

			//Security #1 - Time range
			if ( ( time() - $time ) > 20000 ) {
				return false;
			}

			//Security #2 - Verify nonce
			if ( ! wp_verify_nonce( $nonce, $this->nonce_action ) ) {
				return false;
			}

			//Security #3 - Verify key with shared secret wp_salt
			$key_to_match = md5( $time . wp_salt( 'logged_in' ) . $nonce );
			if ( $key === $key_to_match ) {
				return true;
			}
		} else {
			return false;
		}
	}

	public function render_fetch_data() {
		if ( ! $this->is_fetch() ) {
			return;
		}

		global $wpdb;

		echo '%DEBUG_THIS%';

		$execution_time = timer_stop( 0, 10 );
		echo "%DEBUG_TIME%$execution_time%/DEBUG_TIME%";

		if ( defined( 'SAVEQUERIES' ) && $wpdb->queries ) {
			echo '%DEBUG_QUERIES%' . json_encode( $wpdb->queries ) . '%/DEBUG_QUERIES%';
		}

		echo '%/DEBUG_THIS%';
	}

	public function buffer_page() {

		global $wp;

		$time  = time();
		$nonce = wp_create_nonce( $this->nonce_action );

		$fetch_vars = array(
			self::$query_var . "-fetch" => true,
			self::$query_var . "-key"   => md5( $time . wp_salt( 'logged_in' ) . $nonce ),
			self::$query_var . "-ts"    => $time,
			self::$query_var . "-nonce" => $nonce
		);

		$query_vars = $wp->query_vars;
		unset( $query_vars[ self::$query_var ] );

		$vars         = array_merge( $fetch_vars, $query_vars );
		$query_string = http_build_query( $vars );

		$url = get_bloginfo( 'url' ) . '/' . $wp->request . "?$query_string";

		#Set auth headers for remote fetch
		$cookie_string = '';
		foreach ( $_COOKIE as $k => $v ) {
			if ( preg_match( '/(wordpress_test_cookie|wordpress_logged_in_|wp-settings-1|wp-settings-time-1)/', $k ) ) {
				$cookie_string .= $k . '=' . urlencode( $v ) . '; ';
			}
		}
		$cookie_string = trim( $cookie_string, '; ' );
		$headers       = array(
			'Cookie' => $cookie_string
		);

		$http     = new WP_Http;
		$response = $http->request( $url, array( 'method' => 'GET', 'headers' => $headers ) );
		if ( is_wp_error( $response ) ) {
			$buffer = $response->get_error_message();
		} else {
			$buffer = $response['body'];
		}

		if ( preg_match( '/%DEBUG_TIME%(.+)%\/DEBUG_TIME%/', $buffer, $matches ) ) {
			if ( $matches[1] ) {
				self::$execution_time = $matches[1];
			}
		}

		if ( preg_match( '/%DEBUG_QUERIES%(.+)%\/DEBUG_QUERIES%/', $buffer, $matches ) ) {
			if ( $matches[1] ) {
				self::$queries = json_decode( $matches[1] );
			}
		}

		$this->buffer = preg_replace( '/%DEBUG_THIS%.+%\/DEBUG_THIS%/', '', $buffer );
	}

	protected function is_debug() {
		if ( isset( $_GET[ self::$query_var ] ) ) {
			self::$mode = $_GET[ self::$query_var ] ? $_GET[ self::$query_var ] : apply_filters( 'debug_this_default_mode', $this->default_mode );

			return true;
		}
	}

	protected function is_user_permitted() {
		return is_user_logged_in() && is_super_admin() ? true : false;
	}

	protected function is_domain_permitted() {
		return preg_match( '/(stage|dev|local)/', $_SERVER['SERVER_NAME'] );
	}

	public static function get_no_pre() {
		return self::$no_pre;
	}

	public function debug() {
		global $_debugger_extensions;
		if ( isset( $_debugger_extensions[ self::$mode ] ) && is_array( $_debugger_extensions[ self::$mode ] ) ) {
			$extension         = $_debugger_extensions[ self::$mode ];
			$this->debug       = call_user_func( $extension['callback'], $this->buffer, $this->original_template );
			$this->debug       = apply_filters( 'debug_this_output', $this->debug, self::$mode );
			$this->description = $extension['description'];
			$this->_render();
		} else {
			$debug = '' . __( 'A debug extension could not be found.', 'debug-this' ) . "\n\n";
			$debug .= $this->include_example_extension();
			$this->debug = $debug;
			$this->_render();
		}
	}

	protected function _render() {
		$description = $this->description ? ' - ' . $this->description : '';
		echo '
' . __( 'Debug This Mode', 'debug-this' ) . ': ' . self::$mode . '' . $description . '
';
		echo '
' . self::$debug_header . '
';
		echo $this->debug;
	}

	protected function include_example_extension() {
		$output = file_get_contents( dirname( __FILE__ ) . '/inc/example-extension.txt' );
		$output = htmlentities( str_replace( '$mode', self::$mode, $output ) );
		$output = '
' . __( 'Example Debug Extension', 'debug-this' ) . '
' . $output;

		return $output;
	}

	public function admin_bar() {
		global $wp_admin_bar, $wp;
		if ( ! is_super_admin() || ! is_admin_bar_showing() ) {
			return;
		}

		#Build out query string
		$vars                     = $wp->query_vars;
		$vars[ self::$query_var ] = $this->default_mode;
		$query_string             = http_build_query( $vars );

		$wp_admin_bar->add_menu( array( 'id'    => 'debug_this',
		                                'title' => __( 'Debug This', 'debug-this' ),
		                                'href'  => "?$query_string"
		) );
		foreach ( $this->get_extensions_by_group() as $group => $extensions ) {
			if ( $group === 'Hide' ) {
				continue;
			}
			$group_title = ucwords( str_replace( '-', ' ', $group ) );
			$wp_admin_bar->add_menu( array( 'id'     => $group,
			                                'parent' => 'debug_this',
			                                'title'  => $group_title,
			                                'href'   => false
			) );
			foreach ( $extensions as $id => $values ) {
				#Update query string
				$vars[ self::$query_var ] = $id;
				$query_string             = http_build_query( $vars );
				$wp_admin_bar->add_menu( array( 'id'     => $id,
				                                'parent' => $group,
				                                'title'  => $values['name'],
				                                'href'   => "?$query_string"
				) );
			}
		}
	}

	protected function get_extensions_by_group() {
		global $_debugger_extensions;
		foreach ( $_debugger_extensions as $id => $values ) {
			if ( $id === 'help' ) {
				continue;
			} else {
				$grouped[ $values['group'] ][ $id ] = $values;
			}
		}
		ksort( $grouped );

		return $grouped;
	}

	public function log_current_filters_and_actions() {
		global $debug_this_current_filter;
		$debug_this_current_filter[] = current_filter();
	}

	public static function get_escape_url() {
		global $wp;

		$permalinks = get_option( 'permalink_structure' );
		if ( $permalinks ) {
			$url = $wp->request;
		} else {
			$vars = $wp->query_vars;
			foreach ( $vars as $k => $v ) {
				if ( $v === self::$mode ) {
					unset( $vars[ $k ] );
				}
			}
			$url = ! empty( $vars ) ? '?' . http_build_query( $vars ) : '';
		}

		return $url;
	}

	public static function get_current_debug_url() {
		$url = self::get_escape_url();
		$url .= '&' . self::$query_var . '=' . self::$mode;

		return $url;
	}

	public function template_include_filter( $template ) {
		self::$template_included = $template;

		return $template;
	}

}

add_action( 'init', 'debug_this_init', 0 );
function debug_this_init() {
	new Debug_This;
}

function add_debug_extension( $id, $name, $description, $callback, $group = 'General' ) {
	global $_debugger_extensions;
	$_debugger_extensions[ $id ] = array(
		'name'        => $name,
		'description' => $description,
		'callback'    => $callback,
		'group'       => $group
	);
}

function remove_debug_extension( $id ) {
	global $_debugger_extensions;
	if ( isset( $_debugger_extensions[ $id ] ) ) {
		unset( $_debugger_extensions[ $id ] );
	}
}

function add_debug_header_link( $url, $label, $classes = '' ) {
	Debug_This::$debug_header = Debug_This::$debug_header . "
$label
";
}

function debug_this_get_file_ownership( $file ) {
	$stat = stat( $file );
	if ( $stat ) {
		$group = posix_getgrgid( $stat[5] );
		$user  = posix_getpwuid( $stat[4] );

		return compact( 'user', 'group' );
	} else {
		return false;
	}
}

function debug_this_get_file_perms( $file ) {
	return substr( sprintf( '%o', fileperms( $file ) ), - 4 );
}

function debug_this_convert_perms_to_rwx( $perms, $file ) {
	$rwx    = array(
		'---',
		'--x',
		'-w-',
		'-wx',
		'r--',
		'r-x',
		'rw-',
		'rwx'
	);
	$type   = is_dir( $file ) ? 'd' : '-';
	$user   = $perms[1];
	$group  = $perms[2];
	$public = $perms[3];

	return $type . $rwx[ $user ] . $rwx[ $group ] . $rwx[ $public ];
}


text:
require "json"
require "open3"
require "pandoc_object_filters"
require "pathname"

FILTER = PandocObjectFilters::Filter.new

# Utility class to construct a link to another Pandoc generated document in the
# correct path to the target format.
class DocLinkUrl
  def initialize(url)
    @file = url[/\A[^#]*/]
    @heading = url[/#(.*\z)/, 1]
  end

  def file_path
    File.expand_path("../../../man/#{@file}", __FILE__)
  end

  def path
    @path ||= path_to(doc)
  end

  def doc
    @doc ||=
      begin
        json_doc = JSON.parse(`pandoc -f markdown -t json "#{file_path}"`)
        PandocObjectFilters::Element::Document.new(json_doc)
      end
  end

  def filename
    @filename ||=
      begin
        meta = doc.meta["#{FILTER.format}_link_name"]
        default = File.basename(@file).sub(/\.md\z/, format_extension)
        extract_meta(meta, default)
      end
  end

  def format_extension
    case FILTER.format
    when "markdown_github"
      ".md"
    when "html"
      ".html"
    when "man"
      ""
    else
      raise "Unknown format: #{FILTER.format}"
    end
  end

  def relative_path
    current = Pathname.new(current_path)
    file = Pathname.new(path).join(filename)
    file.relative_path_from(current).to_s
  end

  def heading
    "##{@heading}" unless @heading.to_s.empty?
  end

  def to_s
    case FILTER.format
    when "markdown_github"
      "#{relative_path}#{heading}"
    when "html"
      "#{relative_path.sub(/\.md\z/, ".html")}#{heading}"
    when "man"
      "gemstash help #{filename.sub(/\Agemstash-/, "")}"
    else
      raise "Unknown format: #{FILTER.format}"
    end
  end
end

def current_path
  @current_path ||= path_to(FILTER.doc)
end

def path_to(doc)
  default = FILTER.format == "markdown_github" ? "docs" : "."
  extract_meta(doc.meta["#{FILTER.format}_link_path"], default)
end

def extract_meta(meta, default = nil)
  return default unless meta
  return meta.value if meta.is_a?(PandocObjectFilters::Element::MetaString)
  raise "Unknown meta type: #{meta.class}" unless meta.is_a?(PandocObjectFilters::Element::MetaInlines)

  meta.elements.map do |element|
    if element.is_a?(PandocObjectFilters::Element::Space)
      " "
    else
      element.value
    end
  end.join
end

FILTER.filter do |element|
  next unless element.is_a?(PandocObjectFilters::Element::Link)
  match = %r{\A\./(gemstash-.*)\z}.match(element.target.url)
  next unless match
  element.target.url = DocLinkUrl.new(match[1]).to_s
end


text:
require 'bundler'
begin
  Bundler.setup(:default, :development)
rescue Bundler::BundlerError => e
  $stderr.puts e.message
  $stderr.puts "Run `bundle install` to install missing gems"
  exit e.status_code
end

# $LOAD_PATH.unshift(File.dirname(__FILE__) + '/../../lib')
# require 'tic_tac_toe'
Dir["#{File.dirname(__FILE__)}/../../lib/**/*.rb"].each {|f| require f}

require 'rspec/expectations'


text:
"""Tuner for Scikit-learn Models."""
import collections
import inspect
import os
import pickle
import warnings

import numpy as np
import tensorflow as tf

try:
    import pandas as pd  # pytype: disable=import-error
except ImportError:
    pd = None

try:
    import sklearn  # pytype: disable=import-error
    import sklearn.model_selection
    import sklearn.pipeline
except ImportError:
    sklearn = None

from keras_tuner.engine import base_tuner

def split_data(data, indices):
    if isinstance(data, np.ndarray):
        return data[indices]
    elif pd is not None and isinstance(data, pd.DataFrame):
        return data.iloc[indices]
    else:
        raise TypeError()

class SklearnTuner(base_tuner.BaseTuner):
    """Tuner for Scikit-learn Models.

    Performs cross-validated hyperparameter search for Scikit-learn models.

    Examples:

    ```python
    import keras_tuner
    from sklearn import ensemble
    from sklearn import datasets
    from sklearn import linear_model
    from sklearn import metrics
    from sklearn import model_selection

    def build_model(hp):
      model_type = hp.Choice('model_type', ['random_forest', 'ridge'])
      if model_type == 'random_forest':
        model = ensemble.RandomForestClassifier(
            n_estimators=hp.Int('n_estimators', 10, 50, step=10),
            max_depth=hp.Int('max_depth', 3, 10))
      else:
        model = linear_model.RidgeClassifier(
            alpha=hp.Float('alpha', 1e-3, 1, sampling='log'))
      return model

    tuner = keras_tuner.tuners.SklearnTuner(
        oracle=keras_tuner.oracles.BayesianOptimizationOracle(
            objective=keras_tuner.Objective('score', 'max'),
            max_trials=10),
        hypermodel=build_model,
        scoring=metrics.make_scorer(metrics.accuracy_score),
        cv=model_selection.StratifiedKFold(5),
        directory='.',
        project_name='my_project')

    X, y = datasets.load_iris(return_X_y=True)
    X_train, X_test, y_train, y_test = model_selection.train_test_split(
        X, y, test_size=0.2)

    tuner.search(X_train, y_train)

    best_model = tuner.get_best_models(num_models=1)[0]
    ```

    Args:
        oracle: A `keras_tuner.Oracle` instance. Note that for this `Tuner`,
            the `objective` for the `Oracle` should always be set to
            `Objective('score', direction='max')`. Also, `Oracle`s that exploit
            Neural-Network-specific training (e.g. `Hyperband`) should not be
            used with this `Tuner`.
        hypermodel: A `HyperModel` instance (or callable that takes
            hyperparameters and returns a Model instance).
        scoring: An sklearn `scoring` function. For more information, see
            `sklearn.metrics.make_scorer`. If not provided, the Model's default
            scoring will be used via `model.score`. Note that if you are
            searching across different Model families, the default scoring for
            these Models will often be different. In this case you should
            supply `scoring` here in order to make sure your Models are being
            scored on the same metric.
        metrics: Additional `sklearn.metrics` functions to monitor during search.
            Note that these metrics do not affect the search process.
        cv: An `sklearn.model_selection` Splitter class. Used to
            determine how samples are split up into groups for
            cross-validation.
        **kwargs: Keyword arguments relevant to all `Tuner` subclasses. Please
            see the docstring for `Tuner`.
    """

    def __init__(
        self, oracle, hypermodel, scoring=None, metrics=None, cv=None, **kwargs
    ):
        super().__init__(oracle=oracle, hypermodel=hypermodel, **kwargs)

        if sklearn is None:
            raise ImportError(
                "Please install sklearn before using the `SklearnTuner`."
            )

        self.scoring = scoring

        if metrics is None:
            metrics = []
        if not isinstance(metrics, (list, tuple)):
            metrics = [metrics]
        self.metrics = metrics

        self.cv = cv or sklearn.model_selection.KFold(
            5, shuffle=True, random_state=1
        )

    def search(self, X, y, sample_weight=None, groups=None):
        """Performs hyperparameter search.

        Args:
            X: See docstring for `model.fit` for the `sklearn` Models being tuned.
            y: See docstring for `model.fit` for the `sklearn` Models being tuned.
            sample_weight: Optional. See docstring for `model.fit` for the
                `sklearn` Models being tuned.
            groups: Optional. Required for `sklearn.model_selection` Splitter
                classes that split based on group labels (For example, see
                `sklearn.model_selection.GroupKFold`).
        """
        # Only overridden for the docstring.
        return super().search(X, y, sample_weight=sample_weight, groups=groups)

    def run_trial(self, trial, X, y, sample_weight=None, groups=None):

        metrics = collections.defaultdict(list)
        # For cross-validation methods that expect a `groups` argument.
        cv_kwargs = {"groups": groups} if groups is not None else {}
        for train_indices, test_indices in self.cv.split(X, y, **cv_kwargs):
            X_train = split_data(X, train_indices)
            y_train = split_data(y, train_indices)
            X_test = split_data(X, test_indices)
            y_test = split_data(y, test_indices)

            sample_weight_train = (
                sample_weight[train_indices] if sample_weight is not None else None
            )

            model = self.hypermodel.build(trial.hyperparameters)

            supports_sw = "sample_weight" in inspect.getfullargspec(model.fit).args
            if isinstance(model, sklearn.pipeline.Pipeline) or not supports_sw:
                model.fit(X_train, y_train)
            else:
                model.fit(X_train, y_train, sample_weight=sample_weight_train)

            sample_weight_test = (
                sample_weight[test_indices] if sample_weight is not None else None
            )

            if self.scoring is None:
                score = model.score(X_test, y_test, sample_weight=sample_weight_test)
            else:
                score = self.scoring(
                    model, X_test, y_test, sample_weight=sample_weight_test
                )
            metrics["score"].append(score)

            if self.metrics:
                y_test_pred = model.predict(X_test)
                for metric in self.metrics:
                    result = metric(
                        y_test, y_test_pred, sample_weight=sample_weight_test
                    )
                    metrics[metric.__name__].append(result)

        trial_metrics = {name: np.mean(values) for name, values in metrics.items()}
        self.oracle.update_trial(trial.trial_id, trial_metrics)
        self.save_model(trial.trial_id, model)

    def save_model(self, trial_id, model, step=0):
        fname = os.path.join(self.get_trial_dir(trial_id), "model.pickle")
        with tf.io.gfile.GFile(fname, "wb") as f:
            pickle.dump(model, f)

    def load_model(self, trial):
        fname = os.path.join(self.get_trial_dir(trial.trial_id), "model.pickle")
        with tf.io.gfile.GFile(fname, "rb") as f:
            return pickle.load(f)

class Sklearn(SklearnTuner):
    def __init__(self, *args, **kwargs):
        warnings.warn(
            "The `Sklearn` class is deprecated, please use `SklearnTuner`.",
            DeprecationWarning,
        )
        super().__init__(*args, **kwargs)


text:
struct ALCdevice_struct;
struct ImGuiIO;

namespace boomhs
{
struct PlayerBehavior;

struct DeviceStates
{
  ControllerStates controller;
  MouseStates      mouse;
  CursorManager    cursors;
};

struct MovementState
{
  glm::vec3 forward, backward, left, right;

  glm::vec3 mouse_forward;

  NO_COPY_OR_MOVE(MovementState);
};

struct EngineState
{
  common::Logger&   logger;
  ALCdevice_struct& al_device;
  ImGuiIO&          imgui;

  Frustum         frustum;
  MainMenuState   main_menu;
  common::Time    time;
  PlayerBehaviors behaviors;

  bool                 quit                  = false;
  bool                 game_running          = false;
  bool                 update_orbital_bodies = true;
  GameGraphicsSettings graphics_settings     = {};

  DeviceStates        device_states = {};
  gl_sdl::WindowState window_state  = {};
  UiState             ui_state      = {};

  // Current player movement vector
  MovementState movement_state = {};

  // While the user has "pressed" a mouse button down and held it, this value holds the origin of
  // where the user began holding down the mouse button.
  //
  // This field is useful for drawing things relative to where a user clicks and holds down/drags
  // the mouse.
  //
  // ie: Unit selection from a top-down perspective.
  MouseClickPositions mouse_click_origin;

  bool disable_controller_input;
  bool player_collision;
  bool mariolike_edges;
  bool draw_imguimetrics;

  // rendering state
  bool draw_bounding_boxes;
  bool draw_view_frustum;
  bool draw_2d_billboard_entities;
  bool draw_2d_ui_entities;

  bool draw_3d_entities;
  bool draw_fbo_testwindow;
  bool draw_terrain;
  bool draw_normals;
  bool draw_skybox;

  bool show_global_axis;

  bool show_player_localspace_vectors;
  bool show_player_worldspace_vectors;

  struct GridLinesInfo
  {
    bool      show = false;
    glm::vec3 dimensions = VEC3{10, 1, 10};
  };

  GridLinesInfo grid_lines;

  // Draw *Everything* with a wireframe drawing mode.
  bool wireframe_override;

  // Constructors
  NO_COPY_OR_MOVE(EngineState);
  EngineState(common::Logger&, ALCdevice_struct&, ImGuiIO&, Frustum const& frustum);
};

using EntityRegistries = std::vector<EntityRegistry>;

struct Engine
{
  gl_sdl::SDLWindow window;
  SDLControllers    controllers;

  EntityRegistries registries = {};

  Engine() = delete;
  explicit Engine(gl_sdl::SDLWindow&&, SDLControllers&&);

  // We mark this as no-move/copy so the registries data never moves, allowing the rest of the
  // program to store references into the data owned by registries.
  NO_COPY_OR_MOVE(Engine);

  Viewport window_viewport() const;
};

} // namespace boomhs


text:
package scorex.transaction.assets

import com.google.common.primitives.{Bytes, Longs}
import play.api.libs.json.{JsObject, Json}
import scorex.account.{Account, PrivateKeyAccount, PublicKeyAccount}
import scorex.crypto.EllipticCurveImpl
import scorex.crypto.encode.Base58
import scorex.serialization.Deser
import scorex.transaction.TypedTransaction._
import scorex.transaction.ValidationError
import scorex.transaction._

import scala.util.{Failure, Success, Try}

sealed trait ReissueTransaction extends AssetIssuance {
  def fee: Long
}

object ReissueTransaction extends Deser[ReissueTransaction] {

  private case class ReissueTransactionImpl(sender: PublicKeyAccount,
                                    assetId: Array[Byte],
                                    quantity: Long,
                                    reissuable: Boolean,
                                    fee: Long,
                                    timestamp: Long,
                                    signature: Array[Byte])
      extends ReissueTransaction {

    override val transactionType: TransactionType.Value = TransactionType.ReissueTransaction

    lazy val toSign: Array[Byte] = Bytes.concat(Array(transactionType.id.toByte),
                                                sender.publicKey,
                                                assetId,
                                                Longs.toByteArray(quantity),
                                                if (reissuable) Array(1: Byte) else Array(0: Byte),
                                                Longs.toByteArray(fee),
                                                Longs.toByteArray(timestamp))

    override lazy val json: JsObject = jsonBase() ++ Json.obj(
        "assetId"    -> Base58.encode(assetId),
        "quantity"   -> quantity,
        "reissuable" -> reissuable
      )

    override val assetFee: (Option[AssetId], Long) = (None, fee)
    override lazy val balanceChanges: Seq[BalanceChange] =
      Seq(BalanceChange(AssetAcc(sender, Some(assetId)), quantity), BalanceChange(AssetAcc(sender, assetFee._1), -assetFee._2))

    override lazy val bytes: Array[Byte] = Bytes.concat(Array(transactionType.id.toByte), signature, toSign)

  }

  override def parseBytes(bytes: Array[Byte]): Try[ReissueTransaction] = Try {
    require(bytes.head == TransactionType.ReissueTransaction.id)
    parseTail(bytes.tail).get
  }

  def parseTail(bytes: Array[Byte]): Try[ReissueTransaction] = Try {
    import EllipticCurveImpl._
    val signature = bytes.slice(0, SignatureLength)
    val txId      = bytes(SignatureLength)
    require(txId == TransactionType.ReissueTransaction.id.toByte, s"Signed tx id is not match")
    val sender        = new PublicKeyAccount(bytes.slice(SignatureLength + 1, SignatureLength + KeyLength + 1))
    val assetId       = bytes.slice(SignatureLength + KeyLength + 1, SignatureLength + KeyLength + AssetIdLength + 1)
    val quantityStart = SignatureLength + KeyLength + AssetIdLength + 1

    val quantity   = Longs.fromByteArray(bytes.slice(quantityStart, quantityStart + 8))
    val reissuable = bytes.slice(quantityStart + 8, quantityStart + 9).head == (1: Byte)
    val fee        = Longs.fromByteArray(bytes.slice(quantityStart + 9, quantityStart + 17))
    val timestamp  = Longs.fromByteArray(bytes.slice(quantityStart + 17, quantityStart + 25))
    ReissueTransaction.create(sender, assetId, quantity, reissuable, fee, timestamp, signature)
      .fold(left => Failure(new Exception(left.toString)), right => Success(right))
  }.flatten

  private def createUnverified(sender: PublicKeyAccount,
                               assetId: Array[Byte],
                               quantity: Long,
                               reissuable: Boolean,
                               fee: Long,
                               timestamp: Long,
                               signature: Option[Array[Byte]] = None) =
    if (quantity <= 0) {
      Left(ValidationError.NegativeAmount)
    } else if (!Account.isValid(sender)) {
      Left(ValidationError.InvalidAddress)
    } else if (fee <= 0) {
      Left(ValidationError.InsufficientFee)
    } else {
      Right(ReissueTransactionImpl(sender, assetId, quantity, reissuable, fee, timestamp, signature.orNull))
    }

  def create(sender: PublicKeyAccount,
             assetId: Array[Byte],
             quantity: Long,
             reissuable: Boolean,
             fee: Long,
             timestamp: Long,
             signature: Array[Byte]): Either[ValidationError, ReissueTransaction] =
    createUnverified(sender, assetId, quantity, reissuable, fee, timestamp, Some(signature))
      .right
      .flatMap(SignedTransaction.verify)

  def create(sender: PrivateKeyAccount,
             assetId: Array[Byte],
             quantity: Long,
             reissuable: Boolean,
             fee: Long,
             timestamp: Long): Either[ValidationError, ReissueTransaction] =
    createUnverified(sender, assetId, quantity, reissuable, fee, timestamp).right.map { unsigned =>
      unsigned.copy(signature = EllipticCurveImpl.sign(sender, unsigned.toSign))
    }
}