text:
layout: post
title: "Deploy your MongoDB application on Azure with MongoLab add-on"
subtitle: "Deploy your MongoDB application on Azure with MongoLab add-on"
date: 2015-04-27 18:34
author: "Anuraj"
comments: true
categories: [.Net, .Net 4.0, ASP.Net, ASP.Net MVC, Web API, Windows Azure]
tags: [.Net, ASP.NET 5, ASP.Net MVC, ASP.Net vNext, Azure, C#, MongoDB, MongoLab, Windows Azure]
header-img: "img/post-bg-01.jpg"
---
MongoLab is MongoDB-as-a-Service (DBaaS) platform. The Azure Marketplace MongoLab add-on will provide you with a MongoDB database hosted in the Azure cloud and managed by MongoLab's cloud database platform. To deploy your application in Azure with Mongolab, first you need to provision your Database. You can do it from Azure Management portal. (The MongoLab workflow is not yet supported in the Preview Portal). Open the Azure Market Place, under App Services, you can find MongoLab.

![MongoLab from Azure Marketplace]({{ site.url }}/assets/images/2015/04/mongolab1.png)

In the Next screen you can select the Plan and provide the name of the Database. To evaluate MonogLab comes with a sandbox plan, which is free, for this post I choose the sandbox plan.

![MongoLab - Plan and DB name]({{ site.url }}/assets/images/2015/04/mongolab2.png)

Next screen will confirm the purchase and creates the Mongo Database on Azure.

![MongoLab - Purchase confirmation]({{ site.url }}/assets/images/2015/04/mongolab3.png)

Once the Database created, you can manage it using MongoLab management portal, link to the portal available in the Azure Management Portal. You require a connection string to connect to MongoDB from ASP.NET which is also available in the portal.

![MongoLab - Database options]({{ site.url }}/assets/images/2015/04/mongolab4.png)

You can get the connection details from Connection Info button, which is required to connect to MongoDB from ASP.NET code.

![MongoLab - Database Connection Info]({{ site.url }}/assets/images/2015/04/mongolab5.png)

Now you can use the connection string in C# code. I am using [last post](http://www.dotnetthoughts.net/crud-application-using-asp-net-5-and-mongodb/) code here.

{% highlight CSharp %}
_mongoClient = new MongoClient("mongodb://MongoSample:ABC00129020.ABC18991ABJ@SHJWHJS.mongolab.com:34348/MongoSample");
_mongoDatabase = _mongoClient.GetDatabase("MongoSample");
_employeeCollection = _mongoDatabase.GetCollection<Employee>("Employees");
{% endhighlight %}

_mongoClient.GetDatabase() method, you need to provide the database name you just created with MongoLab. Except this and connection string change, there is no difference in code. You can use kpm publish option to publish the package and can use FTP deploy option to deploy your code to azure.

You can manage your collection and database from MongoLab management portal. Here is the Mongolab Management portal for the MongoDB just created.

![MongoLab - Management Portal]({{ site.url }}/assets/images/2015/04/mongolab6.png)

You can connect to MongoLab DB from Mongo shell as well. Always get the connection string or any other settings from configuration file instead of hard coding it in the code.

Happy Programming :)


text:
<!DOCTYPE html>

    <title>WnCC ♥ Open Source</title>
    <link rel="stylesheet" type="text/css" href="assets/reset.css">
    <link rel="stylesheet" type="text/css" href="assets/grid.css">
    <link rel="stylesheet" type="text/css" href="assets/style.css">

Web n Coding Club

Web and Coding Club is the biggest student club of IIT Bombay with over 1000 members.

Statistics

              public repos

              members

Mail to Manager : admin@anilshanbhag.in

Recently updated View All on GitHub

redpajama_set_name: RedPajamaGithub


text:
package trie

import (
	"bytes"
	"runtime"
	"sync"
	"testing"

	"github.com/okcoin/go-okcoin/common"
	"github.com/okcoin/go-okcoin/crypto"
	"github.com/okcoin/go-okcoin/okcdb"
)

func newEmptySecure() *SecureTrie {
	diskdb, _ := okcdb.NewMemDatabase()
	triedb := NewDatabase(diskdb)

	trie, _ := NewSecure(common.Hash{}, triedb, 0)
	return trie
}

// makeTestSecureTrie creates a large enough secure trie for testing.
func makeTestSecureTrie() (*Database, *SecureTrie, map[string][]byte) {
	// Create an empty trie
	diskdb, _ := okcdb.NewMemDatabase()
	triedb := NewDatabase(diskdb)

	trie, _ := NewSecure(common.Hash{}, triedb, 0)

	// Fill it with some arbitrary data
	content := make(map[string][]byte)
	for i := byte(0); i < 255; i++ {
		// Map the same data under multiple keys
		key, val := common.LeftPadBytes([]byte{1, i}, 32), []byte{i}
		content[string(key)] = val
		trie.Update(key, val)

		key, val = common.LeftPadBytes([]byte{2, i}, 32), []byte{i}
		content[string(key)] = val
		trie.Update(key, val)

		// Add some other data to inflate the trie
		for j := byte(3); j < 13; j++ {
			key, val = common.LeftPadBytes([]byte{j, i}, 32), []byte{j, i}
			content[string(key)] = val
			trie.Update(key, val)
		}
	}
	trie.Commit(nil)

	// Return the generated trie
	return triedb, trie, content
}

func TestSecureDelete(t *testing.T) {
	trie := newEmptySecure()
	vals := []struct{ k, v string }{
		{"do", "verb"},
		{"okcer", "wookiedoo"},
		{"horse", "stallion"},
		{"shaman", "horse"},
		{"doge", "coin"},
		{"okcer", ""},
		{"dog", "puppy"},
		{"shaman", ""},
	}
	for _, val := range vals {
		if val.v != "" {
			trie.Update([]byte(val.k), []byte(val.v))
		} else {
			trie.Delete([]byte(val.k))
		}
	}
	hash := trie.Hash()
	exp := common.HexToHash("29b235a58c3c25ab83010c327d5932bcf05324b7d6b1185e650798034783ca9d")
	if hash != exp {
		t.Errorf("expected %x got %x", exp, hash)
	}
}

func TestSecureGetKey(t *testing.T) {
	trie := newEmptySecure()
	trie.Update([]byte("foo"), []byte("bar"))

	key := []byte("foo")
	value := []byte("bar")
	seckey := crypto.Keccak256(key)

	if !bytes.Equal(trie.Get(key), value) {
		t.Errorf("Get did not return bar")
	}
	if k := trie.GetKey(seckey); !bytes.Equal(k, key) {
		t.Errorf("GetKey returned %q, want %q", k, key)
	}
}

