text:
import {EventActionMap} from 'neuroglancer/util/event_action_map';
import {InputEventBindings} from 'neuroglancer/viewer';

let defaultGlobalBindings: EventActionMap|undefined;

export function getDefaultGlobalBindings() {
  if (defaultGlobalBindings === undefined) {
    const map = new EventActionMap();
    map.set('keyl', 'recolor');
    map.set('keyx', 'clear-segments');
    map.set('keys', 'toggle-show-slices');
    map.set('keyb', 'toggle-scale-bar');
    map.set('shift+keyb', 'toggle-default-annotations');
    map.set('keya', 'toggle-axis-lines');
    map.set('keyo', 'toggle-orthographic-projection');

    for (let i = 1; i <= 9; ++i) {
      map.set('digit' + i, 'toggle-layer-' + i);
      map.set('control+digit' + i, 'select-layer-' + i);
      map.set('alt+digit' + i, 'toggle-pick-layer-' + i);
    }

    map.set('keyn', 'add-layer');
    map.set('keyh', 'help');

    map.set('space', 'toggle-layout');
    map.set('shift+space', 'toggle-layout-alternative');
    map.set('backslash', 'toggle-show-statistics');
    defaultGlobalBindings = map;
  }
  return defaultGlobalBindings;
}

let defaultSelectBindings: EventActionMap|undefined;
export function getDefaultSelectBindings() {
  if (defaultSelectBindings === undefined) {
    defaultSelectBindings = EventActionMap.fromObject({'control+mousedown2': 'select-position'});
  }
  return defaultSelectBindings;
}

let defaultAnnotationListBindings: EventActionMap|undefined;
export function getDefaultAnnotationListBindings() {
  if (defaultAnnotationListBindings === undefined) {
    defaultAnnotationListBindings = EventActionMap.fromObject(
        {
          'click0': 'pin-annotation',
          'mousedown2': 'move-to-annotation',
        },
        {parents: [[getDefaultSelectBindings(), 0]]});
  }
  return defaultAnnotationListBindings;
}

let defaultRenderedDataPanelBindings: EventActionMap|undefined;
export function getDefaultRenderedDataPanelBindings() {
  if (defaultRenderedDataPanelBindings === undefined) {
    defaultRenderedDataPanelBindings = EventActionMap.fromObject(
        {
          'arrowleft': 'x-',
          'arrowright': 'x+',
          'arrowup': 'y-',
          'arrowdown': 'y+',
          'comma': 'z-',
          'period': 'z+',
          'bracketleft': 't-',
          'bracketright': 't+',
          'keyz': 'snap',
          'control+equal': 'zoom-in',
          'alt+equal': 'depth-range-decrease',
          'control+shift+equal': 'zoom-in',
          'alt+shift+equal': 'depth-range-decrease',
          'control+minus': 'zoom-out',
          'alt+minus': 'depth-range-increase',
          'keyr': 'rotate-relative-z-',
          'keye': 'rotate-relative-z+',
          'shift+arrowdown': 'rotate-relative-x-',
          'shift+arrowup': 'rotate-relative-x+',
          'shift+arrowleft': 'rotate-relative-y-',
          'shift+arrowright': 'rotate-relative-y+',
          'control+wheel': {action: 'zoom-via-wheel', preventDefault: true},
          'alt+wheel': {action: 'adjust-depth-range-via-wheel', preventDefault: true},
          'at:wheel': {action: 'z+1-via-wheel', preventDefault: true},
          'at:shift+wheel': {action: 'z+10-via-wheel', preventDefault: true},
          'at:dblclick0': 'select',
          'at:control+mousedown0': 'annotate',
          'at:mousedown2': 'move-to-mouse-position',
          'at:alt+mousedown0': 'move-annotation',
          'at:control+alt+mousedown2': 'delete-annotation',
          'at:touchpinch': 'zoom-via-touchpinch',
          'at:touchrotate': 'rotate-in-plane-via-touchrotate',
          'at:touchtranslate2': 'translate-in-plane-via-touchtranslate',
          'at:touchhold1': 'move-to-mouse-position',
          'at:touchtap1x2': 'select',
          'at:touchtap2x3': 'snap',
        },
        {
          label: 'All Data Panels',
          parents: [[getDefaultSelectBindings(), 0]],
        });
  }
  return defaultRenderedDataPanelBindings;
}

let defaultPerspectivePanelBindings: EventActionMap|undefined;
export function getDefaultPerspectivePanelBindings() {
  if (defaultPerspectivePanelBindings === undefined) {
    defaultPerspectivePanelBindings = EventActionMap.fromObject(
        {
          'at:mousedown0': {action: 'rotate-via-mouse-drag', stopPropagation: true},
          'at:shift+mousedown0': {action: 'translate-via-mouse-drag', stopPropagation: true},
          'at:touchtranslate1': 'rotate-out-of-plane-via-touchtranslate',
        },
        {parents: [[getDefaultRenderedDataPanelBindings(), Number.NEGATIVE_INFINITY]]});
  }
  return defaultPerspectivePanelBindings;
}

let defaultSliceViewPanelBindings: EventActionMap|undefined;
export function getDefaultSliceViewPanelBindings() {
  if (defaultSliceViewPanelBindings === undefined) {
    defaultSliceViewPanelBindings = EventActionMap.fromObject(
        {
          'at:mousedown0': {action: 'translate-via-mouse-drag', stopPropagation: true},
          'at:shift+mousedown0': {action: 'rotate-via-mouse-drag', stopPropagation: true},
          'at:touchtranslate1': 'translate-z-via-touchtranslate',
        },
        {parents: [[getDefaultRenderedDataPanelBindings(), Number.NEGATIVE_INFINITY]]});
  }
  return defaultSliceViewPanelBindings;
}

export function setDefaultInputEventBindings(inputEventBindings: InputEventBindings) {
  inputEventBindings.global.addParent(getDefaultGlobalBindings(), Number.NEGATIVE_INFINITY);
  inputEventBindings.sliceView.addParent(
      getDefaultSliceViewPanelBindings(), Number.NEGATIVE_INFINITY);
  inputEventBindings.perspectiveView.addParent(
      getDefaultPerspectivePanelBindings(), Number.NEGATIVE_INFINITY);
}


text:
namespace v8 {
namespace internal {

HEnvironmentLivenessAnalysisPhase::HEnvironmentLivenessAnalysisPhase(
    HGraph* graph)
    : HPhase("H_Environment liveness analysis", graph),
      block_count_(graph->blocks()->length()),
      maximum_environment_size_(graph->maximum_environment_size()),
      live_at_block_start_(block_count_, zone()),
      first_simulate_(block_count_, zone()),
      first_simulate_invalid_for_index_(block_count_, zone()),
      markers_(maximum_environment_size_, zone()),
      collect_markers_(true),
      last_simulate_(NULL),
      went_live_since_last_simulate_(maximum_environment_size_, zone()) {
  DCHECK(maximum_environment_size_ > 0);
  for (int i = 0; i < block_count_; ++i) {
    live_at_block_start_.Add(
        new(zone()) BitVector(maximum_environment_size_, zone()), zone());
    first_simulate_.Add(NULL, zone());
    first_simulate_invalid_for_index_.Add(
        new(zone()) BitVector(maximum_environment_size_, zone()), zone());
  }
}

void HEnvironmentLivenessAnalysisPhase::ZapEnvironmentSlot(
    int index, HSimulate* simulate) {
  int operand_index = simulate->ToOperandIndex(index);
  if (operand_index == -1) {
    simulate->AddAssignedValue(index, graph()->GetConstantOptimizedOut());
  } else {
    simulate->SetOperandAt(operand_index, graph()->GetConstantOptimizedOut());
  }
}

void HEnvironmentLivenessAnalysisPhase::ZapEnvironmentSlotsInSuccessors(
    HBasicBlock* block, BitVector* live) {
  // When a value is live in successor A but dead in B, we must
  // explicitly zap it in B.
  for (HSuccessorIterator it(block->end()); !it.Done(); it.Advance()) {
    HBasicBlock* successor = it.Current();
    int successor_id = successor->block_id();
    BitVector* live_in_successor = live_at_block_start_[successor_id];
    if (live_in_successor->Equals(*live)) continue;
    for (int i = 0; i < live->length(); ++i) {
      if (!live->Contains(i)) continue;
      if (live_in_successor->Contains(i)) continue;
      if (first_simulate_invalid_for_index_.at(successor_id)->Contains(i)) {
        continue;
      }
      HSimulate* simulate = first_simulate_.at(successor_id);
      if (simulate == NULL) continue;
      DCHECK(VerifyClosures(simulate->closure(),
          block->last_environment()->closure()));
      ZapEnvironmentSlot(i, simulate);
    }
  }
}

void HEnvironmentLivenessAnalysisPhase::ZapEnvironmentSlotsForInstruction(
    HEnvironmentMarker* marker) {
  if (!marker->CheckFlag(HValue::kEndsLiveRange)) return;
  HSimulate* simulate = marker->next_simulate();
  if (simulate != NULL) {
    DCHECK(VerifyClosures(simulate->closure(), marker->closure()));
    ZapEnvironmentSlot(marker->index(), simulate);
  }
}

void HEnvironmentLivenessAnalysisPhase::UpdateLivenessAtBlockEnd(
    HBasicBlock* block,
    BitVector* live) {
  // Liveness at the end of each block: union of liveness in successors.
  live->Clear();
  for (HSuccessorIterator it(block->end()); !it.Done(); it.Advance()) {
    live->Union(*live_at_block_start_[it.Current()->block_id()]);
  }
}

void HEnvironmentLivenessAnalysisPhase::UpdateLivenessAtInstruction(
    HInstruction* instr,
    BitVector* live) {
  switch (instr->opcode()) {
    case HValue::kEnvironmentMarker: {
      HEnvironmentMarker* marker = HEnvironmentMarker::cast(instr);
      int index = marker->index();
      if (!live->Contains(index)) {
        marker->SetFlag(HValue::kEndsLiveRange);
      } else {
        marker->ClearFlag(HValue::kEndsLiveRange);
      }
      if (!went_live_since_last_simulate_.Contains(index)) {
        marker->set_next_simulate(last_simulate_);
      }
      if (marker->kind() == HEnvironmentMarker::LOOKUP) {
        live->Add(index);
      } else {
        DCHECK(marker->kind() == HEnvironmentMarker::BIND);
        live->Remove(index);
        went_live_since_last_simulate_.Add(index);
      }
      if (collect_markers_) {
        // Populate |markers_| list during the first pass.
        markers_.Add(marker, zone());
      }
      break;
    }
    case HValue::kLeaveInlined:
      // No environment values are live at the end of an inlined section.
      live->Clear();
      last_simulate_ = NULL;

      // The following DCHECKs guard the assumption used in case
      // kEnterInlined below:
      DCHECK(instr->next()->IsSimulate());
      DCHECK(instr->next()->next()->IsGoto());

      break;
    case HValue::kEnterInlined: {
      // Those environment values are live that are live at any return
      // target block. Here we make use of the fact that the end of an
      // inline sequence always looks like this: HLeaveInlined, HSimulate,
      // HGoto (to return_target block), with no environment lookups in
      // between (see DCHECKs above).
      HEnterInlined* enter = HEnterInlined::cast(instr);
      live->Clear();
      for (int i = 0; i < enter->return_targets()->length(); ++i) {
        int return_id = enter->return_targets()->at(i)->block_id();
        live->Union(*live_at_block_start_[return_id]);
      }
      last_simulate_ = NULL;
      break;
    }
    case HValue::kSimulate:
      last_simulate_ = HSimulate::cast(instr);
      went_live_since_last_simulate_.Clear();
      break;
    default:
      break;
  }
}

void HEnvironmentLivenessAnalysisPhase::Run() {
  DCHECK(maximum_environment_size_ > 0);

  // Main iteration. Compute liveness of environment slots, and store it
  // for each block until it doesn't change any more. For efficiency, visit
  // blocks in reverse order and walk backwards through each block. We
  // need several iterations to propagate liveness through nested loops.
  BitVector live(maximum_environment_size_, zone());
  BitVector worklist(block_count_, zone());
  for (int i = 0; i < block_count_; ++i) {
    worklist.Add(i);
  }
  while (!worklist.IsEmpty()) {
    for (int block_id = block_count_ - 1; block_id >= 0; --block_id) {
      if (!worklist.Contains(block_id)) {
        continue;
      }
      worklist.Remove(block_id);
      last_simulate_ = NULL;

      HBasicBlock* block = graph()->blocks()->at(block_id);
      UpdateLivenessAtBlockEnd(block, &live);

      for (HInstruction* instr = block->end(); instr != NULL;
           instr = instr->previous()) {
        UpdateLivenessAtInstruction(instr, &live);
      }

      // Reached the start of the block, do necessary bookkeeping:
      // store computed information for this block and add predecessors
      // to the work list as necessary.
      first_simulate_.Set(block_id, last_simulate_);
      first_simulate_invalid_for_index_[block_id]->CopyFrom(
          went_live_since_last_simulate_);
      if (live_at_block_start_[block_id]->UnionIsChanged(live)) {
        for (int i = 0; i < block->predecessors()->length(); ++i) {
          worklist.Add(block->predecessors()->at(i)->block_id());
        }
        if (block->IsInlineReturnTarget()) {
          worklist.Add(block->inlined_entry_block()->block_id());
        }
      }
    }
    // Only collect bind/lookup instructions during the first pass.
    collect_markers_ = false;
  }

  // Analysis finished. Zap dead environment slots.
  for (int i = 0; i < markers_.length(); ++i) {
    ZapEnvironmentSlotsForInstruction(markers_[i]);
  }
  for (int block_id = block_count_ - 1; block_id >= 0; --block_id) {
    HBasicBlock* block = graph()->blocks()->at(block_id);
    UpdateLivenessAtBlockEnd(block, &live);
    ZapEnvironmentSlotsInSuccessors(block, &live);
  }

  // Finally, remove the HEnvironment{Bind,Lookup} markers.
  for (int i = 0; i < markers_.length(); ++i) {
    markers_[i]->DeleteAndReplaceWith(NULL);
  }
}

#ifdef DEBUG
bool HEnvironmentLivenessAnalysisPhase::VerifyClosures(
    Handle<JSFunction> a, Handle<JSFunction> b) {
  Heap::RelocationLock for_heap_access(isolate()->heap());
  AllowHandleDereference for_verification;
  return a.is_identical_to(b);
}
#endif

}  // namespace internal
}  // namespace v8

