text:
"""Tests for contrib.seq2seq.python.seq2seq.basic_decoder."""
# pylint: disable=unused-import,g-bad-import-order
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# pylint: enable=unused-import

import numpy as np

from tensorflow.contrib.seq2seq.python.ops import helper as helper_py
from tensorflow.contrib.seq2seq.python.ops import basic_decoder
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import tensor_shape
from tensorflow.python.layers import core as layers_core
from tensorflow.python.ops import init_ops
from tensorflow.python.ops import rnn_cell
from tensorflow.python.ops import variables
from tensorflow.python.ops import variable_scope
from tensorflow.python.platform import test
# pylint: enable=g-import-not-at-top

class BasicDecoderTest(test.TestCase):

  def _testStepWithTrainingHelper(self, use_output_layer):
    sequence_length = [3, 4, 3, 1, 0]
    batch_size = 5
    max_time = 8
    input_depth = 7
    cell_depth = 10
    output_layer_depth = 3

    with self.test_session(use_gpu=True) as sess:
      inputs = np.random.randn(batch_size, max_time,
                               input_depth).astype(np.float32)
      cell = rnn_cell.LSTMCell(cell_depth)
      helper = helper_py.TrainingHelper(
          inputs, sequence_length, time_major=False)
      if use_output_layer:
        output_layer = layers_core.Dense(output_layer_depth, use_bias=False)
        expected_output_depth = output_layer_depth
      else:
        output_layer = None
        expected_output_depth = cell_depth
      my_decoder = basic_decoder.BasicDecoder(
          cell=cell,
          helper=helper,
          initial_state=cell.zero_state(
              dtype=dtypes.float32, batch_size=batch_size),
          output_layer=output_layer)
      output_size = my_decoder.output_size
      output_dtype = my_decoder.output_dtype
      self.assertEqual(
          basic_decoder.BasicDecoderOutput(expected_output_depth,
                                           tensor_shape.TensorShape([])),
          output_size)
      self.assertEqual(
          basic_decoder.BasicDecoderOutput(dtypes.float32, dtypes.int32),
          output_dtype)

      (first_finished, first_inputs, first_state) = my_decoder.initialize()
      (step_outputs, step_state, step_next_inputs,
       step_finished) = my_decoder.step(
           constant_op.constant(0), first_inputs, first_state)
      batch_size_t = my_decoder.batch_size

      self.assertTrue(isinstance(first_state, rnn_cell.LSTMStateTuple))
      self.assertTrue(isinstance(step_state, rnn_cell.LSTMStateTuple))
      self.assertTrue(
          isinstance(step_outputs, basic_decoder.BasicDecoderOutput))
      self.assertEqual((batch_size, expected_output_depth),
                       step_outputs[0].get_shape())
      self.assertEqual((batch_size,), step_outputs[1].get_shape())
      self.assertEqual((batch_size, cell_depth), first_state[0].get_shape())
      self.assertEqual((batch_size, cell_depth), first_state[1].get_shape())
      self.assertEqual((batch_size, cell_depth), step_state[0].get_shape())
      self.assertEqual((batch_size, cell_depth), step_state[1].get_shape())

      if use_output_layer:
        # The output layer was accessed
        self.assertEqual(len(output_layer.variables), 1)

      sess.run(variables.global_variables_initializer())
      sess_results = sess.run({
          "batch_size": batch_size_t,
          "first_finished": first_finished,
          "first_inputs": first_inputs,
          "first_state": first_state,
          "step_outputs": step_outputs,
          "step_state": step_state,
          "step_next_inputs": step_next_inputs,
          "step_finished": step_finished
      })

      self.assertAllEqual([False, False, False, False, True],
                          sess_results["first_finished"])
      self.assertAllEqual([False, False, False, True, True],
                          sess_results["step_finished"])
      self.assertAllEqual(
          np.argmax(sess_results["step_outputs"].rnn_output, -1),
          sess_results["step_outputs"].sample_id)

  def testStepWithTrainingHelperNoOutputLayer(self):
    self._testStepWithTrainingHelper(use_output_layer=False)

  def testStepWithTrainingHelperWithOutputLayer(self):
    self._testStepWithTrainingHelper(use_output_layer=True)

  def testStepWithGreedyEmbeddingHelper(self):
    batch_size = 5
    vocabulary_size = 7
    cell_depth = vocabulary_size  # cell's logits must match vocabulary size
    input_depth = 10
    start_tokens = np.random.randint(0, vocabulary_size, size=batch_size)
    end_token = 1

    with self.test_session(use_gpu=True) as sess:
      embeddings = np.random.randn(vocabulary_size,
                                   input_depth).astype(np.float32)
      cell = rnn_cell.LSTMCell(vocabulary_size)
      helper = helper_py.GreedyEmbeddingHelper(embeddings, start_tokens,
                                               end_token)
      my_decoder = basic_decoder.BasicDecoder(
          cell=cell,
          helper=helper,
          initial_state=cell.zero_state(
              dtype=dtypes.float32, batch_size=batch_size))
      output_size = my_decoder.output_size
      output_dtype = my_decoder.output_dtype
      self.assertEqual(
          basic_decoder.BasicDecoderOutput(cell_depth,
                                           tensor_shape.TensorShape([])),
          output_size)
      self.assertEqual(
          basic_decoder.BasicDecoderOutput(dtypes.float32, dtypes.int32),
          output_dtype)

      (first_finished, first_inputs, first_state) = my_decoder.initialize()
      (step_outputs, step_state, step_next_inputs,
       step_finished) = my_decoder.step(
           constant_op.constant(0), first_inputs, first_state)
      batch_size_t = my_decoder.batch_size

      self.assertTrue(isinstance(first_state, rnn_cell.LSTMStateTuple))
      self.assertTrue(isinstance(step_state, rnn_cell.LSTMStateTuple))
      self.assertTrue(
          isinstance(step_outputs, basic_decoder.BasicDecoderOutput))
      self.assertEqual((batch_size, cell_depth), step_outputs[0].get_shape())
      self.assertEqual((batch_size,), step_outputs[1].get_shape())
      self.assertEqual((batch_size, cell_depth), first_state[0].get_shape())
      self.assertEqual((batch_size, cell_depth), first_state[1].get_shape())
      self.assertEqual((batch_size, cell_depth), step_state[0].get_shape())
      self.assertEqual((batch_size, cell_depth), step_state[1].get_shape())

      sess.run(variables.global_variables_initializer())
      sess_results = sess.run({
          "batch_size": batch_size_t,
          "first_finished": first_finished,
          "first_inputs": first_inputs,
          "first_state": first_state,
          "step_outputs": step_outputs,
          "step_state": step_state,
          "step_next_inputs": step_next_inputs,
          "step_finished": step_finished
      })

      expected_sample_ids = np.argmax(
          sess_results["step_outputs"].rnn_output, -1)
      expected_step_finished = (expected_sample_ids == end_token)
      expected_step_next_inputs = embeddings[expected_sample_ids]
      self.assertAllEqual([False, False, False, False, False],
                          sess_results["first_finished"])
      self.assertAllEqual(expected_step_finished, sess_results["step_finished"])
      self.assertAllEqual(expected_sample_ids,
                          sess_results["step_outputs"].sample_id)
      self.assertAllEqual(expected_step_next_inputs,
                          sess_results["step_next_inputs"])

  def testStepWithSampleEmbeddingHelper(self):
    batch_size = 5
    vocabulary_size = 7
    cell_depth = vocabulary_size  # cell's logits must match vocabulary size
    input_depth = 10
    np.random.seed(0)
    start_tokens = np.random.randint(0, vocabulary_size, size=batch_size)
    end_token = 1

    with self.test_session(use_gpu=True) as sess:
      with variable_scope.variable_scope(
          "testStepWithSampleEmbeddingHelper",
          initializer=init_ops.constant_initializer(0.01)):
        embeddings = np.random.randn(vocabulary_size,
                                     input_depth).astype(np.float32)
        cell = rnn_cell.LSTMCell(vocabulary_size)
        helper = helper_py.SampleEmbeddingHelper(embeddings, start_tokens,
                                                 end_token, seed=0)
        my_decoder = basic_decoder.BasicDecoder(
            cell=cell,
            helper=helper,
            initial_state=cell.zero_state(
                dtype=dtypes.float32, batch_size=batch_size))
        output_size = my_decoder.output_size
        output_dtype = my_decoder.output_dtype
        self.assertEqual(
            basic_decoder.BasicDecoderOutput(cell_depth,
                                             tensor_shape.TensorShape([])),
            output_size)
        self.assertEqual(
            basic_decoder.BasicDecoderOutput(dtypes.float32, dtypes.int32),
            output_dtype)

        (first_finished, first_inputs, first_state) = my_decoder.initialize()
        (step_outputs, step_state, step_next_inputs,
         step_finished) = my_decoder.step(
             constant_op.constant(0), first_inputs, first_state)
        batch_size_t = my_decoder.batch_size

        self.assertTrue(isinstance(first_state, rnn_cell.LSTMStateTuple))
        self.assertTrue(isinstance(step_state, rnn_cell.LSTMStateTuple))
        self.assertTrue(
            isinstance(step_outputs, basic_decoder.BasicDecoderOutput))
        self.assertEqual((batch_size, cell_depth), step_outputs[0].get_shape())
        self.assertEqual((batch_size,), step_outputs[1].get_shape())
        self.assertEqual((batch_size, cell_depth), first_state[0].get_shape())
        self.assertEqual((batch_size, cell_depth), first_state[1].get_shape())
        self.assertEqual((batch_size, cell_depth), step_state[0].get_shape())
        self.assertEqual((batch_size, cell_depth), step_state[1].get_shape())

        sess.run(variables.global_variables_initializer())
        sess_results = sess.run({
            "batch_size": batch_size_t,
            "first_finished": first_finished,
            "first_inputs": first_inputs,
            "first_state": first_state,
            "step_outputs": step_outputs,
            "step_state": step_state,
            "step_next_inputs": step_next_inputs,
            "step_finished": step_finished
        })

        sample_ids = sess_results["step_outputs"].sample_id
        expected_step_finished = (sample_ids == end_token)
        expected_step_next_inputs = embeddings[sample_ids]
        self.assertAllEqual(expected_step_finished,
                            sess_results["step_finished"])
        self.assertAllEqual(expected_step_next_inputs,
                            sess_results["step_next_inputs"])

  def testStepWithScheduledEmbeddingTrainingHelper(self):
    sequence_length = [3, 4, 3, 1, 0]
    batch_size = 5
    max_time = 8
    input_depth = 7
    vocabulary_size = 10

    with self.test_session(use_gpu=True) as sess:
      inputs = np.random.randn(
          batch_size, max_time, input_depth).astype(np.float32)
      embeddings = np.random.randn(
          vocabulary_size, input_depth).astype(np.float32)
      half = constant_op.constant(0.5)
      cell = rnn_cell.LSTMCell(vocabulary_size)
      helper = helper_py.ScheduledEmbeddingTrainingHelper(
          inputs=inputs,
          sequence_length=sequence_length,
          embedding=embeddings,
          sampling_probability=half,
          time_major=False)
      my_decoder = basic_decoder.BasicDecoder(
          cell=cell,
          helper=helper,
          initial_state=cell.zero_state(
              dtype=dtypes.float32, batch_size=batch_size))
      output_size = my_decoder.output_size
      output_dtype = my_decoder.output_dtype
      self.assertEqual(
          basic_decoder.BasicDecoderOutput(vocabulary_size,
                                           tensor_shape.TensorShape([])),
          output_size)
      self.assertEqual(
          basic_decoder.BasicDecoderOutput(dtypes.float32, dtypes.int32),
          output_dtype)

      (first_finished, first_inputs, first_state) = my_decoder.initialize()
      (step_outputs, step_state, step_next_inputs,
       step_finished) = my_decoder.step(
           constant_op.constant(0), first_inputs, first_state)
      batch_size_t = my_decoder.batch_size

      self.assertTrue(isinstance(first_state, rnn_cell.LSTMStateTuple))
      self.assertTrue(isinstance(step_state, rnn_cell.LSTMStateTuple))
      self.assertTrue(
          isinstance(step_outputs, basic_decoder.BasicDecoderOutput))
      self.assertEqual((batch_size, vocabulary_size),
                       step_outputs[0].get_shape())
      self.assertEqual((batch_size,), step_outputs[1].get_shape())
      self.assertEqual((batch_size, vocabulary_size),
                       first_state[0].get_shape())
      self.assertEqual((batch_size, vocabulary_size),
                       first_state[1].get_shape())
      self.assertEqual((batch_size, vocabulary_size),
                       step_state[0].get_shape())
      self.assertEqual((batch_size, vocabulary_size),
                       step_state[1].get_shape())
      self.assertEqual((batch_size, input_depth),
                       step_next_inputs.get_shape())

      sess.run(variables.global_variables_initializer())
      sess_results = sess.run({
          "batch_size": batch_size_t,
          "first_finished": first_finished,
          "first_inputs": first_inputs,
          "first_state": first_state,
          "step_outputs": step_outputs,
          "step_state": step_state,
          "step_next_inputs": step_next_inputs,
          "step_finished": step_finished
      })

      self.assertAllEqual([False, False, False, False, True],
                          sess_results["first_finished"])
      self.assertAllEqual([False, False, False, True, True],
                          sess_results["step_finished"])
      sample_ids = sess_results["step_outputs"].sample_id
      batch_where_not_sampling = np.where(sample_ids == -1)
      batch_where_sampling = np.where(sample_ids > -1)
      self.assertAllClose(
          sess_results["step_next_inputs"][batch_where_sampling],
          embeddings[sample_ids[batch_where_sampling]])
      self.assertAllClose(
          sess_results["step_next_inputs"][batch_where_not_sampling],
          np.squeeze(inputs[batch_where_not_sampling, 1]))

  def _testStepWithScheduledOutputTrainingHelper(
      self, sampling_probability, use_next_input_layer, use_auxiliary_inputs):
    sequence_length = [3, 4, 3, 1, 0]
    batch_size = 5
    max_time = 8
    input_depth = 7
    cell_depth = input_depth
    if use_next_input_layer:
      cell_depth = 6
    if use_auxiliary_inputs:
      auxiliary_input_depth = 4
      auxiliary_inputs = np.random.randn(
          batch_size, max_time, auxiliary_input_depth).astype(np.float32)
    else:
      auxiliary_inputs = None

    with self.test_session(use_gpu=True) as sess:
      inputs = np.random.randn(batch_size, max_time,
                               input_depth).astype(np.float32)
      cell = rnn_cell.LSTMCell(cell_depth)
      sampling_probability = constant_op.constant(sampling_probability)

      next_input_layer = None
      if use_next_input_layer:
        next_input_layer = layers_core.Dense(input_depth, use_bias=False)

      helper = helper_py.ScheduledOutputTrainingHelper(
          inputs=inputs,
          sequence_length=sequence_length,
          sampling_probability=sampling_probability,
          time_major=False,
          next_input_layer=next_input_layer,
          auxiliary_inputs=auxiliary_inputs)

      my_decoder = basic_decoder.BasicDecoder(
          cell=cell,
          helper=helper,
          initial_state=cell.zero_state(
              dtype=dtypes.float32, batch_size=batch_size))

      output_size = my_decoder.output_size
      output_dtype = my_decoder.output_dtype
      self.assertEqual(
          basic_decoder.BasicDecoderOutput(cell_depth,
                                           tensor_shape.TensorShape([])),
          output_size)
      self.assertEqual(
          basic_decoder.BasicDecoderOutput(dtypes.float32, dtypes.int32),
          output_dtype)

      (first_finished, first_inputs, first_state) = my_decoder.initialize()
      (step_outputs, step_state, step_next_inputs,
       step_finished) = my_decoder.step(
           constant_op.constant(0), first_inputs, first_state)

      if use_next_input_layer:
        output_after_next_input_layer = next_input_layer(
            step_outputs.rnn_output)

      batch_size_t = my_decoder.batch_size

      self.assertTrue(isinstance(first_state, rnn_cell.LSTMStateTuple))
      self.assertTrue(isinstance(step_state, rnn_cell.LSTMStateTuple))
      self.assertTrue(
          isinstance(step_outputs, basic_decoder.BasicDecoderOutput))
      self.assertEqual((batch_size, cell_depth), step_outputs[0].get_shape())
      self.assertEqual((batch_size,), step_outputs[1].get_shape())
      self.assertEqual((batch_size, cell_depth), first_state[0].get_shape())
      self.assertEqual((batch_size, cell_depth), first_state[1].get_shape())
      self.assertEqual((batch_size, cell_depth), step_state[0].get_shape())
      self.assertEqual((batch_size, cell_depth), step_state[1].get_shape())

      sess.run(variables.global_variables_initializer())

      fetches = {
          "batch_size": batch_size_t,
          "first_finished": first_finished,
          "first_inputs": first_inputs,
          "first_state": first_state,
          "step_outputs": step_outputs,
          "step_state": step_state,
          "step_next_inputs": step_next_inputs,
          "step_finished": step_finished
      }
      if use_next_input_layer:
        fetches["output_after_next_input_layer"] = output_after_next_input_layer

      sess_results = sess.run(fetches)

      self.assertAllEqual([False, False, False, False, True],
                          sess_results["first_finished"])
      self.assertAllEqual([False, False, False, True, True],
                          sess_results["step_finished"])

      sample_ids = sess_results["step_outputs"].sample_id
      batch_where_not_sampling = np.where(np.logical_not(sample_ids))
      batch_where_sampling = np.where(sample_ids)

      auxiliary_inputs_to_concat = (
          auxiliary_inputs[:, 1] if use_auxiliary_inputs else
          np.array([]).reshape(batch_size, 0).astype(np.float32))

      expected_next_sampling_inputs = np.concatenate(
          (sess_results["output_after_next_input_layer"][batch_where_sampling]
           if use_next_input_layer else
           sess_results["step_outputs"].rnn_output[batch_where_sampling],
           auxiliary_inputs_to_concat[batch_where_sampling]),
          axis=-1)
      self.assertAllClose(
          sess_results["step_next_inputs"][batch_where_sampling],
          expected_next_sampling_inputs)

      self.assertAllClose(
          sess_results["step_next_inputs"][batch_where_not_sampling],
          np.concatenate(
              (np.squeeze(inputs[batch_where_not_sampling, 1], axis=0),
               auxiliary_inputs_to_concat[batch_where_not_sampling]),
              axis=-1))

  def testStepWithScheduledOutputTrainingHelperWithoutNextInputLayerOrAuxInputs(
      self):
    self._testStepWithScheduledOutputTrainingHelper(
        sampling_probability=0.5, use_next_input_layer=False,
        use_auxiliary_inputs=False)

  def testStepWithScheduledOutputTrainingHelperWithNextInputLayer(self):
    self._testStepWithScheduledOutputTrainingHelper(
        sampling_probability=0.5, use_next_input_layer=True,
        use_auxiliary_inputs=False)

  def testStepWithScheduledOutputTrainingHelperWithAuxiliaryInputs(self):
    self._testStepWithScheduledOutputTrainingHelper(
        sampling_probability=0.5, use_next_input_layer=False,
        use_auxiliary_inputs=True)

  def testStepWithScheduledOutputTrainingHelperWithNextInputLayerAndAuxInputs(
      self):
    self._testStepWithScheduledOutputTrainingHelper(
        sampling_probability=0.5, use_next_input_layer=True,
        use_auxiliary_inputs=True)

  def testStepWithScheduledOutputTrainingHelperWithNoSampling(
      self):
    self._testStepWithScheduledOutputTrainingHelper(
        sampling_probability=0.0, use_next_input_layer=True,
        use_auxiliary_inputs=True)

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


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:state_pressed="true" android:drawable="@color/background_blue"></item>
    <item android:state_pressed="false" android:drawable="@color/transparent"></item>