func TestSecureTrieConcurrency(t *testing.T) {
	// Create an initial trie and copy if for concurrent access
	_, trie, _ := makeTestSecureTrie()

	threads := runtime.NumCPU()
	tries := make([]*SecureTrie, threads)
	for i := 0; i < threads; i++ {
		cpy := *trie
		tries[i] = &cpy
	}
	// Start a batch of goroutines interactng with the trie
	pend := new(sync.WaitGroup)
	pend.Add(threads)
	for i := 0; i < threads; i++ {
		go func(index int) {
			defer pend.Done()

			for j := byte(0); j < 255; j++ {
				// Map the same data under multiple keys
				key, val := common.LeftPadBytes([]byte{byte(index), 1, j}, 32), []byte{j}
				tries[index].Update(key, val)

				key, val = common.LeftPadBytes([]byte{byte(index), 2, j}, 32), []byte{j}
				tries[index].Update(key, val)

				// Add some other data to inflate the trie
				for k := byte(3); k < 13; k++ {
					key, val = common.LeftPadBytes([]byte{byte(index), k, j}, 32), []byte{k, j}
					tries[index].Update(key, val)
				}
			}
			tries[index].Commit(nil)
		}(i)
	}
	// Wait for all threads to finish
	pend.Wait()
}


text:
<!DOCTYPE html>

  <title><cf_soapbox evangelize="true" /></title>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="description" content=".">
  <meta name="robots" content="index, follow">
  <link rel="canonical" href="http://www.ericcarlisle.com/">
  <link rel="alternate" type="application/rss+xml" title=<cf_soapbox evangelize="true" /> href="/feed.xml">
  <link rel="shortcut icon" href="/assets/img/favicon.ico" type="image/x-icon">
  <meta name="generator" content="Hugo 0.16" />

  <link rel="stylesheet" href="/assets/css/main.css">

    FUN WITH

      Static Site Tools

      About SSGs

      Intro to Hugo

      Fun Content!

      Movies

              About SSGs

<cf_soapbox evangelize="true" />

SSGs cultivate different ways of thinking about common challenges.

What’s my web production strategy?

How do I time priority on design and development?

How do we hone in on the Responsive Design moving target?

  Stop “thinking outside the box.”

  Instead, try to hack the Kobiyashi Maru!


text:
import json

from lxml.html import document_fromstring
from werkzeug.exceptions import BadRequest

from aleph.logic.html import sanitize_html
from aleph.views.util import get_url_path, validate
from aleph.tests.util import TestCase

class ViewUtilTest(TestCase):
    def setUp(self):
        super(ViewUtilTest, self).setUp()

    def test_get_url_pat(self):
        self.assertEqual("/", get_url_path(""))
        self.assertEqual("/next", get_url_path("/next"))
        self.assertEqual("/next", get_url_path("https://aleph.ui:3000/next"))
        url = get_url_path("https://example.com\\@aleph.ui/oauth?path=%%2F")
        self.assertEqual("/oauth?path=%%2F", url)
        self.assertEqual("/%%2F", get_url_path("https://example.com\\@aleph.ui/%%2F"))

    def test_sanitize_html(self):
        html_str = '<!doctype html><title>Article</title><link rel="stylesheet" href="http://xss.rocks/xss.css">

We welcome our new React overlords

Published on <time onmouseover="alert(\'XSS\')">1 January 2018</time>

Really the only thing better than the blockchain is ReactJS.

<video> <source onerror = "javascript: alert (XSS)"></video>'  # noqa
        processed = sanitize_html(html_str, "https://example.org/welcome-react")
        html = document_fromstring(processed)
        assert html.find(".//img") is None, html
        assert html.find(".//video") is None, html
        assert html.find(".//style") is None, html
        assert html.find(".//script") is None, html
        assert len(html.findall(".//article")) == 1, html
        attr = html.find(".//time").get("onmouseover")
        assert attr is None, html
        attr = html.find(".//a").get("href")
        assert attr == "https://example.org/blockchain", html
        assert html.find(".//a").get("target") == "_blank", html
        assert "nofollow" in html.find(".//a").get("rel"), html

    def test_validate_returns_errors_for_paths(self):
        # given
        schema = "RoleCreate"  # name min length 4, password min length 6
        data = json.loads('{"name":"Bob","password":"1234","code":"token"}')

        # then
        with self.assertRaises(BadRequest) as ctx:
            validate(data, schema)

        self.assertEqual(
            ctx.exception.response.get_json().get("errors"),
            {"name": "'Bob' is too short", "password": "'1234' is too short"},
        )

    def test_validate_concatenates_multiple_errors_for_the_same_path(self):
        # given
        schema = "RoleCreate"  # requires password and code
        data = json.loads('{"wrong":"No password, no code"}')

        # then
        with self.assertRaises(BadRequest) as ctx:
            validate(data, schema)

        self.assertEqual(
            ctx.exception.response.get_json().get("errors"),
            {"": "'password' is a required property; 'code' is a required property"},
        )


text:
package org.xcri.presentation;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdom.Element;
import org.jdom.Namespace;
import org.xcri.Namespaces;
import org.xcri.core.Provider;
import org.xcri.exceptions.InvalidElementException;
import org.xcri.types.XcriElement;
import org.xcri.util.lax.Lax;
import org.xcri.util.lax.SingleElementException;

public class Venue extends XcriElement{

	private Log log = LogFactory.getLog(Venue.class);

	private Provider provider;

	/* (non-Javadoc)
	 * @see org.xcri.types.XcriElement#getNamespace()
	 */
	@Override
	public Namespace getNamespace() {
		return Namespaces.XCRI_NAMESPACE_NS;
	}

	/* (non-Javadoc)
	 * @see org.xcri.types.XcriElement#getName()
	 */
	@Override
	public String getName() {
		return "venue";
	}

	/* (non-Javadoc)
	 * @see org.xcri.types.XcriElement#toXml()
	 */
	@Override
	public Element toXml() {
		Element element = super.toXml();
		if (this.getProvider() != null) element.addContent(this.getProvider().toXml());
		return element;
	}

	/* (non-Javadoc)
	 * @see org.xcri.types.XcriElement#fromXml(org.jdom.Element)
	 */
	@Override
	public void fromXml(Element element) throws InvalidElementException {
		super.fromXml(element);

		if (!this.getValue().trim().isEmpty()){
			throw new InvalidElementException("venue: If a <venue> element contains any text content, Aggregators MUST treat the <venue> element as being in error.");
		}

		try {
			Lax.getChild(element, "provider", Namespaces.XCRI_NAMESPACE_NS);
		} catch (SingleElementException e) {
			throw new InvalidElementException("venue: If a <venue> element does not contain one and only one <provider> element, Aggregators MUST treat the <venue> element as being in error.");
		}

		Element providerElement = Lax.getChildQuietly(element, "provider", Namespaces.XCRI_NAMESPACE_NS, log);
		if (providerElement != null){
			this.provider = new Provider();
			provider.fromXml(providerElement);

			if (provider.getLocation() == null){
				log.warn("Location: When a provider element is used in a venue element, Producers SHOULD include a location element.");
			}
		} else {
			throw new InvalidElementException("venue: If a <venue> element does not contain one and only one <provider> element, Aggregators MUST treat the <venue> element as being in error.");
		}

		if (element.getChildren().size() != 1){
			throw new InvalidElementException("venue: If a <venue> element contains any child elements other than <provider>, Aggregators MUST treat the <venue> element as being in error.");
		}

		// NOT TESTABLE: Provider: Producers SHOULD use the provider element to describe the organisation which acts as the provider of the venue. This MAY be a sub-organisation of the provider of the presentation (such as a department or school), or it MAY be a third party or external organisation.
		// NOT TESTABLE: Provider Properties: When a provider element is used in a venue element, Producers SHOULD include only basic information about an organisation, such as identifier, title, description, url, image and location.

	}