redpajama_set_name: RedPajamaGithub


text:
Just getting started. Documents to be created include:

* [Manifesto](manifesto.md)
* [Development Principles & Standards](principles.md)


text:
var title = "Mental Block";
var desc = "Create a path to the exit by dropping blocks along the way.";
var offer = "Everything ok? You seem somewhat puzzled. <split butt_txt=\"Do I?\" \/>  Puzzled, confused, perhaps a little stuck?<split butt_txt=\"I feel fine.\" \/>  Well, it's possible I'm seeing into your future. Ah, yes. That's it. My intuition tells me you'll soon be feeling a mental block of sorts. Are you ready?";
var completion = "Well, was I right? Were you confused, puzzled … confuzzled? Doesn't matter. Whatever you felt, it looks like you're over it now. Great job!";

var auto_complete = 0;
var familiar_turnin = 1;
var is_tracked = 0;
var show_alert = 0;
var silent_complete = 0;
var progress = [
];
var giver_progress = [
];
var no_progress = "null";
var prereq_quests = ["radiant_glare"];
var prerequisites = [];
var end_npcs = [];
var locations = {
	"mental_block"	: {
		"dev_tsid"	: "",
		"prod_tsid"	: "LIF3NLRNBBA3HD2"
	}
};

var requirements = {
	"r527"	: {
		"type"		: "flag",
		"name"		: "solved_puzzle",
		"desc"		: "Solved Puzzle"
	},
	"r530"	: {
		"type"		: "flag",
		"name"		: "leave",
		"desc"		: "Complete the Journey"
	}
};

function onComplete(pc){ // generated from rewards
	var xp=0;
	var currants=0;
	var mood=0;
	var energy=0;
	var favor=0;
	var multiplier = pc.buffs_has('gift_of_gab') ? 1.2 : pc.buffs_has('silvertongue') ? 1.05 : 1.0;
	multiplier += pc.imagination_get_quest_modifier();
	currants = pc.stats_add_currants(round_to_5(1500 * multiplier), {type: 'quest_complete', quest: this.class_tsid});
	mood = pc.metabolics_add_mood(round_to_5(200 * multiplier));
	energy = pc.metabolics_add_energy(round_to_5(200 * multiplier));
	favor = pc.stats_add_favor_points("lem", round_to_5(150 * multiplier));
	apiLogAction('QUEST_REWARDS', 'pc='+pc.tsid, 'quest='+this.class_tsid, 'xp='+intval(xp), 'mood='+intval(mood), 'energy='+intval(energy), 'currants='+intval(currants), 'favor='+intval(favor));
	if(pc.buffs_has('gift_of_gab')) {
		pc.buffs_remove('gift_of_gab');
	}
	else if(pc.buffs_has('silvertongue')) {
		pc.buffs_remove('silvertongue');
	}
}
var rewards = {
	"currants"	: 1500,
	"mood"		: 200,
	"energy"	: 200,
	"favor"		: {
		"0"	: {
			"giant"		: "lem",
			"points"	: 150
		}
	}
};

function canOffer(pc){
	if (!pc.imagination_has_upgrade('walk_speed_3')) return false;
	if (!pc.imagination_has_upgrade('jump_2')) return false;

	return true;
}

function onExitLocation(location){
	var pc = this.owner;
	if (!pc) return;

	this.set_flag(pc, 'leave');
	if (!this.is_complete){
		pc.failQuest(this.class_tsid);
	}

	pc.instances_exit('mental_block');
}

function onStarted(pc){
	var location_id = 'mental_block';
	var tsid;
	if (config.is_dev){
		tsid = this.locations[location_id].dev_tsid;
	}
	else{
		tsid = this.locations[location_id].prod_tsid;
	}

	var loc = apiFindObject(tsid);
	var marker = loc.find_items('marker_teleport')[0];

	if (marker){
		this.questInstanceLocation(pc, location_id, marker.x, marker.y, 5*60, {preserve_links: true});
	}
	else{
		this.questInstanceLocation(pc, location_id, 0, 0, 5*60, {preserve_links: true});
	}

	return {ok: 1};
}

// generated ok (NO DATE)


text:
package com.example.tests;

import com.example.framework.ApplicationManager;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;

import java.io.File;
import java.io.FileReader;
import java.util.*;

import static com.example.tests.GroupDataGenerator.generateRandomGroups;
import static com.example.tests.ContactDataGenerator.generateRandomContacts;

public class TestBase {
    protected static ApplicationManager app;
    private int checkCounter;
    private int checkFrequency;

    @BeforeTest
    public void setUp() throws Exception {
        String configFile = System.getProperty("configFile", "chrome.properties");
        Properties properties = new Properties();
        properties.load(new FileReader((new File(configFile))));
        app = new ApplicationManager(properties);
        checkCounter = 0;
        checkFrequency = Integer.parseInt(properties.getProperty("check.frequency"));
    }

    protected boolean wantToCheck(){
        checkCounter ++;
        if(checkCounter > checkFrequency){
            checkCounter = 0;
            return true;
        }else {
            return false;
        }
    }

    @AfterTest
    public void tearDown() throws Exception {
        app.stop();
    }

    @DataProvider
    public Iterator<Object[]> randomValidGroupsGenerator(){
        return wrapGroupsForDataProvider(generateRandomGroups(3)).iterator();
    }

    public static List<Object[]> wrapGroupsForDataProvider(List<GroupData> groups) {
        List<Object[]> list = new ArrayList<Object[]>();
        for (GroupData group : groups){
            list.add(new Object[]{group});
        }
        return list;
    }

    @DataProvider
    public Iterator<Object[]> randomValidContactsGenerator() {
        return wrapContactsForDataProvider(generateRandomContacts(3)).iterator();
    }

    public static List<Object[]> wrapContactsForDataProvider(List<ContactData> contacts) {
        List<Object[]> list = new ArrayList<Object[]>();
        for (ContactData contact : contacts){
            list.add(new Object[]{contact});
        }
        return list;
    }
}


text:
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <string.h>

#include "gstwebvttenc.h"

GST_DEBUG_CATEGORY_STATIC (webvttenc_debug);
#define GST_CAT_DEFAULT webvttenc_debug

enum
{
  PROP_0,
  PROP_TIMESTAMP,
  PROP_DURATION
};

static GstStaticPadTemplate src_template = GST_STATIC_PAD_TEMPLATE ("src",
    GST_PAD_SRC,
    GST_PAD_ALWAYS,
    GST_STATIC_CAPS ("application/x-subtitle-vtt"));

static GstStaticPadTemplate sink_template = GST_STATIC_PAD_TEMPLATE ("sink",
    GST_PAD_SINK,
    GST_PAD_ALWAYS,
    GST_STATIC_CAPS ("text/x-raw, format = { pango-markup, utf8 }"));

static GstFlowReturn gst_webvtt_enc_chain (GstPad * pad, GstObject * parent,
    GstBuffer * buf);
static void gst_webvtt_enc_append_timestamp_to_string (GstClockTime timestamp,
    GString * str);
static void gst_webvtt_enc_get_property (GObject * object, guint prop_id,
    GValue * value, GParamSpec * pspec);
static void gst_webvtt_enc_reset (GstWebvttEnc * webvttenc);
static void gst_webvtt_enc_set_property (GObject * object, guint prop_id,
    const GValue * value, GParamSpec * pspec);

#define parent_class gst_webvtt_enc_parent_class
G_DEFINE_TYPE (GstWebvttEnc, gst_webvtt_enc, GST_TYPE_ELEMENT);

static void
gst_webvtt_enc_append_timestamp_to_string (GstClockTime timestamp,
    GString * str)
{
  guint h, m, s, ms;

  h = timestamp / (3600 * GST_SECOND);

  timestamp -= h * 3600 * GST_SECOND;
  m = timestamp / (60 * GST_SECOND);

  timestamp -= m * 60 * GST_SECOND;
  s = timestamp / GST_SECOND;

  timestamp -= s * GST_SECOND;
  ms = timestamp / GST_MSECOND;

  g_string_append_printf (str, "%02d:%02d:%02d.%03d", h, m, s, ms);
}

static GstFlowReturn
gst_webvtt_enc_chain (GstPad * pad, GstObject * parent, GstBuffer * buf)
{
  GstWebvttEnc *webvttenc = GST_WEBVTT_ENC (parent);
  GstClockTime ts, dur = GST_SECOND;
  GstBuffer *new_buffer;
  GstMapInfo map_info;
  GstFlowReturn ret;
  GString *s;
  gsize buf_size;

  if (!webvttenc->pushed_header) {
    const char *header = "WEBVTT\n\n";

    new_buffer = gst_buffer_new_wrapped (g_strdup (header), strlen (header));

    GST_BUFFER_PTS (new_buffer) = GST_CLOCK_TIME_NONE;
    GST_BUFFER_DURATION (new_buffer) = GST_CLOCK_TIME_NONE;

    ret = gst_pad_push (webvttenc->srcpad, new_buffer);

    if (ret != GST_FLOW_OK)
      goto out;

    webvttenc->pushed_header = TRUE;
  }

  gst_object_sync_values (GST_OBJECT (webvttenc), GST_BUFFER_PTS (buf));

  ts = GST_BUFFER_PTS (buf) + webvttenc->timestamp;
  if (GST_BUFFER_DURATION_IS_VALID (buf))
    dur = GST_BUFFER_DURATION (buf) + webvttenc->duration;
  else if (webvttenc->duration > 0)
    dur = webvttenc->duration;
  else
    dur = GST_SECOND;

  buf_size = gst_buffer_get_size (buf);
  s = g_string_sized_new (50 + buf_size + 1 + 1);

  /* start_time --> end_time */
  gst_webvtt_enc_append_timestamp_to_string (ts, s);
  g_string_append_printf (s, " --> ");
  gst_webvtt_enc_append_timestamp_to_string (ts + dur, s);
  g_string_append_c (s, '\n');

  /* text */
  if (gst_buffer_map (buf, &map_info, GST_MAP_READ)) {
    g_string_append_len (s, (const gchar *) map_info.data, map_info.size);
    gst_buffer_unmap (buf, &map_info);
  }

  g_string_append (s, "\n\n");

  buf_size = s->len;
  new_buffer = gst_buffer_new_wrapped (g_string_free (s, FALSE), buf_size);

  GST_BUFFER_TIMESTAMP (new_buffer) = GST_BUFFER_TIMESTAMP (buf);
  GST_BUFFER_DURATION (new_buffer) = GST_BUFFER_DURATION (buf);

  ret = gst_pad_push (webvttenc->srcpad, new_buffer);

out:

  gst_buffer_unref (buf);

  return ret;
}