</selector>

redpajama_set_name: RedPajamaGithub


text:
<?php
//----------------------------------------------------------------------
// Copyright (c) 2011-2016 Raytheon BBN Technologies
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and/or hardware specification (the "Work") to
// deal in the Work without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Work, and to permit persons to whom the Work
// is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Work.
//
// THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS
// IN THE WORK.
//----------------------------------------------------------------------
?>
<?php
require_once("settings.php");
require_once("user.php");

$user = geni_loadUser();
if (!isset($user) || is_null($user) || ! $user->isActive()) {
  relative_redirect('home.php');
}

// Look up the key...
$outside_key = db_fetch_outside_private_key_cert($user->account_id);
if (! $outside_key) {
  relative_redirect("home.php");
}

/* Construct a filename like "geni-TimWakefield.pem" */
$filename = "geni-" . str_replace(' ', '', $user->prettyName()) . ".pem";

$_SESSION['lastmessage'] = "Downloaded certificate to $filename";

// Set headers for download
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$filename");
header("Content-Type: application/pem");
header("Content-Transfer-Encoding: binary");
print $outside_key['private_key'] . "\n" . $outside_key['certificate'] . "\n";
?>


text:
local _, Addon = ...
local ParentAddon = Addon:GetParent()

local BACKGROUND_COLOR = _G.CreateColor(0, 0, 0, 0.7)
local GRID_COLOR = _G.CreateColor(0.4, 0.4, 0.4, 0.5)