	/**
	 * @return the provider
	 */
	public Provider getProvider() {
		return provider;
	}

	/**
	 * @param provider the provider to set
	 */
	public void setProvider(Provider provider) {
		this.provider = provider;
	}

}


text:
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*
 Copyright (C) 2008, 2009 StatPro Italia srl

 This file is part of QuantLib, a free-software/open-source library
 for financial quantitative analysts and developers - http://quantlib.org/

 QuantLib is free software: you can redistribute it and/or modify it
 under the terms of the QuantLib license.  You should have received a
 copy of the license along with this program; if not, please email
 <quantlib-dev@lists.sf.net>. The license is also available online at
 <http://quantlib.org/license.shtml>.

 This program is distributed in the hope that it will be useful, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 FOR A PARTICULAR PURPOSE.  See the license for more details.
*/

#include "creditdefaultswap.hpp"
#include "utilities.hpp"
#include <ql/instruments/creditdefaultswap.hpp>
#include <ql/pricingengines/credit/midpointcdsengine.hpp>
#include <ql/pricingengines/credit/integralcdsengine.hpp>
#include <ql/termstructures/credit/flathazardrate.hpp>
#include <ql/termstructures/credit/interpolatedhazardratecurve.hpp>
#include <ql/termstructures/yield/flatforward.hpp>
#include <ql/termstructures/yield/discountcurve.hpp>
#include <ql/quotes/simplequote.hpp>
#include <ql/math/interpolations/backwardflatinterpolation.hpp>
#include <ql/time/calendars/target.hpp>
#include <ql/time/calendars/unitedstates.hpp>
#include <ql/time/daycounters/actual360.hpp>
#include <ql/time/daycounters/thirty360.hpp>
#include <iomanip>
#include <iostream>

using namespace QuantLib;
using namespace boost::unit_test_framework;

void CreditDefaultSwapTest::testCachedValue() {

    BOOST_TEST_MESSAGE("Testing credit-default swap against cached values...");

    SavedSettings backup;

    // Initialize curves
    Settings::instance().evaluationDate() = Date(9,June,2006);
    Date today = Settings::instance().evaluationDate();
    Calendar calendar = TARGET();

    Handle<Quote> hazardRate = Handle<Quote>(
                boost::shared_ptr<Quote>(new SimpleQuote(0.01234)));
    RelinkableHandle<DefaultProbabilityTermStructure> probabilityCurve;
    probabilityCurve.linkTo(
        boost::shared_ptr<DefaultProbabilityTermStructure>(
                   new FlatHazardRate(0, calendar, hazardRate, Actual360())));

    RelinkableHandle<YieldTermStructure> discountCurve;

    discountCurve.linkTo(boost::shared_ptr<YieldTermStructure>(
                            new FlatForward(today,0.06,Actual360())));

    // Build the schedule
    Date issueDate = calendar.advance(today, -1, Years);
    Date maturity = calendar.advance(issueDate, 10, Years);
    Frequency frequency = Semiannual;
    BusinessDayConvention convention = ModifiedFollowing;

    Schedule schedule(issueDate, maturity, Period(frequency), calendar,
                      convention, convention, DateGeneration::Forward, false);

    // Build the CDS
    Rate fixedRate = 0.0120;
    DayCounter dayCount = Actual360();
    Real notional = 10000.0;
    Real recoveryRate = 0.4;

    CreditDefaultSwap cds(Protection::Seller, notional, fixedRate,
                          schedule, convention, dayCount, true, true);
    cds.setPricingEngine(boost::shared_ptr<PricingEngine>(
         new MidPointCdsEngine(probabilityCurve,recoveryRate,discountCurve)));

    Real npv = 295.0153398;
    Rate fairRate = 0.007517539081;

    Real calculatedNpv = cds.NPV();
    Rate calculatedFairRate = cds.fairSpread();
    Real tolerance = 1.0e-7;

    if (std::fabs(calculatedNpv - npv) > tolerance)
        BOOST_ERROR(
            "Failed to reproduce NPV with mid-point engine\n"
            << std::setprecision(10)
            << "    calculated NPV: " << calculatedNpv << "\n"
            << "    expected NPV:   " << npv);

    if (std::fabs(calculatedFairRate - fairRate) > tolerance)
        BOOST_ERROR(
            "Failed to reproduce fair rate with mid-point engine\n"
            << std::setprecision(10)
            << "    calculated fair rate: " << calculatedFairRate << "\n"
            << "    expected fair rate:   " << fairRate);

    cds.setPricingEngine(boost::shared_ptr<PricingEngine>(
                          new IntegralCdsEngine(1*Days,probabilityCurve,
                                                recoveryRate,discountCurve)));

    calculatedNpv = cds.NPV();
    calculatedFairRate = cds.fairSpread();
    tolerance = 1.0e-5;

    if (std::fabs(calculatedNpv - npv) > notional*tolerance*10)
        BOOST_ERROR(
            "Failed to reproduce NPV with integral engine "
            "(step = 1 day)\n"
            << std::setprecision(10)
            << "    calculated NPV: " << calculatedNpv << "\n"
            << "    expected NPV:   " << npv);

    if (std::fabs(calculatedFairRate - fairRate) > tolerance)
        BOOST_ERROR(
            "Failed to reproduce fair rate with integral engine "
            "(step = 1 day)\n"
            << std::setprecision(10)
            << "    calculated fair rate: " << calculatedFairRate << "\n"
            << "    expected fair rate:   " << fairRate);

    cds.setPricingEngine(boost::shared_ptr<PricingEngine>(
                          new IntegralCdsEngine(1*Weeks,probabilityCurve,
                                                recoveryRate,discountCurve)));

    calculatedNpv = cds.NPV();
    calculatedFairRate = cds.fairSpread();
    tolerance = 1.0e-5;

    if (std::fabs(calculatedNpv - npv) > notional*tolerance*10)
        BOOST_ERROR(
            "Failed to reproduce NPV with integral engine "
            "(step = 1 week)\n"
            << std::setprecision(10)
            << "    calculated NPV: " << calculatedNpv << "\n"
            << "    expected NPV:   " << npv);

    if (std::fabs(calculatedFairRate - fairRate) > tolerance)
        BOOST_ERROR(
            "Failed to reproduce fair rate with integral engine "
            "(step = 1 week)\n"
            << std::setprecision(10)
            << "    calculated fair rate: " << calculatedFairRate << "\n"
            << "    expected fair rate:   " << fairRate);
}