static gboolean
gst_webvtt_enc_event (GstPad * pad, GstObject * parent, GstEvent * event)
{
  GstWebvttEnc *webvttenc = GST_WEBVTT_ENC (parent);
  gboolean ret;

  switch (GST_EVENT_TYPE (event)) {
    case GST_EVENT_CAPS:
    {
      GstCaps *caps;

      caps = gst_static_pad_template_get_caps (&src_template);
      gst_pad_set_caps (webvttenc->srcpad, caps);
      gst_caps_unref (caps);
      gst_event_unref (event);
      ret = TRUE;
      break;
    }
    default:
      ret = gst_pad_event_default (pad, parent, event);
      break;
  }

  return ret;
}

static void
gst_webvtt_enc_reset (GstWebvttEnc * webvttenc)
{
  webvttenc->counter = 1;
}

static GstStateChangeReturn
gst_webvtt_enc_change_state (GstElement * element, GstStateChange transition)
{
  GstStateChangeReturn ret;
  GstWebvttEnc *webvttenc = GST_WEBVTT_ENC (element);

  ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
  if (ret == GST_STATE_CHANGE_FAILURE)
    return ret;

  switch (transition) {
    case GST_STATE_CHANGE_PAUSED_TO_READY:
      gst_webvtt_enc_reset (webvttenc);
      break;
    default:
      break;
  }

  return ret;
}

static void
gst_webvtt_enc_get_property (GObject * object,
    guint prop_id, GValue * value, GParamSpec * pspec)
{
  GstWebvttEnc *webvttenc;

  webvttenc = GST_WEBVTT_ENC (object);

  switch (prop_id) {
    case PROP_TIMESTAMP:
      g_value_set_int64 (value, webvttenc->timestamp);
      break;
    case PROP_DURATION:
      g_value_set_int64 (value, webvttenc->duration);
      break;
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
  }
}

static void
gst_webvtt_enc_set_property (GObject * object,
    guint prop_id, const GValue * value, GParamSpec * pspec)
{

  GstWebvttEnc *webvttenc;

  webvttenc = GST_WEBVTT_ENC (object);

  switch (prop_id) {
    case PROP_TIMESTAMP:
      webvttenc->timestamp = g_value_get_int64 (value);
      break;
    case PROP_DURATION:
      webvttenc->duration = g_value_get_int64 (value);
      break;
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
  }
}

static void
gst_webvtt_enc_class_init (GstWebvttEncClass * klass)
{
  GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
  GstElementClass *element_class = GST_ELEMENT_CLASS (klass);

  gobject_class->set_property = GST_DEBUG_FUNCPTR (gst_webvtt_enc_set_property);
  gobject_class->get_property = GST_DEBUG_FUNCPTR (gst_webvtt_enc_get_property);

  element_class->change_state = GST_DEBUG_FUNCPTR (gst_webvtt_enc_change_state);

  g_object_class_install_property (gobject_class, PROP_TIMESTAMP,
      g_param_spec_int64 ("timestamp", "Offset for the starttime",
          "Offset for the starttime for the subtitles", G_MININT64, G_MAXINT64,
          0,
          G_PARAM_READWRITE | GST_PARAM_CONTROLLABLE | G_PARAM_STATIC_STRINGS));
  g_object_class_install_property (gobject_class, PROP_DURATION,
      g_param_spec_int64 ("duration", "Offset for the duration",
          "Offset for the duration of the subtitles", G_MININT64, G_MAXINT64,
          0,
          G_PARAM_READWRITE | GST_PARAM_CONTROLLABLE | G_PARAM_STATIC_STRINGS));

  gst_element_class_add_static_pad_template (element_class, &sink_template);
  gst_element_class_add_static_pad_template (element_class, &src_template);

  gst_element_class_set_static_metadata (element_class,
      "WebVTT encoder", "Codec/Encoder/Subtitle",
      "WebVTT subtitle encoder", "David Schleef <ds@schleef.org>");

  GST_DEBUG_CATEGORY_INIT (webvttenc_debug, "webvttenc", 0,
      "SubRip subtitle encoder");
}

static void
gst_webvtt_enc_init (GstWebvttEnc * webvttenc)
{
  gst_webvtt_enc_reset (webvttenc);

  webvttenc->srcpad = gst_pad_new_from_static_template (&src_template, "src");
  gst_element_add_pad (GST_ELEMENT (webvttenc), webvttenc->srcpad);
  webvttenc->sinkpad =
      gst_pad_new_from_static_template (&sink_template, "sink");
  gst_pad_set_chain_function (webvttenc->sinkpad,
      GST_DEBUG_FUNCPTR (gst_webvtt_enc_chain));
  gst_pad_set_event_function (webvttenc->sinkpad,
      GST_DEBUG_FUNCPTR (gst_webvtt_enc_event));
  gst_element_add_pad (GST_ELEMENT (webvttenc), webvttenc->sinkpad);
}


text:
//
//  PPTabBar.m
//  PPZone
//
//  Created by jiaguanglei on 15/11/13.
//  Copyright © 2015年 roseonly. All rights reserved.
//

#import "PPTabBar.h"
#import "MyButton.h"

@interface PPTabBar ()
@property (nonatomic, weak) MyButton *plusBtn;
@end

@implementation PPTabBar

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
         /**  添加加号按钮 ***/
        MyButton *plusBtn = [MyButton buttonWithFrame:CGRectZero type:UIButtonTypeCustom title:nil titleColor:nil image:[UIImage imageNamed:@"tabbar_compose_icon_add"] selectedImage:[UIImage imageNamed:@"tabbar_compose_icon_add_highlighted"] backgroundImage:[UIImage imageNamed:@"tabbar_compose_button"] andBlock:^(MyButton *button) {
        }];

        plusBtn.size = plusBtn.currentBackgroundImage.size;
        [plusBtn addTarget:self action:@selector(plusBtnDidClicked) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:plusBtn];
        self.plusBtn = plusBtn;
    }
    return self;
}

/**
 *  监听加号按钮点击
 */
- (void)plusBtnDidClicked
{
    if ([self.delegate respondsToSelector:@selector(tabBarDidClickedPlusButton:)]) {
        [self.delegate tabBarDidClickedPlusButton:self];
    }
}

- (void)layoutSubviews
{
    [super layoutSubviews];

    // 1. 设置加号按钮的位置
    self.plusBtn.centerX = self.width * 0.5;
    self.plusBtn.centerY = self.height * 0.5;

    // 2. 设置其他tabBarBtn的位置尺寸
    CGFloat tabBarButtonW = self.width / 5;
    CGFloat tabBarButtonIndex = 0;

    for (UIView *child in self.subviews) {
        if ([child isKindOfClass:NSClassFromString(@"UITabBarButton")]) {
            // 设置宽度
            child.width = tabBarButtonW;
            // 设置x
            child.x = tabBarButtonW * tabBarButtonIndex;
            // 增加索引
            tabBarButtonIndex++;
            if (tabBarButtonIndex == 2) {
                tabBarButtonIndex++;
            }
        }
    }
}

@end


text:
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Climbing competition</title>
  <base href="">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-root>Loading...</app-root>
</body>
</html>


text:
var Promise = require('bluebird');
var Task = require('../models/task');

module.exports = (function() {

  var index, show, post, put, destroy;

  index = function (req, res) {
    Task.findAll({where: req.query}).then(function(tasks) {
      res.status(200);
      res.send(tasks);
    });
  };

  show = function (req, res) {
    Task.findById(req.params.id).then(function(task) {
      res.status(200);
      res.send(task);
    });
  };

  put = function (req, res) {
    Task.findById(req.params.id).then(function(task) {
      task.name = req.body.name;
      task.category = req.body.category;
      task.image = req.body.image;
      task.save().then(function() {
        res.status(200);
        res.send(task);
      });
    });
  };

  post = function (req, res) {
    task = Task.create({
      name: req.body.name,
      categoryId: req.body.categoryId,
      image: req.body.image
    }).then(function(task) {
      res.status(200);
      res.send(task);
    });
  };

  destroy = function (req, res) {
    var id = req.params.id;
    Task.findById(id).then(function(task) {
      return task.destroy();
    }).then( function (task) {
      res.status(200);
      res.send(task);
    });
  };

  return {
    index: index,
    show: show,
    put: put,
    post: post,
    destroy: destroy
  };

}());


text:
(function($, cornerstone, cornerstoneMath, cornerstoneTools) {

    'use strict';

    function anyHandlesOutsideImage(renderData, handles) {
        var image = renderData.image;
        var imageRect = {
            left: 0,
            top: 0,
            width: image.width,
            height: image.height
        };

        var handleOutsideImage = false;

        Object.keys(handles).forEach(function(name) {
            var handle = handles[name];
            if (handle.allowedOutsideImage === true) {
                return;
            }

            if (cornerstoneMath.point.insideRect(handle, imageRect) === false) {
                handleOutsideImage = true;
            }
        });

        return handleOutsideImage;
    }

    // module/private exports
    cornerstoneTools.anyHandlesOutsideImage = anyHandlesOutsideImage;

})($, cornerstone, cornerstoneMath, cornerstoneTools);


text:
//
//  PoshReVo-Bridging-Header.h
//  PoshReVo
//
//  Created by Robin Hill on 3/22/16.
//  Copyright © 2016 Robin Hill. All rights reserved.
//

#ifndef PoshReVo_Bridging_Header_h
#define PoshReVo_Bridging_Header_h

#import "ObjCPonto.h"

#endif /* PoshReVo_Bridging_Header_h */


text:
from .instance_profile import InstanceProfile
from .role import Role
from .server_certificate import ServerCertificate

__all__ = [
    'InstanceProfile',
    'Role',
    'ServerCertificate',
]


text:
package com.yuloran.demo.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.yuloran.demo.R;
import com.yuloran.demo.ui.curveview.CurveViewActivity;
import com.yuloran.demo.ui.rxjava2.RxJava2Activity;

/**
 * Author & Date: Yuloran, 2018/7/22 8:14
 * Function:
 */
public class LauncherActivity extends Activity {

    private RecyclerView mRvFunctionWizard;

    private String[] mFunctions;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_launcher);

        mFunctions = getResources().getStringArray(R.array.functions);

        initView();
    }

    private void initView() {
        mRvFunctionWizard = (RecyclerView) findViewById(R.id.rv_function_wizard);
        mRvFunctionWizard.setLayoutManager(new LinearLayoutManager(mRvFunctionWizard.getContext()));
        mRvFunctionWizard.addItemDecoration(new DividerItemDecoration(mRvFunctionWizard
                .getContext(), LinearLayoutManager.VERTICAL));
        mRvFunctionWizard.setAdapter(new RecyclerView.Adapter() {
            @Override
            public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                View itemView = LayoutInflater.from(parent.getContext())
                                              .inflate(android.R.layout.simple_list_item_1, parent, false);
                return new FunctionWizardViewHolder(itemView);
            }

            @Override
            public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
                if (holder instanceof FunctionWizardViewHolder) {
                    ((FunctionWizardViewHolder) holder).tv.setText(mFunctions[position]);
                    holder.itemView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            int position = holder.getAdapterPosition();
                            switch (position) {
                                case 0:
                                    startActivity(new Intent(LauncherActivity.this, RxJava2Activity.class));
                                    break;
                                case 1:
                                    startActivity(new Intent(LauncherActivity.this, CurveViewActivity.class));
                                    break;
                                default:
                            }
                        }
                    });
                }
            }

            @Override
            public int getItemCount() {
                return mFunctions.length;
            }

            class FunctionWizardViewHolder extends RecyclerView.ViewHolder {

                private TextView tv;

                FunctionWizardViewHolder(View itemView) {
                    super(itemView);
                    tv = (TextView) itemView.findViewById(android.R.id.text1);
                }
            }

        });
    }
}


text:
export async function generateRandomNumber() {
  // simulate an asynchronous operation
  return new Promise((res) => setTimeout(res, 1000))
    .then(() => Math.floor(Math.random() * 100));
}


text:
package com.glacier.modules.sys.dao;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class UserRepositoryTest {

	@Autowired
	private UserRepository userRepository;

	@Test
	public void testSaveS() {
		userRepository.test();
	}

}


text:
package org.apache.samoa.evaluation;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.Collections;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.TimeUnit;