-- #731abc
local GRID_HIGHLIGHT_COLOR = _G.CreateColor(0.451, 0.102, 0.737, 0.5)

local GRID_LINE_THICKNESS = 2

local OverlayUI = Addon:NewModule('OverlayUI', 'AceEvent-3.0')

--------------------------------------------------------------------------------
-- Events
--------------------------------------------------------------------------------

function OverlayUI:OnInitialize()
    self.frame = _G.CreateFrame('Frame', nil, _G.UIParent)

    self.frame:SetFrameStrata('BACKGROUND')
    self.frame:EnableMouse(false)
    self.frame:SetAllPoints(self.frame:GetParent())
    self.frame:Hide()

    -- the background to use when showing the overlay
    local bg = self.frame:CreateTexture(nil, "BACKGROUND")

    bg:SetColorTexture(BACKGROUND_COLOR:GetRGBA())
    bg:SetAllPoints(self.frame)

    self.bg = bg

    -- a fade in for when showing
    local fadeInSequence = self.frame:CreateAnimationGroup()

    local fadeIn = fadeInSequence:CreateAnimation('Alpha')

    fadeIn:SetFromAlpha(0)
    fadeIn:SetToAlpha(1)
    fadeIn:SetSmoothing('IN')
    fadeIn:SetDuration(0.2)

    self.fadeInSequence = fadeInSequence

    -- add a fade effect when hiding
    local fadeOutSequence = self.frame:CreateAnimationGroup()

    fadeOutSequence:SetScript('OnFinished', function() self:OnFadeOutFinished() end)

    local fadeOut = fadeOutSequence:CreateAnimation('Alpha')

    fadeOut:SetFromAlpha(1)
    fadeOut:SetToAlpha(0)
    fadeOut:SetSmoothing('OUT')
    fadeOut:SetDuration(0.2)

    self.fadeOutSequence = fadeOutSequence

    self.frame:SetScript("OnShow", function() self:OnShow() end)
    self.frame:SetScript("OnHide", function() self:OnHide() end)
    self.frame:SetScript("OnSizeChanged", function() self:OnSizeChanged() end)

    Addon.HelpDialog:OnLoad(self.frame)
end

function OverlayUI:OnEnable()
    self:RegisterEvent('PLAYER_REGEN_ENABLED')
    self:RegisterEvent('PLAYER_REGEN_DISABLED')

    ParentAddon.RegisterCallback(self, 'ALIGNMENT_GRID_ENABLED')
    ParentAddon.RegisterCallback(self, 'ALIGNMENT_GRID_SIZE_CHANGED')
    ParentAddon.RegisterCallback(self, 'CONFIG_MODE_ENABLED')
    ParentAddon.RegisterCallback(self, 'CONFIG_MODE_DISABLED')
    ParentAddon.RegisterCallback(self, 'LAYOUT_UNLOADED')
    ParentAddon.RegisterCallback(self, 'LAYOUT_LOADED')
    ParentAddon.RegisterCallback(self, 'BAR_DISPLAY_LAYER_UPDATED', 'OnBarDisplayLevelChanged')
    ParentAddon.RegisterCallback(self, 'BAR_DISPLAY_LEVEL_UPDATED', 'OnBarDisplayLevelChanged')

    self:SetVisible(not (ParentAddon:Locked() or _G.InCombatLockdown()))
end

function OverlayUI:OnShow()
    self:UpdateGrid()
    self:ShowDragFrames()
end

function OverlayUI:OnHide()
    self:HideDragFrames()
end

function OverlayUI:OnSizeChanged()
    if ParentAddon:GetAlignmentGridEnabled() then
        self:DrawGrid()
    end
end

function OverlayUI:OnFadeOutFinished()
    self.frame:Hide()
    self:HideDragFrames()
end

function OverlayUI:OnBarDisplayLevelChanged(msg, bar)
    local activeDragFrames = self.activeDragFrames

    if activeDragFrames then
        for i = #activeDragFrames, 1, -1 do
            if activeDragFrames[i].owner == bar then
                activeDragFrames[i]:UpdateFrameLevel()
            end
        end
    end
end

function OverlayUI:CONFIG_MODE_ENABLED()
    self:SetVisible(not _G.InCombatLockdown())
end

function OverlayUI:CONFIG_MODE_DISABLED()
    self:SetVisible(false)
end

function OverlayUI:PLAYER_REGEN_ENABLED()
    self:SetVisible(not ParentAddon:Locked())
end

function OverlayUI:PLAYER_REGEN_DISABLED()
    self:SetVisible(false)
end

function OverlayUI:ALIGNMENT_GRID_ENABLED()
    self:UpdateGrid()
end

function OverlayUI:ALIGNMENT_GRID_SIZE_CHANGED()
    if ParentAddon:GetAlignmentGridEnabled() then
        self:DrawGrid()
    end
end

function OverlayUI:LAYOUT_LOADED()
    if not (ParentAddon:Locked() or _G.InCombatLockdown()) then
        self.frame:Show()
    end
end

function OverlayUI:LAYOUT_UNLOADED()
    self.frame:Hide()
end

function OverlayUI:OnVisibilityChanged(visible)
    if visible then
        self.frame:Show()
        self:FadeIn()
    else
        self:FadeOut()
    end
end

--------------------------------------------------------------------------------
-- Properties
--------------------------------------------------------------------------------

function OverlayUI:SetVisible(visible)
    if self.visible ~= visible then
        self:OnVisibilityChanged(visible)
    end
end

function OverlayUI:GetFrame()
    return self.frame
end

--------------------------------------------------------------------------------
-- Actions
--------------------------------------------------------------------------------

function OverlayUI:FadeIn()
    if self.fadeOutSequence:IsPlaying() then
        self.fadeOutSequence:Stop()
    end

    if not self.fadeInSequence:IsPlaying() then
        self.fadeInSequence:Play()
    end
end

function OverlayUI:FadeOut()
    if self.fadeInSequence:IsPlaying() then
        self.fadeInSequence:Stop()
    end

    if not self.fadeOutSequence:IsPlaying() then
        self.fadeOutSequence:Play()
    end
end

function OverlayUI:UpdateGrid()
    if ParentAddon:GetAlignmentGridEnabled() then
        self:DrawGrid()
    else
        self:ClearGrid()
    end
end

local function SetLinePoint(line, point, relFrame, relPoint, x, y)
    if PixelUtil then
        PixelUtil.SetPoint(line, point, relFrame, relPoint, x, y)
    else
        line:SetPoint(point, relFrame, relPoint, x, y)
    end
end

local function SetLineWidth(line, width)
    if PixelUtil then
        PixelUtil.SetWidth(line, width, 1)
    else
        line:SetWidth(width)
    end
end

local function SetLineHeight(line, height)
    if PixelUtil then
        PixelUtil.SetHeight(line, height, 1)
    else
        line:SetHeight(height)
    end
end