void CreditDefaultSwapTest::testCachedMarketValue() {

    BOOST_TEST_MESSAGE(
        "Testing credit-default swap against cached market values...");

    SavedSettings backup;

    Settings::instance().evaluationDate() = Date(9,June,2006);
    Date evalDate = Settings::instance().evaluationDate();
    Calendar calendar = UnitedStates();

    std::vector<Date> discountDates;
    discountDates.push_back(evalDate);
    discountDates.push_back(calendar.advance(evalDate, 1, Weeks,  ModifiedFollowing));
    discountDates.push_back(calendar.advance(evalDate, 1, Months, ModifiedFollowing));
    discountDates.push_back(calendar.advance(evalDate, 2, Months, ModifiedFollowing));
    discountDates.push_back(calendar.advance(evalDate, 3, Months, ModifiedFollowing));
    discountDates.push_back(calendar.advance(evalDate, 6, Months, ModifiedFollowing));
    discountDates.push_back(calendar.advance(evalDate,12, Months, ModifiedFollowing));
    discountDates.push_back(calendar.advance(evalDate, 2, Years, ModifiedFollowing));
    discountDates.push_back(calendar.advance(evalDate, 3, Years, ModifiedFollowing));
    discountDates.push_back(calendar.advance(evalDate, 4, Years, ModifiedFollowing));
    discountDates.push_back(calendar.advance(evalDate, 5, Years, ModifiedFollowing));
    discountDates.push_back(calendar.advance(evalDate, 6, Years, ModifiedFollowing));
    discountDates.push_back(calendar.advance(evalDate, 7, Years, ModifiedFollowing));
    discountDates.push_back(calendar.advance(evalDate, 8, Years, ModifiedFollowing));
    discountDates.push_back(calendar.advance(evalDate, 9, Years, ModifiedFollowing));
    discountDates.push_back(calendar.advance(evalDate,10, Years, ModifiedFollowing));
    discountDates.push_back(calendar.advance(evalDate,15, Years, ModifiedFollowing));

    std::vector<DiscountFactor> dfs;
    dfs.push_back(1.0);
    dfs.push_back(0.9990151375768731);
    dfs.push_back(0.99570502636871183);
    dfs.push_back(0.99118260474528685);
    dfs.push_back(0.98661167950906203);
    dfs.push_back(0.9732592953359388 );
    dfs.push_back(0.94724424481038083);
    dfs.push_back(0.89844996737120875  );
    dfs.push_back(0.85216647839921411  );
    dfs.push_back(0.80775477692556874  );
    dfs.push_back(0.76517289234200347  );
    dfs.push_back(0.72401019553182933  );
    dfs.push_back(0.68503909569219212  );
    dfs.push_back(0.64797499814013748  );
    dfs.push_back(0.61263171936255534  );
    dfs.push_back(0.5791942350748791   );
    dfs.push_back(0.43518868769953606  );

    const DayCounter& curveDayCounter=Actual360();

    RelinkableHandle<YieldTermStructure> discountCurve;
    discountCurve.linkTo(
        boost::shared_ptr<YieldTermStructure>(
            new DiscountCurve(discountDates, dfs, curveDayCounter)));

    DayCounter dayCounter = Thirty360();
    std::vector<Date> dates;
    dates.push_back(evalDate);
    dates.push_back(calendar.advance(evalDate, 6, Months, ModifiedFollowing));
    dates.push_back(calendar.advance(evalDate, 1, Years, ModifiedFollowing));
    dates.push_back(calendar.advance(evalDate, 2, Years, ModifiedFollowing));
    dates.push_back(calendar.advance(evalDate, 3, Years, ModifiedFollowing));
    dates.push_back(calendar.advance(evalDate, 4, Years, ModifiedFollowing));
    dates.push_back(calendar.advance(evalDate, 5, Years, ModifiedFollowing));
    dates.push_back(calendar.advance(evalDate, 7, Years, ModifiedFollowing));
    dates.push_back(calendar.advance(evalDate,10, Years, ModifiedFollowing));

    std::vector<Probability> defaultProbabilities;
    defaultProbabilities.push_back(0.0000);
    defaultProbabilities.push_back(0.0047);
    defaultProbabilities.push_back(0.0093);
    defaultProbabilities.push_back(0.0286);
    defaultProbabilities.push_back(0.0619);
    defaultProbabilities.push_back(0.0953);
    defaultProbabilities.push_back(0.1508);
    defaultProbabilities.push_back(0.2288);
    defaultProbabilities.push_back(0.3666);

    std::vector<Real> hazardRates;
    hazardRates.push_back(0.0);
    for (Size i=1; i<dates.size(); ++i) {
        Time t1 = dayCounter.yearFraction(dates[0], dates[i-1]);
        Time t2 = dayCounter.yearFraction(dates[0], dates[i]);
        Probability S1 = 1.0 - defaultProbabilities[i-1];
        Probability S2 = 1.0 - defaultProbabilities[i];
        hazardRates.push_back(std::log(S1/S2)/(t2-t1));
    }

    RelinkableHandle<DefaultProbabilityTermStructure> piecewiseFlatHazardRate;
    piecewiseFlatHazardRate.linkTo(
        boost::shared_ptr<DefaultProbabilityTermStructure>(
               new InterpolatedHazardRateCurve<BackwardFlat>(dates,
                                                             hazardRates,
                                                             Thirty360())));

    // Testing credit default swap

    // Build the schedule
    Date issueDate(20, March, 2006);
    Date maturity(20, June, 2013);
    Frequency cdsFrequency = Semiannual;
    BusinessDayConvention cdsConvention = ModifiedFollowing;

    Schedule schedule(issueDate, maturity, Period(cdsFrequency), calendar,
                      cdsConvention, cdsConvention,
                      DateGeneration::Forward, false);

    // Build the CDS
    Real recoveryRate = 0.25;
    Rate fixedRate=0.0224;
    DayCounter dayCount=Actual360();
    Real cdsNotional=100.0;

    CreditDefaultSwap cds(Protection::Seller, cdsNotional, fixedRate,
                          schedule, cdsConvention, dayCount, true, true);
    cds.setPricingEngine(boost::shared_ptr<PricingEngine>(
                          new MidPointCdsEngine(piecewiseFlatHazardRate,
                                                recoveryRate,discountCurve)));

    double calculatedNpv = cds.NPV();
    double calculatedFairRate = cds.fairSpread();

    double npv = -1.364048777;        // from Bloomberg we have 98.15598868 - 100.00;
    double fairRate =  0.0248429452; // from Bloomberg we have 0.0258378;

    Real tolerance = 1e-9;

    if (std::fabs(npv - calculatedNpv) > tolerance)
        BOOST_ERROR(
            "Failed to reproduce the npv for the given credit-default swap\n"
            << std::setprecision(10)
            << "    computed NPV:  " << calculatedNpv << "\n"
            << "    Given NPV:     " << npv);

    if (std::fabs(fairRate - calculatedFairRate) > tolerance)
        BOOST_ERROR(
            "Failed to reproduce the fair rate for the given credit-default swap\n"
            << std::setprecision(10)
            << "    computed fair rate:  " << calculatedFairRate << "\n"
            << "    Given fair rate:     " << fairRate);
}

