text:
title: "WebRTC Video & Data Streaming"
excerpt: "WebRTC, Golang, Javascript, HTML, Docker"
header:
  teaser: /assets/images/webrtc_01.jpg
gallery_01:
  - url: /assets/images/webrtc_02.jpg
    image_path: /assets/images/webrtc_02.jpg
  - url: /assets/images/webrtc_03.jpg
    image_path: /assets/images/webrtc_03.jpg
date: "2019-10-01"
---

## Introduction

In this project, we will develop a real-time video and data broadcasting service using WebRTC in Golang. Video feed will be streamed from the publisher's web camera through WebRTC media API to multiple browser-based end clients. Simultaneously, some accompanying data will be streamed from the publisher to the multiple end-clients through the WebRTC data channel. All the code is containerized using Dockers.

The following tools will be used in this project:
+ WebRTC
+ Docker
+ Golang
+ Javascript
+ HTML

## Learning Outcome

Find the source code in the [repository](https://github.com/Adaickalavan/Go-WebRTC).

At the end of this project, we should be able to:
+ Build a WebRTC video and data broadcasting service in Go.
+ Build a signalling server in Go and automate the exchange of SDPs (Session Description Protocol) between the webpages and the server.
+ Write and deploy Javascript in the browser to initiate WebRTC connections and to communicate with the signalling server.
+ Host the `Publish` and `Join` webpages on a Go server.
+ Remember the publisher and client so as to reconnect upon a loss of connection.
+ Perform dependency management using Go Module.

## Project Structure

The project structure is as follows:

```text
Go-WebRTC                    # Main folder
├── handler
│   └── respond.go           # Generate HTTP responses
├── static
│   └── js
│       └── connect.js       # Javascript to establish WebRTC connection
├── template
│   ├── join.html            # Webpage template for client to join the broadcast
│   └── publish.html         # Webpage template for publisher to broadcast
├── .env
├── docker-compose.yml       # Docker deployment
├── dockerfile               # To create Docker container
├── go.mod
├── go.sum
├── main.go                  # Main file
└── README.md
```

## Instructions
1. Download the code using `git clone https://github.com/Adaickalavan/Go-WebRTC.git`
1. To run locally:
    + Ensure `GO111MODULE=on` in your terminal.
    + Run `go install` in the project folder.
    + Then run the executable, i.e., `Go-WebRTC`.
1. To run the code in Docker, do the following:
    + Run `docker build -t gowebrtc .` in the project folder.
    + Then run `docker-compose up`.
1. Go to `localhost:8088/publish` web page which will start capturing video using your webcam. This video, along with some accompanying data, will be broadcast to multiple clients.
1. Then open another tab in your browser, and go to `localhost:8088/join` to see the broadcasted video and data. Multiple clients can view the broadcast by joining the same weblink.
1. The video and data connection will dynamically resume if the publisher or client disconnects and rejoins later.

The end product of this system is illustrated in the following image.

{% include gallery id="gallery_01" caption="Video and data broadcast to multiple clients through WebRTC. (Left) Publisher's captured video at http://domainId:8088/publish. (Right) Multiple client viewing the broadcast at http://domainId:8088/join. Random text and random box is brodcasted via the data track, whereas video is broadcasted via the video track."%}

## System Design
Certain key aspects of the system is further explored in the following sections.

### Go Server - main.go
1. A Go server named `sdpServer` acts as the signalling server for WebRTC, as well as hosting both the `Publish` and`Join` webpages.
    ```go
    mux.HandleFunc("/sdp", handlerSDP(s))
    mux.HandleFunc("/join", handlerJoin)
    mux.HandleFunc("/publish", handlerPublish)
    mux.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static/"))))
    ```
1. The `handlerSDP()` function returns a handler which
    + receives a video track from the publisher
    + adds a video track and data track to each connected client
1. To mimic data streaming, date-time information and random bounding boxes are generated in the server which is then transmitted to the client using the data channel.

### WebRTC API - main.go
1. The peer connection function `pc.OnTrack()` has been written in a manner  which allows either publisher or client to first connect to the SDP server.
    + Hence, clients may connect to the server even before a publisher is available.
    + This feature also enables the video & data reception on client side to resume automatically when a publisher reconnects after a momentary loss of connection.
1. The peer connection function `pc.OnDataChannel()` generates date-time information and random bounding boxes, which are sent to the client via the data channel.

### Javascript - connect.js
1. The `connect.js` file
    + starts WebRTC media and data connection for both publisher and client
    + communicates with the signalling server by triggering `async function sendToServer()` function.
1. A canvas is used to superimpose the data from WebRTC data channel onto the video being displayed to the end-client. The relevant functions are
    + `function readyToPlayVideo(event)`
    + `function draw(top, left, vidH, vidW)`
    + `function drawRectangle(ctx, x, y, w, h)`
    + `function drawText(ctx, text)`

### Docker - dockerfile
1. The code uses the latest Go Module for dependency management.
1. Hence, the following lines are included in the `dockerfile` to enable Go Module and to automatically download the dependencies inside the Docker image.
    ```dockerfile
    # Enable GO111MODULE
    ENV GO111MODULE=on

    # Automatically install Go dependencies
    COPY ./go.mod ./go.sum ./
    RUN go mod download
    ```


text:
package main

import "C"
import (
	"fmt"

	_ "advanced-go/14.cgo-shared-static-lib/go-export-shared/number"
)

func main() {}

//export goPrintln
func goPrintln(s *C.char) {
	fmt.Println(C.GoString(s))
}

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace Fsv\Microformats\Parser;

use Fsv\Microformats\Model\Geo;

/**
 * Class GeoParser
 * @package Fsv\Microformats\Parser
 * @author Sergey Fedotov <sergey89@gmail.com>
 */
class GeoParser extends AbstractParser
{
    /**
     * @var array
     */
    protected static $singularProperties = [
        'longitude',
        'latitude'
    ];

    /**
     * @return Geo
     */
    public function createObject()
    {
        return new Geo();
    }

    /**
     * @return string
     */
    public function getRootClassName()
    {
        return 'geo';
    }

    /**
     * @param string $propertyName
     * @param mixed $value
     * @return float
     */
    protected function convertValue($propertyName, $value)
    {
        return (float)$value;
    }
}


text:
require File.expand_path('../spec_helper', File.dirname(__FILE__))
require File.expand_path("../../lib/ing/files", File.dirname(__FILE__))

describe Ing::Files::CreateFile do
  include SpecHelpers

  def reset
    ARGV.replace []
    ::FileUtils.rm_rf(destination_root)
  end

  def create_file(destination=nil, config={}, options={})
    @base = MyCounter.new(options)
    @base.destination_root = destination_root
    @base.call 1,2
    MyCounter.send(:define_method, :file_name, Proc.new {'rdoc'} )

    @action = Ing::Files::CreateFile.new(@base, destination, "CONFIGURATION",
                                            { :verbose => !@silence }.merge(config))
  end

  def invoke!
    capture(:stdout){ @action.invoke! }
  end

  def revoke!
    capture(:stdout){ @action.revoke! }
  end

  def silence!
    @silence = true
  end

  # stubs multiple input responses from $stdin.gets
  # not currently used
  class StubInput

    def initialize(expected)
      @s = Array(expected)
    end

    def gets
      @s.shift
    end

    def reply_for(stream=$stdin, &b)
      stream.stub(:gets, self.method(:gets), &b)
    end

  end

  describe "#invoke!" do
    before { reset }

    it "creates a file" do
      create_file("doc/config.rb")
      invoke!
      assert File.exists?(File.join(destination_root, "doc/config.rb"))
    end

    it "does not create a file if pretending" do
      create_file("doc/config.rb", {}, :pretend => true)
      invoke!
      refute File.exists?(File.join(destination_root, "doc/config.rb"))
    end

    it "shows created status to the user" do
      create_file("doc/config.rb")
      assert_equal "      create  doc/config.rb\n", invoke!
    end

    it "does not show any information if log status is false" do
      silence!
      create_file("doc/config.rb")
      assert_empty invoke!
    end

    it "returns the given destination" do
      capture(:stdout) do
        assert_equal "doc/config.rb", create_file("doc/config.rb").invoke!
      end
    end

    it "converts encoded instructions" do
      create_file("doc/%file_name%.rb.tt")
      invoke!
      assert File.exists?(File.join(destination_root, "doc/rdoc.rb.tt"))
    end

    describe "when file exists" do

      describe "and is identical" do
        before do
          reset
          create_file("doc/config.rb")
          invoke!
        end

        it "shows identical status" do
          create_file("doc/config.rb")
          invoke!
          assert_equal "   identical  doc/config.rb\n", invoke!
        end
      end

      describe "and is not identical" do
        before do
          reset
          create_file("doc/config.rb")
          invoke!
          File.open(File.join(destination_root, 'doc/config.rb'), 'w'){ |f| f.write("FOO = 3") }
        end

        it "shows forced status to the user if force is given" do
          refute create_file("doc/config.rb", {}, :force => true).identical?
          assert_equal "       force  doc/config.rb\n", invoke!
        end

        it "shows skipped status to the user if skip is given" do
          refute create_file("doc/config.rb", {}, :skip => true).identical?
          assert_equal "        skip  doc/config.rb\n", invoke!
        end

        it "shows forced status to the user if force is configured" do
          refute create_file("doc/config.rb", :force => true).identical?
          assert_equal "       force  doc/config.rb\n", invoke!
        end

        it "shows skipped status to the user if skip is configured" do
          refute create_file("doc/config.rb", :skip => true).identical?
          assert_equal "        skip  doc/config.rb\n", invoke!
        end

        it "shows conflict status to ther user" do
          refute create_file("doc/config.rb").identical?
          file = File.join(destination_root, 'doc/config.rb')
          content = nil
          $stdin.stub(:gets,'s') do
            content = invoke!
          end
          assert_match(/conflict  doc\/config\.rb/, content)
          assert_match(/Overwrite #{file}\? \(enter "h" for help\) \[Ynaqdh\]/, content)
          assert_match(/skip  doc\/config\.rb/, content)
        end

        it "creates the file if the file collision menu returns true" do
          create_file("doc/config.rb")
          $stdin.stub(:gets,'y') do
            assert_match(/force  doc\/config\.rb/, invoke!)
          end
        end

        it "skips the file if the file collision menu returns false" do
          create_file("doc/config.rb")
          $stdin.stub(:gets,'n') do
            assert_match(/skip  doc\/config\.rb/, invoke!)
          end
        end

# Not sure how to do the mock method here without more flexible mocks....
#        it "executes the block given to show file content" do
#          create_file("doc/config.rb")
#          $stdin.should_receive(:gets).and_return('d')
#          $stdin.should_receive(:gets).and_return('n')
#          @base.shell.should_receive(:system).with(/diff -u/)
#          invoke!
#        end

      end
    end
  end

  describe "#revoke!" do
    before { reset }

    it "removes the destination file" do
      create_file("doc/config.rb")
      invoke!
      revoke!
      refute File.exists?(@action.destination)
    end

    it "does not raise an error if the file does not exist" do
      create_file("doc/config.rb")
      revoke!
      refute File.exists?(@action.destination)
    end
  end

  describe "#exists?" do
    before { reset }
    it "returns true if the destination file exists" do
      create_file("doc/config.rb")
      refute @action.exists?
      invoke!
      assert @action.exists?
    end
  end

  describe "#identical?" do
    before { reset }
    it "returns true if the destination file and is identical" do
      create_file("doc/config.rb")
      refute @action.identical?
      invoke!
      assert @action.identical?
    end
  end
end


text:
#include <boost/assign/list_of.hpp>
#include <boost/foreach.hpp>

#include <sstream>

#include "base/task_annotations.h"
#include "bgp/bgp_factory.h"
#include "bgp/bgp_session_manager.h"
#include "bgp/bgp_update_sender.h"
#include "bgp/bgp_xmpp_channel.h"
#include "bgp/xmpp_message_builder.h"
#include "bgp/inet/inet_table.h"
#include "bgp/inet6/inet6_table.h"
#include "bgp/test/bgp_server_test_util.h"
#include "control-node/control_node.h"
#include "control-node/test/network_agent_mock.h"
#include "io/test/event_manager_test.h"
#include "schema/bgp_schema_types.h"
#include "xmpp/xmpp_factory.h"

using std::string;
using std::auto_ptr;
using boost::assign::list_of;

static const char *config_2_control_nodes = "\
<config>\
    <bgp-router name=\'X\'>\
        <identifier>192.168.0.1</identifier>\
        <address>127.0.0.1</address>\
        <port>%d</port>\
        <session to=\'Y\'>\
            <address-families>\
                <family>inet</family>\
                <family>inet6</family>\
            </address-families>\
        </session>\
    </bgp-router>\
    <bgp-router name=\'Y\'>\
        <identifier>192.168.0.2</identifier>\
        <address>127.0.0.2</address>\
        <port>%d</port>\
        <session to=\'X\'>\
            <address-families>\
                <family>inet</family>\
                <family>inet6</family>\
            </address-families>\
        </session>\
    </bgp-router>\
</config>\
";

//
// Template structure to pass to fixture class template. Needed because
// gtest fixture class template can accept only one template parameter.
//
template <typename T1, typename T2>
struct TypeDefinition {
  typedef T1 TableT;
  typedef T2 PrefixT;
};

// TypeDefinitions that we want to test.
typedef TypeDefinition<InetTable, Ip4Prefix> InetDefinition;
typedef TypeDefinition<Inet6Table, Inet6Prefix> Inet6Definition;

//
// Fixture class template - instantiated later for each TypeDefinition.
// Control Nodes X and Y.
// Agents A and B.
//
template <typename T>
class BgpXmppIpTest : public ::testing::Test {
protected:
    static const int kRouteCount = 512;
    typedef typename T::TableT TableT;
    typedef typename T::PrefixT PrefixT;

    BgpXmppIpTest()
        : thread_(&evm_), xs_x_(NULL), xs_y_(NULL), family_(GetFamily()),
          ipv6_prefix_("::"), master_(BgpConfigManager::kMasterInstance) {
    }

    virtual void SetUp() {
        bs_x_.reset(new BgpServerTest(&evm_, "X"));
        bs_x_->session_manager()->Initialize(0);
        LOG(DEBUG, "Created BGP server at port: " <<
            bs_x_->session_manager()->GetPort());
        xs_x_ = new XmppServer(&evm_, test::XmppDocumentMock::kControlNodeJID);
        xs_x_->Initialize(0, false);
        LOG(DEBUG, "Created XMPP server at port: " <<
            xs_x_->GetPort());
        cm_x_.reset(new BgpXmppChannelManager(xs_x_, bs_x_.get()));

        bs_y_.reset(new BgpServerTest(&evm_, "Y"));
        bs_y_->session_manager()->Initialize(0);
        LOG(DEBUG, "Created BGP server at port: " <<
            bs_y_->session_manager()->GetPort());
        xs_y_ = new XmppServer(&evm_, test::XmppDocumentMock::kControlNodeJID);
        xs_y_->Initialize(0, false);
        LOG(DEBUG, "Created XMPP server at port: " <<
            xs_y_->GetPort());
        cm_y_.reset(new BgpXmppChannelManager(xs_y_, bs_y_.get()));

        thread_.Start();

        Configure();
        task_util::WaitForIdle();

        // Create XMPP Agent A connected to XMPP server X.
        agent_a_.reset(
            new test::NetworkAgentMock(&evm_, "agent-a", xs_x_->GetPort(),
                "127.0.0.1", "127.0.0.1"));
        TASK_UTIL_EXPECT_TRUE(agent_a_->IsEstablished());

        // Create XMPP Agent B connected to XMPP server Y.
        agent_b_.reset(
            new test::NetworkAgentMock(&evm_, "agent-b", xs_y_->GetPort(),
                "127.0.0.2", "127.0.0.2"));
        TASK_UTIL_EXPECT_TRUE(agent_b_->IsEstablished());
    }

    virtual void TearDown() {
        xs_x_->Shutdown();
        task_util::WaitForIdle();
        bs_x_->Shutdown();
        task_util::WaitForIdle();
        cm_x_.reset();

        xs_y_->Shutdown();
        task_util::WaitForIdle();
        bs_y_->Shutdown();
        task_util::WaitForIdle();
        cm_y_.reset();

        TcpServerManager::DeleteServer(xs_x_);
        xs_x_ = NULL;
        TcpServerManager::DeleteServer(xs_y_);
        xs_y_ = NULL;

        if (agent_a_) { agent_a_->Delete(); }
        if (agent_b_) { agent_b_->Delete(); }

        evm_.Shutdown();
        thread_.Join();
        task_util::WaitForIdle();
    }

    void Configure(const char *cfg_template = config_2_control_nodes) {
        char config[4096];
        snprintf(config, sizeof(config), cfg_template,
                 bs_x_->session_manager()->GetPort(),
                 bs_y_->session_manager()->GetPort());
        bs_x_->Configure(config);
        bs_y_->Configure(config);
    }

    Address::Family GetFamily() const {
        assert(false);
        return Address::UNSPEC;
    }

    string BuildPrefix(int index) const {
        assert(index <= 65535);
        string ipv4_prefix("10.1.");
        uint8_t ipv4_plen = Address::kMaxV4PrefixLen;
        string byte3 = integerToString(index / 256);
        string byte4 = integerToString(index % 256);
        if (family_ == Address::INET) {
            return ipv4_prefix + byte3 + "." + byte4 + "/" +
                integerToString(ipv4_plen);
        }
        if (family_ == Address::INET6) {
            return ipv6_prefix_ + ipv4_prefix + byte3 + "." + byte4 + "/" +
                integerToString(96 + ipv4_plen);
        }
        assert(false);
        return "";
    }

    string BuildNextHop(int index) const {
        assert(index <= 255);
        string ipv4_prefix("192.168.1.");
        if (family_ == Address::INET) {
            return ipv4_prefix + integerToString(index);
        }
        if (family_ == Address::INET6) {
            return ipv6_prefix_ + ipv4_prefix + integerToString(index);
        }
        assert(false);
        return "";
    }

    void Subscribe(test::NetworkAgentMockPtr agent, int id) {
        if (family_ == Address::INET) {
            agent->Subscribe(master_, id);
        } else {
            agent->Inet6Subscribe(master_, id);
        }
    }

    void Unsubscribe(test::NetworkAgentMockPtr agent) {
        if (family_ == Address::INET) {
            agent->Unsubscribe(master_);
        } else {
            agent->Inet6Unsubscribe(master_);
        }
    }

    void SessionDown(test::NetworkAgentMockPtr agent) {
        agent->SessionDown();
    }

    void AddRoute(test::NetworkAgentMockPtr agent, const string &prefix,
        const test::NextHop &nexthop, const test::RouteAttributes &attr) {
        if (family_ == Address::INET) {
            agent->AddRoute(master_, prefix, nexthop, attr);
        } else {
            agent->AddInet6Route(master_, prefix, nexthop, attr);
        }
    }

    void DeleteRoute(test::NetworkAgentMockPtr agent, const string &prefix) {
        if (family_ == Address::INET) {
            agent->DeleteRoute(master_, prefix);
        } else {
            agent->DeleteInet6Route(master_, prefix);
        }
    }

    const autogen::ItemType *FindRoute(test::NetworkAgentMockPtr agent,
        const string &prefix) const {
        if (family_ == Address::INET) {
            return agent->RouteLookup(master_, prefix);
        } else {
            return agent->Inet6RouteLookup(master_, prefix);
        }
    }

    bool CheckRouteActual(test::NetworkAgentMockPtr agent, string prefix,
        string nexthop, int local_pref, int med,
        const vector<string> communities, bool *result) const {
        *result = false;
        const autogen::ItemType *rt = FindRoute(agent, prefix);
        if (!rt)
            return false;
        if (local_pref && rt->entry.local_preference != local_pref)
            return false;
        if (med && rt->entry.med != med)
            return false;
        if (rt->entry.next_hops.next_hop.size() != 1)
            return false;
        const autogen::NextHopType &nh = rt->entry.next_hops.next_hop[0];
        if (nh.address != nexthop)
            return false;
        if (!nh.tunnel_encapsulation_list.tunnel_encapsulation.empty())
            return false;
        if (!communities.empty() &&
            rt->entry.community_tag_list.community_tag != communities)
            return false;
        *result = true;
        return true;
    }

    bool CheckRoute(test::NetworkAgentMockPtr agent, string prefix,
                    string nexthop, int local_pref, int med,
                    const vector<string> communities) const {
        bool result;
        task_util::TaskFire(boost::bind(&BgpXmppIpTest::CheckRouteActual, this,
            agent, prefix, nexthop, local_pref, med, communities, &result),
                "bgp::Config");
        return result;
    }

    void VerifyRouteExists(test::NetworkAgentMockPtr agent, string prefix,
        string nexthop, int local_pref = 0, int med = 0) const {
        TASK_UTIL_EXPECT_TRUE(CheckRoute(
            agent, prefix, nexthop, local_pref, med, vector<string>()));
    }

    void VerifyRouteExists(test::NetworkAgentMockPtr agent, string prefix,
        string nexthop, const vector<string> &communities) const {
        TASK_UTIL_EXPECT_TRUE(
            CheckRoute(agent, prefix, nexthop, 0, 0, communities));
    }

    void VerifyRouteNoExists(test::NetworkAgentMockPtr agent,
                             string prefix) const {
        TASK_UTIL_EXPECT_TRUE(FindRoute(agent, prefix) == NULL);
    }

    EventManager evm_;
    ServerThread thread_;
    BgpServerTestPtr bs_x_;
    BgpServerTestPtr bs_y_;
    XmppServer *xs_x_;
    XmppServer *xs_y_;
    Address::Family family_;
    string ipv6_prefix_;
    string master_;
    test::NetworkAgentMockPtr agent_a_;
    test::NetworkAgentMockPtr agent_b_;
    boost::scoped_ptr<BgpXmppChannelManager> cm_x_;
    boost::scoped_ptr<BgpXmppChannelManager> cm_y_;
};

// Specialization of GetFamily for INET.
template<>
Address::Family BgpXmppIpTest<InetDefinition>::GetFamily() const {
    return Address::INET;
}

// Specialization of GetFamily for INET6.
template<>
Address::Family BgpXmppIpTest<Inet6Definition>::GetFamily() const {
    return Address::INET6;
}

// Instantiate fixture class template for each TypeDefinition.
typedef ::testing::Types<InetDefinition, Inet6Definition> TypeDefinitionList;
TYPED_TEST_CASE(BgpXmppIpTest, TypeDefinitionList);

//
// Basic route exchange.
//
TYPED_TEST(BgpXmppIpTest, Basic) {
    // Subscribe to master instance
    this->Subscribe(this->agent_a_, 0);
    this->Subscribe(this->agent_b_, 0);

    // Add route from agent A.
    test::NextHop nexthop(true, this->BuildNextHop(1));
    test::RouteAttributes attr;
    this->AddRoute(this->agent_a_, this->BuildPrefix(1), nexthop, attr);
    task_util::WaitForIdle();

    // Verify that route showed up on agents A and B.
    this->VerifyRouteExists(this->agent_a_, this->BuildPrefix(1),
        this->BuildNextHop(1), 100);
    this->VerifyRouteExists(this->agent_b_, this->BuildPrefix(1),
        this->BuildNextHop(1), 100);

    // Delete route from agent A.
    this->DeleteRoute(this->agent_a_, this->BuildPrefix(1));
    task_util::WaitForIdle();

    // Verify that route is deleted at agents A and B.
    this->VerifyRouteNoExists(this->agent_a_, this->BuildPrefix(1));
    this->VerifyRouteNoExists(this->agent_b_, this->BuildPrefix(1));

    // Close the sessions.
    this->SessionDown(this->agent_a_);
    this->SessionDown(this->agent_b_);
}

//
// Change local preference.
//
TYPED_TEST(BgpXmppIpTest, RouteChangeLocalPref) {
    // Subscribe to master instance
    this->Subscribe(this->agent_a_, 0);
    this->Subscribe(this->agent_b_, 0);

    // Add route from agent A.
    test::NextHop nexthop(true, this->BuildNextHop(1));
    test::RouteAttributes attr(200, 0, 0);
    this->AddRoute(this->agent_a_, this->BuildPrefix(1), nexthop, attr);
    task_util::WaitForIdle();

    // Verify that route showed up on agents A and B.
    this->VerifyRouteExists(this->agent_a_, this->BuildPrefix(1),
        this->BuildNextHop(1), 200);
    this->VerifyRouteExists(this->agent_b_, this->BuildPrefix(1),
        this->BuildNextHop(1), 200);

    // Change route from agent A.
    attr = test::RouteAttributes(300, 0, 0);
    this->AddRoute(this->agent_a_, this->BuildPrefix(1), nexthop, attr);
    task_util::WaitForIdle();

    // Verify that route changed on agents A and B.
    this->VerifyRouteExists(this->agent_a_, this->BuildPrefix(1),
        this->BuildNextHop(1), 300);
    this->VerifyRouteExists(this->agent_b_, this->BuildPrefix(1),
        this->BuildNextHop(1), 300);

    // Add route from agent A without local pref.
    attr = test::RouteAttributes();
    this->AddRoute(this->agent_a_, this->BuildPrefix(1), nexthop, attr);
    task_util::WaitForIdle();

    // Verify that route changed on agents A and B.
    this->VerifyRouteExists(this->agent_a_, this->BuildPrefix(1),
        this->BuildNextHop(1), 100);
    this->VerifyRouteExists(this->agent_b_, this->BuildPrefix(1),
        this->BuildNextHop(1), 100);

    // Delete route from agent A.
    this->DeleteRoute(this->agent_a_, this->BuildPrefix(1));
    task_util::WaitForIdle();

    // Verify that routes are deleted at agents A and B.
    this->VerifyRouteNoExists(this->agent_a_, this->BuildPrefix(1));
    this->VerifyRouteNoExists(this->agent_b_, this->BuildPrefix(1));

    // Close the sessions.
    this->SessionDown(this->agent_a_);
    this->SessionDown(this->agent_b_);
}

//
// Route added with explicit med has expected med.
//
TYPED_TEST(BgpXmppIpTest, RouteExplicitMed) {
    // Subscribe to master instance
    this->Subscribe(this->agent_a_, 0);
    this->Subscribe(this->agent_b_, 0);

    // Add route from agent A with local preference 100 and med 500.
    test::NextHop nexthop(true, this->BuildNextHop(1));
    test::RouteAttributes attr(100, 500, 0);
    this->AddRoute(this->agent_a_, this->BuildPrefix(1), nexthop, attr);
    task_util::WaitForIdle();

    // Verify that route showed up on agents A and B with expected med.
    this->VerifyRouteExists(this->agent_a_, this->BuildPrefix(1),
        this->BuildNextHop(1), 0, 500);
    this->VerifyRouteExists(this->agent_b_, this->BuildPrefix(1),
        this->BuildNextHop(1), 0, 500);

    // Delete route from agent A.
    this->DeleteRoute(this->agent_a_, this->BuildPrefix(1));
    task_util::WaitForIdle();

    // Verify that routes is deleted at agents A and B.
    this->VerifyRouteNoExists(this->agent_a_, this->BuildPrefix(1));
    this->VerifyRouteNoExists(this->agent_b_, this->BuildPrefix(1));

    // Close the sessions.
    this->SessionDown(this->agent_a_);
    this->SessionDown(this->agent_b_);
}

//
// Route added with local preference and no med has auto calculated med.
//
TYPED_TEST(BgpXmppIpTest, RouteLocalPrefToMed) {
    // Subscribe to master instance
    this->Subscribe(this->agent_a_, 0);
    this->Subscribe(this->agent_b_, 0);

    // Add route from agent A with local preference 100.
    test::NextHop nexthop(true, this->BuildNextHop(1));
    test::RouteAttributes attr(100, 0, 0);
    this->AddRoute(this->agent_a_, this->BuildPrefix(1), nexthop, attr);
    task_util::WaitForIdle();

    // Verify that route showed up on agents A and B with expected med.
    this->VerifyRouteExists(this->agent_a_, this->BuildPrefix(1),
        this->BuildNextHop(1), 0, 200);
    this->VerifyRouteExists(this->agent_b_, this->BuildPrefix(1),
        this->BuildNextHop(1), 0, 200);

    // Change route from agent A to have local preference 200.
    attr = test::RouteAttributes(200, 0, 0);
    this->AddRoute(this->agent_a_, this->BuildPrefix(1), nexthop, attr);
    task_util::WaitForIdle();

    // Verify that route showed up on agents A and B with expected med.
    this->VerifyRouteExists(this->agent_a_, this->BuildPrefix(1),
        this->BuildNextHop(1), 0, 100);
    this->VerifyRouteExists(this->agent_b_, this->BuildPrefix(1),
        this->BuildNextHop(1), 0, 100);

    // Delete route from agent A.
    this->DeleteRoute(this->agent_a_, this->BuildPrefix(1));
    task_util::WaitForIdle();

    // Verify that routes is deleted at agents A and B.
    this->VerifyRouteNoExists(this->agent_a_, this->BuildPrefix(1));
    this->VerifyRouteNoExists(this->agent_b_, this->BuildPrefix(1));

    // Close the sessions.
    this->SessionDown(this->agent_a_);
    this->SessionDown(this->agent_b_);
}

//
// Route added with community list.
//
TYPED_TEST(BgpXmppIpTest, RouteWithCommunity) {
    // Subscribe to master instance
    this->Subscribe(this->agent_a_, 0);
    this->Subscribe(this->agent_b_, 0);

    // Add route from agent A.
    test::NextHop nexthop(true, this->BuildNextHop(1));
    vector<string> comm = list_of("64512:101")("64512:102");
    test::RouteAttributes attr(comm);
    this->AddRoute(this->agent_a_, this->BuildPrefix(1), nexthop, attr);
    task_util::WaitForIdle();

    // Verify that route showed up on agents A and B.
    this->VerifyRouteExists(this->agent_a_, this->BuildPrefix(1),
        this->BuildNextHop(1), comm);
    this->VerifyRouteExists(this->agent_b_, this->BuildPrefix(1),
        this->BuildNextHop(1), comm);

    // Change route from agent A.
    comm = list_of("64512:201")("64512:202");
    attr = test::RouteAttributes(comm);
    this->AddRoute(this->agent_a_, this->BuildPrefix(1), nexthop, attr);
    task_util::WaitForIdle();

    // Verify that route showed up on agents A and B.
    this->VerifyRouteExists(this->agent_a_, this->BuildPrefix(1),
        this->BuildNextHop(1), comm);
    this->VerifyRouteExists(this->agent_b_, this->BuildPrefix(1),
        this->BuildNextHop(1), comm);

    // Delete route from agent A.
    this->DeleteRoute(this->agent_a_, this->BuildPrefix(1));
    task_util::WaitForIdle();

    // Verify that route is deleted at agents A and B.
    this->VerifyRouteNoExists(this->agent_a_, this->BuildPrefix(1));
    this->VerifyRouteNoExists(this->agent_b_, this->BuildPrefix(1));

    // Close the sessions.
    this->SessionDown(this->agent_a_);
    this->SessionDown(this->agent_b_);
}

//
// Multiple routes are added/updated.
//
TYPED_TEST(BgpXmppIpTest, MultipleRoutes) {
    // Subscribe to master instance
    this->Subscribe(this->agent_a_, 0);
    this->Subscribe(this->agent_b_, 0);

    // Add multiple routes from agent A.
    for (int idx = 0; idx < this->kRouteCount; ++idx) {
        test::NextHop nexthop(true, this->BuildNextHop(1));
        test::RouteAttributes attr;
        this->AddRoute(this->agent_a_, this->BuildPrefix(idx), nexthop, attr);
    }

    // Verify that routes showed up on agents A and B.
    for (int idx = 0; idx < this->kRouteCount; ++idx) {
        this->VerifyRouteExists(this->agent_a_, this->BuildPrefix(idx),
            this->BuildNextHop(1));
        this->VerifyRouteExists(this->agent_b_, this->BuildPrefix(idx),
            this->BuildNextHop(1));
    }

    // Updates routes from agent A.
    for (int idx = 0; idx < this->kRouteCount; ++idx) {
        test::NextHop nexthop(true, this->BuildNextHop(2));
        test::RouteAttributes attr;
        this->AddRoute(this->agent_a_, this->BuildPrefix(idx), nexthop, attr);
    }

    // Verify that routes are updated up on agents A and B.
    for (int idx = 0; idx < this->kRouteCount; ++idx) {
        this->VerifyRouteExists(this->agent_a_, this->BuildPrefix(idx),
            this->BuildNextHop(2));
        this->VerifyRouteExists(this->agent_b_, this->BuildPrefix(idx),
            this->BuildNextHop(2));
    }

    // Delete route from agent A.
    for (int idx = 0; idx < this->kRouteCount; ++idx) {
        this->DeleteRoute(this->agent_a_, this->BuildPrefix(idx));
    }

    // Verify that routes are deleted at agents A and B.
    for (int idx = 0; idx < this->kRouteCount; ++idx) {
        this->VerifyRouteNoExists(this->agent_a_, this->BuildPrefix(idx));
        this->VerifyRouteNoExists(this->agent_b_, this->BuildPrefix(idx));
    }

    // Close the sessions.
    this->SessionDown(this->agent_a_);
    this->SessionDown(this->agent_b_);
}

//
// Multiple routes are advertised/withdrawn properly on Join/Leave.
//
TYPED_TEST(BgpXmppIpTest, JoinLeave) {
    // Subscribe agent A to master instance.
    this->Subscribe(this->agent_a_, 0);

    // Add routes from agent A.
    for (int idx = 0; idx < this->kRouteCount; ++idx) {
        test::NextHop nexthop(true, this->BuildNextHop(1));
        test::RouteAttributes attr;
        this->AddRoute(this->agent_a_, this->BuildPrefix(idx), nexthop, attr);
    }

    // Verify that routes showed up on agent A.
    for (int idx = 0; idx < this->kRouteCount; ++idx) {
        this->VerifyRouteExists(this->agent_a_, this->BuildPrefix(idx),
            this->BuildNextHop(1));
    }

    // Register agent B to master instance.
    this->Subscribe(this->agent_b_, 0);
    task_util::WaitForIdle();

    // Verify that routes are present at agent A and showed up on agent B.
    for (int idx = 0; idx < this->kRouteCount; ++idx) {
        this->VerifyRouteExists(this->agent_a_, this->BuildPrefix(idx),
            this->BuildNextHop(1));
        this->VerifyRouteExists(this->agent_b_, this->BuildPrefix(idx),
            this->BuildNextHop(1));
    }

    // Unregister agent B from master instance.
    this->Unsubscribe(this->agent_b_);
    task_util::WaitForIdle();

    // Verify that routes are present at agent A and deleted at agent B.
    for (int idx = 0; idx < this->kRouteCount; ++idx) {
        this->VerifyRouteExists(this->agent_a_, this->BuildPrefix(idx),
            this->BuildNextHop(1));
        this->VerifyRouteNoExists(this->agent_b_, this->BuildPrefix(1));
    }

    // Delete routes from agent A.
    for (int idx = 0; idx < this->kRouteCount; ++idx) {
        this->DeleteRoute(this->agent_a_, this->BuildPrefix(idx));
    }

    // Verify that routes are deleted at agents A and B.
    for (int idx = 0; idx < this->kRouteCount; ++idx) {
        this->VerifyRouteNoExists(this->agent_a_, this->BuildPrefix(idx));
        this->VerifyRouteNoExists(this->agent_b_, this->BuildPrefix(idx));
    }

    // Close the sessions.
    this->SessionDown(this->agent_a_);
    this->SessionDown(this->agent_b_);
}

//
// Agent flaps a route by changing it repeatedly.
//
TYPED_TEST(BgpXmppIpTest, RouteFlap) {
    // Subscribe to master instance
    this->Subscribe(this->agent_a_, 0);
    this->Subscribe(this->agent_b_, 0);

    // Add route from agent A and change it repeatedly.
    for (int idx = 0; idx < 128; ++idx) {
        test::NextHop nexthop1(true, this->BuildNextHop(1));
        test::NextHop nexthop2(true, this->BuildNextHop(2));
        test::RouteAttributes attr;
        this->AddRoute(this->agent_a_, this->BuildPrefix(1), nexthop1, attr);
        this->AddRoute(this->agent_a_, this->BuildPrefix(1), nexthop2, attr);
    }

    // Delete route from agent A.
    this->DeleteRoute(this->agent_a_, this->BuildPrefix(1));
    task_util::WaitForIdle();

    // Verify that routes is deleted at agents A and B.
    this->VerifyRouteNoExists(this->agent_a_, this->BuildPrefix(1));
    this->VerifyRouteNoExists(this->agent_b_, this->BuildPrefix(1));

    // Close the sessions.
    this->SessionDown(this->agent_a_);
    this->SessionDown(this->agent_b_);
}

class TestEnvironment : public ::testing::Environment {
    virtual ~TestEnvironment() { }
    virtual void SetUp() {
    }
    virtual void TearDown() {
    }
};

static void SetUp() {
    BgpServer::Initialize();
    ControlNode::SetDefaultSchedulingPolicy();
    BgpServerTest::GlobalSetUp();
    BgpObjectFactory::Register<StateMachine>(
        boost::factory<StateMachineTest *>());
    BgpObjectFactory::Register<BgpXmppMessageBuilder>(
        boost::factory<BgpXmppMessageBuilder *>());
    XmppObjectFactory::Register<XmppStateMachine>(
        boost::factory<XmppStateMachineTest *>());
}
static void TearDown() {
    BgpServer::Terminate();
    TaskScheduler *scheduler = TaskScheduler::GetInstance();
    scheduler->Terminate();
}

int main(int argc, char **argv) {
    bgp_log_test::init();
    ::testing::InitGoogleTest(&argc, argv);
    ::testing::AddGlobalTestEnvironment(new TestEnvironment());
    DB::SetPartitionCount(1);
    SetUp();
    int result = RUN_ALL_TESTS();
    TearDown();

    return result;
}


text:
using System.Diagnostics;
using Contoso.Threading;
namespace Contoso.IO
{
    public partial class FileEx
    {
        static FileEx()
        {
            RegisterVfs(new VirtualFileSystem(), 1);
        }

        public static RC OsOpen(VirtualFileSystem pVfs, string zPath, VirtualFile pFile, VirtualFileSystem.OPEN flags, ref VirtualFileSystem.OPEN pFlagsOut)
        {
            // 0x87f3f is a mask of SQLITE_OPEN_ flags that are valid to be passed down into the VFS layer.  Some SQLITE_OPEN_ flags (for example,
            // SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before reaching the VFS.
            var rc = pVfs.xOpen(zPath, pFile, (VirtualFileSystem.OPEN)((int)flags & 0x87f3f), out pFlagsOut); Debug.Assert(rc == RC.OK || !pFile.IsOpen); return rc;
        }
        //internal static SQLITE sqlite3OsDelete(VirtualFileSystem pVfs, string zPath, int dirSync) { return pVfs.xDelete(zPath, dirSync); }
        //internal static SQLITE sqlite3OsAccess(VirtualFileSystem pVfs, string zPath, VirtualFileSystem.ACCESS flags, ref int pResOut) { return pVfs.xAccess(zPath, flags, out pResOut); }
        //internal static SQLITE sqlite3OsFullPathname(VirtualFileSystem pVfs, string zPath, int nPathOut, StringBuilder zPathOut) { zPathOut.Length = 0; return pVfs.xFullPathname(zPath, nPathOut, zPathOut); }
#if !SQLITE_OMIT_LOAD_EXTENSION
        //internal static IntPtr sqlite3OsDlOpen(VirtualFileSystem pVfs, string zPath) { return pVfs.xDlOpen(zPath); }
        //internal static void sqlite3OsDlError(VirtualFileSystem pVfs, int nByte, string zBufOut) { pVfs.xDlError(nByte, zBufOut); }
        //internal static object sqlite3OsDlSym(VirtualFileSystem pVfs, IntPtr pHdle, ref string zSym) { return pVfs.xDlSym(pHdle, zSym); }
        //internal static void sqlite3OsDlClose(VirtualFileSystem pVfs, IntPtr pHandle) { pVfs.xDlClose(pHandle); }
#endif
        //internal static int sqlite3OsRandomness(VirtualFileSystem pVfs, int nByte, byte[] zBufOut) { return pVfs.xRandomness(nByte, zBufOut); }
        //internal static int sqlite3OsSleep(VirtualFileSystem pVfs, int nMicro) { return pVfs.xSleep(nMicro); }

        //internal static SQLITE sqlite3OsCurrentTimeInt64(VirtualFileSystem pVfs, ref long pTimeOut)
        //{
        //    // IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64() method to get the current date and time if that method is available
        //    // (if iVersion is 2 or greater and the function pointer is not NULL) and will fall back to xCurrentTime() if xCurrentTimeInt64() is unavailable.
        //    SQLITE rc;
        //    if (pVfs.iVersion >= 2)
        //        rc = pVfs.xCurrentTimeInt64(ref pTimeOut);
        //    else
        //    {
        //        double r = 0;
        //        rc = pVfs.xCurrentTime(ref r);
        //        pTimeOut = (long)(r * 86400000.0);
        //    }
        //    return rc;
        //}

        internal static RC OsOpenWithAlloc(ref VirtualFileSystem pVfs, string zFile, ref VirtualFile ppFile, VirtualFileSystem.OPEN flags, ref VirtualFileSystem.OPEN pOutFlags)
        {
            var rc = RC.NOMEM;
            var pFile = new VirtualFile();
            if (pFile != null)
            {
                rc = OsOpen(pVfs, zFile, pFile, flags, ref pOutFlags);
                if (rc != RC.OK)
                    pFile = null;
                else
                    ppFile = pFile;
            }
            return rc;
        }

        internal static int OsInit() { return 0; }

        internal static VirtualFileSystem vfsList;

        internal static bool isInit = false;

        public static VirtualFileSystem FindVfs(string zVfs)
        {
            VirtualFileSystem pVfs = null;
            //#if !SQLITE_OMIT_AUTOINIT
            //            var rc = sqlite3_initialize();
            //            if (rc != SQLITE.OK)
            //                return null;
            //#endif
#if SQLITE_THREADSAFE
            var mutex = MutexEx.Alloc(MutexEx.MUTEX.STATIC_MASTER);
#endif
            MutexEx.Enter(mutex);
            for (pVfs = vfsList; pVfs != null; pVfs = pVfs.pNext)
            {
                if (zVfs == null || zVfs == "") break;
                if (zVfs == pVfs.zName) break;
            }
            MutexEx.Leave(mutex);
            return pVfs;
        }

        internal static void vfsUnlink(VirtualFileSystem pVfs)
        {
            Debug.Assert(MutexEx.Held(MutexEx.Alloc(MutexEx.MUTEX.STATIC_MASTER)));
            if (pVfs == null) { /* No-op */ }
            else if (vfsList == pVfs)
                vfsList = pVfs.pNext;
            else if (vfsList != null)
            {
                var p = vfsList;
                while (p.pNext != null && p.pNext != pVfs)
                    p = p.pNext;
                if (p.pNext == pVfs)
                    p.pNext = pVfs.pNext;
            }
        }

        public static RC RegisterVfs(VirtualFileSystem pVfs, int makeDflt)
        {
            //#if !SQLITE_OMIT_AUTOINIT
            //            var rc = sqlite3_initialize();
            //            if (rc != SQLITE.OK)
            //                return rc;
            //#endif
            var mutex = MutexEx.Alloc(MutexEx.MUTEX.STATIC_MASTER);
            MutexEx.Enter(mutex);
            vfsUnlink(pVfs);
            if (makeDflt != 0 || vfsList == null)
            {
                pVfs.pNext = vfsList;
                vfsList = pVfs;
            }
            else
            {
                pVfs.pNext = vfsList.pNext;
                vfsList.pNext = pVfs;
            }
            Debug.Assert(vfsList != null);
            MutexEx.Leave(mutex);
            return RC.OK;
        }

        public static RC UnregisterVfs(VirtualFileSystem pVfs)
        {
#if SQLITE_THREADSAFE
            var mutex = MutexEx.Alloc(MutexEx.MUTEX.STATIC_MASTER);
#endif
            MutexEx.Enter(mutex);
            vfsUnlink(pVfs);
            MutexEx.Leave(mutex);
            return RC.OK;
        }
    }
}


text:
package hu.sanyi.demo.todolist.ui;

import java.util.List;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.FlowPane;

public class TaskListView extends BorderPane {

	Button logoutButton = new Button();
	ListView<String> list = new ListView<>();
	ObservableList<String> items =FXCollections.observableArrayList (
            "Single", "Double", "Suite", "Family App");
	Button refreshButton = new Button();

	public TaskListView() {
		refreshButton.setText("Refresh");
		logoutButton.setText("Logout");
		FlowPane buttonPane = new FlowPane();
		buttonPane.getChildren().add(refreshButton);
		buttonPane.getChildren().add(logoutButton);

		list.setItems(items);
        setBottom(buttonPane);
        setCenter(list);
	}

	public void updateTaskList(List<String> taskLists) {
		items.clear();
		items.addAll(taskLists);
	}

	public void addLogoutButtonEventHandler(EventHandler<ActionEvent> eventHandler) {
		logoutButton.setOnAction(eventHandler);
	}

	public void addRefreshButtonEventHandler(
			EventHandler<ActionEvent> eventHandler) {
		refreshButton.setOnAction(eventHandler);
	}

}


text:
from net_system.models import NetworkDevice, Credentials
devices = NetworkDevice.objects.all()
creds = Credentials.objects.all()
std_creds = creds[0]
arista_creds = creds[1]
for device in devices:
    print device.device_name
    if 'pynet-sw' in device.device_name:
        print "  Arista switch: use arista_creds"
        device.credentials = arista_creds
    else:
        print "  Not Arista: use std_creds"
        device.credentials = std_creds
    device.save()

for device in devices:
    print "%s %s" %(device.device_name, device.credentials)


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.cognitiveservices.models;

import com.azure.resourcemanager.cognitiveservices.fluent.models.CommitmentTierInner;

/** An immutable client-side representation of CommitmentTier. */
public interface CommitmentTier {
    /**
     * Gets the kind property: The Kind of the resource.
     *
     * @return the kind value.
     */
    String kind();

    /**
     * Gets the skuName property: The name of the SKU. Ex - P3. It is typically a letter+number code.
     *
     * @return the skuName value.
     */
    String skuName();

    /**
     * Gets the hostingModel property: Account hosting model.
     *
     * @return the hostingModel value.
     */
    HostingModel hostingModel();

    /**
     * Gets the planType property: Commitment plan type.
     *
     * @return the planType value.
     */
    String planType();

    /**
     * Gets the tier property: Commitment period commitment tier.
     *
     * @return the tier value.
     */
    String tier();

    /**
     * Gets the maxCount property: Commitment period commitment max count.
     *
     * @return the maxCount value.
     */
    Integer maxCount();

    /**
     * Gets the quota property: Cognitive Services account commitment quota.
     *
     * @return the quota value.
     */
    CommitmentQuota quota();

    /**
     * Gets the cost property: Cognitive Services account commitment cost.
     *
     * @return the cost value.
     */
    CommitmentCost cost();

    /**
     * Gets the inner com.azure.resourcemanager.cognitiveservices.fluent.models.CommitmentTierInner object.
     *
     * @return the inner object.
     */
    CommitmentTierInner innerModel();
}


text:
\hypertarget{class_hardware_serial}{}\section{Hardware\+Serial Class Reference}
\label{class_hardware_serial}\index{Hardware\+Serial@{Hardware\+Serial}}

{\ttfamily \#include $<$Hardware\+Serial.\+h$>$}

Inheritance diagram for Hardware\+Serial\+:
\nopagebreak
\begin{figure}[H]
\begin{center}
\leavevmode
\includegraphics[width=162pt]{class_hardware_serial__inherit__graph}
\end{center}
\end{figure}

Collaboration diagram for Hardware\+Serial\+:
\nopagebreak
\begin{figure}[H]
\begin{center}
\leavevmode
\includegraphics[width=162pt]{class_hardware_serial__coll__graph}
\end{center}
\end{figure}
\subsection*{Public Member Functions}
\begin{DoxyCompactItemize}
\item
\hyperlink{class_hardware_serial_ab181fe0181fb1fc198b33af34ee13cb4}{Hardware\+Serial} (volatile uint8\+\_\+t $\ast$ubrrh, volatile uint8\+\_\+t $\ast$ubrrl, volatile uint8\+\_\+t $\ast$ucsra, volatile uint8\+\_\+t $\ast$ucsrb, volatile uint8\+\_\+t $\ast$ucsrc, volatile uint8\+\_\+t $\ast$udr)
\item
void \hyperlink{class_hardware_serial_a384e10dd459783bcba27090520119f3c}{begin} (unsigned long baud)
\item
void \hyperlink{class_hardware_serial_a6d7cd41eca940345e2ffad77cf08c3bc}{begin} (unsigned long, uint8\+\_\+t)
\item
void \hyperlink{class_hardware_serial_aaf81d3fdaf258088d7692fa70cece087}{end} ()
\item
virtual int \hyperlink{class_hardware_serial_aeec8f4dbef97221a6041d6cdc6e9b716}{available} (void)
\item
virtual int \hyperlink{class_hardware_serial_a65e3a688fcd31f2f486d3af02c400d8f}{peek} (void)
\item
virtual int \hyperlink{class_hardware_serial_aead319e2866cf90d56c10f2ed39a4396}{read} (void)
\item
int \hyperlink{class_hardware_serial_a4afe5933dbdb0ad962857d00e04c3bfc}{available\+For\+Write} (void)
\item
virtual void \hyperlink{class_hardware_serial_a0a4efd3d0f68d057f23eb5dfcd16c17c}{flush} (void)
\item
virtual size\+\_\+t \hyperlink{class_hardware_serial_a0c15a57daf1517586523b8d270d34c7d}{write} (uint8\+\_\+t)
\item
size\+\_\+t \hyperlink{class_hardware_serial_a0ba52a995edf9b6c2cdf3d396be84ff1}{write} (unsigned long n)
\item
size\+\_\+t \hyperlink{class_hardware_serial_a3cfec102ee6f58a2f7e617999ce9f5bb}{write} (long n)
\item
size\+\_\+t \hyperlink{class_hardware_serial_a2d9bc6ac05e45a7023be3cd1ca224407}{write} (unsigned int n)
\item
size\+\_\+t \hyperlink{class_hardware_serial_a22e7ab55e0aa268cff5b48e763429ec3}{write} (int n)
\item
\hyperlink{class_hardware_serial_a9b3baad8c612d81b96e46f84d7e97580}{operator bool} ()
\item
void \hyperlink{class_hardware_serial_a1e53ef70365848217cf98758e9391ca1}{\+\_\+rx\+\_\+complete\+\_\+irq} (void)
\item
void \hyperlink{class_hardware_serial_aa3d3b6e82dac8974a0a70c3abf301e70}{\+\_\+tx\+\_\+udr\+\_\+empty\+\_\+irq} (void)
\end{DoxyCompactItemize}
\subsection*{Protected Attributes}
\begin{DoxyCompactItemize}
\item
volatile uint8\+\_\+t $\ast$const \hyperlink{class_hardware_serial_ac2dd0caa2b74a2992e1b9b0d63dec696}{\+\_\+ubrrh}
\item
volatile uint8\+\_\+t $\ast$const \hyperlink{class_hardware_serial_ad61fd40f665d597de97ec3995e251e93}{\+\_\+ubrrl}
\item
volatile uint8\+\_\+t $\ast$const \hyperlink{class_hardware_serial_a691bd409418c1acc6fc583692b54764f}{\+\_\+ucsra}
\item
volatile uint8\+\_\+t $\ast$const \hyperlink{class_hardware_serial_a06c3d929aa3eb0e48227139d1750a3a7}{\+\_\+ucsrb}
\item
volatile uint8\+\_\+t $\ast$const \hyperlink{class_hardware_serial_a3599c284453c515776147539d753d1bf}{\+\_\+ucsrc}
\item
volatile uint8\+\_\+t $\ast$const \hyperlink{class_hardware_serial_a9123daf6c7d2bc8c3997d73f7b30bece}{\+\_\+udr}
\item
bool \hyperlink{class_hardware_serial_a491255f295202ef6556a978224fdc71e}{\+\_\+written}
\item
volatile \hyperlink{_hardware_serial_8h_a335e37d0726278844b068d565a4e66b7}{rx\+\_\+buffer\+\_\+index\+\_\+t} \hyperlink{class_hardware_serial_a797ebcc80bc2806b3ebbfc509e7aeabe}{\+\_\+rx\+\_\+buffer\+\_\+head}
\item
volatile \hyperlink{_hardware_serial_8h_a335e37d0726278844b068d565a4e66b7}{rx\+\_\+buffer\+\_\+index\+\_\+t} \hyperlink{class_hardware_serial_a0343d5d99eb23a56dd3ad5b48928a94a}{\+\_\+rx\+\_\+buffer\+\_\+tail}
\item
volatile \hyperlink{_hardware_serial_8h_a20cdd352151af0ecef9f3f68c8b20256}{tx\+\_\+buffer\+\_\+index\+\_\+t} \hyperlink{class_hardware_serial_abc7b62797e816bc704bfe3ec80f68607}{\+\_\+tx\+\_\+buffer\+\_\+head}
\item
volatile \hyperlink{_hardware_serial_8h_a20cdd352151af0ecef9f3f68c8b20256}{tx\+\_\+buffer\+\_\+index\+\_\+t} \hyperlink{class_hardware_serial_a3aad9ccd1bebab9d9226e0c38ee54465}{\+\_\+tx\+\_\+buffer\+\_\+tail}
\item
unsigned char \hyperlink{class_hardware_serial_ae33d584001d6c3fbbc6a8097b0ab19c7}{\+\_\+rx\+\_\+buffer} \mbox{[}\hyperlink{_hardware_serial_8h_aba0ceec384cf3acb51e0d6f45f31379c}{S\+E\+R\+I\+A\+L\+\_\+\+R\+X\+\_\+\+B\+U\+F\+F\+E\+R\+\_\+\+S\+I\+Z\+E}\mbox{]}
\item
unsigned char \hyperlink{class_hardware_serial_ae29711a762cbc9a7f622b4f4ff64d374}{\+\_\+tx\+\_\+buffer} \mbox{[}\hyperlink{_hardware_serial_8h_af0d9a9a9aac810bf58f698086f76e516}{S\+E\+R\+I\+A\+L\+\_\+\+T\+X\+\_\+\+B\+U\+F\+F\+E\+R\+\_\+\+S\+I\+Z\+E}\mbox{]}
\end{DoxyCompactItemize}
\subsection*{Additional Inherited Members}

\subsection{Detailed Description}

Definition at line 83 of file Hardware\+Serial.\+h.

\subsection{Constructor \& Destructor Documentation}
\hypertarget{class_hardware_serial_ab181fe0181fb1fc198b33af34ee13cb4}{}\index{Hardware\+Serial@{Hardware\+Serial}!Hardware\+Serial@{Hardware\+Serial}}
\index{Hardware\+Serial@{Hardware\+Serial}!Hardware\+Serial@{Hardware\+Serial}}
\subsubsection[{Hardware\+Serial(volatile uint8\+\_\+t $\ast$ubrrh, volatile uint8\+\_\+t $\ast$ubrrl, volatile uint8\+\_\+t $\ast$ucsra, volatile uint8\+\_\+t $\ast$ucsrb, volatile uint8\+\_\+t $\ast$ucsrc, volatile uint8\+\_\+t $\ast$udr)}]{\setlength{\rightskip}{0pt plus 5cm}{\bf Hardware\+Serial} (
\begin{DoxyParamCaption}
\item[{volatile uint8\+\_\+t $\ast$}]{ubrrh, }
\item[{volatile uint8\+\_\+t $\ast$}]{ubrrl, }
\item[{volatile uint8\+\_\+t $\ast$}]{ucsra, }
\item[{volatile uint8\+\_\+t $\ast$}]{ucsrb, }
\item[{volatile uint8\+\_\+t $\ast$}]{ucsrc, }
\item[{volatile uint8\+\_\+t $\ast$}]{udr}
\end{DoxyParamCaption}
)\hspace{0.3cm}{\ttfamily [inline]}}\label{class_hardware_serial_ab181fe0181fb1fc198b33af34ee13cb4}

\subsection{Member Function Documentation}
\hypertarget{class_hardware_serial_a1e53ef70365848217cf98758e9391ca1}{}\index{Hardware\+Serial@{Hardware\+Serial}!\+\_\+rx\+\_\+complete\+\_\+irq@{\+\_\+rx\+\_\+complete\+\_\+irq}}
\index{\+\_\+rx\+\_\+complete\+\_\+irq@{\+\_\+rx\+\_\+complete\+\_\+irq}!Hardware\+Serial@{Hardware\+Serial}}
\subsubsection[{\+\_\+rx\+\_\+complete\+\_\+irq(void)}]{\setlength{\rightskip}{0pt plus 5cm}void \+\_\+rx\+\_\+complete\+\_\+irq (
\begin{DoxyParamCaption}
\item[{void}]{}
\end{DoxyParamCaption}
)\hspace{0.3cm}{\ttfamily [inline]}}\label{class_hardware_serial_a1e53ef70365848217cf98758e9391ca1}
\hypertarget{class_hardware_serial_aa3d3b6e82dac8974a0a70c3abf301e70}{}\index{Hardware\+Serial@{Hardware\+Serial}!\+\_\+tx\+\_\+udr\+\_\+empty\+\_\+irq@{\+\_\+tx\+\_\+udr\+\_\+empty\+\_\+irq}}
\index{\+\_\+tx\+\_\+udr\+\_\+empty\+\_\+irq@{\+\_\+tx\+\_\+udr\+\_\+empty\+\_\+irq}!Hardware\+Serial@{Hardware\+Serial}}
\subsubsection[{\+\_\+tx\+\_\+udr\+\_\+empty\+\_\+irq(void)}]{\setlength{\rightskip}{0pt plus 5cm}void \+\_\+tx\+\_\+udr\+\_\+empty\+\_\+irq (
\begin{DoxyParamCaption}
\item[{void}]{}
\end{DoxyParamCaption}
)}\label{class_hardware_serial_aa3d3b6e82dac8974a0a70c3abf301e70}
\hypertarget{class_hardware_serial_aeec8f4dbef97221a6041d6cdc6e9b716}{}\index{Hardware\+Serial@{Hardware\+Serial}!available@{available}}
\index{available@{available}!Hardware\+Serial@{Hardware\+Serial}}
\subsubsection[{available(void)}]{\setlength{\rightskip}{0pt plus 5cm}virtual int available (
\begin{DoxyParamCaption}
\item[{void}]{}
\end{DoxyParamCaption}
)\hspace{0.3cm}{\ttfamily [virtual]}}\label{class_hardware_serial_aeec8f4dbef97221a6041d6cdc6e9b716}

Implements \hyperlink{class_stream_aebd60457902debb30b07971a16f24ebd}{Stream}.

\hypertarget{class_hardware_serial_a4afe5933dbdb0ad962857d00e04c3bfc}{}\index{Hardware\+Serial@{Hardware\+Serial}!available\+For\+Write@{available\+For\+Write}}
\index{available\+For\+Write@{available\+For\+Write}!Hardware\+Serial@{Hardware\+Serial}}
\subsubsection[{available\+For\+Write(void)}]{\setlength{\rightskip}{0pt plus 5cm}int available\+For\+Write (
\begin{DoxyParamCaption}
\item[{void}]{}
\end{DoxyParamCaption}
)}\label{class_hardware_serial_a4afe5933dbdb0ad962857d00e04c3bfc}
\hypertarget{class_hardware_serial_a384e10dd459783bcba27090520119f3c}{}\index{Hardware\+Serial@{Hardware\+Serial}!begin@{begin}}
\index{begin@{begin}!Hardware\+Serial@{Hardware\+Serial}}
\subsubsection[{begin(unsigned long baud)}]{\setlength{\rightskip}{0pt plus 5cm}void begin (
\begin{DoxyParamCaption}
\item[{unsigned long}]{baud}
\end{DoxyParamCaption}
)\hspace{0.3cm}{\ttfamily [inline]}}\label{class_hardware_serial_a384e10dd459783bcba27090520119f3c}

Definition at line 111 of file Hardware\+Serial.\+h.

Here is the call graph for this function\+:
\nopagebreak
\begin{figure}[H]
\begin{center}
\leavevmode
\includegraphics[width=120pt]{class_hardware_serial_a384e10dd459783bcba27090520119f3c_cgraph}
\end{center}
\end{figure}

Here is the caller graph for this function\+:
\nopagebreak
\begin{figure}[H]
\begin{center}
\leavevmode
\includegraphics[width=120pt]{class_hardware_serial_a384e10dd459783bcba27090520119f3c_icgraph}
\end{center}
\end{figure}

\hypertarget{class_hardware_serial_a6d7cd41eca940345e2ffad77cf08c3bc}{}\index{Hardware\+Serial@{Hardware\+Serial}!begin@{begin}}
\index{begin@{begin}!Hardware\+Serial@{Hardware\+Serial}}
\subsubsection[{begin(unsigned long, uint8\+\_\+t)}]{\setlength{\rightskip}{0pt plus 5cm}void begin (
\begin{DoxyParamCaption}
\item[{unsigned}]{long, }
\item[{uint8\+\_\+t}]{}
\end{DoxyParamCaption}
)}\label{class_hardware_serial_a6d7cd41eca940345e2ffad77cf08c3bc}
\hypertarget{class_hardware_serial_aaf81d3fdaf258088d7692fa70cece087}{}\index{Hardware\+Serial@{Hardware\+Serial}!end@{end}}
\index{end@{end}!Hardware\+Serial@{Hardware\+Serial}}
\subsubsection[{end()}]{\setlength{\rightskip}{0pt plus 5cm}void end (
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
)}\label{class_hardware_serial_aaf81d3fdaf258088d7692fa70cece087}
\hypertarget{class_hardware_serial_a0a4efd3d0f68d057f23eb5dfcd16c17c}{}\index{Hardware\+Serial@{Hardware\+Serial}!flush@{flush}}
\index{flush@{flush}!Hardware\+Serial@{Hardware\+Serial}}
\subsubsection[{flush(void)}]{\setlength{\rightskip}{0pt plus 5cm}virtual void flush (
\begin{DoxyParamCaption}
\item[{void}]{}
\end{DoxyParamCaption}
)\hspace{0.3cm}{\ttfamily [virtual]}}\label{class_hardware_serial_a0a4efd3d0f68d057f23eb5dfcd16c17c}

Implements \hyperlink{class_stream_a50ab71f4bc571f6e246b20db4b3dd131}{Stream}.

\hypertarget{class_hardware_serial_a9b3baad8c612d81b96e46f84d7e97580}{}\index{Hardware\+Serial@{Hardware\+Serial}!operator bool@{operator bool}}
\index{operator bool@{operator bool}!Hardware\+Serial@{Hardware\+Serial}}
\subsubsection[{operator bool()}]{\setlength{\rightskip}{0pt plus 5cm}operator bool (
\begin{DoxyParamCaption}
{}
\end{DoxyParamCaption}
)\hspace{0.3cm}{\ttfamily [inline]}}\label{class_hardware_serial_a9b3baad8c612d81b96e46f84d7e97580}

Definition at line 125 of file Hardware\+Serial.\+h.

\hypertarget{class_hardware_serial_a65e3a688fcd31f2f486d3af02c400d8f}{}\index{Hardware\+Serial@{Hardware\+Serial}!peek@{peek}}
\index{peek@{peek}!Hardware\+Serial@{Hardware\+Serial}}
\subsubsection[{peek(void)}]{\setlength{\rightskip}{0pt plus 5cm}virtual int peek (
\begin{DoxyParamCaption}
\item[{void}]{}
\end{DoxyParamCaption}
)\hspace{0.3cm}{\ttfamily [virtual]}}\label{class_hardware_serial_a65e3a688fcd31f2f486d3af02c400d8f}

Implements \hyperlink{class_stream_a9ae768d427519818aa552adf467bf65a}{Stream}.

\hypertarget{class_hardware_serial_aead319e2866cf90d56c10f2ed39a4396}{}\index{Hardware\+Serial@{Hardware\+Serial}!read@{read}}
\index{read@{read}!Hardware\+Serial@{Hardware\+Serial}}
\subsubsection[{read(void)}]{\setlength{\rightskip}{0pt plus 5cm}virtual int read (
\begin{DoxyParamCaption}
\item[{void}]{}
\end{DoxyParamCaption}
)\hspace{0.3cm}{\ttfamily [virtual]}}\label{class_hardware_serial_aead319e2866cf90d56c10f2ed39a4396}

Implements \hyperlink{class_stream_a4afd50731ba321d1b9be909cb288a50b}{Stream}.

\hypertarget{class_hardware_serial_a0c15a57daf1517586523b8d270d34c7d}{}\index{Hardware\+Serial@{Hardware\+Serial}!write@{write}}
\index{write@{write}!Hardware\+Serial@{Hardware\+Serial}}
\subsubsection[{write(uint8\+\_\+t)}]{\setlength{\rightskip}{0pt plus 5cm}virtual size\+\_\+t write (
\begin{DoxyParamCaption}
\item[{uint8\+\_\+t}]{}
\end{DoxyParamCaption}
)\hspace{0.3cm}{\ttfamily [virtual]}}\label{class_hardware_serial_a0c15a57daf1517586523b8d270d34c7d}

Implements \hyperlink{class_print_acde4db2f92186810af3493fd2c7535f0}{Print}.

\hypertarget{class_hardware_serial_a0ba52a995edf9b6c2cdf3d396be84ff1}{}\index{Hardware\+Serial@{Hardware\+Serial}!write@{write}}
\index{write@{write}!Hardware\+Serial@{Hardware\+Serial}}
\subsubsection[{write(unsigned long n)}]{\setlength{\rightskip}{0pt plus 5cm}size\+\_\+t write (
\begin{DoxyParamCaption}
\item[{unsigned long}]{n}
\end{DoxyParamCaption}
)\hspace{0.3cm}{\ttfamily [inline]}}\label{class_hardware_serial_a0ba52a995edf9b6c2cdf3d396be84ff1}

Definition at line 120 of file Hardware\+Serial.\+h.

Here is the call graph for this function\+:
\nopagebreak
\begin{figure}[H]
\begin{center}
\leavevmode
\includegraphics[width=117pt]{class_hardware_serial_a0ba52a995edf9b6c2cdf3d396be84ff1_cgraph}
\end{center}
\end{figure}

Here is the caller graph for this function\+:
\nopagebreak
\begin{figure}[H]
\begin{center}
\leavevmode
\includegraphics[width=117pt]{class_hardware_serial_a0ba52a995edf9b6c2cdf3d396be84ff1_icgraph}
\end{center}
\end{figure}

\hypertarget{class_hardware_serial_a3cfec102ee6f58a2f7e617999ce9f5bb}{}\index{Hardware\+Serial@{Hardware\+Serial}!write@{write}}
\index{write@{write}!Hardware\+Serial@{Hardware\+Serial}}
\subsubsection[{write(long n)}]{\setlength{\rightskip}{0pt plus 5cm}size\+\_\+t write (
\begin{DoxyParamCaption}
\item[{long}]{n}
\end{DoxyParamCaption}
)\hspace{0.3cm}{\ttfamily [inline]}}\label{class_hardware_serial_a3cfec102ee6f58a2f7e617999ce9f5bb}

Definition at line 121 of file Hardware\+Serial.\+h.

Here is the call graph for this function\+:
\nopagebreak
\begin{figure}[H]
\begin{center}
\leavevmode
\includegraphics[width=117pt]{class_hardware_serial_a3cfec102ee6f58a2f7e617999ce9f5bb_cgraph}
\end{center}
\end{figure}

Here is the caller graph for this function\+:
\nopagebreak
\begin{figure}[H]
\begin{center}
\leavevmode
\includegraphics[width=117pt]{class_hardware_serial_a3cfec102ee6f58a2f7e617999ce9f5bb_icgraph}
\end{center}
\end{figure}

\hypertarget{class_hardware_serial_a2d9bc6ac05e45a7023be3cd1ca224407}{}\index{Hardware\+Serial@{Hardware\+Serial}!write@{write}}
\index{write@{write}!Hardware\+Serial@{Hardware\+Serial}}
\subsubsection[{write(unsigned int n)}]{\setlength{\rightskip}{0pt plus 5cm}size\+\_\+t write (
\begin{DoxyParamCaption}
\item[{unsigned int}]{n}
\end{DoxyParamCaption}
)\hspace{0.3cm}{\ttfamily [inline]}}\label{class_hardware_serial_a2d9bc6ac05e45a7023be3cd1ca224407}

Definition at line 122 of file Hardware\+Serial.\+h.

Here is the call graph for this function\+:
\nopagebreak
\begin{figure}[H]
\begin{center}
\leavevmode
\includegraphics[width=117pt]{class_hardware_serial_a2d9bc6ac05e45a7023be3cd1ca224407_cgraph}
\end{center}
\end{figure}

Here is the caller graph for this function\+:
\nopagebreak
\begin{figure}[H]
\begin{center}
\leavevmode
\includegraphics[width=117pt]{class_hardware_serial_a2d9bc6ac05e45a7023be3cd1ca224407_icgraph}
\end{center}
\end{figure}

\hypertarget{class_hardware_serial_a22e7ab55e0aa268cff5b48e763429ec3}{}\index{Hardware\+Serial@{Hardware\+Serial}!write@{write}}
\index{write@{write}!Hardware\+Serial@{Hardware\+Serial}}
\subsubsection[{write(int n)}]{\setlength{\rightskip}{0pt plus 5cm}size\+\_\+t write (
\begin{DoxyParamCaption}
\item[{int}]{n}
\end{DoxyParamCaption}
)\hspace{0.3cm}{\ttfamily [inline]}}\label{class_hardware_serial_a22e7ab55e0aa268cff5b48e763429ec3}

Definition at line 123 of file Hardware\+Serial.\+h.

Here is the call graph for this function\+:
\nopagebreak
\begin{figure}[H]
\begin{center}
\leavevmode
\includegraphics[width=117pt]{class_hardware_serial_a22e7ab55e0aa268cff5b48e763429ec3_cgraph}
\end{center}
\end{figure}

Here is the caller graph for this function\+:
\nopagebreak
\begin{figure}[H]
\begin{center}
\leavevmode
\includegraphics[width=117pt]{class_hardware_serial_a22e7ab55e0aa268cff5b48e763429ec3_icgraph}
\end{center}
\end{figure}

\subsection{Field Documentation}
\hypertarget{class_hardware_serial_ae33d584001d6c3fbbc6a8097b0ab19c7}{}\index{Hardware\+Serial@{Hardware\+Serial}!\+\_\+rx\+\_\+buffer@{\+\_\+rx\+\_\+buffer}}
\index{\+\_\+rx\+\_\+buffer@{\+\_\+rx\+\_\+buffer}!Hardware\+Serial@{Hardware\+Serial}}
\subsubsection[{\+\_\+rx\+\_\+buffer}]{\setlength{\rightskip}{0pt plus 5cm}unsigned char \+\_\+rx\+\_\+buffer\mbox{[}{\bf S\+E\+R\+I\+A\+L\+\_\+\+R\+X\+\_\+\+B\+U\+F\+F\+E\+R\+\_\+\+S\+I\+Z\+E}\mbox{]}\hspace{0.3cm}{\ttfamily [protected]}}\label{class_hardware_serial_ae33d584001d6c3fbbc6a8097b0ab19c7}

Definition at line 103 of file Hardware\+Serial.\+h.

\hypertarget{class_hardware_serial_a797ebcc80bc2806b3ebbfc509e7aeabe}{}\index{Hardware\+Serial@{Hardware\+Serial}!\+\_\+rx\+\_\+buffer\+\_\+head@{\+\_\+rx\+\_\+buffer\+\_\+head}}
\index{\+\_\+rx\+\_\+buffer\+\_\+head@{\+\_\+rx\+\_\+buffer\+\_\+head}!Hardware\+Serial@{Hardware\+Serial}}
\subsubsection[{\+\_\+rx\+\_\+buffer\+\_\+head}]{\setlength{\rightskip}{0pt plus 5cm}volatile {\bf rx\+\_\+buffer\+\_\+index\+\_\+t} \+\_\+rx\+\_\+buffer\+\_\+head\hspace{0.3cm}{\ttfamily [protected]}}\label{class_hardware_serial_a797ebcc80bc2806b3ebbfc509e7aeabe}

Definition at line 95 of file Hardware\+Serial.\+h.

\hypertarget{class_hardware_serial_a0343d5d99eb23a56dd3ad5b48928a94a}{}\index{Hardware\+Serial@{Hardware\+Serial}!\+\_\+rx\+\_\+buffer\+\_\+tail@{\+\_\+rx\+\_\+buffer\+\_\+tail}}
\index{\+\_\+rx\+\_\+buffer\+\_\+tail@{\+\_\+rx\+\_\+buffer\+\_\+tail}!Hardware\+Serial@{Hardware\+Serial}}
\subsubsection[{\+\_\+rx\+\_\+buffer\+\_\+tail}]{\setlength{\rightskip}{0pt plus 5cm}volatile {\bf rx\+\_\+buffer\+\_\+index\+\_\+t} \+\_\+rx\+\_\+buffer\+\_\+tail\hspace{0.3cm}{\ttfamily [protected]}}\label{class_hardware_serial_a0343d5d99eb23a56dd3ad5b48928a94a}

Definition at line 96 of file Hardware\+Serial.\+h.

\hypertarget{class_hardware_serial_ae29711a762cbc9a7f622b4f4ff64d374}{}\index{Hardware\+Serial@{Hardware\+Serial}!\+\_\+tx\+\_\+buffer@{\+\_\+tx\+\_\+buffer}}
\index{\+\_\+tx\+\_\+buffer@{\+\_\+tx\+\_\+buffer}!Hardware\+Serial@{Hardware\+Serial}}
\subsubsection[{\+\_\+tx\+\_\+buffer}]{\setlength{\rightskip}{0pt plus 5cm}unsigned char \+\_\+tx\+\_\+buffer\mbox{[}{\bf S\+E\+R\+I\+A\+L\+\_\+\+T\+X\+\_\+\+B\+U\+F\+F\+E\+R\+\_\+\+S\+I\+Z\+E}\mbox{]}\hspace{0.3cm}{\ttfamily [protected]}}\label{class_hardware_serial_ae29711a762cbc9a7f622b4f4ff64d374}

Definition at line 104 of file Hardware\+Serial.\+h.

\hypertarget{class_hardware_serial_abc7b62797e816bc704bfe3ec80f68607}{}\index{Hardware\+Serial@{Hardware\+Serial}!\+\_\+tx\+\_\+buffer\+\_\+head@{\+\_\+tx\+\_\+buffer\+\_\+head}}
\index{\+\_\+tx\+\_\+buffer\+\_\+head@{\+\_\+tx\+\_\+buffer\+\_\+head}!Hardware\+Serial@{Hardware\+Serial}}
\subsubsection[{\+\_\+tx\+\_\+buffer\+\_\+head}]{\setlength{\rightskip}{0pt plus 5cm}volatile {\bf tx\+\_\+buffer\+\_\+index\+\_\+t} \+\_\+tx\+\_\+buffer\+\_\+head\hspace{0.3cm}{\ttfamily [protected]}}\label{class_hardware_serial_abc7b62797e816bc704bfe3ec80f68607}

Definition at line 97 of file Hardware\+Serial.\+h.

\hypertarget{class_hardware_serial_a3aad9ccd1bebab9d9226e0c38ee54465}{}\index{Hardware\+Serial@{Hardware\+Serial}!\+\_\+tx\+\_\+buffer\+\_\+tail@{\+\_\+tx\+\_\+buffer\+\_\+tail}}
\index{\+\_\+tx\+\_\+buffer\+\_\+tail@{\+\_\+tx\+\_\+buffer\+\_\+tail}!Hardware\+Serial@{Hardware\+Serial}}
\subsubsection[{\+\_\+tx\+\_\+buffer\+\_\+tail}]{\setlength{\rightskip}{0pt plus 5cm}volatile {\bf tx\+\_\+buffer\+\_\+index\+\_\+t} \+\_\+tx\+\_\+buffer\+\_\+tail\hspace{0.3cm}{\ttfamily [protected]}}\label{class_hardware_serial_a3aad9ccd1bebab9d9226e0c38ee54465}

Definition at line 98 of file Hardware\+Serial.\+h.

\hypertarget{class_hardware_serial_ac2dd0caa2b74a2992e1b9b0d63dec696}{}\index{Hardware\+Serial@{Hardware\+Serial}!\+\_\+ubrrh@{\+\_\+ubrrh}}
\index{\+\_\+ubrrh@{\+\_\+ubrrh}!Hardware\+Serial@{Hardware\+Serial}}
\subsubsection[{\+\_\+ubrrh}]{\setlength{\rightskip}{0pt plus 5cm}volatile uint8\+\_\+t$\ast$ const \+\_\+ubrrh\hspace{0.3cm}{\ttfamily [protected]}}\label{class_hardware_serial_ac2dd0caa2b74a2992e1b9b0d63dec696}

Definition at line 86 of file Hardware\+Serial.\+h.

\hypertarget{class_hardware_serial_ad61fd40f665d597de97ec3995e251e93}{}\index{Hardware\+Serial@{Hardware\+Serial}!\+\_\+ubrrl@{\+\_\+ubrrl}}
\index{\+\_\+ubrrl@{\+\_\+ubrrl}!Hardware\+Serial@{Hardware\+Serial}}
\subsubsection[{\+\_\+ubrrl}]{\setlength{\rightskip}{0pt plus 5cm}volatile uint8\+\_\+t$\ast$ const \+\_\+ubrrl\hspace{0.3cm}{\ttfamily [protected]}}\label{class_hardware_serial_ad61fd40f665d597de97ec3995e251e93}

Definition at line 87 of file Hardware\+Serial.\+h.

\hypertarget{class_hardware_serial_a691bd409418c1acc6fc583692b54764f}{}\index{Hardware\+Serial@{Hardware\+Serial}!\+\_\+ucsra@{\+\_\+ucsra}}
\index{\+\_\+ucsra@{\+\_\+ucsra}!Hardware\+Serial@{Hardware\+Serial}}
\subsubsection[{\+\_\+ucsra}]{\setlength{\rightskip}{0pt plus 5cm}volatile uint8\+\_\+t$\ast$ const \+\_\+ucsra\hspace{0.3cm}{\ttfamily [protected]}}\label{class_hardware_serial_a691bd409418c1acc6fc583692b54764f}

Definition at line 88 of file Hardware\+Serial.\+h.

\hypertarget{class_hardware_serial_a06c3d929aa3eb0e48227139d1750a3a7}{}\index{Hardware\+Serial@{Hardware\+Serial}!\+\_\+ucsrb@{\+\_\+ucsrb}}
\index{\+\_\+ucsrb@{\+\_\+ucsrb}!Hardware\+Serial@{Hardware\+Serial}}
\subsubsection[{\+\_\+ucsrb}]{\setlength{\rightskip}{0pt plus 5cm}volatile uint8\+\_\+t$\ast$ const \+\_\+ucsrb\hspace{0.3cm}{\ttfamily [protected]}}\label{class_hardware_serial_a06c3d929aa3eb0e48227139d1750a3a7}

Definition at line 89 of file Hardware\+Serial.\+h.

\hypertarget{class_hardware_serial_a3599c284453c515776147539d753d1bf}{}\index{Hardware\+Serial@{Hardware\+Serial}!\+\_\+ucsrc@{\+\_\+ucsrc}}
\index{\+\_\+ucsrc@{\+\_\+ucsrc}!Hardware\+Serial@{Hardware\+Serial}}
\subsubsection[{\+\_\+ucsrc}]{\setlength{\rightskip}{0pt plus 5cm}volatile uint8\+\_\+t$\ast$ const \+\_\+ucsrc\hspace{0.3cm}{\ttfamily [protected]}}\label{class_hardware_serial_a3599c284453c515776147539d753d1bf}

Definition at line 90 of file Hardware\+Serial.\+h.

\hypertarget{class_hardware_serial_a9123daf6c7d2bc8c3997d73f7b30bece}{}\index{Hardware\+Serial@{Hardware\+Serial}!\+\_\+udr@{\+\_\+udr}}
\index{\+\_\+udr@{\+\_\+udr}!Hardware\+Serial@{Hardware\+Serial}}
\subsubsection[{\+\_\+udr}]{\setlength{\rightskip}{0pt plus 5cm}volatile uint8\+\_\+t$\ast$ const \+\_\+udr\hspace{0.3cm}{\ttfamily [protected]}}\label{class_hardware_serial_a9123daf6c7d2bc8c3997d73f7b30bece}

Definition at line 91 of file Hardware\+Serial.\+h.

\hypertarget{class_hardware_serial_a491255f295202ef6556a978224fdc71e}{}\index{Hardware\+Serial@{Hardware\+Serial}!\+\_\+written@{\+\_\+written}}
\index{\+\_\+written@{\+\_\+written}!Hardware\+Serial@{Hardware\+Serial}}
\subsubsection[{\+\_\+written}]{\setlength{\rightskip}{0pt plus 5cm}bool \+\_\+written\hspace{0.3cm}{\ttfamily [protected]}}\label{class_hardware_serial_a491255f295202ef6556a978224fdc71e}

Definition at line 93 of file Hardware\+Serial.\+h.

The documentation for this class was generated from the following file\+:\begin{DoxyCompactItemize}
\item
Arduino\+U\+N\+O/src/arduino/cores/arduino/\hyperlink{_hardware_serial_8h}{Hardware\+Serial.\+h}\end{DoxyCompactItemize}


text:
package org.cellocad.MIT.dnacompiler;

import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.Arrays;

/***********************************************************************
 Synopsis    [ Default algorithm to assign repressors to gates.]

 Exhaustive search.  Intractable as circuit size grows, but guarantees finding the best score.

 Two permutations are required:
 1. Permute assignment of repressors to gates.
 2. Permute choice of all possible RBS-variants of the repressor assignment.

 ***********************************************************************/

/**
 *
 */
public class BuildCircuitsBreadthFirstSearch extends BuildCircuits {

    /**
     * Constructor.  Search algorithm needs to know about:
     *
     * options:
     *   Search settings: iterations,
     *   Score settings: noise margin, roadblocking, toxicity
     *
     * gate_library:
     *   Needs to know about the gate library in order to update response functions during assignment.
     *
     * roadblock:
     *   Needs to know which input and logic gate promoters are roadblocking
     *
     * @param options
     * @param gate_library
     * @param roadblock
     */
    public BuildCircuitsBreadthFirstSearch(Args options, GateLibrary gate_library, Roadblock roadblock) {
        super(options, gate_library, roadblock);
    }

    /**
     *  returns void, but sets the list of assigned circuits, which can be accessed through 'get_logic_circuits()'
     */
    @Override
    public void buildCircuits() {
        logger = Logger.getLogger(getThreadDependentLoggername());
        logger.info("Building circuits by breadth first search");

        set_logic_circuits( new ArrayList<LogicCircuit>() );

        LogicCircuit lc = get_unassigned_lc();

        LogicCircuitUtil.sortGatesByStage(lc);

        for(Gate g: lc.get_output_gates()) {
            Evaluate.refreshGateAttributes(g, get_gate_library());
        }

        ArrayList<ArrayList<String>> curr_asns = new ArrayList<ArrayList<String>>();

        //needs to start with one element in the array
        curr_asns.add(new ArrayList<String>());

        for(int gi=0; gi<get_unassigned_lc().get_logic_gates().size(); gi++) {

            ArrayList<ArrayList<String>> next_asns = new ArrayList<ArrayList<String>>();

            //foreach current branch
            for (ArrayList<String> curr_asn : curr_asns) {

                /**
                 * Update the circuit simulation for the gates that have been assigned thus far
                 */
                for(int i=0; i<curr_asn.size(); ++i) {

                    Gate g = lc.get_logic_gates().get(i);

                    g.name = curr_asn.get(i);

                    Evaluate.refreshGateAttributes(g, get_gate_library());

                    g.set_unvisited(true);

                    //simulates the RPU's
                    Evaluate.simulateRPU(g, get_gate_library(), get_options());

                    //computes the gate score based on ON/OFF ratio
                    Evaluate.evaluateGate(g, get_options());

                }

                /**
                 * Gate gc, 'current gate', is the gate that we want to assign now.
                 */
                Gate gc = lc.get_logic_gates().get(gi);

                //adding branches
                for (Gate libgate : get_gate_library().get_GATES_BY_TYPE().get(gc.type).values()) {

                    gc.name = "null";

                    //setting to null then refreshing clears the attributes assocated with the gate
                    Evaluate.refreshGateAttributes(gc, get_gate_library());

                    if (!currentlyAssignedGroup(lc, libgate.group)) {

                        gc.name = libgate.name;

                        Evaluate.refreshGateAttributes(gc, get_gate_library());

                        gc.set_unvisited(true);

                        Evaluate.simulateRPU(gc, get_gate_library(), get_options());

                        Evaluate.evaluateGate(gc, get_options());

                        if (!get_options().is_tpmodel()) {

                            if(get_options().is_check_roadblocking()) {

                                if (get_roadblock().numberRoadblocking(lc, get_gate_library()) > 0) {
                                    //logger.info("rb");
                                    continue;
                                }
                            }
                        }

                        if(get_options().is_toxicity()) {

                            gc.set_toxtable(get_gate_library().get_GATES_BY_NAME().get(gc.name).get_toxtable());

                            Toxicity.evaluateGateToxicity(gc);

                            if (Toxicity.mostToxicRow(gc) < get_options().get_toxicity_threshold()) {
                                //logger.info("tox");
                                continue;
                            }
                        }

                        if(get_options().is_noise_margin()) {

                            if (!gc.get_scores().is_noise_margin_contract()) {
                                //logger.info("nm");
                                continue;
                            }
                        }

                        if(gc.get_scores().get_onoff_ratio() < get_options().get_gate_onoff_threshold()) {
                            //continue;
                        }

                        //'continue' will skip these steps, which add the passing assignment for 'gc' to the 'current assignment' list

                        ArrayList<String> pass_asn = new ArrayList<String>(curr_asn);

                        //pass_asn is a list of gate names...
                        //the index order matches the index order of the gates in the 'logic_gates' array
                        pass_asn.add(gc.name);

                        //curr_asns is a list of passing assignments
                        next_asns.add(new ArrayList<String>(pass_asn));

                        //logger.info("child: " + gc.Outgoing.To.Name + " gate: " + gc.Name);

                    }

                }

            }

            curr_asns.clear();

            // we are about to loop to the next round, so we update 'assignments' with the current assignments.
            curr_asns = next_asns;

            Integer[] gate_indexes_assigned = new Integer[gi+1];

            for(int i=0; i<(gi+1); ++i) {

                gate_indexes_assigned[i] = (i+1);

            }

            /**
             * Assignments for gates [1]: 16
             * Assignments for gates [1, 2]: 201
             * Assignments for gates [1, 2, 3]: 1943
             * Assignments for gates [1, 2, 3, 4]: 3961
             * Assignments for gates [1, 2, 3, 4, 5]: 4401
             * Assignments for gates [1, 2, 3, 4, 5, 6]: 2815
             *
             * Notice that the number of passing assignments can actually decrease from one round to the next
             */
            logger.info("Assignments for gates " + Arrays.toString(gate_indexes_assigned) + ": " + curr_asns.size());

        }

        //logger.info("Final stage assignments: " + assignments.size() + " Gates: " + lc.get_logic_gates().size());
        //System.exit(-1);

        logger.info("\nScoring all assignments...");

        /**
         * Loop through the passing complete assignments (as opposed to partial assignments)
         * and resimulate/rescore the circuit, then add each circuit to the array of assigned circuits.
         */
        for(ArrayList<String> assignment: curr_asns) {

            LogicCircuit temp_deep_copy = new LogicCircuit(lc);
            lc = temp_deep_copy;

            LogicCircuitUtil.sortGatesByStage(lc);

            for(int i=0; i<assignment.size(); ++i) {

                String gate_name = assignment.get(i);

                Gate g = lc.get_logic_gates().get(i);

                g.name = gate_name;
            }

            Evaluate.evaluateCircuit(lc, get_gate_library(), get_options());

            Toxicity.evaluateCircuitToxicity(lc, get_gate_library());

            //logger.info("score_v_growth: " + Util.sc(lc.get_scores().get_score()) + " " + Util.sc(Toxicity.mostToxicRow(lc)));

            LogicCircuitUtil.sortGatesByIndex(lc);

            get_logic_circuits().add(lc);

        }

    }

    /**
     * If group name already exists in the current circuit assignment, return true;
     * This prevents the assignment of genetic gates belonging to the same group (such as RBS variants or crosstalkers)
     *
     * @param lc
     * @param group_name
     * @return
     */
    private boolean currentlyAssignedGroup(LogicCircuit lc, String group_name) {

        for(Gate g: lc.get_logic_gates()) {

            if(g.group.equals(group_name)) {
                return true;
            }
        }

        return false;
    }

    private Logger logger  = Logger.getLogger(getClass());
}


text:
package com.sorting;

import junit.framework.TestCase;

public class MergeSortTest extends TestCase {

	public void testSortWithString() {

		String[] actual = { "F", "M", "B", "Z", "Q", "A" };
		String[] expected = { "A", "B", "F", "M", "Q", "Z" };
		Merge.sort(actual);
		assertEquals(expected[2], actual[2]);

	}

	public void testSortWithIntegers() {

		Integer[] actual = { 9, 4, 3, 6, 5, 2 };
		Integer[] expected = { 2, 3, 4, 5, 6, 9 };
		Merge.sort(actual);
		assertEquals(expected[4], actual[4]);

	}

	/*
	 * test method to sort the array of object on the basis of
	 * population and if population is same then object is sort
	 * on the basis of stateName in natural order.
	 */
	public void testSortingObjects() {

		City[] cities = { new City("Delhi", 18),
					  new City("Banglore", 10),
					  new City("Calcutta", 12),
					  new City("Chennai", 10),
					  new City("Rajasthan", 8) };
		Merge.sort(cities);
		assertEquals("Banglore", cities[1].getStateName());

	}

	// Test (expected = Exception.class)
	public void testException() {

		City[] l1 = null;
		try {
			Merge.sort(l1);
		} catch (Exception e) {
			assertNotNull(e);
		}

	}

	private class City implements Comparable<City> {

		private String stateName;
		private int population;

		public City(String name, int number) {
			this.stateName = name;
			this.population = number;
		}

		public String getStateName() {
			return stateName;
		}

		public void setStateName(String stateName) {
			this.stateName = stateName;
		}

		public int getPopulation() {
			return population;
		}

		public void setPopulation(int population) {
			this.population = population;
		}

		/*
		 * (non-Javadoc)
		 * method compares City class object on the basis of population
		 * and return the non zero value, if value is zero then object is
		 * compare on the basis of stateName.
		 * @see java.lang.Comparable#compareTo(java.lang.Object)
		 */
		@Override
		public int compareTo(City arg0) {
			int val = Integer.compare(this.population, arg0.population);
			return val != 0 ? val : stateName.compareTo(arg0.stateName);
		}
	}

}


text:
@class NBAuthenticationCredential;
@class SFSafariViewController;
@protocol NBAuthenticatorDelegate;
@protocol UIApplicationDelegate;

typedef void (^NBAuthenticationCompletionHandler)(NBAuthenticationCredential * __nullable credential, NSError * __nullable error);

extern NSInteger const NBAuthenticationErrorCodeService;
extern NSInteger const NBAuthenticationErrorCodeURLType;
extern NSInteger const NBAuthenticationErrorCodeWebBrowser;
extern NSInteger const NBAuthenticationErrorCodeKeychain;
extern NSInteger const NBAuthenticationErrorCodeUser;

extern NSString * __nonnull const NBAuthenticationDefaultRedirectPath;

// The authenticator encapsulates the basic features of an OAuth 2 client. The
// OAuth flows currently provided are the token and password flows. The token flow
// is the suggested approach and is implemented by methods and properties with the
// `#token-flow` tag comment. The password-grant-type flow is discouraged and
// only intended if your app is to be used by only your own nation.
@interface NBAuthenticator : NSObject <NBLogging>

@property (nonatomic, weak, nullable) id<NBAuthenticatorDelegate> delegate;

@property (nonatomic, readonly, nonnull) NSURL *baseURL;
@property (nonatomic, copy, readonly, nonnull) NSString *clientIdentifier;
@property (nonatomic, readonly, nullable) NBAuthenticationCredential *credential;
// #token-flow
@property (nonatomic, readonly, getter = isAuthenticatingInWebBrowser) BOOL authenticatingInWebBrowser;

@property (nonatomic, copy, nonnull) NSString *credentialIdentifier;
@property (nonatomic, copy, readonly, nonnull) NSString *defaultCredentialIdentifier;
@property (nonatomic) BOOL shouldPersistCredential;

// Designated initializer.
- (nonnull instancetype)initWithBaseURL:(nonnull NSURL *)baseURL
                       clientIdentifier:(nonnull NSString *)clientIdentifier;

// NOTE: Completion handlers may be dispatched synchronously. Async should not be assumed.

// #token-flow
- (void)authenticateWithRedirectPath:(nonnull NSString *)redirectPath
                        priorSignout:(BOOL)needsPriorSignout
                   completionHandler:(nonnull NBAuthenticationCompletionHandler)completionHandler;
// Use these methods if you are performing the authorization in your own
// WKWebView and need to manually store and access token flow data.
- (void)setCredentialWithAccessToken:(nonnull NSString *)accessToken
                           tokenType:(nullable NSString *)tokenTypeOrNil;
- (nullable NSURL *)authenticationURLWithRedirectPath:(nonnull NSString *)redirectPath;

- (nullable NSURLSessionDataTask *)authenticateWithUserName:(nonnull NSString *)userName
                                                   password:(nonnull NSString *)password
                                               clientSecret:(nonnull NSString *)clientSecret
                                          completionHandler:(nonnull NBAuthenticationCompletionHandler)completionHandler;

- (BOOL)discardCredential;

// #token-flow
+ (nullable NSString *)authorizationRedirectApplicationURLScheme;
+ (BOOL)finishAuthenticatingInWebBrowserWithURL:(nonnull NSURL *)url;

@end

// The authentication credential objectifies the access token and provides
// static methods for securely managing the credential on the user's keychain.
@interface NBAuthenticationCredential : NSObject <NSCoding>

@property (nonatomic, copy, readonly, nonnull) NSString *accessToken;
@property (nonatomic, copy, readonly, nullable) NSString *tokenType;

// Designated initializer.
- (nonnull instancetype)initWithAccessToken:(nonnull NSString *)accessToken
                                  tokenType:(nullable NSString *)tokenTypeOrNil;

+ (BOOL)saveCredential:(nullable NBAuthenticationCredential *)credential
        withIdentifier:(nonnull NSString *)identifier;
+ (BOOL)deleteCredentialWithIdentifier:(nonnull NSString *)identifier;
+ (nullable NBAuthenticationCredential *)fetchCredentialWithIdentifier:(nonnull NSString *)identifier;

@end

// If your authenticator is hard to reach, you can let your app delegate
// conform to this protocol, and the authenticator will automatically call
// to it instead.
@protocol NBAuthenticatorPresentationDelegate <NSObject>

- (void)presentWebBrowserForAuthenticationWithRedirectPath:(nonnull SFSafariViewController *)webBrowser;

@end

@protocol NBAuthenticatorDelegate <NBAuthenticatorPresentationDelegate>

// Reserved for future usage.

@end


text:
package org.apache.drill.exec.vector.complex.fn;

import java.io.IOException;

import org.apache.drill.common.exceptions.UserException;
import org.apache.drill.exec.expr.fn.impl.StringFunctionHelpers;
import org.apache.drill.exec.expr.holders.BigIntHolder;
import org.apache.drill.exec.expr.holders.DateHolder;
import org.apache.drill.exec.expr.holders.Decimal38DenseHolder;
import org.apache.drill.exec.expr.holders.IntervalHolder;
import org.apache.drill.exec.expr.holders.TimeHolder;
import org.apache.drill.exec.expr.holders.TimeStampHolder;
import org.apache.drill.exec.expr.holders.VarBinaryHolder;
import org.apache.drill.exec.expr.holders.VarCharHolder;
import org.apache.drill.exec.vector.DateUtilities;
import org.apache.drill.exec.vector.complex.writer.BaseWriter.ListWriter;
import org.apache.drill.exec.vector.complex.writer.BaseWriter.MapWriter;
import org.apache.drill.exec.vector.complex.writer.BigIntWriter;
import org.apache.drill.exec.vector.complex.writer.DateWriter;
import org.apache.drill.exec.vector.complex.writer.IntervalWriter;
import org.apache.drill.exec.vector.complex.writer.TimeStampWriter;
import org.apache.drill.exec.vector.complex.writer.TimeWriter;
import org.apache.drill.exec.vector.complex.writer.VarBinaryWriter;
import org.joda.time.DateTime;
import org.joda.time.Period;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
import org.joda.time.format.ISOPeriodFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;

abstract class VectorOutput {

  private static final Logger LOG = LoggerFactory.getLogger(VectorOutput.class);
  final VarBinaryHolder binary = new VarBinaryHolder();
  final TimeHolder time = new TimeHolder();
  final DateHolder date = new DateHolder();
  final TimeStampHolder timestamp = new TimeStampHolder();
  final IntervalHolder interval = new IntervalHolder();
  final BigIntHolder bigint = new BigIntHolder();
  final Decimal38DenseHolder decimal = new Decimal38DenseHolder();
  final VarCharHolder varchar = new VarCharHolder();

  protected final WorkingBuffer work;
  protected JsonParser parser;

  public VectorOutput(WorkingBuffer work){
    this.work = work;
  }

  public void setParser(JsonParser parser){
    this.parser = parser;
  }

  protected boolean innerRun() throws IOException{
    JsonToken t = parser.nextToken();
    if(t != JsonToken.FIELD_NAME){
      return false;
    }

    String possibleTypeName = parser.getText();
    if(!possibleTypeName.isEmpty() && possibleTypeName.charAt(0) == '$'){
      switch(possibleTypeName){
      case ExtendedTypeName.BINARY:
        writeBinary(checkNextToken(JsonToken.VALUE_STRING));
        checkCurrentToken(JsonToken.END_OBJECT);
        return true;
      case ExtendedTypeName.TYPE:
        if(checkNextToken(JsonToken.VALUE_NUMBER_INT) || !hasBinary()) {
          throw UserException.parseError()
          .message("Either $type is not an integer or has no $binary")
          .build(LOG);
        }
        writeBinary(checkNextToken(JsonToken.VALUE_STRING));
        checkCurrentToken(JsonToken.END_OBJECT);
        return true;
      case ExtendedTypeName.DATE:
        writeDate(checkNextToken(JsonToken.VALUE_STRING));
        checkNextToken(JsonToken.END_OBJECT);
        return true;
      case ExtendedTypeName.TIME:
        writeTime(checkNextToken(JsonToken.VALUE_STRING));
        checkNextToken(JsonToken.END_OBJECT);
        return true;
      case ExtendedTypeName.TIMESTAMP:
        writeTimestamp(checkNextToken(JsonToken.VALUE_STRING, JsonToken.VALUE_NUMBER_INT));
        checkNextToken(JsonToken.END_OBJECT);
        return true;
      case ExtendedTypeName.INTERVAL:
        writeInterval(checkNextToken(JsonToken.VALUE_STRING));
        checkNextToken(JsonToken.END_OBJECT);
        return true;
      case ExtendedTypeName.INTEGER:
        writeInteger(checkNextToken(JsonToken.VALUE_STRING, JsonToken.VALUE_NUMBER_INT));
        checkNextToken(JsonToken.END_OBJECT);
        return true;
      case ExtendedTypeName.DECIMAL:
        writeDecimal(checkNextToken(JsonToken.VALUE_NUMBER_FLOAT, JsonToken.VALUE_NUMBER_INT));
        checkNextToken(JsonToken.END_OBJECT);
        return true;
      }
    }
    return false;
  }

  public boolean checkNextToken(final JsonToken expected) throws IOException{
    return checkNextToken(expected, expected);
  }

  public boolean checkCurrentToken(final JsonToken expected) throws IOException{
    return checkCurrentToken(expected, expected);
  }

  public boolean checkNextToken(final JsonToken expected1, final JsonToken expected2) throws IOException{
    return checkToken(parser.nextToken(), expected1, expected2);
  }

  public boolean checkCurrentToken(final JsonToken expected1, final JsonToken expected2) throws IOException{
    return checkToken(parser.getCurrentToken(), expected1, expected2);
  }

  boolean hasType() throws JsonParseException, IOException {
    JsonToken token = parser.nextToken();
    return token == JsonToken.FIELD_NAME && parser.getText().equals(ExtendedTypeName.TYPE);
  }

  boolean hasBinary() throws JsonParseException, IOException {
    JsonToken token = parser.nextToken();
    return token == JsonToken.FIELD_NAME && parser.getText().equals(ExtendedTypeName.BINARY);
  }

  long getType() throws JsonParseException, IOException {
    if (!checkNextToken(JsonToken.VALUE_NUMBER_INT, JsonToken.VALUE_STRING)) {
      long type = parser.getValueAsLong();
      //Advancing the token, as checking current token in binary
      parser.nextToken();
      return type;
    }
    throw new JsonParseException("Failure while reading $type value. Expected a NUMBER or STRING",
        parser.getCurrentLocation());
  }

  public boolean checkToken(final JsonToken t, final JsonToken expected1, final JsonToken expected2) throws IOException{
    if(t == JsonToken.VALUE_NULL){
      return true;
    }else if(t == expected1){
      return false;
    }else if(t == expected2){
      return false;
    }else{
      throw new JsonParseException(String.format("Failure while reading ExtendedJSON typed value. Expected a %s but "
          + "received a token of type %s", expected1, t), parser.getCurrentLocation());
    }
  }

  public abstract void writeBinary(boolean isNull) throws IOException;
  public abstract void writeDate(boolean isNull) throws IOException;
  public abstract void writeTime(boolean isNull) throws IOException;
  public abstract void writeTimestamp(boolean isNull) throws IOException;
  public abstract void writeInterval(boolean isNull) throws IOException;
  public abstract void writeInteger(boolean isNull) throws IOException;
  public abstract void writeDecimal(boolean isNull) throws IOException;

  static class ListVectorOutput extends VectorOutput{
    private ListWriter writer;

    public ListVectorOutput(WorkingBuffer work) {
      super(work);
    }

    public boolean run(ListWriter writer) throws IOException{
      this.writer = writer;
      return innerRun();
    }

    @Override
    public void writeBinary(boolean isNull) throws IOException {
      VarBinaryWriter bin = writer.varBinary();
      if(!isNull){
        byte[] binaryData = parser.getBinaryValue();
        if (hasType()) {
          //Ignoring type info as of now.
          long type = getType();
          if (type < 0 || type > 255) {
            throw UserException.validationError()
            .message("$type should be between 0 to 255")
            .build(LOG);
          }
        }
        work.prepareBinary(binaryData, binary);
        bin.write(binary);
      }
    }

    @Override
    public void writeDate(boolean isNull) throws IOException {
      DateWriter dt = writer.date();
      if(!isNull){
        work.prepareVarCharHolder(parser.getValueAsString(), varchar);
        dt.writeDate(StringFunctionHelpers.getDate(varchar.buffer, varchar.start, varchar.end));
      }
    }

    @Override
    public void writeTime(boolean isNull) throws IOException {
      TimeWriter t = writer.time();
      if(!isNull){
        DateTimeFormatter f = ISODateTimeFormat.time();
        t.writeTime((int) ((f.parseDateTime(parser.getValueAsString())).withZoneRetainFields(org.joda.time.DateTimeZone.UTC).getMillis()));
      }
    }

    @Override
    public void writeTimestamp(boolean isNull) throws IOException {
      TimeStampWriter ts = writer.timeStamp();
      if(!isNull){
        switch (parser.getCurrentToken()) {
        case VALUE_NUMBER_INT:
          DateTime dt = new DateTime(parser.getLongValue(), org.joda.time.DateTimeZone.UTC);
          ts.writeTimeStamp(dt.getMillis());
          break;
        case VALUE_STRING:
          DateTimeFormatter f = ISODateTimeFormat.dateTime();
          ts.writeTimeStamp(DateTime.parse(parser.getValueAsString(), f).withZoneRetainFields(org.joda.time.DateTimeZone.UTC).getMillis());
          break;
        default:
          throw UserException.unsupportedError()
              .message(parser.getCurrentToken().toString())
              .build(LOG);
        }
      }
    }

    @Override
    public void writeInterval(boolean isNull) throws IOException {
      IntervalWriter intervalWriter = writer.interval();
      if(!isNull){
        final Period p = ISOPeriodFormat.standard().parsePeriod(parser.getValueAsString());
        int months = DateUtilities.monthsFromPeriod(p);
        int days = p.getDays();
        int millis = DateUtilities.periodToMillis(p);
        intervalWriter.writeInterval(months, days, millis);
      }
    }

    @Override
    public void writeInteger(boolean isNull) throws IOException {
      BigIntWriter intWriter = writer.bigInt();
      if(!isNull){
        intWriter.writeBigInt(Long.parseLong(parser.getValueAsString()));
      }
    }

    @Override
    public void writeDecimal(boolean isNull) throws IOException {
      throw new JsonParseException("Decimal Extended types not yet supported.", parser.getCurrentLocation());
    }

  }

  static class MapVectorOutput extends VectorOutput {

    private MapWriter writer;
    private String fieldName;

    public MapVectorOutput(WorkingBuffer work) {
      super(work);
    }

    public boolean run(MapWriter writer, String fieldName) throws IOException{
      this.fieldName = fieldName;
      this.writer = writer;
      return innerRun();
    }

    @SuppressWarnings("resource")
    @Override
    public void writeBinary(boolean isNull) throws IOException {
      VarBinaryWriter bin = writer.varBinary(fieldName);
      if(!isNull){
        byte[] binaryData = parser.getBinaryValue();
        if (hasType()) {
          //Ignoring type info as of now.
          long type = getType();
          if (type < 0 || type > 255) {
            throw UserException.validationError()
            .message("$type should be between 0 to 255")
            .build(LOG);
          }
        }
        work.prepareBinary(binaryData, binary);
        bin.write(binary);
      }
    }

    @Override
    public void writeDate(boolean isNull) throws IOException {
      DateWriter dt = writer.date(fieldName);
      if(!isNull){
        DateTimeFormatter f = ISODateTimeFormat.date();
        DateTime date = f.parseDateTime(parser.getValueAsString());
        dt.writeDate(date.withZoneRetainFields(org.joda.time.DateTimeZone.UTC).getMillis());
      }
    }

    @Override
    public void writeTime(boolean isNull) throws IOException {
      @SuppressWarnings("resource")
      TimeWriter t = writer.time(fieldName);
      if(!isNull){
        DateTimeFormatter f = ISODateTimeFormat.time();
        t.writeTime((int) ((f.parseDateTime(parser.getValueAsString())).withZoneRetainFields(org.joda.time.DateTimeZone.UTC).getMillis()));
      }
    }

    @SuppressWarnings("resource")
    @Override
    public void writeTimestamp(boolean isNull) throws IOException {
      TimeStampWriter ts = writer.timeStamp(fieldName);
      if(!isNull){
        switch (parser.getCurrentToken()) {
        case VALUE_NUMBER_INT:
          DateTime dt = new DateTime(parser.getLongValue(), org.joda.time.DateTimeZone.UTC);
          ts.writeTimeStamp(dt.getMillis());
          break;
        case VALUE_STRING:
          DateTimeFormatter f = ISODateTimeFormat.dateTime();
          ts.writeTimeStamp(DateTime.parse(parser.getValueAsString(), f).withZoneRetainFields(org.joda.time.DateTimeZone.UTC).getMillis());
          break;
        default:
          throw UserException.unsupportedError()
          .message(parser.getCurrentToken().toString())
          .build(LOG);
        }
      }
    }

    @Override
    public void writeInterval(boolean isNull) throws IOException {
      IntervalWriter intervalWriter = writer.interval(fieldName);
      if(!isNull){
        final Period p = ISOPeriodFormat.standard().parsePeriod(parser.getValueAsString());
        int months = DateUtilities.monthsFromPeriod(p);
        int days = p.getDays();
        int millis = DateUtilities.periodToMillis(p);
        intervalWriter.writeInterval(months, days, millis);
      }
    }

    @Override
    public void writeInteger(boolean isNull) throws IOException {
      @SuppressWarnings("resource")
      BigIntWriter intWriter = writer.bigInt(fieldName);
      if(!isNull){
        intWriter.writeBigInt(Long.parseLong(parser.getValueAsString()));
      }
    }

    @Override
    public void writeDecimal(boolean isNull) throws IOException {
      throw new IOException("Decimal Extended types not yet supported.");
    }

  }

}