function OverlayUI:DrawGrid()
    self:ClearGrid()

    local parent = self.frame
    local cx, cy = parent:GetCenter()
	local spacing = (parent:GetHeight() / ParentAddon:GetAlignmentGridSize())

    -- draw center lines
    local cvLine = self:AcquireGridLine()
    cvLine:SetColorTexture(GRID_HIGHLIGHT_COLOR:GetRGBA())
    SetLineWidth(cvLine, GRID_LINE_THICKNESS)
    SetLinePoint(cvLine, 'TOP', parent, 'TOPLEFT', cx, 0)
    SetLinePoint(cvLine, 'BOTTOM', parent, 'BOTTOMLEFT', cx, 0)

    local chLine = self:AcquireGridLine()
    chLine:SetColorTexture(GRID_HIGHLIGHT_COLOR:GetRGBA())
    SetLineHeight(chLine, GRID_LINE_THICKNESS)
    SetLinePoint(chLine, 'LEFT', parent, 'BOTTOMLEFT', 0, cy)
    SetLinePoint(chLine, 'RIGHT', parent, 'BOTTOMRIGHT', 0, cy)

    -- draw vertical lines
    for x = spacing, cx, spacing do
        local line = self:AcquireGridLine()
        line:SetColorTexture(GRID_COLOR:GetRGBA())
        SetLineWidth(line, GRID_LINE_THICKNESS)
        SetLinePoint(line, 'TOP', parent, 'TOPLEFT', cx + x, 0)
        SetLinePoint(line, 'BOTTOM', parent, 'BOTTOMLEFT', cx + x, 0)

        line = self:AcquireGridLine()
        line:SetColorTexture(GRID_COLOR:GetRGBA())
        SetLineWidth(line, GRID_LINE_THICKNESS)
        SetLinePoint(line, 'TOP', parent, 'TOPLEFT', cx - x, 0)
        SetLinePoint(line, 'BOTTOM', parent, 'BOTTOMLEFT', cx - x, 0)
    end

    -- draw horizontal lines
    for y = spacing, cy, spacing do
        local line = self:AcquireGridLine()
        line:SetColorTexture(GRID_COLOR:GetRGBA())
        SetLineHeight(line, GRID_LINE_THICKNESS)
        SetLinePoint(line, 'LEFT', parent, 'BOTTOMLEFT', 0, cy + y)
        SetLinePoint(line, 'RIGHT', parent, 'BOTTOMRIGHT', 0, cy + y)

        line = self:AcquireGridLine()
        line:SetColorTexture(GRID_COLOR:GetRGBA())
        SetLineHeight(line, GRID_LINE_THICKNESS)
        SetLinePoint(line, 'LEFT', parent, 'BOTTOMLEFT', 0, cy - y)
        SetLinePoint(line, 'RIGHT', parent, 'BOTTOMRIGHT', 0, cy - y)
    end
end

function OverlayUI:ClearGrid()
    local activeLines = self.activeGridLines

    if activeLines then
        for i = #activeLines, 1, -1 do
            self:ReleaseGridLine(activeLines[i])
            activeLines[i] = nil
        end
    end
end