void CreditDefaultSwapTest::testImpliedHazardRate() {

    BOOST_TEST_MESSAGE("Testing implied hazard-rate for credit-default swaps...");

    SavedSettings backup;

    // Initialize curves
    Calendar calendar = TARGET();
    Date today = calendar.adjust(Date::todaysDate());
    Settings::instance().evaluationDate() = today;

    Rate h1 = 0.30, h2 = 0.40;
    DayCounter dayCounter = Actual365Fixed();

    std::vector<Date> dates(3);
    std::vector<Real> hazardRates(3);
    dates[0] = today;
    hazardRates[0] = h1;

    dates[1] = today + 5*Years;
    hazardRates[1] = h1;

    dates[2] = today + 10*Years;
    hazardRates[2] = h2;

    RelinkableHandle<DefaultProbabilityTermStructure> probabilityCurve;
    probabilityCurve.linkTo(boost::shared_ptr<DefaultProbabilityTermStructure>(
                    new InterpolatedHazardRateCurve<BackwardFlat>(dates,
                                                                  hazardRates,
                                                                  dayCounter)));

    RelinkableHandle<YieldTermStructure> discountCurve;
    discountCurve.linkTo(boost::shared_ptr<YieldTermStructure>(
                            new FlatForward(today,0.03,Actual360())));

    Frequency frequency = Semiannual;
    BusinessDayConvention convention = ModifiedFollowing;

    Date issueDate = calendar.advance(today, -6, Months);
    Rate fixedRate = 0.0120;
    DayCounter cdsDayCount = Actual360();
    Real notional = 10000.0;
    Real recoveryRate = 0.4;

    Rate latestRate = Null<Rate>();
    for (Integer n=6; n<=10; ++n) {

        Date maturity = calendar.advance(issueDate, n, Years);
        Schedule schedule(issueDate, maturity, Period(frequency), calendar,
                          convention, convention,
                          DateGeneration::Forward, false);

        CreditDefaultSwap cds(Protection::Seller, notional, fixedRate,
                              schedule, convention, cdsDayCount,
                              true, true);
        cds.setPricingEngine(boost::shared_ptr<PricingEngine>(
                         new MidPointCdsEngine(probabilityCurve,
                                               recoveryRate, discountCurve)));

        Real NPV = cds.NPV();
        Rate flatRate = cds.impliedHazardRate(NPV, discountCurve,
                                              dayCounter,
                                              recoveryRate);

        if (flatRate < h1 || flatRate > h2) {
            BOOST_ERROR("implied hazard rate outside expected range\n"
                        << "    maturity: " << n << " years\n"
                        << "    expected minimum: " << h1 << "\n"
                        << "    expected maximum: " << h2 << "\n"
                        << "    implied rate:     " << flatRate);
        }

        if (n > 6 && flatRate < latestRate) {
            BOOST_ERROR("implied hazard rate decreasing with swap maturity\n"
                        << "    maturity: " << n << " years\n"
                        << "    previous rate: " << latestRate << "\n"
                        << "    implied rate:  " << flatRate);
        }

        latestRate = flatRate;

        RelinkableHandle<DefaultProbabilityTermStructure> probability;
        probability.linkTo(boost::shared_ptr<DefaultProbabilityTermStructure>(
         new FlatHazardRate(
           today,
           Handle<Quote>(boost::shared_ptr<Quote>(new SimpleQuote(flatRate))),
           dayCounter)));

        CreditDefaultSwap cds2(Protection::Seller, notional, fixedRate,
                               schedule, convention, cdsDayCount,
                               true, true);
        cds2.setPricingEngine(boost::shared_ptr<PricingEngine>(
                               new MidPointCdsEngine(probability,recoveryRate,
                                                     discountCurve)));

        Real NPV2 = cds2.NPV();
        Real tolerance = 1.0;
        if (std::fabs(NPV-NPV2) > tolerance) {
            BOOST_ERROR("failed to reproduce NPV with implied rate\n"
                        << "    expected:   " << NPV << "\n"
                        << "    calculated: " << NPV2);
        }
    }
}

void CreditDefaultSwapTest::testFairSpread() {

    BOOST_TEST_MESSAGE(
        "Testing fair-spread calculation for credit-default swaps...");

    SavedSettings backup;

    // Initialize curves
    Calendar calendar = TARGET();
    Date today = calendar.adjust(Date::todaysDate());
    Settings::instance().evaluationDate() = today;

    Handle<Quote> hazardRate = Handle<Quote>(
                boost::shared_ptr<Quote>(new SimpleQuote(0.01234)));
    RelinkableHandle<DefaultProbabilityTermStructure> probabilityCurve;
    probabilityCurve.linkTo(
        boost::shared_ptr<DefaultProbabilityTermStructure>(
                   new FlatHazardRate(0, calendar, hazardRate, Actual360())));

    RelinkableHandle<YieldTermStructure> discountCurve;
    discountCurve.linkTo(boost::shared_ptr<YieldTermStructure>(
                            new FlatForward(today,0.06,Actual360())));

    // Build the schedule
    Date issueDate = calendar.advance(today, -1, Years);
    Date maturity = calendar.advance(issueDate, 10, Years);
    BusinessDayConvention convention = Following;

    Schedule schedule =
        MakeSchedule().from(issueDate)
                      .to(maturity)
                      .withFrequency(Quarterly)
                      .withCalendar(calendar)
                      .withTerminationDateConvention(convention)
                      .withRule(DateGeneration::TwentiethIMM);

    // Build the CDS
    Rate fixedRate = 0.001;
    DayCounter dayCount = Actual360();
    Real notional = 10000.0;
    Real recoveryRate = 0.4;

    boost::shared_ptr<PricingEngine> engine(
          new MidPointCdsEngine(probabilityCurve,recoveryRate,discountCurve));

    CreditDefaultSwap cds(Protection::Seller, notional, fixedRate,
                          schedule, convention, dayCount, true, true);
    cds.setPricingEngine(engine);

    Rate fairRate = cds.fairSpread();

    CreditDefaultSwap fairCds(Protection::Seller, notional, fairRate,
                              schedule, convention, dayCount, true, true);
    fairCds.setPricingEngine(engine);

    Real fairNPV = fairCds.NPV();
    Real tolerance = 1e-10;

    if (std::fabs(fairNPV) > tolerance)
        BOOST_ERROR(
            "Failed to reproduce null NPV with calculated fair spread\n"
            << "    calculated spread: " << io::rate(fairRate) << "\n"
            << "    calculated NPV:    " << fairNPV);
}