import org.apache.samoa.core.ContentEvent;
import org.apache.samoa.core.Processor;
import org.apache.samoa.learners.ResultContentEvent;
import org.apache.samoa.moa.core.Measurement;
import org.apache.samoa.moa.core.Vote;
import org.apache.samoa.moa.evaluation.LearningCurve;
import org.apache.samoa.moa.evaluation.LearningEvaluation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class EvaluatorProcessor implements Processor {

  /**
   *
   */
  private static final long serialVersionUID = -2778051819116753612L;

  private static final Logger logger = LoggerFactory.getLogger(EvaluatorProcessor.class);

  private static final String ORDERING_MEASUREMENT_NAME = "evaluation instances";

  private final PerformanceEvaluator evaluator;
  private final int samplingFrequency;
  private final File dumpFile;
  private final File predictionFile;
  private final int labelSamplingFrequency;
  private transient PrintStream immediateResultStream = null;
  private transient PrintStream immediatePredictionStream = null;
  private transient boolean firstDump = true;
  private transient boolean firstVoteDump = true;

  private long totalCount = 0;
  private long experimentStart = 0;

  private long sampleStart = 0;

  private LearningCurve learningCurve;
  private int id;

  private EvaluatorProcessor(Builder builder) {
    this.evaluator = builder.evaluator;
    this.samplingFrequency = builder.samplingFrequency;
    this.dumpFile = builder.dumpFile;
    this.predictionFile = builder.predictionFile;
    this.labelSamplingFrequency = builder.labelSamplingFrequency;
  }

  @Override
  public boolean process(ContentEvent event) {

    ResultContentEvent result = (ResultContentEvent) event;

    if ((totalCount > 0) && (totalCount % samplingFrequency) == 0) {
      long sampleEnd = System.nanoTime();
      long sampleDuration = TimeUnit.SECONDS.convert(sampleEnd - sampleStart, TimeUnit.NANOSECONDS);
      sampleStart = sampleEnd;

      logger.info("{} seconds for {} instances", sampleDuration, samplingFrequency);
      this.addMeasurement();
    }

    //adding a vote - true class value, predicted class value and for classification - votes
    if ((immediatePredictionStream != null) && (totalCount > 0) && (totalCount % labelSamplingFrequency) == 0) {
      this.addVote();
    }

    if (result.isLastEvent()) {
      this.concludeMeasurement();
      return true;
    }

    String instanceIndex = String.valueOf(result.getInstanceIndex());
    evaluator.addResult(result.getInstance(), result.getClassVotes(), instanceIndex,
            System.currentTimeMillis() - result.getArrivalTimestamp());
    totalCount += 1;

    if (totalCount == 1) {
      sampleStart = System.nanoTime();
      experimentStart = sampleStart;
    }

    return false;
  }

  @Override
  public void onCreate(int id) {
    this.id = id;
    this.learningCurve = new LearningCurve(ORDERING_MEASUREMENT_NAME);

    if (this.dumpFile != null) {
      try {
        if (dumpFile.exists()) {
          this.immediateResultStream = new PrintStream(
              new FileOutputStream(dumpFile, true), true);
        } else {
          this.immediateResultStream = new PrintStream(
              new FileOutputStream(dumpFile), true);
        }

      } catch (FileNotFoundException e) {
        this.immediateResultStream = null;
        logger.error("File not found exception for {}:{}", this.dumpFile.getAbsolutePath(), e.toString());

      } catch (Exception e) {
        this.immediateResultStream = null;
        logger.error("Exception when creating {}:{}", this.dumpFile.getAbsolutePath(), e.toString());
      }
    }

    if (this.predictionFile != null) {
      try {
        this.immediatePredictionStream = new PrintStream(new FileOutputStream(predictionFile), true);
      } catch (FileNotFoundException e) {
        this.immediatePredictionStream = null;
        logger.error("File not found exception for {}:{}", this.predictionFile.getAbsolutePath(), e.toString());
      } catch (Exception e) {
        this.immediatePredictionStream = null;
        logger.error("Exception when creating {}:{}", this.predictionFile.getAbsolutePath(), e.toString());
      }
    }

    this.firstDump = true;
    this.firstVoteDump = true;
  }

  @Override
  public Processor newProcessor(Processor p) {
    EvaluatorProcessor originalProcessor = (EvaluatorProcessor) p;
    EvaluatorProcessor newProcessor = new EvaluatorProcessor.Builder(originalProcessor).build();

    if (originalProcessor.learningCurve != null) {
      newProcessor.learningCurve = originalProcessor.learningCurve;
    }

    return newProcessor;
  }

  @Override
  public String toString() {
    StringBuilder report = new StringBuilder();

    report.append(EvaluatorProcessor.class.getCanonicalName());
    report.append("id = ").append(this.id);
    report.append('\n');

    if (learningCurve.numEntries() > 0) {
      report.append(learningCurve.toString());
      report.append('\n');
    }
    return report.toString();
  }

  private void addMeasurement() {
    List<Measurement> measurements = new Vector<>();
    measurements.add(new Measurement(ORDERING_MEASUREMENT_NAME, totalCount));

    Collections.addAll(measurements, evaluator.getPerformanceMeasurements());

    Measurement[] finalMeasurements = measurements.toArray(new Measurement[measurements.size()]);

    LearningEvaluation learningEvaluation = new LearningEvaluation(finalMeasurements);
    learningCurve.insertEntry(learningEvaluation);
    logger.debug("evaluator id = {}", this.id);
    logger.info(learningEvaluation.toString());

    if (immediateResultStream != null) {
      if (firstDump) {
        immediateResultStream.println(learningCurve.headerToString());
        firstDump = false;
      }

      immediateResultStream.println(learningCurve.entryToString(learningCurve.numEntries() - 1));
      immediateResultStream.flush();
    }
  }

  /**
   * This method is used to create one line of a text file containing predictions and votes (for classification only).
   * In case, this is the first line a header line is also added
   */
  private void addVote() {
    Vote[] finalVotes = evaluator.getPredictionVotes();
    learningCurve.setVote(finalVotes);
    logger.debug("evaluator id = {}", this.id);

    if (immediatePredictionStream != null) {
      if (firstVoteDump) {
        immediatePredictionStream.println(learningCurve.voteHeaderToString());
        firstVoteDump = false;
      }

      immediatePredictionStream.println(learningCurve.voteEntryToString());
      immediatePredictionStream.flush();
    }
  }

  private void concludeMeasurement() {
    logger.info("last event is received!");
    logger.info("total count: {}", this.totalCount);

    String learningCurveSummary = this.toString();
    logger.info(learningCurveSummary);

    long experimentEnd = System.nanoTime();
    long totalExperimentTime = TimeUnit.SECONDS.convert(experimentEnd - experimentStart, TimeUnit.NANOSECONDS);
    logger.info("total evaluation time: {} seconds for {} instances", totalExperimentTime, totalCount);

    if (immediateResultStream != null) {
      immediateResultStream.println("# COMPLETED");
      //
      immediateResultStream
          .println("# Total evaluation time: " + totalExperimentTime + " seconds for " + totalCount + " instances");
      immediateResultStream.flush();
    }
    // logger.info("average throughput rate: {} instances/seconds",
    // (totalCount/totalExperimentTime));
  }

  public static class Builder {

    private final PerformanceEvaluator evaluator;
    private int samplingFrequency = 100000;
    private File dumpFile = null;
    private File predictionFile = null;
    private int labelSamplingFrequency = 1;

    public Builder(PerformanceEvaluator evaluator) {
      this.evaluator = evaluator;
    }

    public Builder(EvaluatorProcessor oldProcessor) {
      this.evaluator = oldProcessor.evaluator;
      this.samplingFrequency = oldProcessor.samplingFrequency;
      this.dumpFile = oldProcessor.dumpFile;
      this.predictionFile = oldProcessor.predictionFile;
      this.labelSamplingFrequency = oldProcessor.labelSamplingFrequency;
    }

    public Builder samplingFrequency(int samplingFrequency) {
      this.samplingFrequency = samplingFrequency;
      return this;
    }

    public Builder dumpFile(File file) {
      this.dumpFile = file;
      return this;
    }

    public Builder predictionFile(File file) {
      this.predictionFile = file;
      return this;
    }

    public Builder labelSamplingFrequency(int samplingFrequency) {
      this.labelSamplingFrequency = samplingFrequency;
      return this;
    }

    public EvaluatorProcessor build() {
      return new EvaluatorProcessor(this);
    }
  }
}


text:
namespace OpenCube.IO.FileSystem
{
	/// <summary>
	/// Creates the correct FileSystem based on the input
	/// </summary>
	public interface IFileSystemFactory
	{
		/// <summary>
		/// Try to create a <see cref="IFileSystem"/> form the file.
		/// </summary>
		/// <param name="file">The file to create a <see cref="IFileSystem"/> from.</param>
		/// <returns>The IFileSystem if a provider that understands the file could be found, oherwise <c>null</c>.</returns>
		IFileSystem FromFile(IFile file);
	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GenericStl
{
    public interface IDataStructureCreator<TTriangle, TVertex, TNormal>
    {
        TTriangle CreateTriangle(TVertex v1, TVertex v2, TVertex v3, TNormal n);
        TNormal CreateNormal(float x, float y, float z);
        TVertex CreateVertex(float x, float y, float z);
    }
}


text:
import { renderToString } from 'react-dom/server'
import { Provider } from 'react-redux'
import { App } from '../../components'
import { Router } from 'express'
import initialState from '../../data/client'
import storeFactory from '../../store'
import { match, RouterContext } from 'react-router'
import routes from '../../routes'

const clientStore = storeFactory(true, false, initialState)

const router = Router()

const createPage = (html, state) => `<!DOCTYPE html>

  <meta name="viewport" content="minimum-scale=1.0, width=device-width, maximum-scale=1.0, user-scalable=no" />
  <meta charset="utf-8">
  <link rel="icon" type="image/ico" href="/favicon.ico">
  <title>Cyber Chat</title>

${html}

`

router.get('*', (req, res) => {
    match({routes, location: req.url}, (error, redirectLocation, renderProps) => {
        if (error) {
            res.status(500).send(error.message)
        } else if (redirectLocation) {
            res.redirect(302, redirectLocation.pathname + redirectLocation.search)
        } else if (renderProps) {
            let html = renderToString(
                <Provider store={clientStore}>
                    <RouterContext {...renderProps} />
                </Provider>
            )
            res.status(200).send(createPage(html, clientStore.getState()))
        } else {
            res.status(404).send('Not found')
        }
    })
})

module.exports = router


text:
package fundamental.games.metropolis.cards.decks.base.violet;

import fundamental.games.metropolis.R;
import fundamental.games.metropolis.cards.CardTemplate;
import fundamental.games.metropolis.cards.decks.BaseDeck;
import fundamental.games.metropolis.global.Range;

/**
 * Created by Adam on 2015-05-03.
 */
public class TelevisionChannel extends CardTemplate {

    public TelevisionChannel() {
        super(
                BaseDeck.TELEVISION_CHANNEL,
                Color.Violet,
                Type.Monument,
                "Television channel",
                "If this is your turn, take 5 coins from any one player.",
                7,
                new Range(6),
                R.drawable.television_channel_icon,
                R.drawable.television_channel,
                R.drawable.monument_violet
        );
    }
}


text:
export * from './browse.service';
export * from './browse.component';


text:
//
//  ViewAnimationViewController.m
//  PAFinal
//
//  Created by STANLEY CALIXTE on 5/26/14.
//  Copyright (c) 2014 STANLEY CALIXTE. All rights reserved.
//

#import "ViewAnimationViewController.h"

@interface ViewAnimationViewController ()

@end

@implementation ViewAnimationViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    CGRect frame = self.viewBox.frame;

    UITouch* touch = [touches anyObject];
    CGPoint point = [touch locationInView:self.view];

    frame.origin = point;