function OverlayUI:AcquireGridLine()
    local inactiveLines = self.inactiveGridLines

    -- restore
    local line = inactiveLines and inactiveLines[#inactiveLines]
    if line then
        inactiveLines[#inactiveLines] = nil
    else
        line = self.frame:CreateTexture(nil, 'BACKGROUND', nil, 7)
    end

    -- add
    local activeLines = self.activeGridLines
    if activeLines then
        activeLines[#activeLines+1] = line
    else
        self.activeGridLines = { line }
    end

    line:Show()
    return line
end

function OverlayUI:ReleaseGridLine(line)
    line:ClearAllPoints()
    line:Hide()

    local inactiveLines = self.inactiveGridLines
    if inactiveLines then
        inactiveLines[#inactiveLines+1] = line
    else
        self.inactiveGridLines = { line }
    end
end

function OverlayUI:ShowDragFrames()
    for _, frame in ParentAddon.Frame:GetAll() do
        self:AcquireDragFrame():SetOwner(frame)
    end
end

function OverlayUI:HideDragFrames()
    local activeDragFrames = self.activeDragFrames

    if activeDragFrames then
        for i = #activeDragFrames, 1, -1 do
            self:ReleaseDragFrame(activeDragFrames[i])
            activeDragFrames[i] = nil
        end
    end
end

function OverlayUI:AcquireDragFrame()
    local inactiveDragFrames = self.inactiveDragFrames

    -- restore
    local frame = inactiveDragFrames and inactiveDragFrames[#inactiveDragFrames]
    if frame then
        inactiveDragFrames[#inactiveDragFrames] = nil
    else
        frame = Addon.DragFrame:Create(self.frame)
    end

    -- add
    local activeDragFrames = self.activeDragFrames
    if activeDragFrames then
        activeDragFrames[#activeDragFrames+1] = frame
    else
        self.activeDragFrames = { frame }
    end

    return frame
end

function OverlayUI:ReleaseDragFrame(frame)
    frame:SetOwner(nil)

    local inactiveFrames = self.inactiveDragFrames
    if inactiveFrames then
        inactiveFrames[#inactiveFrames+1] = frame
    else
        self.inactiveDragFrames = { frame }
    end
end

--------------------------------------------------------------------------------
-- exports
--------------------------------------------------------------------------------

Addon.OverlayUI = OverlayUI


text:
import { Request, Response, Next } from 'restify';
import { handleJsonData, handleErrors } from './helpers';
import * as sensorTypeValidator from '../validation/sensor-type';
import { sensorTypeRepository } from '../repositories';

export function addSensorType(req: Request, res: Response, next: Next) {
    req.body.unit = {
        name: req.body.unitName? req.body.unitName : null,
        description: req.body.unitDescription? req.body.unitDescription : null
    }
    sensorTypeValidator.validate(req.body, false)
    .then(sensorTypeRepository.create)
    .then(sensorTypes => handleJsonData(req, res, next, sensorTypes))
    .catch(err => handleErrors(next, err));
}

export function updateSensorType(req: Request, res: Response, next: Next) {
    req.body.id = req.params.id;
    req.body.unit = {
        name: req.body.unitName? req.body.unitName : null,
        description: req.body.unitDescription? req.body.unitDescription : null
    }
    sensorTypeValidator.validate(req.body)
    .then(sensorTypeRepository.update)
    .then(sensorTypes => handleJsonData(req, res, next, sensorTypes))
    .catch(err => handleErrors(next, err));
}

export function deleteSensorType(req: Request, res: Response, next: Next) {
    sensorTypeRepository.remove(req.params.id)
    .then(sensorType => handleJsonData(req, res, next, sensorType))
    .catch(err => handleErrors(next, err));
}

export function fetchSensorTypes(req: Request, res: Response, next: Next) {
    sensorTypeRepository.findAll()
    .then(sensorTypes => handleJsonData(req, res, next, sensorTypes))
    .catch(err => handleErrors(next, err));
}

export function getSensorType(req: Request, res: Response, next: Next) {
    sensorTypeRepository.find(req.params.id)
    .then(sensorType => handleJsonData(req, res, next, sensorType))
    .catch(err => handleErrors(next, err));
}


text:
<?php

declare(strict_types=1);

namespace WoohooLabs\Zen\Tests\Double;

use WoohooLabs\Zen\Config\EntryPoint\AbstractEntryPoint;

class TestEntryPoint extends AbstractEntryPoint
{
    /**
     * @return string[]
     */
    public function getClassNames(): array
    {
        return [];
    }
}


text:
CREATE OR REPLACE package pkg_oh_rate_and_base as

procedure get_oh_rate_and_base_for_per(av_proposal_number  IN osp$budget_details.PROPOSAL_NUMBER%TYPE,
		  					   av_version_number  IN osp$budget_details.VERSION_NUMBER%TYPE,
							   av_budget_period   IN osp$budget_details.BUDGET_PERIOD%TYPE,
							   cur_type IN OUT result_sets.cur_generic);

end;
/

CREATE OR REPLACE package body pkg_oh_rate_and_base as

PROCEDURE  get_oh_rate_and_base_for_per(av_proposal_number  IN osp$budget_details.PROPOSAL_NUMBER%TYPE,
		  					   av_version_number  IN osp$budget_details.VERSION_NUMBER%TYPE,
							   av_budget_period   IN osp$budget_details.BUDGET_PERIOD%TYPE,
           		         cur_type IN OUT result_sets.cur_generic)

IS

ls_modular_flag	varchar2(3);

begin

-- determine if this is a modular budget

SELECT MODULAR_BUDGET_FLAG
INTO   ls_modular_flag
FROM	 OSP$BUDGET
WHERE  PROPOSAL_NUMBER = av_proposal_number
AND    VERSION_NUMBER = av_version_number;

if ls_modular_flag = 'N' then

	OPEN cur_type FOR
     	select 	proposal_number,
            	version_number,
			 		budget_period,
   		   	osp$budget_rate_and_base.rate_class_code AS RATE_CLASS_CODE,
			 		osp$rate_class.description as DESCRIPTION,
		    		rate_type_code,
			 		applied_rate as APPLIED_RATE,
			 		sum(base_cost) BASE_COST,
			 		sum(base_cost_sharing) BASE_COST_SHARING,
			 		sum(calculated_cost) CALCULATED_COST,
			 		sum(calculated_cost_sharing) CALCULATED_COST_SHARING
		from   	osp$budget_rate_and_base, osp$rate_class
		where  	proposal_number = av_proposal_number
   	and      version_number = av_version_number
   	AND      budget_period = av_budget_period
   	and    	osp$budget_rate_and_base.rate_class_code = osp$rate_class.rate_class_code
   	and      rate_class_type = 'O'
		group by proposal_number, version_number, budget_period,
					osp$budget_rate_and_base.rate_class_code,
					osp$rate_class.description,
					rate_type_code, applied_rate;

 else
	--modular budget
   BEGIN
    OPEN cur_type FOR
		select 	proposal_number,
            	version_number,
			 		budget_period,
			 		description ,
			 		idc_rate as APPLIED_RATE,
			 		sum(idc_base) BASE_COST,
			 		sum(funds_requested) CALCULATED_COST
		from   	osp$budget_modular_idc
		where  	proposal_number = av_proposal_number
   	and      version_number = av_version_number
   	AND      budget_period = av_budget_period
		group by proposal_number, version_number, budget_period,
					description,
					idc_rate;

	END;
 end if;

end;

END;

/


text:
<!doctype html>

<meta charset = "utf-8" >
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name = description content = "File wrangler. Default index.html file. Opens HTML or Markdown files. Passes location.hash." >
<meta name = keywords content = "ShowDown,Markdown,AJAX,JavaScript,HTML,CSS,GitHub,FOSS" >
<meta name = date content = "2017-08-16" >
<title></title>

 ☰ slide

 Edit this file


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>com.mobile.restaurant.error</title>
<meta name="date" content="2017-08-30">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

com.mobile.restaurant.error

Enums

ApplicationErrorInfo


text:
package de.javagl.jgltf.model.io;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.junit.Test;

import de.javagl.jgltf.model.GltfModel;

/**
 * Tests for the {@link GltfModelWriter} class for glTF 2.0.

 *

 * The tests read a default glTF 2.0 model using the {@link GltfModelReader},
 * write it as default, embededd, and binary glTF, and compare the resulting
 * files to the files that contain the expected output.
 */
@SuppressWarnings("javadoc")
public class TestGltfModelWriterV2
{
    @Test
    public void testGltfToGltfV2() throws IOException
    {
        String basePath = "./src/test/resources/testModels/v2/";

        Path inputPath = Paths.get(basePath, "testBox/glTF");
        Path outputPath = Paths.get(basePath,
            "testBox/output-glTF-to-glTF");
        Files.createDirectories(outputPath);

        String inputFileName = "Box.gltf";
        String outputFileName = "Box.gltf";

        Path inputFile = Paths.get(inputPath.toString(), inputFileName);
        Path outputFile = Paths.get(outputPath.toString(), outputFileName);

        GltfModelReader gltfModelReader = new GltfModelReader();
        GltfModel gltfModel = gltfModelReader.read(inputFile.toUri());

        GltfModelWriter gltfModelWriter = new GltfModelWriter();
        gltfModelWriter.write(gltfModel, outputFile.toFile());

        TestUtils.assertFileEquals(
            inputPath.toString(), "Box.gltf",
            outputPath.toString(), "Box.gltf");

        TestUtils.assertFileEquals(
            inputPath.toString(), "Box0.bin",
            outputPath.toString(), "Box0.bin");
    }

    @Test
    public void testGltfToGltfEmbeddedV2() throws IOException
    {
        String basePath = "./src/test/resources/testModels/v2/";

        Path inputPath = Paths.get(basePath, "testBox/glTF");
        Path outputPath = Paths.get(basePath,
            "testBox/output-glTF-to-glTF-Embedded");
        Files.createDirectories(outputPath);
        Path referencePath = Paths.get(basePath, "testBox/glTF-Embedded");

        String inputFileName = "Box.gltf";
        String outputFileName = "Box.gltf";
        String referenceFileName = "Box.gltf";

        Path inputFile = Paths.get(inputPath.toString(), inputFileName);
        Path outputFile = Paths.get(outputPath.toString(), outputFileName);

        GltfModelReader gltfModelReader = new GltfModelReader();
        GltfModel gltfModel = gltfModelReader.read(inputFile.toUri());

        GltfModelWriter gltfModelWriter = new GltfModelWriter();
        gltfModelWriter.writeEmbedded(gltfModel, outputFile.toFile());

        TestUtils.assertFileEquals(
            referencePath.toString(), referenceFileName,
            outputPath.toString(), outputFileName);
    }

    @Test
    public void testGltfToGltfBinaryV2() throws IOException
    {
        String basePath = "./src/test/resources/testModels/v2/";

        Path inputPath = Paths.get(basePath, "testBox/glTF");
        Path outputPath = Paths.get(basePath,
            "testBox/output-glTF-to-glTF-Binary");
        Files.createDirectories(outputPath);
        Path referencePath = Paths.get(basePath, "testBox/glTF-Binary");

        String inputFileName = "Box.gltf";
        String outputFileName = "Box.glb";
        String referenceFileName = "Box.glb";

        Path inputFile = Paths.get(inputPath.toString(), inputFileName);
        Path outputFile = Paths.get(outputPath.toString(), outputFileName);

        GltfModelReader gltfModelReader = new GltfModelReader();
        GltfModel gltfModel = gltfModelReader.read(inputFile.toUri());

        GltfModelWriter gltfModelWriter = new GltfModelWriter();
        gltfModelWriter.writeBinary(gltfModel, outputFile.toFile());

        TestUtils.assertFileEquals(
            referencePath.toString(), referenceFileName,
            outputPath.toString(), outputFileName);
    }

}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Cahiers de La Maboké 4(1): 13 (1966)

#### Original name
null

### Remarks
null


text:
package org.kaaproject.kaa.demo.powerplant.data;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.kaaproject.kaa.demo.powerplant.pojo.DataPoint;
import org.kaaproject.kaa.demo.powerplant.pojo.DataReport;

import android.util.Log;
import android.content.Context;

import com.couchbase.lite.Manager;
import com.couchbase.lite.Database;
import com.couchbase.lite.CouchbaseLiteException;
import com.couchbase.lite.QueryRow;
import com.couchbase.lite.View;
import com.couchbase.lite.Mapper;
import com.couchbase.lite.Emitter;
import com.couchbase.lite.Query;
import com.couchbase.lite.QueryEnumerator;
import com.couchbase.lite.Query.IndexUpdateMode;
import com.couchbase.lite.android.AndroidContext;
import com.couchbase.lite.auth.Authenticator;
import com.couchbase.lite.auth.BasicAuthenticator;
import com.couchbase.lite.replicator.Replication;

public class CouchBaseDataEndpoint extends AbstractDataEndpoint {
	private static final String TAG = CouchBaseDataEndpoint.class.getSimpleName();

	private static final int MAX_QUERY_SIZE = 300;
	private static final String ZONES_FIELD = "zones";
	private static final String TIMESTAMP_FIELD = "ts";
	private static final String ZONE_ID_FIELD = "zoneId";
	private static final String COUNT_FIELD = "count";
	private static final String SUM_FIELD = "sum";
	private static final String VIEW_NAME = "powerplant_view";

	private URL dbURL;
	private Context parentContext;
	private Manager manager;
	private Database database;
	private Replication pull;

	public CouchBaseDataEndpoint(Context parentContext, String dbURLStr, String localDBName,
			String gatewayName, String channelName, String username, String password) {
		this.parentContext = parentContext;
		Log.i(TAG, "Creating new CouchBaseDataEndpoint");

		try {
			this.manager = new Manager(new AndroidContext(parentContext), Manager.DEFAULT_OPTIONS);
			Log.d(TAG, "Manager created");

			database = manager.getDatabase(localDBName);

			URL dbURL = new URL(dbURLStr + gatewayName);
			pull = database.createPullReplication(dbURL);
            List<String> channels = Arrays.asList(channelName);
            Authenticator auth = new BasicAuthenticator(username, password);
            pull.setAuthenticator(auth);
            pull.setChannels(channels);
            pull.setContinuous(true);
			pull.start();

		} catch (IOException e) {
			Log.e(TAG, "Can't start communication with db", e);
			throw new RuntimeException(e);
		} catch (CouchbaseLiteException e) {
			Log.e(TAG, "Can't get database with name: " + localDBName, e);
			throw new RuntimeException(e);
		}

		View reportView = database.getView(VIEW_NAME);
		reportView.setMap(new Mapper() {
			@SuppressWarnings("unchecked")
            @Override
            public void map(Map<String, Object> document, Emitter emitter) {
                Object timeValue = document.get(TIMESTAMP_FIELD);
                Long timestamp = timeValue instanceof Number ? (Long) ((Number) timeValue).longValue() :
                        (timeValue instanceof String ? Long.parseLong((String) timeValue) : null);
                if (timestamp != null) {
                    emitter.emit(timestamp, document);
                }
            }
        }, "4");
	}

	@Override
	public DataReport getLatestData() {
		List<DataReport> reports = getHistoryDataWithLimit(0, 1);
		DataReport report = null;
		if (reports != null && !reports.isEmpty()) {
			report = reports.get(0);
//			Log.i(TAG, report.toString());
		} else {
			Log.i(TAG, "no data");
		}

		return report;
	}

	@Override
	public List<DataReport> getHistoryData(long fromTime) {
		return getHistoryDataWithLimit(fromTime, MAX_QUERY_SIZE);
	}

	private List<DataReport> getHistoryDataWithLimit(long fromTime, int limit) {
        Query query = database.getView(VIEW_NAME).createQuery();
        query.setIncludeDeleted(false);
        query.setDescending(true);
        query.setLimit(limit);
        query.setIndexUpdateMode(IndexUpdateMode.BEFORE);

        List<DataReport> reports = new ArrayList<DataReport>();
        try {
			QueryEnumerator enumerator = query.run();

			while (enumerator.hasNext()) {
				QueryRow row = enumerator.next();
				DataReport report = toDataReport(row);
				reports.add(report);
			}

		} catch (CouchbaseLiteException e) {
			Log.e(TAG, "Some problem has occured while enumerating result set");
		}

		return reports;
	}

	@SuppressWarnings("unchecked")
	private DataReport toDataReport(QueryRow row) {
		Map<String, Object> reportVals = (Map<String, Object>) row.getValue();
        List<Object> zones = (List<Object>) reportVals.get(ZONES_FIELD);

        Object timestampVal = reportVals.get(TIMESTAMP_FIELD);
        Long timestamp = timestampVal instanceof Number ? (Long)((Number)timestampVal).longValue() :
                (timestampVal instanceof String ? Long.parseLong((String)timestampVal) : null);

        List<DataPoint> dataPoints = new ArrayList<>();
        int sumPanelCount = 0;
        for (Object zoneObj : zones) {
            Map<String, Object> sample = (Map<String, Object>) zoneObj;
            int curPanelCount = (int) sample.get(COUNT_FIELD);
            DataPoint point = new DataPoint((int) sample.get(ZONE_ID_FIELD),
            		curPanelCount * 1000, ((Double) sample.get(SUM_FIELD)).floatValue());
            dataPoints.add(point);
            sumPanelCount += curPanelCount;
        }

        return new DataReport(timestamp, dataPoints, getConsumption(sumPanelCount));
	}

	@Override
	public void stop() {
		if (pull != null) {
			pull.stop();
		}

		if (database != null) {
			database.close();
		}

		if (manager != null) {
			manager.close();
		}
	}
}


text:
package com.vmware.vim25;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for RemoteDeviceNotSupported complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="RemoteDeviceNotSupported">
 *   <complexContent>
 *     <extension base="{urn:vim25}DeviceNotSupported">
 *       <sequence>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "RemoteDeviceNotSupported")
public class RemoteDeviceNotSupported
    extends DeviceNotSupported
{

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Treehopper;
using Treehopper.Libraries;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using Treehopper.Libraries.Sensors.Temperature;
using Treehopper.Libraries.Sensors.Optical;
using Treehopper.Libraries.Sensors;
using Treehopper.Libraries.Sensors.Pressure;
using Treehopper.Libraries.Motors;

namespace TreehopperApp.Pages.Libraries
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class Servo : LibraryComponent
    {
        public Pwm SelectedPin { get; set; }
        public TreehopperUsb Board { get; }

        public HobbyServo HobbyServo { get; set; }

        public Servo(LibrariesPage page, TreehopperUsb Board = null) : base("Servo", page)
        {
            this.Board = Board;
            InitializeComponent();
            BindingContext = this;
        }

        public Servo() : base("Servo", new LibrariesPage())
        {
            InitializeComponent();
        }

        public override async Task Start()
        {
            HobbyServo = new HobbyServo(SelectedPin);
            HobbyServo.Angle = 90;
            OnPropertyChanged("HobbyServo");
        }

        public override async Task Stop()
        {
            HobbyServo?.Dispose();
            HobbyServo = null;
        }

        public override void Dispose()
        {

        }

        public override async Task Update()
        {

        }
    }
}


text:
namespace Zu.ChromeDevTools.Page
{
    using Newtonsoft.Json;

    /// <summary>
    /// Emitted only when `page.interceptFileChooser` is enabled.
    /// </summary>
    public sealed class FileChooserOpenedEvent : IEvent
    {
        /// <summary>
        /// Id of the frame containing input node.
        /// </summary>
        [JsonProperty("frameId")]
        public string FrameId
        {
            get;
            set;
        }
        /// <summary>
        /// Input node id.
        /// </summary>
        [JsonProperty("backendNodeId")]
        public long BackendNodeId
        {
            get;
            set;
        }
        /// <summary>
        /// Input mode.
        /// </summary>
        [JsonProperty("mode")]
        public string Mode
        {
            get;
            set;
        }
    }
}


text:
body {
  padding: 0 20px;
  font-family: "Lucida Sans", "Lucida Grande", Verdana, Arial, sans-serif;
  font-size: 13px;
}

body.frames { padding: 0 5px; }

h1 { font-size: 25px; border-top: 0px; margin-top: 0; padding-top: 4px; }
h1 small { color: #888; font-size: 18px }

h2 {
  padding: 0;
  padding-bottom: 3px;
  border-bottom: 1px #aaa solid;
  font-size: 1.4em;
  margin: 1.8em 0 0.5em;
}

.clear { clear: both; }

li.r1 { background: #f0f0f0; }
li.r2 { background: #fafafa; }

ul.summary_links {
  margin: 0em;
  margin-bottom: 1em;
  padding: 0em;
}

ul.summary_links li {
  display: inline-block;
  list-style-type: none;
  text-align: center;
  width: 7em;
  background: #f0f0f0;
}

div.docstring, p.docstring { margin-right: 6em; }
.docstring h1, .docstring h2, .docstring h3, .docstring h4 { padding: 0; border: 0; border-bottom: 0; }
.docstring h1 { font-size: 1.3em; }
.docstring h2 { font-size: 1.2em; }
.docstring h3, .docstring h4 { font-size: 1em; padding-top: 10px; }
.docstring pre, .codeblock, .elixir {
  padding: 0.5em;
  border: #ffe0bb dotted 1px;
  background: #fffde8;
  display: block;
}

div.breadcrumbs {
  padding-bottom: 0.5em;
}

div.detail_header {
  background: #e5e8ff; border: 1px solid #d8d8e5; -moz-border-radius: 3px; -webkit-border-radius: 3px;
  padding: 6px 10px; margin-top: 18px;
}

span.signature {
  font-size: 1.1em; font-weight: normal; font-family: Monaco, Consolas, Courier, monospace;
}

div.detail_header_links {
  float: right;
}

span.detail_type {
  font-size: 0.9em; font-style: italic;
}

a.detail_link {
  padding-left: 0.3em;
}

a.to_top_link {
  padding-left: 0.3em; font-size: 1em; font-weight: normal;
}

ul.spec {
  font-size: 1.0em; font-weight: bold; font-family: Courier, monospace;
  padding: 6px 10px; padding-left: 25px; list-style-type: none;
}

a:link, a:visited { text-decoration: none; color: #05a; }
a:hover { color: #27c; }

.detail { border-top: 1px dotted #aaa; margin-top: 15px; padding-top: 0; }
.detail:nth-child(2) { border: 0; }

.type_detail {
  margin-top: 15px; padding-top: 0;
}
.type_detail > p.typespec {
  font-size: 1.0em; font-weight: bold; font-family: Courier, monospace;
}
.type_detail > div.typespec_doc {
  margin-left: 3em;
}

table {
  border: 1px solid #aaaaaa;
  border-collapse: collapse;
  margin-top: 1em;
}

table tr:nth-child(odd) { background: #f0f0f0; }
table tr:nth-child(even) { background: #fafafa; }

table th {
  background: #fafafa;
}

table th, table td {
  border: 1px solid #dddddd;
  padding: 0.4em 1em 0.4em 0.4em;
}

/* Summary */
ul.summary {
  list-style: none;
  font-family: monospace;
  font-size: 1em;
  line-height: 1.5em;
  margin: 0;
  padding: 0;
}
ul.summary li { display: inline-block; margin: 0px 5px 0px 0px; line-height: 2.6em;}
ul.summary a:link, ul.summary a:visited {
  text-decoration: none; font-size: 1.1em;
}
ul.summary .summary_signature {
  padding: 5px 7px; padding-right: 4px;
  background: #eaeaff; border: 1px solid #dfdfe5;
  -moz-border-radius: 3px; -webkit-border-radius: 3px;
}
ul.summary .summary_signature:hover { background: #eeeeff; cursor: pointer; }

table.summary { border: 0; border-collapse: separate; }
table.summary tr:nth-child(odd) { background: #f0f0f0; }
table.summary tr:nth-child(even) { background: #fafafa; }
table.summary tr td { border: 0; padding-top: 0.5em; padding-bottom: 0.5em; }

td.summary_signature { padding-right: 0.5em; }
td.summary_synopsis { padding-left: 0.5em; }
td.summary_synopsis p { margin: 0em 0em; }

/* File contents */
#filecontents li > p, .docstring li > p { margin: 0px; }
#filecontents ul, .docstring ul { padding-left: 20px; }

#filecontents dl, .docstring dl { border: 1px solid #ccc; }
#filecontents dt, .docstring dt { background: #ddd; font-weight: bold; padding: 3px 5px; }
#filecontents dd, .docstring dd { padding: 5px 0px; margin-left: 18px; }
#filecontents dd > p, .docstring dd > p { margin: 0px; }
#filecontents dl.box, dl.box {
  border: 0;
  width: 520px;
  font-size: 1em;
}
#filecontents dl.box dt, dl.box dt {
  float: left;
  display: block;
  width: 100px;
  margin: 0;
  text-align: right;
  font-weight: bold;
  background: transparent;
  border: 1px solid #aaa;
  border-width: 1px 0px 0px 1px;
  padding: 6px 0;
  padding-right: 10px;
}
#filecontents dl.box dd, dl.box dd {
  float: left;
  display: block;
  width: 380px;
  margin: 0;
  padding: 6px 0;
  padding-right: 20px;
  border: 1px solid #aaa;
  border-width: 1px 1px 0 0;
}
#filecontents dl.box .last, dl.box .last {
  border-bottom: 1px solid #aaa;
}
#filecontents dl.box .r1, dl.box .r1 { background: #eee; }

/* Footer */
#footer { margin-top: 15px; border-top: 1px solid #ccc; text-align: center; padding: 7px 0; color: #999; }

/* TOC */
#toc {
  padding: 20px; padding-right: 30px; border: 1px solid #ddd; float: right; background: #fff; margin-left: 20px; margin-bottom: 20px;
  max-width: 300px;
  -webkit-box-shadow: -2px 2px 6px #bbb;
  -moz-box-shadow: -2px 2px 6px #bbb;
  z-index: 5000;
  position: relative;
}
#toc.nofloat { float: none; max-width: none; border: none; padding: 0; margin: 20px 0; -webkit-box-shadow: none; -moz-box-shadow: none; }
#toc.nofloat.hidden { padding: 0; background: 0; margin-bottom: 5px; }
#toc .title { margin: 0; }
#toc ol { padding-left: 1.8em; }
#toc li { font-size: 1.1em; line-height: 1.7em; }
#toc > ol > li { font-size: 1.1em; font-weight: bold; }
#toc ol > ol { font-size: 0.9em; }
#toc ol ol > ol { padding-left: 2.3em; }
#toc ol + li { margin-top: 0.3em; }
#toc.hidden { padding: 10px; background: #f6f6f6; -webkit-box-shadow: none; -moz-box-shadow: none; }
#filecontents h1 + #toc.nofloat { margin-top: 0; }


text:
package com.google.schemaorg;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMultimap;
import com.google.schemaorg.core.Thing;

import java.util.List;

import javax.annotation.Nullable;

/**
 * Interface of JSON-LD node.
 */
public interface JsonLdNode extends ValueType {

  /**
   * Builder interface of JSON-LD node.
   */
  public interface Builder extends ValueType.Builder {

    /**
     * Add a value to {@literal @context} in current JSON-LD node.
     */
    Builder addJsonLdContext(@Nullable JsonLdContext context);

    /**
     * Add a value to {@literal @context} in current JSON-LD node.
     */
    Builder addJsonLdContext(@Nullable JsonLdContext.Builder builder);

    /**
     * Set value to {@literal @id} in current JSON-LD node.
     */
    Builder setJsonLdId(@Nullable String value);

    /**
     * Add value to {@literal @reverse} in current JSON-LD node.
     * @param property The full or short name of the property.
     * @param obj The object that the property is set in.
     */
    Builder setJsonLdReverse(String property, Thing obj) throws SchemaOrgException;

    /**
     * Add value to {@literal @reverse} in current JSON-LD node.
     * @param property The full or short name of the property.
     * @param builder The object builder that the property is set in.
     */
    Builder setJsonLdReverse(String property, Thing.Builder builder) throws SchemaOrgException;
  }

  /**
   * Whether current JSON-LD node contains {@literal @id} value.
   */
  boolean containsJsonLdId();

  /**
   * Returns the list of JSON-LD context. Empty list is returned if
   * {@literal @context} is not set in current JSON-LD node.
   */
  ImmutableList<ValueType> getJsonLdContextList();

  /**
   * Returns the value of {@literal @id}. Null value means either
   * {@literal @id} value is null or current JSON-LD node doesn't contain
   * {@literal @id} value.
   */
  @Nullable
  String getJsonLdId() throws SchemaOrgException;

  /**
   * Returns the value of {@literal @reverse}. Empty multimap is returned if
   * {@literal @reverse} is not set in current JSON-LD node.
   */
  ImmutableMultimap<String, Thing> getJsonLdReverseMap();
}


text:
package org.apache.hadoop.hbase.types;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;

import org.apache.hadoop.hbase.HBaseClassTestRule;
import org.apache.hadoop.hbase.testclassification.MiscTests;
import org.apache.hadoop.hbase.testclassification.SmallTests;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.Order;
import org.apache.hadoop.hbase.util.PositionedByteRange;
import org.apache.hadoop.hbase.util.SimplePositionedMutableByteRange;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.experimental.categories.Category;

@Category({ MiscTests.class, SmallTests.class })
public class TestOrderedBlob {
  @ClassRule
  public static final HBaseClassTestRule CLASS_RULE =
    HBaseClassTestRule.forClass(TestOrderedBlob.class);

  private static final byte[][] VALUES =
    new byte[][] { null, Bytes.toBytes(""), Bytes.toBytes("1"), Bytes.toBytes("22"),
      Bytes.toBytes("333"), Bytes.toBytes("4444"), Bytes.toBytes("55555"), Bytes.toBytes("666666"),
      Bytes.toBytes("7777777"), Bytes.toBytes("88888888"), Bytes.toBytes("999999999"), };

  @Test
  public void testIsSkippableFalse() {
    final DataType<byte[]> type = new OrderedBlob(Order.ASCENDING);

    assertFalse(type.isSkippable());
  }

  @Test
  public void testEncodedLength() {
    PositionedByteRange buff = new SimplePositionedMutableByteRange(20);
    for (final DataType<byte[]> type : new OrderedBlob[] { new OrderedBlob(Order.ASCENDING),
      new OrderedBlob(Order.DESCENDING) }) {
      for (final byte[] val : VALUES) {
        buff.setPosition(0);
        type.encode(buff, val);
        assertEquals("encodedLength does not match actual, " + Bytes.toStringBinary(val),
          buff.getPosition(), type.encodedLength(val));
      }
    }
  }

  @Test
  public void testEncodedClassByteArray() {
    final DataType<byte[]> type = new OrderedBlob(Order.ASCENDING);

    assertEquals(byte[].class, type.encodedClass());
  }
}


text:
package osmedile.intellij.stringmanip.escaping;

import org.junit.experimental.theories.DataPoints;
import org.junit.experimental.theories.FromDataPoints;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;

import java.util.stream.IntStream;

import static org.junit.Assert.assertEquals;

@RunWith(Theories.class)
public class EscapeCSharpTest {
    //
    // Data
    //

    public static String[] raw = new String[]{
            "",
            "All your base are belong to us",
            "\0\u0007\b\f\t\u000B\n\r\"{}",
            "\u007F\u0080\uDEAD\uFFFF",
    };

    public static String[] regular = new String[]{
            "",
            "All your base are belong to us",
            "\\0\\a\\b\\f\\t\\v\\n\\r\\\"{}",
            "\u007F\\u0080\\uDEAD\\uFFFF",
    };

    public static String[] verbatim = new String[]{
            "",
            "All your base are belong to us",
            "\0\u0007\b\f\t\u000B\n\r\"\"{}",
            "\u007F\u0080\uDEAD\uFFFF",
    };

    public static String[] interpolated = new String[]{
            "",
            "All your base are belong to us",
            "\\0\\a\\b\\f\\t\\v\\n\\r\\\"{{}}",
            "\u007F\\u0080\\uDEAD\\uFFFF",
    };

    public static String[] interpolatedVerbatim = new String[]{
            "",
            "All your base are belong to us",
            "\0\u0007\b\f\t\u000B\n\r\"\"{{}}",
            "\u007F\u0080\uDEAD\uFFFF",
    };

    //
    // Tests
    //

    @Theory
    public void escapeRegular(@FromDataPoints("regular") String[] rawEscaped) {
        EscapeCSharpRegularAction action = new EscapeCSharpRegularAction();
        assertEquals(rawEscaped[1], action.test_transformByLine(rawEscaped[0]));
    }

    @Theory
    public void escapeVerbatim(@FromDataPoints("verbatim") String[] rawEscaped) {
        EscapeCSharpVerbatimAction action = new EscapeCSharpVerbatimAction();
        assertEquals(rawEscaped[1], action.test_transformByLine(rawEscaped[0]));
    }

    @Theory
    public void escapeInterpolated(@FromDataPoints("interpolated") String[] rawEscaped) {
        EscapeCSharpInterpolatedAction action = new EscapeCSharpInterpolatedAction();
        assertEquals(rawEscaped[1], action.test_transformByLine(rawEscaped[0]));
    }

    @Theory
    public void escapeInterpolatedVerbatim(@FromDataPoints("interpolatedVerbatim") String[] rawEscaped) {
        EscapeCSharpInterpolatedVerbatimAction action = new EscapeCSharpInterpolatedVerbatimAction();
        assertEquals(rawEscaped[1], action.test_transformByLine(rawEscaped[0]));
    }

    //
    // Helpers
    //

    @DataPoints("regular")
    public static String[][] rawToRegular() {
        return rawToEscaped(regular);
    }

    @DataPoints("verbatim")
    public static String[][] rawToVerbatim() {
        return rawToEscaped(verbatim);
    }

    @DataPoints("interpolated")
    public static String[][] rawToInterpolated() {
        return rawToEscaped(interpolated);
    }

    @DataPoints("interpolatedVerbatim")
    public static String[][] rawToInterpolatedVerbatim() {
        return rawToEscaped(interpolatedVerbatim);
    }

    public static String[][] rawToEscaped(String[] escaped) {
        return IntStream
                .range(0, raw.length)
                .mapToObj(i -> new String[] {raw[i], escaped[i]})
                .toArray(String[][]::new);
    }
}


text:
using System;
using System.Collections.Generic;
using System.Globalization;

namespace Config.Net.TypeParsers
{
   class DoubleParser : ITypeParser
   {
      public IEnumerable<Type> SupportedTypes => new[] { typeof(double) };

      public bool TryParse(string? value, Type t, out object? result)
      {
         double dr;
         bool parsed = double.TryParse(value, NumberStyles.Float, TypeParserSettings.DefaultCulture, out dr);
         result = dr;
         return parsed;

      }

      public string? ToRawString(object? value)
      {
         return ((double?)value)?.ToString(TypeParserSettings.DefaultNumericFormat, TypeParserSettings.DefaultCulture);
      }
   }
}


text:
using System;
using System.Collections.Generic;
using Newtonsoft.Json;

namespace Avalara.AvaTax.RestClient
{
    /// <summary>
    /// Represents information about a type of telecommunications transaction
    /// </summary>
    public class CommunicationsTransactionTypeModel
    {
        /// <summary>
        /// The numeric Id of the transaction type.
        /// </summary>
        public Int32 transactionTypeId { get; set; }

        /// <summary>
        /// The name of the transaction type.
        /// </summary>
        [JsonProperty(PropertyName = "AvaTax.Communications.TransactionType")]
        public String TransactionType { get; set; }

        /// <summary>
        /// Convert this object to a JSON string of itself
        /// </summary>
        /// <returns>A JSON string of this object</returns>
        public override string ToString()
        {
            return JsonConvert.SerializeObject(this, new JsonSerializerSettings() { Formatting = Formatting.Indented });
        }
    }
}


text:
var async = require('async');
var spawn = require('child_process').spawn;

async.waterfall(
	[
		function(callback){
			var child = spawn('casperjs',['./user.casper.js'],{
				cwd: __dirname,
			});
			child.stdout.on('end', function(){
				process.stdin.end();
				callback(null);
			});
			child.stdout.pipe(process.stdout);
			process.stdin.pipe(child.stdin);
		},
		function(callback){
			var child = spawn('casperjs',['./confirm.casper.js'],{
				cwd: __dirname,
			});
			child.stdout.on('end', function(){
				process.stdin.end();
				callback(null);
			});
			child.stdout.pipe(process.stdout);
			process.stdin.pipe(child.stdin);
		},
		function(callback){
			var child = spawn('casperjs',['./reset.casper.js'],{
				cwd: __dirname,
			});
			child.stdout.on('end', function(){
				process.stdin.end();
				callback(null);
			});
			child.stdout.pipe(process.stdout);
			process.stdin.pipe(child.stdin);
		},
		function(callback){
			var child = spawn('casperjs',['./admin.casper.js'],{
				cwd: __dirname,
			});
			child.stdout.on('end', function(){
				process.stdin.end();
				callback(null);
			});
			child.stdout.pipe(process.stdout);
			process.stdin.pipe(child.stdin);
		},
	],
	function(err,result){
		if(err) console.log(err);
	}
);


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using JSONAPI.Documents;
using Newtonsoft.Json;

namespace JSONAPI.Json
{
    /// <summary>
    /// Default implementation of IResourceCollectionDocumentFormatter
    /// </summary>
    public class ResourceCollectionDocumentFormatter : IResourceCollectionDocumentFormatter
    {
        private IResourceObjectFormatter _resourceObjectFormatter;
        private IMetadataFormatter _metadataFormatter;
        private const string PrimaryDataKeyName = "data";
        private const string RelatedDataKeyName = "included";
        private const string MetaKeyName = "meta";

        /// <summary>
        /// Creates a ResourceCollectionDocumentFormatter
        /// </summary>
        public ResourceCollectionDocumentFormatter()
        {

        }

        /// <summary>
        /// Creates a ResourceCollectionDocumentFormatter
        /// </summary>
        /// <param name="resourceObjectFormatter"></param>
        /// <param name="metadataFormatter"></param>
        public ResourceCollectionDocumentFormatter(IResourceObjectFormatter resourceObjectFormatter, IMetadataFormatter metadataFormatter)
        {
            _resourceObjectFormatter = resourceObjectFormatter;
            _metadataFormatter = metadataFormatter;
        }

        /// <summary>
        /// The formatter to use for resource objects found in this document
        /// </summary>
        /// <exception cref="InvalidOperationException"></exception>
        public IResourceObjectFormatter ResourceObjectFormatter
        {
            get
            {
                return _resourceObjectFormatter ?? (_resourceObjectFormatter = new ResourceObjectFormatter());
            }
            set
            {
                if (_resourceObjectFormatter != null) throw new InvalidOperationException("This property can only be set once.");
                _resourceObjectFormatter = value;
            }
        }

        /// <summary>
        /// The formatter to use for document-level metadata
        /// </summary>
        /// <exception cref="InvalidOperationException"></exception>
        public IMetadataFormatter MetadataFormatter
        {
            get
            {
                return _metadataFormatter ?? (_metadataFormatter = new MetadataFormatter());
            }
            set
            {
                if (_metadataFormatter != null) throw new InvalidOperationException("This property can only be set once.");
                _metadataFormatter = value;
            }
        }

        public Task Serialize(IResourceCollectionDocument document, JsonWriter writer)
        {
            writer.WriteStartObject();

            if (document.Metadata != null)
            {
                writer.WritePropertyName(MetaKeyName);
                MetadataFormatter.Serialize(document.Metadata, writer);
            }

            writer.WritePropertyName(PrimaryDataKeyName);

            writer.WriteStartArray();
            foreach (var resourceObject in document.PrimaryData)
            {
                ResourceObjectFormatter.Serialize(resourceObject, writer);
            }
            writer.WriteEndArray();

            if (document.RelatedData != null && document.RelatedData.Any())
            {
                writer.WritePropertyName(RelatedDataKeyName);
                writer.WriteStartArray();
                foreach (var resourceObject in document.RelatedData)
                {
                    ResourceObjectFormatter.Serialize(resourceObject, writer);
                }
                writer.WriteEndArray();
            }

            writer.WriteEndObject();

            writer.Flush();

            return Task.FromResult(0);
        }

        public async Task<IResourceCollectionDocument> Deserialize(JsonReader reader, string currentPath)
        {
            if (reader.TokenType != JsonToken.StartObject)
                throw new JsonSerializationException("Document root is not an object!");

            IResourceObject[] primaryData = null;
            IMetadata metadata = null;

            while (reader.Read())
            {
                if (reader.TokenType != JsonToken.PropertyName) break;

                // Has to be a property name
                var propertyName = (string)reader.Value;
                reader.Read();

                switch (propertyName)
                {
                    case RelatedDataKeyName:
                        // TODO: If we want to capture related resources, this would be the place to do it
                        reader.Skip();
                        break;
                    case PrimaryDataKeyName:
                        primaryData = await DeserializePrimaryData(reader, currentPath + "/" + PrimaryDataKeyName);
                        break;
                    case MetaKeyName:
                        metadata = await MetadataFormatter.Deserialize(reader, currentPath + "/" + MetaKeyName);
                        break;
                    default:
                        reader.Skip();
                        break;
                }
            }

            return new ResourceCollectionDocument(primaryData ?? new IResourceObject[] { }, new IResourceObject[] { }, metadata);
        }

        private async Task<IResourceObject[]> DeserializePrimaryData(JsonReader reader, string currentPath)
        {
            if (reader.TokenType != JsonToken.StartArray)
                throw new JsonSerializationException("Expected an array, but encountered " + reader.TokenType);

            var primaryData = new List<IResourceObject>();

            var index = 0;
            while (reader.Read())
            {
                if (reader.TokenType == JsonToken.EndArray)
                    break;

                var resourceObject = await ResourceObjectFormatter.Deserialize(reader, currentPath + "/" + index);
                primaryData.Add(resourceObject);

                index++;
            }

            return primaryData.ToArray();
        }
    }
}


text:
/*
Title: Deploying Raneto to Heroku
Sort: 9
*/

**Table of Contents**

- [Prerequisites](#prerequisites)
- [Login to Heroku](#login-to-heroku)
- [Create a Procfile](#create-a-procfile)
- [Create a Git Repo](#create-a-git-repo)
- [Deploy Raneto to Heroku](#deploy-raneto-to-heroku)
- [Further Reading](#further-reading)

[Heroku](https://www.heroku.com) is a cloud hosting platform which allows you to host your code for
free (for 1 dyno, see [pricing](https://www.heroku.com/pricing) for more info). In this tutorial we
are going to use Heroku to host our Raneto Knowledgebase.

## Prerequisites

Before we get going there are a few things we need to make sure we have in place first:

1. We are going to assume you have already [installed](%base_url%/install/installing-raneto) and setup Raneto on your local machine
2. You are going to need a [Heroku user account](https://signup.heroku.com/signup) (its free)
3. You will also need to have the [Heroku Toolbelt](https://toolbelt.heroku.com) installed

## Login to Heroku

First you need to open a command shell in the root of your Raneto install. You then need to login to Heroku
using the `heroku login` command. You will be asked to setup some `ssh` keys if you haven't done so already.
Just follow the instructions.

	$ heroku login
	Enter your Heroku credentials.
	Email: zeke@example.com
	Password:
	Could not find an existing public key.
	Would you like to generate one? [Yn]
	Generating new SSH public key.
	Uploading ssh public key /Users/adam/.ssh/id_rsa.pub

## Create a Procfile

Next you will need to create a `Procfile` in the root of your Raneto install. This lets Heroku know how to
run the app. Simple create a file called `Procfile` (with no extension) and add the following line:

    web: node bin/www

This lets Heroku know we want to run a `web` server and the node command we need to start the app.

## Create a Git Repo

Heroku works by deploying a Git repository to their servers. So we need to make your Raneto install is a
Git repository. This also means you will need to commit any changes you make to Git before deploying
them to Heroku. Thankfully this is easy to setup.

	$ git init
	$ git add .
	$ git commit -m "init"

Remeber you will need to `git commit` any future changes you make before deployment.

## Deploy Raneto to Heroku

First we need to create the app in Heroku by running:

	$ heroku create
	Creating sharp-rain-871... done, stack is cedar
	http://sharp-rain-871.herokuapp.com/ | git@heroku.com:sharp-rain-871.git
	Git remote heroku added

Heroku will assign you a random subdomain that your app will be available at.

Next we need to "push" our Git repository to Heroku by running:

    $ git push heroku master

You should see Heroku do a bunch of stuff and successfully deploy your app. Note that you will need to run the
`git push heroku master` command every time you want to publish changes to your Raneto site.

Finally we just need to make sure that we have one dyno running our `web` process. This command only
needs to be run this one time.

    $ heroku ps:scale web=1

You can now visit your live Raneto install in the browser by running the `heroku open` command.

	$ heroku open
	Opening sharp-rain-871... done

## Further Reading

* [Getting Started with Node.js on Heroku](https://devcenter.heroku.com/articles/getting-started-with-nodejs)
* [Process Types and the Procfile](https://devcenter.heroku.com/articles/procfile)
* [Dynos and the Dyno Manager](https://devcenter.heroku.com/articles/dynos)
* [Custom Domains](https://devcenter.heroku.com/articles/custom-domains)