void CreditDefaultSwapTest::testFairUpfront() {

    BOOST_TEST_MESSAGE(
        "Testing fair-upfront calculation for credit-default swaps...");

    SavedSettings backup;

    // Initialize curves
    Calendar calendar = TARGET();
    Date today = calendar.adjust(Date::todaysDate());
    Settings::instance().evaluationDate() = today;

    Handle<Quote> hazardRate = Handle<Quote>(
                boost::shared_ptr<Quote>(new SimpleQuote(0.01234)));
    RelinkableHandle<DefaultProbabilityTermStructure> probabilityCurve;
    probabilityCurve.linkTo(
        boost::shared_ptr<DefaultProbabilityTermStructure>(
                   new FlatHazardRate(0, calendar, hazardRate, Actual360())));

    RelinkableHandle<YieldTermStructure> discountCurve;
    discountCurve.linkTo(boost::shared_ptr<YieldTermStructure>(
                            new FlatForward(today,0.06,Actual360())));

    // Build the schedule
    Date issueDate = today;
    Date maturity = calendar.advance(issueDate, 10, Years);
    BusinessDayConvention convention = Following;

    Schedule schedule =
        MakeSchedule().from(issueDate)
                      .to(maturity)
                      .withFrequency(Quarterly)
                      .withCalendar(calendar)
                      .withTerminationDateConvention(convention)
                      .withRule(DateGeneration::TwentiethIMM);

    // Build the CDS
    Rate fixedRate = 0.05;
    Rate upfront = 0.001;
    DayCounter dayCount = Actual360();
    Real notional = 10000.0;
    Real recoveryRate = 0.4;

    boost::shared_ptr<PricingEngine> engine(
          new MidPointCdsEngine(probabilityCurve, recoveryRate,
                                discountCurve, true));

    CreditDefaultSwap cds(Protection::Seller, notional, upfront, fixedRate,
                          schedule, convention, dayCount, true, true);
    cds.setPricingEngine(engine);

    Rate fairUpfront = cds.fairUpfront();

    CreditDefaultSwap fairCds(Protection::Seller, notional,
                              fairUpfront, fixedRate,
                              schedule, convention, dayCount, true, true);
    fairCds.setPricingEngine(engine);

    Real fairNPV = fairCds.NPV();
    Real tolerance = 1e-10;

    if (std::fabs(fairNPV) > tolerance)
        BOOST_ERROR(
            "Failed to reproduce null NPV with calculated fair upfront\n"
            << "    calculated upfront: " << io::rate(fairUpfront) << "\n"
            << "    calculated NPV:     " << fairNPV);

    // same with null upfront to begin with
    upfront = 0.0;
    CreditDefaultSwap cds2(Protection::Seller, notional, upfront, fixedRate,
                           schedule, convention, dayCount, true, true);
    cds2.setPricingEngine(engine);

    fairUpfront = cds2.fairUpfront();

    CreditDefaultSwap fairCds2(Protection::Seller, notional,
                               fairUpfront, fixedRate,
                               schedule, convention, dayCount, true, true);
    fairCds2.setPricingEngine(engine);

    fairNPV = fairCds2.NPV();

    if (std::fabs(fairNPV) > tolerance)
        BOOST_ERROR(
            "Failed to reproduce null NPV with calculated fair upfront\n"
            << "    calculated upfront: " << io::rate(fairUpfront) << "\n"
            << "    calculated NPV:     " << fairNPV);
}

test_suite* CreditDefaultSwapTest::suite() {
    test_suite* suite = BOOST_TEST_SUITE("Credit-default swap tests");
    suite->add(QUANTLIB_TEST_CASE(&CreditDefaultSwapTest::testCachedValue));
    suite->add(QUANTLIB_TEST_CASE(
                              &CreditDefaultSwapTest::testCachedMarketValue));
    suite->add(QUANTLIB_TEST_CASE(
                              &CreditDefaultSwapTest::testImpliedHazardRate));
    suite->add(QUANTLIB_TEST_CASE(&CreditDefaultSwapTest::testFairSpread));
    suite->add(QUANTLIB_TEST_CASE(&CreditDefaultSwapTest::testFairUpfront));
    return suite;
}


text:
from fylm.model.constants import Constants
from fylm.model.image_slice import ImageSlice
from fylm.service.interactor.base import HumanInteractor
import logging
from matplotlib import pyplot as plt
import time

log = logging.getLogger(__name__)

class ExactChannelFinder(HumanInteractor):
    """
    Gets the user to define the exact location of all 28 channels, one-by-one. The user clicks on the notch, then the top right corner of the catch tube (i.e. the
    corner of the catch tube and the central trench). The location of the bottom right corner is inferred from this data.

    """
    def __init__(self, location_model, image):
        super(ExactChannelFinder, self).__init__()
        # some constants
        self._top_left = location_model.top_left
        self._bottom_right = location_model.bottom_right
        self._current_image_slice = None
        self._total_height = self._bottom_right.y - self._top_left.y  # numpy arrays have y increasing as you go downwards
        self._likely_distance = self._total_height / ((Constants.NUM_CATCH_CHANNELS / 2) - 1)  # exclude the first channel because math
        self._expected_channel_width = 230
        self._expected_channel_height = 30
        self._width_margin = 60
        self._height_margin = 30
        self._image = image
        # dynamic variables
        self._location_model = location_model
        self._current_channel_number = 0
        self._done = False
        while not self._done:
            self._start()
            if not self._done:
                self._reset()

    def _get_image_slice(self):
        # we need a row number from 0 to 13 to calculate the offset from the first row
        row = (self._current_channel_number - self._current_channel_number % 2) / 2
        if self._current_channel_number % 2 == 0:
            # left catch channel
            x = max(0, self._top_left.x - self._width_margin)
            y = max(0, self._top_left.y + self._likely_distance * row - self._height_margin * 2)
            width = self._expected_channel_width + self._width_margin * 2
            height = self._expected_channel_height + self._height_margin
            image_slice = ImageSlice(x, y, width, height)
        else:
            # right catch channel
            x = max(0, self._bottom_right.x - self._expected_channel_width - self._width_margin)
            y = max(0, self._top_left.y + self._likely_distance * row - self._height_margin * 2)
            width = self._expected_channel_width + self._width_margin * 2
            height = self._expected_channel_height + self._height_margin
            image_slice = ImageSlice(x, y, width, height)
        image_slice.set_image(self._image)
        return image_slice

    def _on_mouse_click(self, human_input):
        if human_input.left_click and len(self._coordinates) < 2:
            self._add_point(human_input.coordinates.x, human_input.coordinates.y)
        if human_input.right_click:
            self._remove_last_point()

    def _on_key_press(self, human_input):
        if human_input.key == 'w':
            self._location_model.skip_remaining()
            self._done = True
            self._clear()
        elif human_input.key == 'enter' and len(self._coordinates) == 2:
            self._handle_results()
            self._increment_channel()
            self._clear()
        elif human_input.key == 'escape':
            self._handle_results()
            self._clear()
            self._increment_channel()
        elif human_input.key == 'left':
            if not self._coordinates:
                self._handle_results()
            self._clear()
            self._decrement_channel()
        elif human_input.key == 'right':
            if not self._coordinates:
                self._handle_results()
            self._clear()
            self._increment_channel()

    def _decrement_channel(self):
        self._current_channel_number -= 1
        if self._current_channel_number == -1:
            self._current_channel_number = Constants.NUM_CATCH_CHANNELS - 1

    def _increment_channel(self):
        self._current_channel_number += 1
        if self._current_channel_number == Constants.NUM_CATCH_CHANNELS:
            self._current_channel_number = 0

    def _clear(self):
        self._erase_all_points()
        self._close()
        time.sleep(0.2)

    def _handle_results(self):
        if self._coordinates:
            notch = self._current_image_slice.get_parent_coordinates(self._coordinates[0])
            tube = self._current_image_slice.get_parent_coordinates(self._coordinates[1])
            self._location_model.set_channel_location(self._current_channel_number, notch.x, notch.y, tube.x, tube.y)
        else:
            self._location_model.skip_channel(self._current_channel_number)
        self._clear()

    def _start(self):
        self._current_image_slice = self._get_image_slice()
        self._fig.suptitle("Channel: " + str(self._current_channel_number + 1), fontsize=20)
        self._ax.imshow(self._current_image_slice.image_data, cmap='gray')
        self._ax.autoscale(False)
        self._draw_existing_data()
        mng = plt.get_current_fig_manager()
        mng.resize(*mng.window.maxsize())
        plt.show()

    def _draw_existing_data(self):
        coordinates = self._location_model.get_channel_location(self._current_channel_number)
        if coordinates == "skipped":
            # draw an X
            pass
        elif coordinates:
            notch = self._current_image_slice.get_child_coordinates(coordinates[0])
            tube = self._current_image_slice.get_child_coordinates(coordinates[1])
            self._add_point(notch.x, notch.y)
            self._add_point(tube.x, tube.y)