    [UIView animateWithDuration:1.0 animations:^{
        self.viewBox.frame = frame;

        if (self.viewBox.backgroundColor == [UIColor redColor]){
            self.viewBox.backgroundColor = [UIColor greenColor];
        }
        else if (self.viewBox.backgroundColor == [UIColor greenColor]){
            self.viewBox.backgroundColor = [UIColor blueColor];
        }
        else if (self.viewBox.backgroundColor == [UIColor blueColor]){
            self.viewBox.backgroundColor = [UIColor redColor];
        }
    }];
}

- (void) awakeFromNib
{
    [super awakeFromNib];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.title = @"View Animations";
    self.viewBox.backgroundColor = [UIColor redColor];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
 */

@end


text:
constexpr int fun_constexpr();
int fun_not_constexpr();

constexpr int overloaded_fun(int i) {
    return 5;
}

int overloaded_fun(float f) {
    return 6;
}

template <typename T>
constexpr int template_fun(T t) {
    return overloaded_fun(t);
}

void caller(void) {
    int i;
    float f;
    template_fun(i);
    template_fun(f);
}


text:
class MockLogger
  def log(*_) ; end
  def say(*_) ; end
  def say_status(*_); end
  def say_json(*_) ; end
end


text:
from mule_local.JobMule import *
from mule.exec_program import *

#
# REXI specific
#
from mule_local.rexi.REXICoefficients import *
from mule_local.rexi.trexi.TREXI import *
from mule_local.rexi.cirexi.CIREXI import *
from mule_local.rexi.brexi.BREXI import *

from itertools import product

jg = JobGeneration()

jg.compile.program = 'rexi_approximation'
jg.unique_id_filter = ['compile', 'parallelization']
jg.unique_id_filter +=  ['simparams', 'benchmark', 'timestep_order', 'timestep_size', 'disc_space', 'compile']

rexi_file_methods = ["trexi", "cirexi", "brexi"]

num_timesteps = 1
jg.runtime.timestep_size = 1.0

jg.runtime.user_defined_parameters['function_name'] = {
        'id': 'fun',
        'value' : 'phi0',
        'option' : '--function-name=',
    }

jg.runtime.user_defined_parameters['test_mode'] = {
        'id': 'tm',
        'value' : 0,
        'option' : '--test-mode=',
    }

lambda_params = numpy.array([numpy.power(2, float(n))*1.0j for n in range(-6, 8)])

#function_name_list = ["phi0", "phi1", "phi2", "phi3", "phi4", "ups1", "ups2", "ups3", "psi1", "psi2", "psi3"]
function_name_list = ["phi0"] #, "phi1", "phi2", "phi3", "phi4", "ups1", "ups2", "ups3"]

efloat_mode = "float"
#efloat_mode = "mpfloat"

for function_name in function_name_list:

    for lambda_val in lambda_params:

        jg.runtime.max_simulation_time = jg.runtime.timestep_size*num_timesteps

        jg.runtime.user_defined_parameters['lambda_real'] = {
                'id': 'lamre',
                'value' : lambda_val.real,
                'option' : '--lambda-real=',
            }

        jg.runtime.user_defined_parameters['lambda_imag'] = {
                'id': 'lamim',
                'value' : lambda_val.imag,
                'option' : '--lambda-imag=',
            }

        for rexi_file_method in rexi_file_methods:

            if rexi_file_method == "trexi":

                if function_name != "phi0":
                    continue

                trexi = TREXI(efloat_mode = efloat_mode)

                M_list = [64, 128, 256]
                h_list = [0.1, 0.2, 0.5, 1.0, 1.5, 2.0]

                for (M, h) in product(M_list, h_list):
                    coeffs = trexi.setup(M=M, h=h).toFloat()
                    jg.runtime.rexi_files_coefficients = [coeffs]
                    jg.gen_jobscript_directory()

                    if True:
                        # Validate with C-implementation of T-REXI method
                        jg.runtime.rexi_method = "terry"
                        jg.runtime.rexi_terry_m = M
                        jg.runtime.rexi_terry_h = h
                        jg.gen_jobscript_directory()

                        # Back to original version
                        jg.runtime.rexi_method = "file"

            elif rexi_file_method == "cirexi":

                cirexi = CIREXI(efloat_mode = efloat_mode)

                # CI-REXI: Number of quadrature poles
                N_list = [256, 512, 1024, 2048]

                # CI-REXI: Value on imaginary axis to be included
                lambda_include_imag_list = [15, 20, 40, 80]

                # CI-REXI: Maximum value of quadrature pole
                lambda_max_real_list = [1, 2, 4, 8, 16]

                for (N, lambda_include_imag, lambda_max_real) in product(N_list, lambda_include_imag_list, lambda_max_real_list):
                    coeffs = cirexi.setup(function_name=function_name, N=N, lambda_include_imag=lambda_include_imag, lambda_max_real=lambda_max_real).toFloat()
                    jg.runtime.rexi_files_coefficients = [coeffs]
                    jg.gen_jobscript_directory()

                    if True:
                        # Validate with C-implementation of CI-REXI method
                        jg.runtime.rexi_method = "ci"
                        jg.runtime.rexi_ci_n = N
                        jg.runtime.rexi_ci_max_real = lambda_max_real
                        jg.runtime.rexi_ci_max_imag = lambda_include_imag
                        jg.gen_jobscript_directory()

                        # Back to original version
                        jg.runtime.rexi_method = "file"

            elif rexi_file_method == "brexi":

                if function_name != "phi0":
                    continue

                brexi = BREXI(efloat_mode = efloat_mode)

                # CI-REXI: Number of quadrature poles
                N_list = [8, 10, 12, 14, 16]
                #N_list = [8, 10]

                quadrature_method_list = ["gauss", "radau", "chebyshev"]

                for (N, quadrature_method) in product(N_list, quadrature_method_list):
                    coeffs = brexi.setup(N=N, quadrature_method=quadrature_method).toFloat()
                    jg.runtime.rexi_files_coefficients = [coeffs]
                    jg.gen_jobscript_directory()

            else:
                raise Exception("Unknown method "+rexi_file_methods)

#exitcode = exec_program('mule.benchmark.jobs_run_directly', catch_output=False)
#if exitcode != 0:
#    sys.exit(exitcode)
#print("Benchmarks successfully finished")
#exec_program('mule.benchmark.cleanup_all', catch_output=False)


text:
FROM nginx

ADD etc/nginx/conf.d/ssl.conf /etc/nginx/conf.d/ssl.conf

RUN apt-get update && \
	apt-get install -y tcpdump

EXPOSE 443

VOLUME [ "/var/log/nginx" ]


text:
package org.switchyard.common.camel;

import java.io.InputStream;

import javax.xml.bind.Binder;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.camel.builder.xml.Namespaces;
import org.apache.camel.model.Constants;
import org.apache.camel.spi.NamespaceAware;
import org.apache.camel.spring.CamelContextFactoryBean;
import org.apache.camel.spring.SpringModelJAXBContextFactory;
import org.switchyard.SwitchYardException;
import org.switchyard.common.type.Classes;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

/**
 * Utility class to handle camel JAXB model objects.
 */
public final class CamelModelFactory {

    private static final String NS_SPRING = "http://www.springframework.org/schema/beans";
    private static final String NS_CAMEL_SPRING = "http://camel.apache.org/schema/spring";

    /**
     * JAXB context for reading XML definitions.
     */
    private static JAXBContext JAXB_CONTEXT;

    static {
        try {
            JAXB_CONTEXT = JAXBContext.newInstance(
                    Constants.JAXB_CONTEXT_PACKAGES + SpringModelJAXBContextFactory.ADDITIONAL_JAXB_CONTEXT_PACKAGES,
                    SpringModelJAXBContextFactory.class.getClassLoader());
        } catch (JAXBException e) {
            throw new SwitchYardException(e);
        }
    }

    /**
     * Utility class - so no need to directly instantiate.
     */
    private CamelModelFactory() {

    }

    /**
     * Creates camel model object like CamelContextFactoryBean, RouteDefinition or RoutesDefinition
     * from XML file.
     *
     * @param xmlPath path to the file
     * @return created camel model object
     * @throws Exception failed to unmarshall camel model object from XML file
     */
    public static Object createCamelModelObjectFromXML(String xmlPath) throws Exception {
        InputStream input = Classes.getResourceAsStream(xmlPath);
        if (input == null) {
            throw CommonCamelMessages.MESSAGES.specifiedCamelContextFileIsNotFound(xmlPath);
        }

        InputSource source =  new InputSource(input);
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(source);
        Element element = document.getDocumentElement();
        Element camelModelElement = findCamelModelElement(element, xmlPath);
        if (camelModelElement == null) {
            throw CommonCamelMessages.MESSAGES.noCamelContextElementFound(xmlPath);
        }

        Binder<Node> binder = JAXB_CONTEXT.createBinder();
        Object obj = binder.unmarshal(camelModelElement);
        injectNamespaces(camelModelElement, binder);
        return obj;
    }

    private static Element findCamelModelElement(Element top, String xmlPath) {
        if (top.getNamespaceURI().equals(NS_SPRING) && top.getNodeName().equals("beans")) {
            Element camelContext = null;
            NodeList list = top.getChildNodes();
            for (int i=0; i<list.getLength(); i++) {
                Node node = list.item(i);
                if (node.getNodeType() != Node.ELEMENT_NODE) {
                    continue;
                }

                Element element = (Element)node;
                if (element.getNamespaceURI().equals(NS_CAMEL_SPRING)
                        && element.getNodeName().equals("camelContext")) {
                    if (camelContext == null) {
                        camelContext = element;
                    } else {
                        CommonCamelLogger.ROOT_LOGGER.ignoringMultipleCamelContextElement(xmlPath);
                    }
                } else {
                    CommonCamelLogger.ROOT_LOGGER.ignoringUnsupportedElement(xmlPath, new QName(element.getNamespaceURI(), element.getNodeName()));
                }
            }
            return camelContext != null ? camelContext : null;
        }
        // Assuming anything other than spring <beans> is a camel model object
        return top;
    }

    private static void injectNamespaces(Element element, Binder<Node> binder) {
        NodeList list = element.getChildNodes();
        Namespaces namespaces = null;
        int size = list.getLength();
        for (int i = 0; i < size; i++) {
            Node child = list.item(i);
            if (child instanceof Element) {
                Element childElement = (Element) child;
                Object object = binder.getJAXBNode(child);
                if (object instanceof NamespaceAware) {
                    NamespaceAware namespaceAware = (NamespaceAware) object;
                    if (namespaces == null) {
                        namespaces = new Namespaces(element);
                    }
                    namespaces.configure(namespaceAware);
                }
                injectNamespaces(childElement, binder);
            }
        }
    }

    /**
     * Imports CamelContext configuration  into existing SwitchYardCamelContext instance
     * from CamelContextFactoryBean JAXB object.
     *
     * @param context SwitchYardCamelContext
     * @param bean CamelContextFactoryBean JAXB object
     * @throws Exception failed to import configurations
     */
    public static void importCamelContextFactoryBean(SwitchYardCamelContext context, CamelContextFactoryBean bean) throws Exception {
        new CamelContextFactoryBeanDelegate(context, bean).importConfiguration();
    }

}


text:
<meta charset="UTF-8">
<title>COLORS.WHITE_ISH_GOLD - core</title>
<link rel="stylesheet" href="..\..\..\style.css">

core / com.erikcupal.theblackcatclient / COLORS / WHITE_ISH_GOLD

WHITE_ISH_GOLD

val WHITE_ISH_GOLD: Color


text:
'use strict'

const
  fsp = require('fs-promise'),
  co = require('co'),
  url = require('url'),
  path = require('path'),
  log = require('loglevel'),
  minimatch = require('minimatch'),
  mkdirs = require('./mkdirs')

/**
 * serves a cache file
 */
function serve(res, file, maxAge) {
  log.debug(`Serving: ${ file }`)
  res.status(200)
    .set('Cache-Control', `max-age=${ maxAge }`)
    .sendFile(file, err => {
      if (err) {
        log.error(err)
        res.status(err.status).end()
        return
      }
    })
}

/**
 * finds a handler matched with pathname
 */
function find(pathname, patterns) {
  for (const entry of patterns)
    if (minimatch(pathname, entry.pattern))
      return entry.handler
  return null
}

module.exports = function(opts) {
  return co.wrap(function* (req, res, next) {
    const
      pathname = url.parse(req.url).pathname.slice(1),
      src = path.join(opts.root, opts.src, pathname),
      cache = path.join(opts.root, opts.cache, pathname)

    log.debug(`Request: ${ pathname }`)

    if (req.method != 'GET' && req.method != 'HEAD') return next()

    for (const pattern of opts.excludes)
      if (minimatch(pathname, pattern))
        return

    for (const ref in opts.external)
      if (ref == pathname) {
        serve(res, cache, opts.maxAge)
        return
      }

    if (/\.map$/.test(pathname)) {
      try {
        yield fsp.access(cache, fsp.F_OK)
        serve(res, cache, opts.maxAge)
        return
      } catch (err) {
        return next()
      }
    }

    const handler = find(pathname, opts.patterns)
    if (!handler) return next()

    try {
      yield fsp.access(src, fsp.F_OK)
      log.debug(`Source found: ${ src }`)
    } catch (err) {
      return next()
    }

    if (opts.update == 'always') {
      yield mkdirs(path.dirname(cache))
      log.debug(`Compiling: ${ pathname }`)
      yield handler(src, cache)
    } else {
      try {
        yield fsp.access(cache, fsp.F_OK)
        log.debug(`Cache found: ${ cache }`)
      } catch (err) {
        if (opts.update == 'never') {
          log.error('No compiled file found')
          return
        }
        yield mkdirs(path.dirname(cache))
        log.debug(`Compiling: ${ pathname }`)
        yield handler(src, cache)
      }
    }

    serve(res, cache, opts.maxAge)
  })
}


text:
package org.diorite.material.blocks.plants;

import java.util.Map;

import org.diorite.cfg.magic.MagicNumbers;
import org.diorite.utils.collections.maps.CaseInsensitiveMap;

import gnu.trove.map.TByteObjectMap;
import gnu.trove.map.hash.TByteObjectHashMap;

/**
 * Class representing block "TallGrass" and all its subtypes.
 */
public class TallGrassMat extends FlowerMat
{
    /**
     * Sub-ids used by diorite/minecraft by default
     */
    public static final byte  USED_DATA_VALUES = 3;
    /**
     * Blast resistance of block, can be changed only before server start.
     * Final copy of blast resistance from {@link MagicNumbers} class.
     */
    public static final float BLAST_RESISTANCE = MagicNumbers.MATERIAL__TALL_GRASS__BLAST_RESISTANCE;
    /**
     * Hardness of block, can be changed only before server start.
     * Final copy of hardness from {@link MagicNumbers} class.
     */
    public static final float HARDNESS         = MagicNumbers.MATERIAL__TALL_GRASS__HARDNESS;

    public static final TallGrassMat TALL_GRASS_SHRUB = new TallGrassMat();
    public static final TallGrassMat TALL_GRASS_GRASS = new TallGrassMat(0x1, FlowerTypeMat.GRASS);
    public static final TallGrassMat TALL_GRASS_FERN  = new TallGrassMat(0x2, FlowerTypeMat.FERN);

    private static final Map<String, TallGrassMat>    byName = new CaseInsensitiveMap<>(USED_DATA_VALUES, SMALL_LOAD_FACTOR);
    private static final TByteObjectMap<TallGrassMat> byID   = new TByteObjectHashMap<>(USED_DATA_VALUES, SMALL_LOAD_FACTOR);

    @SuppressWarnings("MagicNumber")
    protected TallGrassMat()
    {
        super("TALL_GRASS", 31, "minecraft:tallgrass", (byte) 0x00, FlowerTypeMat.SHRUB);
    }

    protected TallGrassMat(final int type, final FlowerTypeMat flowerType)
    {
        super(TALL_GRASS_SHRUB.name(), TALL_GRASS_SHRUB.ordinal(), TALL_GRASS_SHRUB.getMinecraftId(), (byte) type, flowerType);
    }

    protected TallGrassMat(final String enumName, final int id, final String minecraftId, final int maxStack, final String typeName, final byte type, final FlowerTypeMat flowerType)
    {
        super(enumName, id, minecraftId, maxStack, typeName, type, flowerType);
    }

    @Override
    public float getBlastResistance()
    {
        return BLAST_RESISTANCE;
    }

    @Override
    public float getHardness()
    {
        return HARDNESS;
    }

    @Override
    public TallGrassMat getType(final String name)
    {
        return getByEnumName(name);
    }

    @Override
    public TallGrassMat getType(final int id)
    {
        return getByID(id);
    }

    @Override
    public TallGrassMat getFlowerType(final FlowerTypeMat flowerType)
    {
        return getTallGrass(flowerType);
    }

    /**
     * Returns one of TallGrass sub-type based on sub-id, may return null
     *
     * @param id sub-type id
     *
     * @return sub-type of TallGrass or null
     */
    public static TallGrassMat getByID(final int id)
    {
        return byID.get((byte) id);
    }

    /**
     * Returns one of TallGrass sub-type based on name (selected by diorite team), may return null
     * If block contains only one type, sub-name of it will be this same as name of material.
     *
     * @param name name of sub-type
     *
     * @return sub-type of TallGrass or null
     */
    public static TallGrassMat getByEnumName(final String name)
    {
        return byName.get(name);
    }

    /**
     * Returns one of TallGrass sub-type based on {@link FlowerTypeMat}
     * If this flower don't supprot given type, it will return default one.
     *
     * @param flowerType type of flower
     *
     * @return sub-type of TallGrass
     */
    public static TallGrassMat getTallGrass(final FlowerTypeMat flowerType)
    {
        for (final TallGrassMat mat : byName.values())
        {
            if (mat.flowerType == flowerType)
            {
                return mat;
            }
        }
        return TALL_GRASS_SHRUB;
    }

    /**
     * Register new sub-type, may replace existing sub-types.
     * Should be used only if you know what are you doing, it will not create fully usable material.
     *
     * @param element sub-type to register
     */
    public static void register(final TallGrassMat element)
    {
        byID.put((byte) element.getType(), element);
        byName.put(element.name(), element);
    }

    @Override
    public TallGrassMat[] types()
    {
        return TallGrassMat.tallGrassTypes();
    }

    /**
     * @return array that contains all sub-types of this block.
     */
    public static TallGrassMat[] tallGrassTypes()
    {
        return byID.values(new TallGrassMat[byID.size()]);
    }

    static
    {
        TallGrassMat.register(TALL_GRASS_SHRUB);
        TallGrassMat.register(TALL_GRASS_GRASS);
        TallGrassMat.register(TALL_GRASS_FERN);
    }
}


text:
ITEM.Name = 'Laser Trail'
ITEM.Price = 150
ITEM.Material = 'trails/laser.vmt'

function ITEM:OnEquip(ply, modifications)
	ply.LaserTrail = util.SpriteTrail(ply, 0, modifications.color, false, 15, 1, 4, 0.125, self.Material)
end

function ITEM:OnHolster(ply)
	SafeRemoveEntity(ply.LaserTrail)
end

function ITEM:Modify(modifications)
	PS:ShowColorChooser(self, modifications)
end

function ITEM:OnModify(ply, modifications)
	SafeRemoveEntity(ply.LaserTrail)
	self:OnEquip(ply, modifications)
end


text:
package capn_test

import (
	"bytes"
	"fmt"
	"testing"

	capn "github.com/glycerine/go-capnproto"
	air "github.com/glycerine/go-capnproto/aircraftlib"
	cv "github.com/glycerine/goconvey/convey"
)

func TestV0ListofEmptyShouldMatchCapnp(t *testing.T) {

	exp := CapnpEncode("(mylist = [(),()])", "HoldsVerEmptyList")

	cv.Convey("Given an empty struct with 0 data/0 ptr fields", t, func() {
		cv.Convey("then a list of 2 empty structs should match the capnp representation", func() {

			seg := capn.NewBuffer(nil)
			scratch := capn.NewBuffer(nil)
			holder := air.NewRootHoldsVerEmptyList(seg)

			ShowSeg("          after NewRootHoldsVerEmptyList(seg), segment seg is:", seg)

			elist := air.NewVerEmptyList(seg, 2)
			plist := capn.PointerList(elist)

			ShowSeg("          pre NewVerEmpty(scratch), segment seg is:", seg)

			e0 := air.NewVerEmpty(scratch)
			e1 := air.NewVerEmpty(scratch)
			plist.Set(0, capn.Object(e0))
			plist.Set(1, capn.Object(e1))

			ShowSeg("          pre SetMylist, segment seg is:", seg)

			fmt.Printf("Then we do the SetMylist():\n")
			holder.SetMylist(elist)

			// save
			buf := bytes.Buffer{}
			seg.WriteTo(&buf)
			act := buf.Bytes()
			save(act, "my.act.holder.elist")

			// show
			ShowSeg("          actual:\n", seg)

			fmt.Printf("act decoded by capnp: '%s'\n", string(CapnpDecode(act, "HoldsVerEmptyList")))

			fmt.Printf("expected:\n")
			ShowBytes(exp, 10)
			fmt.Printf("exp decoded by capnp: '%s'\n", string(CapnpDecode(exp, "HoldsVerEmptyList")))

			cv.So(act, cv.ShouldResemble, exp)
		})
	})
}

func TestV1DataVersioningBiggerToEmpty(t *testing.T) {

	//expTwoSet := CapnpEncode("(mylist = [(val = 27, duo = 26),(val = 42, duo = 41)])", "HoldsVerTwoDataList")
	//expOneDataOneDefault := CapnpEncode("(mylist = [(val = 27, duo = 0),(val = 42, duo = 0)])", "HoldsVerTwoDataList")
	//expTwoEmpty := CapnpEncode("(mylist = [(),()])", "HoldsVerTwoDataList")

	//expEmpty := CapnpEncode("(mylist = [(),()])", "HoldsVerEmptyList")
	//expOne := CapnpEncode("(mylist = [(val = 27),(val = 42)])", "HoldsVerOneDataList")

	cv.Convey("Given a struct with 0 data/0 ptr fields, and a newer version of the struct with 2 data fields", t, func() {
		cv.Convey("then reading serialized bigger-struct-list into the smaller (empty or one data-member) list should work, truncating/ignoring the new fields", func() {

			seg := capn.NewBuffer(nil)
			scratch := capn.NewBuffer(nil)
			holder := air.NewRootHoldsVerTwoDataList(seg)

			twolist := air.NewVerTwoDataList(scratch, 2)
			plist := capn.PointerList(twolist)

			d0 := air.NewVerTwoData(scratch)
			d0.SetVal(27)
			d0.SetDuo(26)
			d1 := air.NewVerTwoData(scratch)
			d1.SetVal(42)
			d1.SetDuo(41)
			plist.Set(0, capn.Object(d0))
			plist.Set(1, capn.Object(d1))

			holder.SetMylist(twolist)

			ShowSeg("     before serializing out, segment scratch is:", scratch)
			ShowSeg("     before serializing out, segment seg is:", seg)

			// serialize out
			buf := bytes.Buffer{}
			seg.WriteTo(&buf)
			segbytes := buf.Bytes()

			// and read-back in using smaller expectations
			reseg, _, err := capn.ReadFromMemoryZeroCopy(segbytes)
			if err != nil {
				panic(err)
			}
			ShowSeg("      after re-reading segbytes, segment reseg is:", reseg)
			fmt.Printf("segbytes decoded by capnp as HoldsVerEmptyList: '%s'\n", string(CapnpDecode(segbytes, "HoldsVerEmptyList")))
			fmt.Printf("segbytes decoded by capnp as HoldsVerOneDataList: '%s'\n", string(CapnpDecode(segbytes, "HoldsVerOneDataList")))
			fmt.Printf("segbytes decoded by capnp as HoldsVerTwoDataList: '%s'\n", string(CapnpDecode(segbytes, "HoldsVerTwoDataList")))

			reHolder := air.ReadRootHoldsVerEmptyList(reseg)
			elist := reHolder.Mylist()
			lene := elist.Len()
			cv.So(lene, cv.ShouldEqual, 2)

			reHolder1 := air.ReadRootHoldsVerOneDataList(reseg)
			onelist := reHolder1.Mylist()
			lenone := onelist.Len()
			cv.So(lenone, cv.ShouldEqual, 2)

			for i := 0; i < 2; i++ {
				ele := onelist.At(i)
				val := ele.Val()
				cv.So(val, cv.ShouldEqual, twolist.At(i).Val())
			}

			reHolder2 := air.ReadRootHoldsVerTwoDataList(reseg)
			twolist2 := reHolder2.Mylist()
			lentwo2 := twolist2.Len()
			cv.So(lentwo2, cv.ShouldEqual, 2)

			for i := 0; i < 2; i++ {
				ele := twolist2.At(i)
				val := ele.Val()
				duo := ele.Duo()
				cv.So(val, cv.ShouldEqual, twolist.At(i).Val())
				cv.So(duo, cv.ShouldEqual, twolist.At(i).Duo())
			}

		})
	})
}

func TestV1DataVersioningEmptyToBigger(t *testing.T) {

	//expOneSet := CapnpEncode("(mylist = [(val = 27),(val = 42)])", "HoldsVerOneDataList")
	//expOneZeroed := CapnpEncode("(mylist = [(val = 0),(val = 0)])", "HoldsVerOneDataList")
	//expOneEmpty := CapnpEncode("(mylist = [(),()])", "HoldsVerOneDataList")
	expEmpty := CapnpEncode("(mylist = [(),()])", "HoldsVerEmptyList")

	cv.Convey("Given a struct with 0 data/0 ptr fields, and a newer version of the struct with 1 data fields", t, func() {
		cv.Convey("then reading from serialized form the small list into the bigger (one or two data values) list should work, getting default value 0 for val/duo.", func() {

			seg := capn.NewBuffer(nil)
			scratch := capn.NewBuffer(nil)

			emptyholder := air.NewRootHoldsVerEmptyList(seg)
			elist := air.NewVerEmptyList(scratch, 2)
			emptyholder.SetMylist(elist)

			actEmpty := ShowSeg("          after NewRootHoldsVerEmptyList(seg) and SetMylist(elist), segment seg is:", seg)
			actEmptyCap := string(CapnpDecode(actEmpty, "HoldsVerEmptyList"))
			expEmptyCap := string(CapnpDecode(expEmpty, "HoldsVerEmptyList"))
			cv.So(actEmptyCap, cv.ShouldResemble, expEmptyCap)

			fmt.Printf("\n actEmpty is \n")
			ShowBytes(actEmpty, 10)
			fmt.Printf("actEmpty decoded by capnp: '%s'\n", string(CapnpDecode(actEmpty, "HoldsVerEmptyList")))
			cv.So(actEmpty, cv.ShouldResemble, expEmpty)

			// seg is set, now read into bigger list
			buf := bytes.Buffer{}
			seg.WriteTo(&buf)
			segbytes := buf.Bytes()

			reseg, _, err := capn.ReadFromMemoryZeroCopy(segbytes)
			if err != nil {
				panic(err)
			}
			ShowSeg("      after re-reading segbytes, segment reseg is:", reseg)
			fmt.Printf("segbytes decoded by capnp as HoldsVerOneDataList: '%s'\n", string(CapnpDecode(segbytes, "HoldsVerOneDataList")))

			reHolder := air.ReadRootHoldsVerOneDataList(reseg)
			onelist := reHolder.Mylist()
			lenone := onelist.Len()
			cv.So(lenone, cv.ShouldEqual, 2)
			for i := 0; i < 2; i++ {
				ele := onelist.At(i)
				val := ele.Val()
				cv.So(val, cv.ShouldEqual, 0)
			}

			reHolder2 := air.ReadRootHoldsVerTwoDataList(reseg)
			twolist := reHolder2.Mylist()
			lentwo := twolist.Len()
			cv.So(lentwo, cv.ShouldEqual, 2)
			for i := 0; i < 2; i++ {
				ele := twolist.At(i)
				val := ele.Val()
				cv.So(val, cv.ShouldEqual, 0)
				duo := ele.Duo()
				cv.So(duo, cv.ShouldEqual, 0)
			}

		})
	})
}

func TestDataVersioningZeroPointersToMore(t *testing.T) {

	expEmpty := CapnpEncode("(mylist = [(),()])", "HoldsVerEmptyList")

	cv.Convey("Given a struct with 0 ptr fields, and a newer version of the struct with 1-2 pointer fields", t, func() {
		cv.Convey("then serializing the empty list and reading it back into 1 or 2 pointer fields should default initialize the pointer fields", func() {

			seg := capn.NewBuffer(nil)
			scratch := capn.NewBuffer(nil)

			emptyholder := air.NewRootHoldsVerEmptyList(seg)
			elist := air.NewVerEmptyList(scratch, 2)
			emptyholder.SetMylist(elist)

			actEmpty := ShowSeg("          after NewRootHoldsVerEmptyList(seg) and SetMylist(elist), segment seg is:", seg)
			actEmptyCap := string(CapnpDecode(actEmpty, "HoldsVerEmptyList"))
			expEmptyCap := string(CapnpDecode(expEmpty, "HoldsVerEmptyList"))
			cv.So(actEmptyCap, cv.ShouldResemble, expEmptyCap)

			fmt.Printf("\n actEmpty is \n")
			ShowBytes(actEmpty, 10)
			fmt.Printf("actEmpty decoded by capnp: '%s'\n", string(CapnpDecode(actEmpty, "HoldsVerEmptyList")))
			cv.So(actEmpty, cv.ShouldResemble, expEmpty)

			// seg is set, now read into bigger list
			buf := bytes.Buffer{}
			seg.WriteTo(&buf)
			segbytes := buf.Bytes()

			reseg, _, err := capn.ReadFromMemoryZeroCopy(segbytes)
			if err != nil {
				panic(err)
			}
			ShowSeg("      after re-reading segbytes, segment reseg is:", reseg)
			fmt.Printf("segbytes decoded by capnp as HoldsVerOneDataList: '%s'\n", string(CapnpDecode(segbytes, "HoldsVerOneDataList")))

			reHolder := air.ReadRootHoldsVerTwoTwoList(reseg)
			list22 := reHolder.Mylist()
			len22 := list22.Len()
			cv.So(len22, cv.ShouldEqual, 2)
			for i := 0; i < 2; i++ {
				ele := list22.At(i)
				val := ele.Val()
				cv.So(val, cv.ShouldEqual, 0)
				duo := ele.Duo()
				cv.So(duo, cv.ShouldEqual, 0)
				ptr1 := ele.Ptr1()
				ptr2 := ele.Ptr2()
				fmt.Printf("ptr1 = %#v\n", ptr1)
				cv.So(ptr1.Segment, cv.ShouldEqual, nil)
				fmt.Printf("ptr2 = %#v\n", ptr2)
				cv.So(ptr2.Segment, cv.ShouldEqual, nil)
			}

		})
	})
}

func TestDataVersioningZeroPointersToTwo(t *testing.T) {
	cv.Convey("Given a struct with 2 ptr fields, and another version of the struct with 0 or 1 pointer fields", t, func() {
		cv.Convey("then reading serialized bigger-struct-list into the smaller (empty or one data-pointer) list should work, truncating/ignoring the new fields", func() {

			seg := capn.NewBuffer(nil)
			scratch := capn.NewBuffer(nil)
			holder := air.NewRootHoldsVerTwoTwoList(seg)

			twolist := air.NewVerTwoDataTwoPtrList(scratch, 2)
			plist := capn.PointerList(twolist)

			d0 := air.NewVerTwoDataTwoPtr(scratch)
			d0.SetVal(27)
			d0.SetDuo(26)

			v1 := air.NewVerOneData(scratch)
			v1.SetVal(25)
			v2 := air.NewVerOneData(scratch)
			v2.SetVal(23)

			d0.SetPtr1(v1)
			d0.SetPtr2(v2)

			d1 := air.NewVerTwoDataTwoPtr(scratch)
			d1.SetVal(42)
			d1.SetDuo(41)

			w1 := air.NewVerOneData(scratch)
			w1.SetVal(40)
			w2 := air.NewVerOneData(scratch)
			w2.SetVal(38)

			d1.SetPtr1(w1)
			d1.SetPtr2(w2)

			plist.Set(0, capn.Object(d0))
			plist.Set(1, capn.Object(d1))

			holder.SetMylist(twolist)

			ShowSeg("     before serializing out, segment scratch is:", scratch)
			ShowSeg("     before serializing out, segment seg is:", seg)

			// serialize out
			buf := bytes.Buffer{}
			seg.WriteTo(&buf)
			segbytes := buf.Bytes()

			// and read-back in using smaller expectations
			reseg, _, err := capn.ReadFromMemoryZeroCopy(segbytes)
			if err != nil {
				panic(err)
			}
			ShowSeg("      after re-reading segbytes, segment reseg is:", reseg)
			fmt.Printf("segbytes decoded by capnp as HoldsVerEmptyList: '%s'\n", string(CapnpDecode(segbytes, "HoldsVerEmptyList")))
			fmt.Printf("segbytes decoded by capnp as HoldsVerOnePtrList: '%s'\n", string(CapnpDecode(segbytes, "HoldsVerOnePtrList")))
			fmt.Printf("segbytes decoded by capnp as HoldsVerTwoTwoList: '%s'\n", string(CapnpDecode(segbytes, "HoldsVerTwoTwoList")))

			reHolder := air.ReadRootHoldsVerEmptyList(reseg)
			elist := reHolder.Mylist()
			lene := elist.Len()
			cv.So(lene, cv.ShouldEqual, 2)

			reHolder1 := air.ReadRootHoldsVerOnePtrList(reseg)
			onelist := reHolder1.Mylist()
			lenone := onelist.Len()
			cv.So(lenone, cv.ShouldEqual, 2)

			for i := 0; i < 2; i++ {
				ele := onelist.At(i)
				ptr1 := ele.Ptr()
				cv.So(ptr1.Val(), cv.ShouldEqual, twolist.At(i).Ptr1().Val())
			}

			reHolder2 := air.ReadRootHoldsVerTwoTwoPlus(reseg)
			twolist2 := reHolder2.Mylist()
			lentwo2 := twolist2.Len()
			cv.So(lentwo2, cv.ShouldEqual, 2)

			for i := 0; i < 2; i++ {
				ele := twolist2.At(i)
				ptr1 := ele.Ptr1()
				ptr2 := ele.Ptr2()
				cv.So(ptr1.Val(), cv.ShouldEqual, twolist.At(i).Ptr1().Val())
				//cv.So(ptr1.Duo(), cv.ShouldEqual, twolist.At(i).Ptr1().Duo())
				cv.So(ptr2.Val(), cv.ShouldEqual, twolist.At(i).Ptr2().Val())
				//cv.So(ptr2.Duo(), cv.ShouldEqual, twolist.At(i).Ptr2().Duo())
				cv.So(ele.Tre(), cv.ShouldEqual, 0)
				cv.So(ele.Lst3().Len(), cv.ShouldEqual, 0)
			}

		})
	})
}


text:
/*
 * This class is based in the article "Writing a Parser in Java: The Tokenizer" by Cogito Learning.
 * See:
 * http://cogitolearning.co.uk/?p=523
 * http://cogitolearning.co.uk/wp-content/uploads/2013/04/CogitoLearningTokenizer.zip
 */

package com.panoramagl.interpreters;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.panoramagl.PLObjectBase;
import com.panoramagl.enumerations.PLTokenType;

public class PLTokenizer extends PLObjectBase implements PLITokenizer
{
	/**member variables*/

	private List<PLIToken> mTokens;
	private List<PLTokenData> mTokensData;

	/**init methods*/

	public PLTokenizer()
	{
		super();
	}

	@Override
	protected void initializeValues()
	{
		mTokens = new ArrayList<PLIToken>();
		mTokensData = new ArrayList<PLTokenData>();
	}

	/**property methods*/

	@Override
	public List<PLIToken> getTokens()
	{
		return mTokens;
	}

	protected List<PLTokenData> getTokensData()
	{
		return mTokensData;
	}

	/**token methods*/

	@Override
	public void addToken(PLTokenType tokenType, String regex)
	{
		mTokensData.add(PLTokenData.PLTokenDataMake(tokenType, Pattern.compile("^(" + regex + ")")));
	}

	@Override
	public void tokenize(String input)
	{
		String inputText = input.trim();
		mTokens.clear();
		while(!inputText.equals(""))
		{
			boolean match = false;
			for(int i = 0, tokensDataLength = mTokensData.size(); i < tokensDataLength; i++)
			{
				PLTokenData tokenData = mTokensData.get(i);
				Matcher matcher = tokenData.regex.matcher(inputText);
				if(matcher.find())
				{
					match = true;
					String sequence = matcher.group().trim();
					inputText = matcher.replaceFirst("").trim();
					mTokens.add(new PLToken(tokenData.type, sequence));
					break;
				}
			}
			if(!match)
				throw new RuntimeException("Unexpected character in input: " + inputText);
		}
	}

	/**dealloc methods*/

	@Override
	protected void finalize() throws Throwable
	{
		mTokens.clear();
		mTokens = null;
		mTokensData.clear();
		mTokensData = null;
		super.finalize();
	}

	/**internal classes declaration*/

	protected static class PLTokenData
	{
		/**member variables*/

		public PLTokenType type;
		public Pattern regex;

		/**init methods*/

		public PLTokenData(PLTokenType typeValue, Pattern regexValue)
		{
			super();
			type = typeValue;
			regex = regexValue;
		}

		public static PLTokenData PLTokenDataMake(PLTokenType type, Pattern regex)
		{
			return new PLTokenData(type, regex);
		}

		/**dealloc methods*/

		@Override
		protected void finalize() throws Throwable
		{
			type = null;
			regex = null;
			super.finalize();
		}
	}
}


text:
/**
 *
 */
package org.minnal.api;

import java.lang.annotation.Annotation;
import java.net.InetAddress;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

import org.minnal.api.filter.ExcludeAnnotationsConvertor;
import org.minnal.api.filter.MinnalApiSpecFilter;
import org.minnal.core.Application;
import org.minnal.core.Bundle;
import org.minnal.core.Container;
import org.minnal.core.ContainerAdapter;
import org.minnal.core.config.ApplicationConfiguration;
import org.minnal.core.config.ConnectorConfiguration;
import org.minnal.core.config.ConnectorConfiguration.Scheme;

import com.fasterxml.jackson.annotation.JsonBackReference;
import com.google.common.collect.Lists;
import com.wordnik.swagger.config.ConfigFactory;
import com.wordnik.swagger.config.FilterFactory;
import com.wordnik.swagger.config.ScannerFactory;
import com.wordnik.swagger.config.SwaggerConfig;
import com.wordnik.swagger.converter.ModelConverters;
import com.wordnik.swagger.converter.OverrideConverter;
import com.wordnik.swagger.jaxrs.config.DefaultJaxrsScanner;
import com.wordnik.swagger.jaxrs.reader.DefaultJaxrsApiReader;
import com.wordnik.swagger.reader.ClassReaders;

/**
 * @author ganeshs
 *
 */
public class ApiBundle extends ContainerAdapter implements Bundle<ApiBundleConfiguration> {

	private ApiBundleConfiguration configuration;

	@Override
	public void init(Container container, ApiBundleConfiguration configuration) {
		this.configuration = configuration;
		container.registerListener(this);

		SwaggerConfig config = ConfigFactory.config();
		config.setApiVersion("1.0.1");

		for (ConnectorConfiguration connector : container.getConfiguration().getServerConfiguration().getConnectorConfigurations()) {
			if (connector.getScheme() == Scheme.http) {
				config.setBasePath(connector.getScheme().toString() + "://" + getHostName() + ":" + connector.getPort());
				break;
			}
		}

		ScannerFactory.setScanner(new DefaultJaxrsScanner());
		ClassReaders.setReader(new DefaultJaxrsApiReader());
		FilterFactory.setFilter(new MinnalApiSpecFilter());
		ModelConverters.addConverter(getExcludeAnnotationsConvertor(), true);
		ModelConverters.addConverter(getOverrideConverter(), true);
	}

	/**
	 * Returns the override converter
	 *
	 * @return
	 */
	protected OverrideConverter getOverrideConverter() {
		OverrideConverter converter = new OverrideConverter();
		String dateJson = "{\"id\": \"date-time\", \"name\": \"date-time\", \"qualifiedType\": \"date-time\"}";
		converter.add(Date.class.getCanonicalName(), dateJson);
		converter.add(Timestamp.class.getCanonicalName(), dateJson);
		return converter;
	}

	/**
	 * Returns the model convertor
	 *
	 * @return
	 */
	protected ExcludeAnnotationsConvertor getExcludeAnnotationsConvertor() {
		List<Class<? extends Annotation>> excludedAnnotations = Lists.<Class<? extends Annotation>>newArrayList(JsonBackReference.class);
		excludedAnnotations.addAll(configuration.getExcludedAnnotations());
		return new ExcludeAnnotationsConvertor(excludedAnnotations);
	}

	@Override
	public void start() {
	}

	@Override
	public void stop() {
	}

	@Override
	public void preMount(Application<ApplicationConfiguration> application) {
		 application.registerPlugin(new ApiPlugin(configuration.isEnableCors()));
	}

	@Override
	public int getOrder() {
		return Integer.MAX_VALUE - 1;
	}

	protected String getHostName() {
		try {
			return InetAddress.getLocalHost().getHostAddress();
		} catch (Exception e) {
			return "localhost";
		}
	}
}


text:
from .model import *
from .behavior import *
from .util import *


text:
package org.xnio.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.Set;
import org.xnio.Option;
import org.xnio.Options;

/**
 * @author David M. Lloyd
 */
final class NioSocketStreamConnection extends AbstractNioStreamConnection {

    private final NioTcpServerHandle serverConduit;
    private final NioSocketConduit conduit;

    NioSocketStreamConnection(final WorkerThread workerThread, final SelectionKey key, final NioTcpServerHandle serverConduit) {
        super(workerThread);
        conduit = new NioSocketConduit(workerThread, key, this);
        key.attach(conduit);
        this.serverConduit = serverConduit;
        setSinkConduit(conduit);
        setSourceConduit(conduit);
    }

    public SocketAddress getPeerAddress() {
        final Socket socket = conduit.getSocketChannel().socket();
        return new InetSocketAddress(socket.getInetAddress(), socket.getPort());
    }

    public SocketAddress getLocalAddress() {
        final Socket socket = conduit.getSocketChannel().socket();
        return new InetSocketAddress(socket.getLocalAddress(), socket.getLocalPort());
    }

    private static final Set<Option<?>> OPTIONS = Option.setBuilder()
            .add(Options.CLOSE_ABORT)
            .add(Options.IP_TRAFFIC_CLASS)
            .add(Options.KEEP_ALIVE)
            .add(Options.READ_TIMEOUT)
            .add(Options.RECEIVE_BUFFER)
            .add(Options.SEND_BUFFER)
            .add(Options.TCP_NODELAY)
            .add(Options.TCP_OOB_INLINE)
            .add(Options.WRITE_TIMEOUT)
            .create();

    public boolean supportsOption(final Option<?> option) {
        return OPTIONS.contains(option);
    }

    public <T> T getOption(final Option<T> option) throws IOException {
        if (option == Options.CLOSE_ABORT) {
            return option.cast(Boolean.valueOf(conduit.getSocketChannel().socket().getSoLinger() == 0));
        } else if (option == Options.IP_TRAFFIC_CLASS) {
            return option.cast(Integer.valueOf(conduit.getSocketChannel().socket().getTrafficClass()));
        } else if (option == Options.KEEP_ALIVE) {
            return option.cast(Boolean.valueOf(conduit.getSocketChannel().socket().getKeepAlive()));
        } else if (option == Options.READ_TIMEOUT) {
            return option.cast(Integer.valueOf(conduit.getReadTimeout()));
        } else if (option == Options.RECEIVE_BUFFER) {
            return option.cast(Integer.valueOf(conduit.getSocketChannel().socket().getReceiveBufferSize()));
        } else if (option == Options.SEND_BUFFER) {
            return option.cast(Integer.valueOf(conduit.getSocketChannel().socket().getSendBufferSize()));
        } else if (option == Options.TCP_NODELAY) {
            return option.cast(Boolean.valueOf(conduit.getSocketChannel().socket().getTcpNoDelay()));
        } else if (option == Options.TCP_OOB_INLINE) {
            return option.cast(Boolean.valueOf(conduit.getSocketChannel().socket().getOOBInline()));
        } else if (option == Options.WRITE_TIMEOUT) {
            return option.cast(Integer.valueOf(conduit.getWriteTimeout()));
        } else {
            return null;
        }
    }

    public <T> T setOption(final Option<T> option, final T value) throws IllegalArgumentException, IOException {
        T result;
        if (option == Options.CLOSE_ABORT) {
            result = option.cast(Boolean.valueOf(conduit.getSocketChannel().socket().getSoLinger() == 0));
            conduit.getSocketChannel().socket().setSoLinger(Options.CLOSE_ABORT.cast(value, Boolean.FALSE).booleanValue(), 0);
        } else if (option == Options.IP_TRAFFIC_CLASS) {
            result = option.cast(Integer.valueOf(conduit.getSocketChannel().socket().getTrafficClass()));
            conduit.getSocketChannel().socket().setTrafficClass(Options.IP_TRAFFIC_CLASS.cast(value).intValue());
        } else if (option == Options.KEEP_ALIVE) {
            result = option.cast(Boolean.valueOf(conduit.getSocketChannel().socket().getKeepAlive()));
            conduit.getSocketChannel().socket().setKeepAlive(Options.KEEP_ALIVE.cast(value, Boolean.FALSE).booleanValue());
        } else if (option == Options.READ_TIMEOUT) {
            result = option.cast(Integer.valueOf(conduit.getAndSetReadTimeout(value == null ? 0 : Options.READ_TIMEOUT.cast(value).intValue())));
        } else if (option == Options.RECEIVE_BUFFER) {
            result = option.cast(Integer.valueOf(conduit.getSocketChannel().socket().getReceiveBufferSize()));
            conduit.getSocketChannel().socket().setReceiveBufferSize(Options.RECEIVE_BUFFER.cast(value).intValue());
        } else if (option == Options.SEND_BUFFER) {
            result = option.cast(Integer.valueOf(conduit.getSocketChannel().socket().getSendBufferSize()));
            conduit.getSocketChannel().socket().setSendBufferSize(Options.SEND_BUFFER.cast(value).intValue());
        } else if (option == Options.TCP_NODELAY) {
            result = option.cast(Boolean.valueOf(conduit.getSocketChannel().socket().getTcpNoDelay()));
            conduit.getSocketChannel().socket().setTcpNoDelay(Options.TCP_NODELAY.cast(value, Boolean.FALSE).booleanValue());
        } else if (option == Options.TCP_OOB_INLINE) {
            result = option.cast(Boolean.valueOf(conduit.getSocketChannel().socket().getOOBInline()));
            conduit.getSocketChannel().socket().setOOBInline(Options.TCP_OOB_INLINE.cast(value, Boolean.FALSE).booleanValue());
        } else if (option == Options.WRITE_TIMEOUT) {
            result = option.cast(Integer.valueOf(conduit.getAndSetWriteTimeout(value == null ? 0 : Options.WRITE_TIMEOUT.cast(value).intValue())));
        } else {
            return null;
        }
        return result;
    }

    protected void closeAction() throws IOException {
        try {
            conduit.getWorkerThread().cancelKey(conduit.getSelectionKey());
            conduit.getSocketChannel().close();
        } catch (ClosedChannelException ignored) {
        } finally {
            final NioTcpServerHandle conduit = this.serverConduit;
            if (conduit!= null) conduit.channelClosed();
        }
    }

    protected void notifyWriteClosed() {
        conduit.writeTerminated();
    }

    protected void notifyReadClosed() {
        conduit.readTerminated();
    }

    SocketChannel getChannel() {
        return conduit.getSocketChannel();
    }

    NioSocketConduit getConduit() {
        return conduit;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TechTalk.SpecFlow;

namespace Selenium_SpecFlow.Support
{
    [Binding]
    public static class SeleniumSupport
    {
        private static bool ReuseWebSession
        {
            get { return ConfigurationManager.AppSettings["ReuseWebSession"] == "true"; }
        }

        [BeforeScenario("web")]
        public static void BeforeWebScenario()
        {
            SeleniumController.Instance.Start();
        }

        [AfterScenario("web")]
        public static void AfterWebScenario()
        {
            if (!ReuseWebSession)
                SeleniumController.Instance.Stop();
        }

        //[AfterFeature]
        [AfterTestRun]
        public static void AfterWebFeature()
        {
            SeleniumController.Instance.Stop();
        }
    }
}


text:
package php.runtime.ext.support.compile;

import php.runtime.Memory;
import php.runtime.annotation.Reflection;
import php.runtime.env.Environment;
import php.runtime.env.TraceInfo;
import php.runtime.invoke.Invoker;
import php.runtime.memory.ObjectMemory;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

abstract public class FunctionsContainer {

    protected static boolean expectingReference(Environment env, TraceInfo trace, Memory memory){
        if (!memory.isReference()){
            env.warning(trace, "Only variables can be passed by reference");
            return false;
        }
        return true;
    }

    protected static boolean expecting(Environment env, TraceInfo trace, int index, Memory memory, Memory.Type type){
        if (memory.getRealType() != type) {
            env.warning(trace, "expects parameter " + index + " to be " + type.toString() +
                    ", " + memory.getRealType().toString() + " given");
            return false;
        }
        return true;
    }

    protected static boolean expectingImplement(Environment env, TraceInfo trace,
                                                int index, Memory memory, Class<?> clazz){
        if (!memory.isObject() || !memory.toValue(ObjectMemory.class).getClass().isAssignableFrom(clazz)) {
            String given = memory.getRealType().toString();
            if (memory.isObject())
                given = memory.toValue(ObjectMemory.class).getReflection().getName();

            env.warning(trace, "expects parameter " + index + " must implement "
                    + (clazz.isInterface() ? "interface " : "") + clazz.getSimpleName() +
                    ", " + given + " given");
            return false;
        }
        return true;
    }

    protected static Invoker expectingCallback(Environment env, TraceInfo trace, int index, Memory memory){
        Invoker invoker = Invoker.valueOf(env, null, memory);
        if (invoker == null) {
            env.warning(trace, "expects parameter " + index + " to be valid callback");
            return null;
        }
        if (invoker.canAccess(env) != 0) {
            env.warning(trace, "expects parameter " + index + " to be valid callback, cannot access");
            return null;
        }
        return invoker;
    }

    protected Map<String, Method> getNativeFunctions() {
        return new HashMap<String, Method>();
    }

    protected Method getNative(Class clazz, String name, Class<?>... argumentTypes) {
        try {
            return clazz.getDeclaredMethod(name, argumentTypes);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
    }

    public Collection<CompileFunction> getFunctions() {
        Map<String, CompileFunction> result = new HashMap<String, CompileFunction>();

        for(Method method : getClass().getDeclaredMethods()){
            int mod = method.getModifiers();
            if (Modifier.isStatic(mod) && Modifier.isPublic(mod)){
                String name = method.getName();
                Reflection.Name altName = method.getAnnotation(Reflection.Name.class);
                if (altName != null)
                    name = altName.value();

                CompileFunction function = result.get(name);
                if (function == null)
                    result.put(name, function = new CompileFunction(name));

                function.addMethod(method);
            }
        }

        for(Map.Entry<String, Method> item : getNativeFunctions().entrySet()){
            Method method = item.getValue();
            CompileFunction function = result.get(item.getKey());
            if (function == null){
                result.put(item.getKey(),
                        function = new CompileFunction(
                                item.getKey()
                        )
                );
            }
            function.addMethod(method, true);
        }

        return result.values();
    }
}