text:
package private

import (
	"encoding/json"
	"fmt"
	"net/http"
	"net/url"

	"code.gitea.io/gitea/modules/setting"
)

// Git environment variables
const (
	GitAlternativeObjectDirectories = "GIT_ALTERNATE_OBJECT_DIRECTORIES"
	GitObjectDirectory              = "GIT_OBJECT_DIRECTORY"
	GitQuarantinePath               = "GIT_QUARANTINE_PATH"
)

// HookOptions represents the options for the Hook calls
type HookOptions struct {
	OldCommitID                     string
	NewCommitID                     string
	RefFullName                     string
	UserID                          int64
	UserName                        string
	GitObjectDirectory              string
	GitAlternativeObjectDirectories string
	GitQuarantinePath               string
	ProtectedBranchID               int64
	IsDeployKey                     bool
}

// HookPreReceive check whether the provided commits are allowed
func HookPreReceive(ownerName, repoName string, opts HookOptions) (int, string) {
	reqURL := setting.LocalURL + fmt.Sprintf("api/internal/hook/pre-receive/%s/%s?old=%s&new=%s&ref=%s&userID=%d&gitObjectDirectory=%s&gitAlternativeObjectDirectories=%s&gitQuarantinePath=%s&prID=%d&isDeployKey=%t",
		url.PathEscape(ownerName),
		url.PathEscape(repoName),
		url.QueryEscape(opts.OldCommitID),
		url.QueryEscape(opts.NewCommitID),
		url.QueryEscape(opts.RefFullName),
		opts.UserID,
		url.QueryEscape(opts.GitObjectDirectory),
		url.QueryEscape(opts.GitAlternativeObjectDirectories),
		url.QueryEscape(opts.GitQuarantinePath),
		opts.ProtectedBranchID,
		opts.IsDeployKey,
	)

	resp, err := newInternalRequest(reqURL, "GET").Response()
	if err != nil {
		return http.StatusInternalServerError, fmt.Sprintf("Unable to contact gitea: %v", err.Error())
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return resp.StatusCode, decodeJSONError(resp).Err
	}

	return http.StatusOK, ""
}

// HookPostReceive updates services and users
func HookPostReceive(ownerName, repoName string, opts HookOptions) (map[string]interface{}, string) {
	reqURL := setting.LocalURL + fmt.Sprintf("api/internal/hook/post-receive/%s/%s?old=%s&new=%s&ref=%s&userID=%d&username=%s",
		url.PathEscape(ownerName),
		url.PathEscape(repoName),
		url.QueryEscape(opts.OldCommitID),
		url.QueryEscape(opts.NewCommitID),
		url.QueryEscape(opts.RefFullName),
		opts.UserID,
		url.QueryEscape(opts.UserName))

	resp, err := newInternalRequest(reqURL, "GET").Response()
	if err != nil {
		return nil, fmt.Sprintf("Unable to contact gitea: %v", err.Error())
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return nil, decodeJSONError(resp).Err
	}
	res := map[string]interface{}{}
	_ = json.NewDecoder(resp.Body).Decode(&res)

	return res, ""
}


text:
package devicemapper // import "github.com/docker/docker/pkg/devicemapper"

// LibraryDeferredRemovalSupport tells if the feature is supported by the
// current Docker invocation.
const LibraryDeferredRemovalSupport = false

func dmTaskDeferredRemoveFct(task *cdmTask) int {
	// Error. Nobody should be calling it.
	return -1
}

func dmTaskGetInfoWithDeferredFct(task *cdmTask, info *Info) int {
	return -1
}


text:
require 'active_record'

module Protokoll
  class Counter
    def self.next(object, options)
      element = Models::CustomAutoIncrement.find_or_create_by(build_attrs(object, options))

      element.counter = options[:start] if outdated?(element, options) || element.counter == 0
      element.counter += 1

      element.touch unless element.changed?
      element.save! if element.changed?

      element.save!

      Formater.new.format(element.counter, options)
    end

    private

    def self.build_attrs(object, options)
      attrs = {counter_model_name: object.model_name.name.underscore}
      return attrs unless options[:scope_by]

      scope_by =  options[:scope_by].respond_to?(:call) ?
                  object.instance_eval(&options[:scope_by]) :
                  object.send(options[:scope_by])

      attrs.merge(counter_model_scope: scope_by)
    end

    def self.outdated?(record, options)
      event = update_event(options)
      return false if event.empty?

      Time.now.utc.strftime(event).to_i > record.updated_at.strftime(event).to_i
    end

    def self.update_event(options)
      pattern = options[:pattern]
      event = String.new

      event << "%Y" if pattern.include? "%y" or pattern.include? "%Y"
      event << "%m" if pattern.include? "%m"
      event << "%H" if pattern.include? "%H"
      event << "%M" if pattern.include? "%M"
      event << "%d" if pattern.include? "%d"
      event
    end
  end
end


text:
package jspb

import "github.com/gopherjs/gopherjs/js"

// Writer encapsulates the jspb.BinaryWriter.
type Writer interface {
	GetResult() []byte

	// Scalars
	WriteInt32(int, int32)
	WriteInt64(int, int64)
	WriteUint32(int, uint32)
	WriteUint64(int, uint64)
	WriteSint32(int, int32)
	WriteSint64(int, int64)
	WriteFixed32(int, uint32)
	WriteFixed64(int, uint64)
	WriteSfixed32(int, int32)
	WriteSfixed64(int, int64)
	WriteFloat32(int, float32)
	WriteFloat64(int, float64)
	WriteEnum(int, int)
	WriteBool(int, bool)
	WriteString(int, string)
	WriteBytes(int, []byte)

	// Scalar Slices
	WriteInt32Slice(int, []int32)
	WriteInt64Slice(int, []int64)
	WriteUint32Slice(int, []uint32)
	WriteUint64Slice(int, []uint64)
	WriteSint32Slice(int, []int32)
	WriteSint64Slice(int, []int64)
	WriteFixed32Slice(int, []uint32)
	WriteFixed64Slice(int, []uint64)
	WriteSfixed32Slice(int, []int32)
	WriteSfixed64Slice(int, []int64)
	WriteFloat32Slice(int, []float32)
	WriteFloat64Slice(int, []float64)
	WriteBoolSlice(int, []bool)
	WriteEnumSlice(int, []int)

	// Specials
	WriteMessage(int, func())
}

// NewWriter returns a new Writer ready for writing.
func NewWriter() Writer {
	return &writer{
		Object: js.Global.Get("BinaryWriter").New(),
	}
}

// writer implements the Writer interface.
type writer struct {
	*js.Object
}

// GetResult returns the contents of the buffer as a byte slice.
func (w writer) GetResult() []byte {
	return w.Call("getResultBuffer").Interface().([]byte)
}

// WriteInt32 writes an int32 field to the buffer.
func (w writer) WriteInt32(field int, value int32) {
	w.Call("writeInt32", field, value)
}

// WriteInt64 writes an int64 field to the buffer.
func (w writer) WriteInt64(field int, value int64) {
	w.Call("writeInt64", field, value)
}

// WriteUint32 writes a uint32 field to the buffer.
func (w writer) WriteUint32(field int, value uint32) {
	w.Call("writeUint32", field, value)
}

// WriteUint64 writes a uint64 field to the buffer.
func (w writer) WriteUint64(field int, value uint64) {
	w.Call("writeUint64", field, value)
}

// WriteSint32 writes an sint32 field to the buffer.
func (w writer) WriteSint32(field int, value int32) {
	w.Call("writeSint32", field, value)
}

// WriteSint64 writes an sint64 field to the buffer.
func (w writer) WriteSint64(field int, value int64) {
	w.Call("writeSint64", field, value)
}

// WriteFixed32 writes a fixed32 field to the buffer.
func (w writer) WriteFixed32(field int, value uint32) {
	w.Call("writeFixed32", field, value)
}

// WriteFixed64 writes a fixed64 field to the buffer.
func (w writer) WriteFixed64(field int, value uint64) {
	w.Call("writeFixed64", field, value)
}

// WriteSfixed32 writes an sfixed32 field to the buffer.
func (w writer) WriteSfixed32(field int, value int32) {
	w.Call("writeSfixed32", field, value)
}

// WriteSfixed64 writes an sfixed64 field to the buffer.
func (w writer) WriteSfixed64(field int, value int64) {
	w.Call("writeSfixed64", field, value)
}

// WriteFloat32 writes a float32 field to the buffer
func (w writer) WriteFloat32(field int, value float32) {
	w.Call("writeFloat", field, value)
}

// WriteFloat64 writes a float64 field to the buffer
func (w writer) WriteFloat64(field int, value float64) {
	w.Call("writeDouble", field, value)
}

// WriteEnum writes an enum (as an int) to the buffer
func (w writer) WriteEnum(field int, value int) {
	w.Call("writeEnum", field, value)
}

// WriteBool writes a bool field to the buffer
func (w writer) WriteBool(field int, value bool) {
	w.Call("writeBool", field, value)
}

// WriteString writes a string field to the buffer
func (w writer) WriteString(field int, value string) {
	w.Call("writeString", field, value)
}

// WriteBytes writes a bytes field to the buffer
func (w writer) WriteBytes(field int, value []byte) {
	w.Call("writeBytes", field, value)
}

// WriteMessage writes a message to the buffer using writeFunc
func (w writer) WriteMessage(field int, writeFunc func()) {
	w.Call("writeMessage", field, 0 /* Unused */, writeFunc)
}

// WriteInt32Slice writes a repeated int32 field to the buffer.
func (w writer) WriteInt32Slice(field int, value []int32) {
	w.Call("writePackedInt32", field, value)
}

// WriteInt64Slice writes a repeated int64 field to the buffer.
func (w writer) WriteInt64Slice(field int, value []int64) {
	w.Call("writePackedInt64", field, value)
}

// WriteUint32Slice writes a repeated uint32 field to the buffer.
func (w writer) WriteUint32Slice(field int, value []uint32) {
	w.Call("writePackedUint32", field, value)
}

// WriteUint64Slice writes a repeated uint64 field to the buffer.
func (w writer) WriteUint64Slice(field int, value []uint64) {
	w.Call("writePackedUint64", field, value)
}

// WriteSint32Slice writes a repeated sint32 field to the buffer.
func (w writer) WriteSint32Slice(field int, value []int32) {
	w.Call("writePackedSint32", field, value)
}

// WriteSint64Slice writes a repeated sint64 field to the buffer.
func (w writer) WriteSint64Slice(field int, value []int64) {
	w.Call("writePackedSint64", field, value)
}

// WriteFixed32Slice writes a repeated fixed32 field to the buffer.
func (w writer) WriteFixed32Slice(field int, value []uint32) {
	w.Call("writePackedFixed32", field, value)
}

// WriteFixed64Slice writes a repeated fixed64 field to the buffer.
func (w writer) WriteFixed64Slice(field int, value []uint64) {
	w.Call("writePackedFixed64", field, value)
}

// WriteSfixed32Slice writes a repeated sfixed32 field to the buffer.
func (w writer) WriteSfixed32Slice(field int, value []int32) {
	w.Call("writePackedSfixed32", field, value)
}

// WriteSfixed64Slice writes a repeated sfixed64 field to the buffer.
func (w writer) WriteSfixed64Slice(field int, value []int64) {
	w.Call("writePackedSfixed64", field, value)
}

// WriteFloat32Slice writes a repeated float32 field to the buffer
func (w writer) WriteFloat32Slice(field int, value []float32) {
	w.Call("writePackedFloat", field, value)
}

// WriteFloat64Slice writes a repeated float64 field to the buffer
func (w writer) WriteFloat64Slice(field int, value []float64) {
	w.Call("writePackedDouble", field, value)
}

// WriteEnumSlice writes a repeated enum (as ints) to the buffer
func (w writer) WriteEnumSlice(field int, value []int) {
	w.Call("writePackedEnum", field, value)
}

// WriteBoolSlice writes a repeated bool field to the buffer
func (w writer) WriteBoolSlice(field int, value []bool) {
	w.Call("writePackedBool", field, value)
}


text:
using CodeModel.Graphs;

namespace CodeModel.Primitives
{
    public class ApplicationEntryPoint : Node
    {
        public const string NodeId = "ApplicationEntryPoint";

        public ApplicationEntryPoint() : base(NodeId)
        {
        }

        public override string DisplayLabel
        {
            get { return "Application Entry Point"; }
        }
    }
}