text:
#include "stdafx.h"
#include <stdexcept>

#ifdef _MS_WINDOWS
#ifdef __cplusplus_winrt
#define __WRL_NO_DEFAULT_LIB__
#include <wrl.h>
#include <msxml6.h>
#else
#include <windows.h>
#include <winhttp.h>
#endif
#endif

using namespace web;
using namespace utility;
using namespace concurrency;
using namespace web::http;
using namespace web::http::client;

using namespace tests::functional::http::utilities;

namespace tests { namespace functional { namespace http { namespace client {

SUITE(authentication_tests)
{

TEST_FIXTURE(uri_address, auth_no_data, "Ignore:Linux", "698420", "Ignore:Apple", "698420")
{
    test_http_server::scoped_server scoped(m_uri);
    http_client_config client_config;
    credentials cred(U("some_user"), U("some_password")); // WinHTTP requires non-empty password
    client_config.set_credentials(cred);
    http_client client(m_uri, client_config);
    const method mtd = methods::POST;

    http_request msg(mtd);

    auto replyFunc = [&](test_request *p_request)
        {
            http_asserts::assert_test_request_equals(p_request, methods::POST, U("/"));
            p_request->reply(200);
        };

    scoped.server()->next_request().then([&](test_request *p_request)
    {
        http_asserts::assert_test_request_equals(p_request, mtd, U("/"));

        // Auth header
        std::map<utility::string_t, utility::string_t> headers;
        headers[U("WWW-Authenticate")] = U("Basic realm = \"WallyWorld\"");

        // unauthorized
        p_request->reply(status_codes::Unauthorized, U("Authentication Failed"), headers);

    }).then([&scoped, replyFunc]()
    {
        // Client resent the request
        scoped.server()->next_request().then(replyFunc);
    });

    http_asserts::assert_response_equals(client.request(msg).get(), status_codes::OK);
}

// TFS 648783
#ifndef __cplusplus_winrt
TEST_FIXTURE(uri_address, proxy_auth_known_contentlength, "Ignore:Linux", "646268", "Ignore:Apple", "646268")
{
    test_http_server::scoped_server scoped(m_uri);
    http_client_config client_config;
    credentials cred(U("some_user"), U("some_password")); // WinHTTP requires non-empty password
    client_config.set_credentials(cred);
    http_client client(m_uri, client_config);
    const method mtd = methods::POST;
    utility::string_t contents(U("Hello World"));

    http_request msg(mtd);
    msg.set_body(contents);

    auto replyFunc = [&](test_request *p_request)
        {
            http_asserts::assert_test_request_equals(p_request, methods::POST, U("/"), U("text/plain; charset=utf-8"), contents);

            p_request->reply(200);
        };

    scoped.server()->next_request().then([&](test_request *p_request)
    {
        http_asserts::assert_test_request_equals(p_request, mtd, U("/"));

        // Auth header
        std::map<utility::string_t, utility::string_t> headers;
        headers[U("WWW-Authenticate")] = U("Basic realm = \"WallyWorld\"");

        // unauthorized
        p_request->reply(status_codes::Unauthorized, U("Authentication Failed"), headers);

    }).then([&scoped, replyFunc]()
    {
        // Client resent the request
        scoped.server()->next_request().then(replyFunc);
    });

    http_asserts::assert_response_equals(client.request(msg).get(), status_codes::OK);
}
#endif

TEST_FIXTURE(uri_address, proxy_auth_noseek,
             "Ignore:Linux", "646268",
             "Ignore:Apple", "646268")
{
    web::http::uri uri(U("http://localhost:34567/"));
    test_http_server::scoped_server scoped(uri);
    http_client client(uri); // In this test, the request cannot be resent, so the username and password are not required
    const method mtd = methods::POST;

    auto buf = streams::producer_consumer_buffer<unsigned char>();
    buf.putc('a').get();
    buf.close(std::ios_base::out).get();

    http_request msg(mtd);
    msg.set_body(buf.create_istream(), 1);

    scoped.server()->next_request().then([&](test_request *p_request)
    {
        http_asserts::assert_test_request_equals(p_request, mtd, U("/"));

        // Auth header
        std::map<utility::string_t, utility::string_t> headers;
        headers[U("WWW-Authenticate")] = U("Basic realm = \"WallyWorld\"");

        // unauthorized
        p_request->reply(status_codes::Unauthorized, U("Authentication Failed"), headers);

    });

    http_asserts::assert_response_equals(client.request(msg).get(), status_codes::Unauthorized);
}

// Must specify content length with winrt client, so this test case isn't possible.
#ifndef __cplusplus_winrt
TEST_FIXTURE(uri_address, proxy_auth_unknown_contentlength,
            "Ignore:Linux", "646268",
            "Ignore:Apple", "646268")
{
    test_http_server::scoped_server scoped(m_uri);
    http_client_config client_config;
    credentials cred(U("some_user"), U("some_password")); // WinHTTP requires non-empty password
    client_config.set_credentials(cred);
    http_client client(m_uri, client_config);
    const method mtd = methods::POST;

    std::vector<uint8_t> msg_body;
    msg_body.push_back('a');

    http_request msg(mtd);
    msg.set_body(streams::container_stream<std::vector<uint8_t>>::open_istream(std::move(msg_body)));

    auto replyFunc = [&](test_request *p_request)
        {
            utility::string_t contents(U("a"));
            http_asserts::assert_test_request_equals(p_request, methods::POST, U("/"), U("application/octet-stream"), contents);

            p_request->reply(200);
        };

    scoped.server()->next_request().then([&](test_request *p_request)
    {
        http_asserts::assert_test_request_equals(p_request, mtd, U("/"));

        // Auth header
        std::map<utility::string_t, utility::string_t> headers;
        headers[U("WWW-Authenticate")] = U("Basic realm = \"WallyWorld\"");

        // unauthorized
        p_request->reply(status_codes::Unauthorized, U("Authentication Failed"), headers);

    }).then([&scoped, replyFunc]()
    {
        // Client resent the request
        scoped.server()->next_request().then(replyFunc);
    });

    http_asserts::assert_response_equals(client.request(msg).get(), status_codes::OK);
}

// Accessing a server that returns 401 with an empty user name should not resend the request with an empty password
TEST_FIXTURE(uri_address, empty_username_password)
{
    test_http_server::scoped_server scoped(m_uri);
    http_client client(m_uri);

    scoped.server()->next_request().then([&](test_request *p_request)
    {
        std::map<utility::string_t, utility::string_t> headers;
        headers[U("h1")] = U("data1");
        // Auth header
        headers[U("WWW-Authenticate")] = U("Basic realm = \"myRealm\"");
        // unauthorized
        p_request->reply(status_codes::Unauthorized, U("Authentication Failed"), headers, "a" );
    });

    http_response response = client.request(methods::GET).get();
    auto str_body = response.extract_vector().get();
    auto h1 = response.headers()[U("h1")];
    VERIFY_ARE_EQUAL(status_codes::Unauthorized, response.status_code());
    VERIFY_ARE_EQUAL(str_body[0], 'a');
    VERIFY_ARE_EQUAL(h1, U("data1"));
}
#endif

// Fails on WinRT due to TFS 648278
// Accessing a server that supports auth, but returns 401, even after the user has provided valid creds
// We're making sure the error is reported properly, and the response data from the second response is received
TEST_FIXTURE(uri_address, error_after_valid_credentials, "Ignore:Linux", "646268", "Ignore:Apple", "646268")
{
    web::http::uri uri(U("http://localhost:34569/"));
    test_http_server::scoped_server scoped(uri);
    http_client_config client_config;
    credentials cred(U("some_user"), U("some_password"));
    client_config.set_credentials(cred);
    http_client client(uri, client_config);

    auto replyFunc = [&](test_request *p_request)
        {
            std::map<utility::string_t, utility::string_t> headers;
            // Auth header
            headers[U("WWW-Authenticate")] = U("Basic realm = \"WallyWorld\"");
            headers[U("h1")] = U("data2");
            // still unauthorized after the user has resent the request with the credentials
            p_request->reply(status_codes::Unauthorized, U("Authentication Failed"), headers, "def" );
        };

    scoped.server()->next_request().then([&](test_request *p_request)
    {
        std::map<utility::string_t, utility::string_t> headers;
        headers[U("h1")] = U("data1");
        // Auth header
        headers[U("WWW-Authenticate")] = U("Basic realm = \"myRealm\"");
        // unauthorized
        p_request->reply(status_codes::Unauthorized, U("Authentication Failed"), headers, "abc" );
    }).then([&scoped, &replyFunc]()
    {
        // Client resent the request
        scoped.server()->next_request().then(replyFunc);
    })
#ifdef __cplusplus_winrt
        .then([&scoped, &replyFunc]()
    {
        // in winrt, client resent the request again
        scoped.server()->next_request().then(replyFunc);
    })
#endif
    ;

    http_response response = client.request(methods::GET).get();
    auto str_body = response.extract_vector().get();
    auto h1 = response.headers()[U("h1")];
    VERIFY_ARE_EQUAL(status_codes::Unauthorized, response.status_code());
    VERIFY_ARE_EQUAL(str_body[0], 'd');
    VERIFY_ARE_EQUAL(str_body[1], 'e');
    VERIFY_ARE_EQUAL(str_body[2], 'f');
    VERIFY_ARE_EQUAL(h1, U("data2"));
}

// These tests are disabled since they require a server with authentication running.
// The server portion to use is the C# AuthenticationListener.
#pragma region Manual Server Authentication Tests

class server_properties
{
public:
    server_properties() {}

    // Helper function to retrieve all parameters necessary for setup tests.
    void load_parameters()
    {
        m_uri = uri(utility::conversions::to_string_t(UnitTest::GlobalSettings::Get("Server")));
        if(UnitTest::GlobalSettings::Has("UserName"))
        {
            m_username = utility::conversions::to_string_t(UnitTest::GlobalSettings::Get("UserName"));
        }
        if(UnitTest::GlobalSettings::Has("Password"))
        {
            m_password = utility::conversions::to_string_t(UnitTest::GlobalSettings::Get("Password"));
        }
    }

    web::http::uri m_uri;
    string_t m_username;
    string_t m_password;
};

// This test should be executed for NTLM, Negotiate, IntegratedWindowsAuth, and Anonymous.
TEST_FIXTURE(server_properties, successful_auth_no_cred, "Requires", "Server")
{
    load_parameters();

    http_client client(m_uri);
    http_response response = client.request(methods::GET).get();
    VERIFY_ARE_EQUAL(status_codes::OK, response.status_code());
}

TEST_FIXTURE(server_properties, digest_basic_auth_no_cred, "Requires", "Server")
{
    load_parameters();

    http_client client(m_uri);
    http_response response = client.request(methods::GET).get();
    VERIFY_ARE_EQUAL(status_codes::Unauthorized, response.status_code());
}

TEST_FIXTURE(server_properties, none_auth_no_cred, "Requires", "Server")
{
    load_parameters();

    http_client client(m_uri);
    http_response response = client.request(methods::GET).get();
    VERIFY_ARE_EQUAL(status_codes::Forbidden, response.status_code());
}

// This test should be executed for NTLM, Negotiate, IntegratedWindowsAuth, and Digest.
TEST_FIXTURE(server_properties, unsuccessful_auth_with_basic_cred, "Requires", "Server;UserName;Password")
{
    load_parameters();

    http_client_config config;
    config.set_credentials(credentials(m_username, m_password));

    http_client client(m_uri, config);
    http_response response = client.request(methods::GET).get();
    VERIFY_ARE_EQUAL(status_codes::Unauthorized, response.status_code());
}

TEST_FIXTURE(server_properties, basic_anonymous_auth_with_basic_cred, "Requires", "Server;UserName;Password")
{
    load_parameters();

    http_client_config config;
    config.set_credentials(credentials(m_username, m_password));
    http_client client(m_uri, config);
    http_request req(methods::GET);
    req.headers().add(U("UserName"), m_username);
    req.headers().add(U("Password"), m_password);
    http_response response = client.request(req).get();
    VERIFY_ARE_EQUAL(status_codes::OK, response.status_code());
}

TEST_FIXTURE(server_properties, none_auth_with_cred, "Requires", "Server;UserName;Password")
{
    load_parameters();

    http_client_config config;
    config.set_credentials(credentials(m_username, m_password));
    http_client client(m_uri, config);
    http_response response = client.request(methods::GET).get();
    VERIFY_ARE_EQUAL(status_codes::Forbidden, response.status_code());
}

// This test should be executed for all authentication schemes except None.
TEST_FIXTURE(server_properties, successful_auth_with_domain_cred, "Requires", "Server;UserName;Password")
{
    load_parameters();

    http_client_config config;
    config.set_credentials(credentials(m_username, m_password));
    http_client client(m_uri, config);
    http_request req(methods::GET);
    req.headers().add(U("UserName"), m_username);
    req.headers().add(U("Password"), m_password);
    http_response response = client.request(req).get();
    VERIFY_ARE_EQUAL(status_codes::OK, response.status_code());
}

TEST_FIXTURE(server_properties, failed_authentication_resend_request_error, "Requires", "Server;UserName;Password")
{
    load_parameters();

    http_client_config config;
    config.set_credentials(credentials(m_username, m_password));
    http_client client(m_uri, config);

    const size_t rawDataSize = 8;

    std::vector<unsigned char> data(rawDataSize);
    memcpy(&data[0], "raw data", rawDataSize);

    http_request request;
    request.set_method(methods::POST);
    request.set_body(data);
    auto responseTask = client.request(request);

    http_response response;

    response = responseTask.get();

    VERIFY_ARE_EQUAL(200, response.status_code());
}

#ifdef __cplusplus_winrt
TEST_FIXTURE(uri_address, set_user_options_winrt)
{
    test_http_server::scoped_server scoped(m_uri);
    scoped.server()->next_request().then([](test_request *p_request)
    {
        p_request->reply(status_codes::OK);
    });

    http_client_config config;
    config.set_nativehandle_options([](native_handle handle)->void{
        auto hr = handle->SetProperty(XHR_PROP_TIMEOUT, 1000);
        if(!SUCCEEDED(hr))
            throw std::runtime_error("The Test Exception");
    });
    http_client client(m_uri, config);
    auto response = client.request(methods::GET).get();
    VERIFY_ARE_EQUAL(200, response.status_code());
}
#endif // __cplusplus_winrt

#ifdef _MS_WINDOWS
#if !defined(__cplusplus_winrt)
TEST_FIXTURE(server_properties, set_user_options, "Requires", "Server;UserName;Password")
{
    load_parameters();

    http_client_config config;
    config.set_credentials(credentials(m_username, m_password));

    config.set_nativehandle_options([&](native_handle handle)->void{
        DWORD policy = WINHTTP_AUTOLOGON_SECURITY_LEVEL_LOW;
        if (!WinHttpSetOption(handle,
                         WINHTTP_OPTION_AUTOLOGON_POLICY,
                         &policy,
                         sizeof(policy)))
        {
            throw std::runtime_error("The Test Error");
        }
    });

    http_client client(m_uri, config);

    const size_t rawDataSize = 8;

    std::vector<unsigned char> data(rawDataSize);
    memcpy(&data[0], "raw data", rawDataSize);

    http_request request;
    request.set_method(methods::POST);
    request.set_body(data);

    VERIFY_ARE_EQUAL(200, client.request(request).get().status_code());
}

TEST_FIXTURE(uri_address, auth_producer_comsumer_buffer)
{
    auto buf = streams::producer_consumer_buffer<unsigned char>();
    buf.putc('a').get();
    buf.putc('a').get();
    buf.putc('a').get();
    buf.putc('a').get();
    buf.close(std::ios_base::out).get();
    http_request msg(methods::POST);
    msg.set_body(buf.create_istream());

    http_client_config config;
    config.set_credentials(credentials(U("USERNAME"), U("PASSWORD")));

    http_client client(m_uri, config);

    test_http_server::scoped_server scoped(m_uri);

    auto replyFunc = [&](test_request *p_request)
    {
        http_asserts::assert_test_request_equals(p_request, methods::POST, U("/"), U("application/octet-stream"), U("aaaa"));
        p_request->reply(200);
    };

    scoped.server()->next_request().then([&](test_request *p_request)
    {
        http_asserts::assert_test_request_equals(p_request, methods::POST, U("/"), U("application/octet-stream"), U("aaaa"));
        std::map<utility::string_t, utility::string_t> headers;
        headers[U("WWW-Authenticate")] = U("Basic realm = \"WallyWorld\"");

        p_request->reply(status_codes::Unauthorized, U("Authentication Failed"), headers);
    })
        .then([&scoped, replyFunc](){
        scoped.server()->next_request().then(replyFunc);
    });

    http_asserts::assert_response_equals(client.request(msg).get(), status_codes::OK);
}

TEST_FIXTURE(uri_address, auth_producer_comsumer_buffer_fail_no_cred)
{
    auto buf = streams::producer_consumer_buffer<unsigned char>();
    buf.putc('a').get();
    buf.putc('a').get();
    buf.putc('a').get();
    buf.putc('a').get();
    buf.close(std::ios_base::out).get();
    http_request msg(methods::POST);
    msg.set_body(buf.create_istream());

    http_client client(m_uri);

    test_http_server::scoped_server scoped(m_uri);

    scoped.server()->next_request().then([&](test_request *p_request)
    {
        http_asserts::assert_test_request_equals(p_request, methods::POST, U("/"), U("application/octet-stream"), U("aaaa"));
        std::map<utility::string_t, utility::string_t> headers;
        headers[U("WWW-Authenticate")] = U("Basic realm = \"WallyWorld\"");

        p_request->reply(status_codes::Unauthorized, U("Authentication Failed"), headers);
    });

    http_asserts::assert_response_equals(client.request(msg).get(), status_codes::Unauthorized);
}

TEST_FIXTURE(uri_address, auth_producer_comsumer_buffer_fail)
{
    auto buf = streams::producer_consumer_buffer<unsigned char>();
    buf.putc('a').get();
    buf.close(std::ios_base::out).get();
    http_request msg(methods::POST);
    msg.set_body(buf.create_istream());

    http_client_config config;
    config.set_credentials(credentials(U("USERNAME"), U("PASSWORD")));

    http_client client(m_uri, config);

    test_http_server::scoped_server scoped(m_uri);

    auto replyFunc = [&](test_request *p_request)
    {
        http_asserts::assert_test_request_equals(p_request, methods::POST, U("/"), U("application/octet-stream"), U("a"));
        std::map<utility::string_t, utility::string_t> headers;
        headers[U("WWW-Authenticate")] = U("Basic realm = \"WallyWorld2\"");

        p_request->reply(status_codes::Unauthorized, U("Authentication Failed"), headers);
    };

    scoped.server()->next_request().then([&](test_request *p_request)
    {
        http_asserts::assert_test_request_equals(p_request, methods::POST, U("/"), U("application/octet-stream"), U("a"));
        std::map<utility::string_t, utility::string_t> headers;
        headers[U("WWW-Authenticate")] = U("Basic realm = \"WallyWorld\"");

        p_request->reply(status_codes::Unauthorized, U("Authentication Failed"), headers);
    })
        .then([&scoped, replyFunc](){
        scoped.server()->next_request().then(replyFunc);
    });

    http_asserts::assert_response_equals(client.request(msg).get(), status_codes::Unauthorized);
}
#endif

TEST_FIXTURE(uri_address, set_user_options_exceptions)
{
    test_http_server::scoped_server scoped(m_uri);
    http_client_config config;
    class TestException;
    config.set_nativehandle_options([](native_handle handle)->void{
        (handle);
        throw std::runtime_error("The Test exception");
    });
    http_client client(m_uri, config);
    VERIFY_THROWS(client.request(methods::GET).get(), std::runtime_error);
}
#endif // _MS_WINDOWS
#pragma endregion

// Fix for 522831 AV after failed authentication attempt
TEST_FIXTURE(uri_address, failed_authentication_attempt, "Ignore:Linux", "698420", "Ignore:Apple", "698420")
{
    http_client_config config;
    credentials cred(U("user"),U("schmuser"));
    config.set_credentials(cred);
    http_client client(U("https://apis.live.net"),config);
    http_response response = client.request(methods::GET, U("V5.0/me/skydrive/files")).get();
    VERIFY_ARE_EQUAL(status_codes::Unauthorized, response.status_code());
    auto v = response.extract_vector().get();
    std::string s(v.begin(), v.end());
    // The resulting data must be non-empty (an error about missing access token)
    VERIFY_IS_FALSE(s.empty());
}

} // SUITE(authentication_tests)

}}}}


text:
class Die
  def initialize(sides)
  	unless sides >= 1
  		raise ArgumentError.new("Please have at least one side.")
  	end
    @sides = sides
    puts "Your die has #{@sides} sides."
  end

  def sides
    return @sides
  end

  def roll
    rand(1..@sides)
  end
end

# 3. Refactored Solution

# I think that's as simple as we can get!

# 4. Reflection

# What is an ArgumentError and why would you use one?
# 	An ArgumentError is what it sounds like - an error with the argument you've given a method.
# 	Usually it will be the wrong number of arguments or the wrong argument type, but we can define our own ArgumentErrors.
# 	By using the unless...raise...end syntax, we can define what kind of arguments we don't want,
# 	then use raise ArgumentError.new("message") to give the user a custom error.

# What new Ruby methods did you implement? What challenges and successes did you have in implementing them?
# 	I didn't need to use any new methods, but I used instance variables and created an ArgumentError for the first time.
# 	I actually didn't have any trouble using them!

# What is a Ruby class?
# 	String, array, and hash are Ruby classes, and we can make our own, too.
# 	A class is a definition - objects that are an instance of a class, and methods are class specific too.
# 	Making our own classes is useful for writing programs because we can define all objects and methods and then use it over and over again.
# 	Another way to think of this is that class is (so far) the top level in Ruby.

# Why would you use a Ruby class?
# 	As stated in the video, a good metaphor is that classes are blueprints.
# 	We define a class, its methods, and even what its objects look like, and then we can use that data whenever we want.
# 	It's the ultimate in Ruby customization!

# What is the difference between a local variable and an instance variable?
# 	A local variable is local - it scopes to the method and disappears right after.
# 	Instance variables are scoped to the class - you can use them over and over inside and outside of methods.

# Where can an instance variable be used?
# 	Inside a class, but in many different methods within that class.

redpajama_set_name: RedPajamaGithub


text:
cosmted
=======

Hook your Ted up to COSM (http://cosm.com)

You need the cosm.py library from https://gist.github.com/3692126 and remove the example bits.


text:
button.pipeline-submit {
  margin: 10px 0;
  width: 40%;
}

div.pipeline-submit {
  display: flex;
  align-items: center;
  justify-content: center;
}

.pipeline-spinner {
  margin-bottom: 10px;
}


text:
package columnpkg

import (
	"fmt"
	"math"
	"runtime"
	"sort"
	"strconv"
	"strings"
	"sync"
)

type EncodedColumn struct {
	name              string
	Dv                Seq    //Dictionary Vector
	Av                []byte //Attribute Vector
	AvNr              int    //Nr of Elements in AV
	ElementSize       int    // size of one element (of the AV)
	compressedAv      bool
	compressedAv_type string
}

// Seq für das Sortieren definieren
type Seq []string

func (s Seq) Len() int      { return len(s) }
func (s Seq) Swap(i, j int) { s[i], s[j] = s[j], s[i] }

//Nicht unterscheiden zwischen klein und groß beim Sortieren
func (s Seq) Less(i, j int) bool {
	return strings.ToLower(s[i]) < strings.ToLower(s[j])
}

//helper Function for PrintStats()
func printCol(column []byte, name string) {
	lc := len(column)
	str := "Column " + name + " (Length=" + strconv.Itoa(lc) + ") : "

	if lc < 10 {
		fmt.Println(str, column[0:lc])
	} else {
		fmt.Println(str, column[0:4], "...", column[lc-4:lc])
	}
}

//helper Function for PrintStats()
//find out how to overload a function and combine with printCol()
func printColStr(column []string, name string) {
	lc := len(column)
	str := "Column " + name + " (Length=" + strconv.Itoa(lc) + ") : "

	if lc < 10 {
		fmt.Println(str, column[0:lc])
	} else {
		fmt.Println(str, column[0:4], "...", column[lc-4:lc])
	}
}

func (c *EncodedColumn) PrintStats() {
	fmt.Println("Attribute Vector element length in bit: ", c.ElementSize)
	fmt.Println("Attribute Vector in Bytes: ", len(c.Av))
	fmt.Println("Dictionary Vector (Distinct Records): ", len(c.Dv))
	fmt.Println("Dictionary Vector (size in Byte): ", c.calcDvSize())

	printCol(c.Av, "Attribute Vector")
	printColStr(c.Dv, "Dictionary Vector")
}

//size in Byte
func (c *EncodedColumn) calcDvSize() int {
	ret := 0
	for _, val := range c.Dv {
		ret += len(val) // assumes that one char is one Byte
	}
	return ret
}

func (c *EncodedColumn) DictEnc(column []string) {
	runtime.GOMAXPROCS(runtime.NumCPU())
	c.AvNr = len(column)
	c.Dv = removeDuplicates(column)
	c.ElementSize = getNeededBits(c.Dv)
	sort.Sort(Seq(c.Dv))
	if c.AvNr > 1000 {  	//decides if to run the decoding in parallel
				//if more than 1000 elements in Attribute Vector
		c.buildAVector_parallel(column, runtime.NumCPU()) //parallel on all cores
	} else {
		c.buildAVector(column) //sequential
	}
}

func (c *EncodedColumn) buildAVector(column []string) {
	AV_size := sizeOfAV(c.ElementSize, len(column))
	var AV = make([]byte, AV_size)
	c.Av = AV
	for i, v := range column {
		//Search for v: Position in DictVector -> Write DV Position (payload) in AV
		pos_DV := sort.Search(len(c.Dv),
			func(i int) bool {
				return strings.ToLower(c.Dv[i]) >= strings.ToLower(v)
			})
		//writeElementOfAV(pos_DV, i, oneElementSize, AV)
		c.writeAvElement_new(pos_DV, i)
	}
}

func (c *EncodedColumn) buildAVector_parallel(column []string, workerNr int) {
	AV_size := sizeOfAV(c.ElementSize, len(column))
	var AV = make([]byte, AV_size)
	c.Av = AV
	partSize := c.AvNr / workerNr
	var wg sync.WaitGroup
	for i := 0; i < workerNr; i++ {
		wg.Add(1)
		endsize := (i+1)*partSize
		if i == workerNr - 1 {
			endsize = c.AvNr
		}
		go c.buildAVector_worker(column[i*partSize:endsize], i*partSize, &wg)
	}
	wg.Wait()
	//fmt.Println("All workers finished")
}

func (c *EncodedColumn) buildAVector_worker(column []string, startOffset int, wg *sync.WaitGroup) {
	for k, v := range column {
		//fmt.Print("Column: ", k, " ", v)
		//Search for v: Position in DictVector -> Write DV Position (payload) in AV
		pos_DV := sort.Search(len(c.Dv),
			func(i int) bool {
				return strings.ToLower(c.Dv[i]) >= strings.ToLower(v)
			})
		//fmt.Print("posDV: ", pos_DV, " posAV: ", k+startOffset)
		c.writeAvElement_new(pos_DV, k+startOffset)
	}
	wg.Done()
}

//Schreibe einen Payload (eine DV Position) in den Attribut Vektor (AV)
func (c *EncodedColumn) writeAvElement_new(payload int, posAV int) {
	//1. Aufteilen des Payload in den Teil für dieses Byte und den Rest
	//1.a) Wieviel passt in dieses Byte noch rein? (in bit) Dazu: Beginn (Position) im Byte
	SHIFT := shiftNumber(posAV, c.ElementSize)
	BYTENR := findWriteByte(posAV, c.ElementSize)
	payload_new_size := 8 - SHIFT
	var payload_new byte = byte(payload)
	payload_new = payload_new << uint(SHIFT)
	var payload_rest int = payload >> uint(payload_new_size)
	var payload_rest_size int = c.ElementSize - payload_new_size
	//2. Schreiben was in dieses Byte passt
	c.Av[BYTENR] = c.Av[BYTENR] | payload_new
	//3. Den Rest schreiben
	if payload_rest_size > 0 {
		c.writeAvElement_rest(payload_rest, payload_rest_size, BYTENR+1)
	}
}

//Schreibe restlichen Payload in folgende Bytes
func (c *EncodedColumn) writeAvElement_rest(payload int, payload_size int, byteNR int) {
	c.Av[byteNR] = c.Av[byteNR] | byte(payload)
	if payload_size > 8 {
		payload_rest := payload >> 8
		payload_rest_size := payload_size - 8
		c.writeAvElement_rest(payload_rest, payload_rest_size, byteNR+1)
	}
}

//What shift is needed for a given Position
func shiftNumber(pos int, size int) int {
	return (pos * size) % 8
}

//What byte to Write to?
func findWriteByte(pos int, size int) int {
	return (pos * size) / 8
}

//überprüfen!!
//if return == 0: fits in Byte, else return == number of bits that don't fit
func fitsInByte(pos int, size int) int {
	return size - shiftNumber(pos, size)
}

//How many Byte are needed for the Attribute Vector?
func sizeOfAV(elementSize, numberOfElements int) int {
	//fmt.Print("Elementgröße: ", sizeForElementInBit, " ")
	//fmt.Println("Anzahl der Elemente: ", numberOfElements)
	return int(math.Ceil(float64(elementSize*numberOfElements) / 8))
}

//doppelte Einträge entfernen und sortieren
func removeDuplicates(a []string) []string {
	result := []string{}
	seen := map[string]string{}
	for _, val := range a {
		if _, ok := seen[val]; !ok {
			result = append(result, val)
			seen[val] = val
		}
	}
	return result
}

//How many Bit are needed to count all Elements (Cardinality of Column)
func getNeededBits(column []string) int {
	length := math.Floor(math.Log2(float64(len(column))))

	return int(length) + 1
}

//DECODE
func (c *EncodedColumn) DecodeCol() []string {
	//size_ele := getNeededBits(c.Dv)
	var column = make([]string, c.AvNr)
	value := new(int)
	// Schleife für jedes Element des AV (nicht Byte des AV)
	for i := 0; i < c.AvNr; i++ {
		*value = 0
		var posAV int = c.ElementSize * i
		c.decodeValPart_new(value, posAV) //posAV ist die bit position des Elements
		column[i] = c.Dv[*value]
	}
	return column
}

func (c *EncodedColumn) decodeValPart_new(value *int, posAV int) {
	SHIFT := posAV % 8
	BYTENR := posAV / 8
	payload_size := c.ElementSize
	var payload_size_new int = 0
	//fmt.Println("Bytenr: ", BYTENR, " Länge: ", len(c.Av))
	BYTE := c.Av[BYTENR]

	if payload_size+SHIFT < 8 {
		payload_size_new = payload_size
		left_shift := 8 - (payload_size + SHIFT)
		BYTE = BYTE << uint(left_shift)
	} else {
		payload_size_new = 8 - SHIFT
	}

	BYTE = BYTE >> uint(8-payload_size_new)
	*value = *value | int(BYTE)
	offset := payload_size_new
	rest_size := payload_size - payload_size_new

	if rest_size > 0 {
		c.decodeValPart_rest(value, BYTENR+1, rest_size, offset)
	}
}

func (c *EncodedColumn) decodeValPart_rest(value *int, BYTENR int,
	payload_size int, offset int) {
	BYTE := c.Av[BYTENR]
	var payload_size_new int = 0
	if payload_size < 8 {
		payload_size_new = payload_size
		left_shift := 8 - payload_size
		BYTE = BYTE << uint(left_shift)
	} else {
		payload_size_new = 8
	}
	var INTEGER int = int(BYTE >> uint(8-payload_size_new))
	//right shift um offset
	INTEGER = INTEGER << uint(offset)
	*value = *value | INTEGER
	rest_size := payload_size - payload_size_new
	if rest_size > 0 {
		c.decodeValPart_rest(value, BYTENR+1, rest_size, offset+payload_size_new)
	}
}

func (c *EncodedColumn) findAvPositionsForValue(searchStr string) []int {
	var result []int

	DvPos := c.findDvPosForValue(searchStr)
	value := new(int)
	var posAV int
	for i := 0; i < c.AvNr; i++ {
		*value = 0
		posAV = c.ElementSize * i
		c.decodeValPart_new(value, posAV) //posAV ist die bit position des Elements
		if DvPos == *value {
			result = append(result, i)
		}
	}
	return result
}

func (c *EncodedColumn) findDvPosForValue(searchStr string) int {
	var result int = -1
	i := sort.Search(len(c.Dv), func(i int) bool { return c.Dv[i] >= searchStr })
	if i < len(c.Dv) && c.Dv[i] == searchStr {
		result = i
	}
	return result
}


text:
#ifndef TENSORFLOW_CORE_COMMON_RUNTIME_RENDEZVOUS_MGR_H_
#define TENSORFLOW_CORE_COMMON_RUNTIME_RENDEZVOUS_MGR_H_

#include <string>
#include <unordered_map>

#include "tensorflow/core/common_runtime/device_mgr.h"
#include "tensorflow/core/framework/local_rendezvous.h"
#include "tensorflow/core/framework/rendezvous.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/types.h"

namespace tensorflow {

// IntraProcessRendezvous is a Rendezvous which expects all producers
// and consumers to be devices immediately accessible within the
// process. That is, it will never be necessary to perform an RPC to
// communicate with either.
//
// Buffering of Tensor values is delegated to a `LocalRendezvous`. This class
// just adds functionality to coordinate multiple process-local devices.
class IntraProcessRendezvous : public Rendezvous {
 public:
  explicit IntraProcessRendezvous(const DeviceMgr* device_mgr);

  // Forwards to local_, where the Tensor "val" will be buffered and
  // any waiting callback stored.
  Status Send(const ParsedKey& key, const Rendezvous::Args& args,
              const Tensor& val, const bool is_dead) override;

  // This method is called only by the RecvOp.  It tests to see
  // whether the value will be produced by a local or remote device
  // and handles accordingly.  In the local case it forwards to
  // local_, in the remote case it initiates an RPC request.
  void RecvAsync(const ParsedKey& key, const Rendezvous::Args& args,
                 DoneCallback done) override;

  void StartAbort(const Status& status) override;

 private:
  const DeviceMgr* device_mgr_;
  LocalRendezvous local_;

  ~IntraProcessRendezvous() override;

  // Callback handling the case when a rendezvous has been
  // accomplished in local_ and the consumer is local to this process.
  // Tensor "in" will be copied into "out". The key "parsed" encodes
  // the src and dst devices.
  typedef std::function<void(const Status&)> StatusCallback;
  void SameWorkerRecvDone(const Rendezvous::ParsedKey& parsed,
                          const Rendezvous::Args& send_args,
                          const Rendezvous::Args& recv_args, const Tensor& in,
                          Tensor* out, StatusCallback done);

  TF_DISALLOW_COPY_AND_ASSIGN(IntraProcessRendezvous);
};

}  // end namespace tensorflow

#endif  // TENSORFLOW_CORE_COMMON_RUNTIME_RENDEZVOUS_MGR_H_


text:
from __future__ import unicode_literals

from django.core.exceptions import ValidationError
from django.forms import models
from djanban.apps.hourly_rates.models import HourlyRate
from django import forms

# Hourly rate creation and edition form
class HourlyRateForm(models.ModelForm):
    class Meta:
        model = HourlyRate
        fields = ["name", "start_date", "end_date", "amount", "is_active"]
        widgets = {
            'start_date': forms.SelectDateWidget(),
            'end_date': forms.SelectDateWidget(empty_label=u"Until now"),
        }

    def __init__(self, *args, **kwargs):
        super(HourlyRateForm, self).__init__(*args, **kwargs)

    def clean(self):
        cleaned_data = super(HourlyRateForm, self).clean()
        if cleaned_data.get("end_date") and cleaned_data.get("start_date") > cleaned_data.get("end_date"):
            raise ValidationError(u"Start date can't be greater that end date")
        return cleaned_data

class DeleteHourlyRateForm(forms.Form):
    confirmed = forms.BooleanField(label=u"Please confirm you really want to do this action", required=True)


text:
import json
import webapp2
import logging
import urllib
import urllib2
import urlparse
import jinja2
import os

from properties import properties
from models import user

from webapp2_extras import sessions

jinja_environment = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__) +
                                   '/../templates'))

class BaseHandler(webapp2.RequestHandler):

    context = {}

    def dispatch(self):
        # Get a session store for this request.
        self.session_store = sessions.get_store(request=self.request)

        try:
            # Dispatch the request.
            webapp2.RequestHandler.dispatch(self)
        finally:
            # Save all sessions.
            self.session_store.save_sessions(self.response)

    @webapp2.cached_property
    def session(self):
        # Returns a session using the default cookie key.
        return self.session_store.get_session()

    def render(self, template_name):
        template = jinja_environment.get_template(template_name + '.html')
        self.response.out.write(template.render(self.context))
        return

    def set_request_arguments(self):
        try:
            request_args = dict()
            for arg in self.request.arguments():
                request_args[arg] = self.request.get(arg)
            self.context['request_args'] = request_args
            return
        except UnicodeDecodeError, unicode_error:
            self.context['request_args'] = dict()
            logging.exception(unicode_error)
        except Exception, e:
            self.context['request_args'] = dict()
            logging.exception(e)
            raise e

    def FacebookLogin(self):
        verification_code = self.request.get('code')
        args = dict(
            client_id=properties.FACEBOOK_APP_ID,
            redirect_uri=self.request.path_url)
        if verification_code:

            args["client_secret"] = properties.FACEBOOK_APP_SECRET
            args["code"] = verification_code

            headers = {'User-Agent': 'Mozilla/5.0'}
            req = urllib2.Request(
                properties.FACEBOOK_URL + properties.FACEBOOK_OAUTH_URL,
                urllib.urlencode(args), headers)
            response = urllib2.urlopen(req)
            tokens = urlparse.parse_qs(response.read())

            # stores session
            self.session[
                'facebook-token'] = self.context[
                'token'] = tokens['access_token'][0]

            # saves FB profile
            self.context['profile'] = json.load(urllib.urlopen(
                properties.FACEBOOK_URL + "/me?" + urllib.urlencode(
                    dict(access_token=self.context['token']))))

            # adds user
            current = user.User(key_name=str(self.context['profile']["id"]),
                                id=str(self.context['profile']["id"]),
                                name=self.context['profile']["name"],
                                access_token=self.context['token'],
                                profile_url=self.context['profile']["link"])
            current.put()
            self.redirect('/')
        else:
            self.redirect(
                properties.FACEBOOK_URL + properties.FACEBOOK_OAUTH_AUTHORISE +
                urllib.urlencode(args))

    def FacebookLogout(self):
        return


text:
NSString * const WFSharePlatformWeChat = @"微信好友";
NSString * const WFSharePlatformWeChatFriends = @"微信朋友圈";
NSString * const WFSharePlatformSinaWeibo = @"新浪微博";
NSString * const WFSharePlatformQQ = @"QQ";
NSString * const WFSharePlatformMail = @"邮件";
NSString * const WFSharePlatformNULL = @"NULL";
NSString * const WFSharePlatformCopyLink = @"复制链接";
NSString * const WFSharePlatformYouDao = @"有道云笔记"; // 有道云
NSString * const WFSharePlatformYinXiang = @"印象笔记";//印象笔记
NSString * const WFSharePlatformTencentWeibo = @"腾讯微博";//腾讯微博
NSString * const WFSharePlatformMessage = @"信息";//信息
NSString * const WFSharePlatformInstapaper = @"Instapaper";//Instapaper
NSString * const WFSharePlatformTwitter = @"推特";//推特
NSString * const WFSharePlatformRenRen = @"人人";//人人

#define kCellW  65
#define kCellH  80

#define kOffSetX (kScreenWidth - 4 * kCellW)/5

@implementation WFSharePanelView
{
    NSDictionary *_platformDict;
    int _platformCount;//平台个数
    UIScrollView *_scrollView;
    float kPanelH;
    UIPageControl *_pageControl;
}

#pragma mark - 初始化相关
+ (WFSharePanelView *)sharedManager {

    static dispatch_once_t onceToken;
    static WFSharePanelView *_instance = nil;
    dispatch_once(&onceToken, ^{
        _instance = [[WFSharePanelView alloc] init];
    });
    return _instance;
}

- (id)init{

    if (self = [super init]){

        self.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);

        self.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];

        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissSelf)];
        [self addGestureRecognizer:tapGesture];
        self.userInteractionEnabled = YES;

        _platformDict = @{WFSharePlatformWeChat:@[@(SharePlatformWeChat),@"weChat.png"],
                          WFSharePlatformWeChatFriends:@[@(SharePlatformWeChatFriends),@"weChaFriend.png"],
                          WFSharePlatformSinaWeibo:@[@(SharePlatformSinaWeibo),@"sinaWeiBo.png"],
                          WFSharePlatformQQ:@[@(SharePlatformQQ),@"QQ.png"],
                          WFSharePlatformCopyLink:@[@(SharePlatformCopyLink),@"copyLink.png"],
                          WFSharePlatformYouDao:@[@(SharePlatformYouDao),@"youDao.png"],
                          WFSharePlatformYinXiang:@[@(SharePlatformYinXiang),@"yinXiang.png"],
                          WFSharePlatformTencentWeibo:@[@(SharePlatformTencentWeibo),@"tencentWeiBo.png"],
                          WFSharePlatformMessage:@[@(SharePlatformMessage),@"message.png"],
                          WFSharePlatformInstapaper:@[@(SharePlatformInstapaper),@"instapaper.png"],
                          WFSharePlatformTwitter:@[@(SharePlatformTwitter),@"twitter.png"],
                          WFSharePlatformRenRen:@[@(SharePlatformRenRen),@"renRen.png"],
                          WFSharePlatformMail:@[@(SharePlatformMail),@"mail.png"]};
        _platformCount = 0;
    }
    return self;
}

#pragma mark - 外部方法
- (void)showSharePanelHasStore:(BOOL)hasStore
                       byClick:(ClickActionBlock)actionBlock
                  withPlatform:(NSString *)platformTitle,...NS_REQUIRES_NIL_TERMINATION{

    if(_whitePanel){
        return;
    }
    _actionBlock = [actionBlock copy];
    kPanelH = hasStore?350.f:300.f;
    [self addWhitePanel];
    [self addCancelCell];
    [self addScrollView];
    [self addPageControl];
    [self addOtherButton];

    if([self canOpenWithPlatformTitle:platformTitle]) {
        [self addButtonWithPlatform:platformTitle];
    }

    if (platformTitle) {

        va_list args;
        va_start(args, platformTitle);
        NSString *title = nil;
        while ((title = va_arg(args, NSString *))) {
            if([self canOpenWithPlatformTitle:title]) {
                [self addButtonWithPlatform:title];
            }
        }
        va_end(args);
    }

    [self show];

}

#pragma mark - 内部方法
#pragma mark - 白板部分
- (void)addWhitePanel{

    _whitePanel = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight , kScreenWidth, kPanelH)];
    _whitePanel.backgroundColor = RGBColor(233, 233, 233, 1.0f);
    [self addSubview:_whitePanel];
}

- (void)addScrollView{

    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, kCellW - 10, kScreenWidth, 160)];
    _scrollView.pagingEnabled = YES;
    _scrollView.delegate = self;
    _scrollView.showsVerticalScrollIndicator = NO;
    _scrollView.showsHorizontalScrollIndicator = NO;
    _scrollView.directionalLockEnabled = YES;
    [_whitePanel addSubview:_scrollView];

}

- (void)addPageControl{

    _pageControl = [[UIPageControl alloc] init];
    _pageControl.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin;
    _pageControl.enabled = NO;
    [_whitePanel addSubview:_pageControl];

}

- (void)addCancelCell{

    UILabel *tipLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kCellW)];
    tipLab.text = @"分享这篇内容";
    tipLab.backgroundColor = [UIColor clearColor];
    tipLab.textAlignment = NSTextAlignmentCenter;
    tipLab.font = [UIFont boldSystemFontOfSize:18.0f];
    tipLab.textColor = RGBColor(87.f, 87.f, 87.f, 1);
    [_whitePanel addSubview:tipLab];

}

- (void)addOtherButton{

    if (kPanelH == 350.f) {

        UIButton *storeBtn = [UIButton buttonWithType:0];
        storeBtn.frame = CGRectMake(20, _scrollView.frame.origin.y + _scrollView.frame.size.height + 20, kScreenWidth - 40, 40);
        storeBtn.backgroundColor = [UIColor whiteColor];
        [storeBtn setTitle:@"收藏" forState:0];
        storeBtn.titleLabel.font = [UIFont systemFontOfSize:16.f];
        [storeBtn setTitleColor:[UIColor grayColor] forState:0];
        [storeBtn addTarget:self action:@selector(storeNewsInfo) forControlEvents:1<<6];
        [_whitePanel addSubview:storeBtn];

        UIButton *cancelBtn = [UIButton buttonWithType:0];
        cancelBtn.frame = CGRectMake(20, storeBtn.frame.origin.y + storeBtn.frame.size.height + 16, kScreenWidth - 40, 40);
        cancelBtn.backgroundColor = [UIColor whiteColor];
        [cancelBtn setTitle:@"取消" forState:0];
        cancelBtn.titleLabel.font = [UIFont systemFontOfSize:16.f];
        [cancelBtn setTitleColor:[UIColor grayColor] forState:0];
        [cancelBtn addTarget:self action:@selector(dismissSelf) forControlEvents:1<<6];
        [_whitePanel addSubview:cancelBtn];

    }else{

        UIButton *cancelBtn = [UIButton buttonWithType:0];
        cancelBtn.frame = CGRectMake(20, _scrollView.frame.origin.y + _scrollView.frame.size.height + 20, kScreenWidth - 40, 40);
        cancelBtn.backgroundColor = [UIColor whiteColor];
        [cancelBtn setTitle:@"取消" forState:0];
        cancelBtn.titleLabel.font = [UIFont systemFontOfSize:16.f];
        [cancelBtn setTitleColor:[UIColor grayColor] forState:0];
        [cancelBtn addTarget:self action:@selector(dismissSelf) forControlEvents:1<<6];
        [_whitePanel addSubview:cancelBtn];

    }

}

#pragma mark - 分享按钮
- (void)addButtonWithPlatform:(NSString *)platform{

    WFShareButton *btn = [[WFShareButton alloc] initWithFrame:CGRectMake(kScreenWidth * (_platformCount/8) + (_platformCount%8)%4 * kCellW + kOffSetX * ((_platformCount%8)%4 + 1), 0 + ((_platformCount%8)/4) * kCellH , kCellW, kCellH)];
    btn.backgroundColor = [UIColor clearColor];
    [btn setTitleColor:RGBColor(87.f, 87.f, 87.f, 1) forState:0];
     btn.platform = [[[_platformDict valueForKey:platform] objectAtIndex:0] integerValue];
    [btn setImage:Image([[_platformDict valueForKey:platform] objectAtIndex:1]) forState:0];
    [btn addTarget:self action:@selector(shareButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [_scrollView addSubview:btn];

    _scrollView.contentSize = CGSizeMake(kScreenWidth * (_platformCount/8 + 1) , 0);
    CGSize pcSize = [_pageControl sizeForNumberOfPages:_platformCount/8 + 1];
    _pageControl.frame = CGRectMake((kScreenWidth - pcSize.width) * 0.5, _scrollView.frame.origin.y + _scrollView.frame.size.height - 10, pcSize.width, pcSize.height);
    _pageControl.numberOfPages = _platformCount/8 + 1;

    _platformCount ++;
}

#pragma mark - 判断 是否显示该分享功能
- (BOOL)canOpenWithPlatformTitle:(NSString *)platformTitle {

    if (platformTitle == WFSharePlatformWeChat || platformTitle == WFSharePlatformWeChatFriends ) {
        return YES;//是否能打开微信  这里默认打开
    }else if (platformTitle == WFSharePlatformQQ) {
        return YES;//是否能打开qq 这里默认打开
    }else if (platformTitle == WFSharePlatformNULL) {
        return NO;
    }
    return YES;
}

#pragma mark - ScrollView Delegate-
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {

    _pageControl.currentPage = scrollView.contentOffset.x / kScreenWidth;
}

#pragma mark - 按钮事件
- (void)shareButtonAction:(WFShareButton *)sender{

    _actionBlock(sender.platform);
    DELAYEXECUTE(.4, {[self dismissSelf];});

}

#pragma mark - 展现
- (void)show{

    _whitePanel.frame = CGRectMake(0, kScreenHeight , kScreenWidth,kPanelH);
    [[self getUnhiddenFrontWindowOfApplication] addSubview:self];

    [UIView animateWithDuration:.4 animations:^{

        _whitePanel.frame = CGRectMake(0, kScreenHeight - kPanelH, kScreenWidth,kPanelH);
    } completion:^(BOOL finished) {

    }];
}

#pragma mark - 消失
- (void)dismissSelf{

    [UIView animateWithDuration:.4 animations:^{

        _whitePanel.frame = CGRectMake(0, kScreenHeight , kScreenWidth,kPanelH);

    } completion:^(BOOL finished) {
        for (UIView *btn in _whitePanel.subviews) {
            [btn removeFromSuperview];
        }

        [_whitePanel removeFromSuperview];
        _whitePanel = nil;
        [self removeFromSuperview];
        _platformCount = 0;

    }];
}

#pragma mark - 收藏
- (void)storeNewsInfo{

    [WFToastView showMsg:@"收藏" inView:nil];
}

#pragma mark - 获得window
- (UIWindow *) getUnhiddenFrontWindowOfApplication{

    NSArray *windows = [[UIApplication sharedApplication] windows];
    NSInteger windowCnt = [windows count];
    for (NSInteger i = windowCnt - 1; i >= 0; i--) {
        UIWindow* window = [windows objectAtIndex:i];
        if (FALSE == window.hidden) {
            //定制:防止产生bar提示,用的是新增window,排除这个window
            if (window.frame.size.height > 50.0f) {
                window.windowLevel = 1001;
                return window;
            }
        }
    }
    return NULL;
}

@end


text:
/* eslint no-underscore-dangle: ["error", { "allow": ["_status", "_updated_at", "_i"] }]*/

import React, { PropTypes } from 'react';
import Moment from 'moment';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './HoursMiles.css';
import fulcrumDateHelpers from '../../utils/fulcrumDateHelpers';
import fulcrumFormHelpers from '../../utils/fulcrumFormHelpers';
import fulcrumSQLTsHelpers from '../../utils/fulcrumSQLTsHelpers';
import fulcrumVarHelpers from '../../utils/fulcrumVarHelpers';

class HoursMiles extends React.Component {

  static propTypes = {
    whichView: PropTypes.string,
  }

  constructor(props) {
    super(props);
    this.state = {
      formObj: {},
      timesheetRecordsObj: {},
    };
  }

  componentDidMount() {
    // console.log('Surveys component mounted.');
    fulcrumSQLTsHelpers.getTsData()
      .then((datas) => {
        this.setState({
          timesheetRecordsObj: datas,
        });
      });
    this.loadTimer = setTimeout(() => {
      this.setState({
        formObj: fulcrumFormHelpers.getAppInfo(),
      });
    }, 3000);
  }

  componentWillUnmount() {
    // console.log('Surveys component unmounted.');
    clearTimeout(this.loadTimer);
    if (this.loadTimer) {
      clearTimeout(this.loadTimer);
      this.loadTimer = null;
    }
  }

  render() {
    const selectedMileHours = this.props.whichView;

    const dateItemsObjList = fulcrumDateHelpers;

    const timesheetRecordsObjList = typeof (this.state.timesheetRecordsObj.data) !== 'undefined' ?
      this.state.timesheetRecordsObj.data.rows : [];
    const allStaff = typeof (this.state.formObj.form) !== 'undefined' ?
      this.state.formObj.form.elements[fulcrumVarHelpers.fieldStaffSectionPosition].elements[fulcrumVarHelpers.fieldStaffListPosition].choices
       : [];

    const allStaffNames = allStaff.map(staffOb => staffOb.label.toUpperCase());
    const allStaffNamesS = allStaffNames.sort();
    const allStaffNamesStd = allStaffNamesS.map((item) =>
      0	);
    const totalDateList = dateItemsObjList.allDatesList.map(item => item._i);
    const totalDateListZero = totalDateList.map(item => item.replace(/T\d\d:\d\d:\d\d.\d\d\dZ/g, 'T00:00:00.000Z'));

    const siftStatsMH = function siftStatsMH(dateSift) {
      const tableData = allStaffNamesStd;
      const newTableData = [];
      const matchedDates = [];

      timesheetRecordsObjList.forEach((timesheetEntryOb) => {
        // console.log(dateSift.slice(0,dateSift.indexOf('T')))
        // console.log(timesheetEntryOb.date.slice(0,timesheetEntryOb.date.indexOf('T')))
        const dataSiftMoment = Moment(dateSift, 'YYYY-MM-DDTHH:mm:ss.SSSSZ');
        const timesheetEntryObMoment = Moment(timesheetEntryOb.date, 'YYYY-MM-DDTHH:mm:ss.SSSSZ');
        // if (timesheetEntryObMoment.diff(dataSiftMoment, 'days') === 0) {
        if (timesheetEntryObMoment.isSame(dataSiftMoment, 'days')) {
          matchedDates.push(timesheetEntryOb);
        }
      });

      tableData.forEach((tdata) => {
        let allUnits = 0;
        matchedDates.forEach((matchedD) => {
          if (matchedD.fieldstaffname) {
            if (tdata.key === matchedD.fieldstaffname.toUpperCase()) {
              allUnits += parseInt(matchedD[selectedMileHours], 10);
            }
          }
        });
        newTableData.push({allUnits}	);
      });

      return newTableData;
    };

    const staffListNames = typeof (allStaff) !== 'undefined' || allStaff !== [] ?
        allStaffNamesS.map((staffOb, i) =>
          {staffOb.toUpperCase().slice(0, 1) + staffOb.toLowerCase().slice(1)}	,
        ) : (

          0
          0
          0
          0

);

    const staffListMH = totalDateListZero.map((dateOb, i) =>

        {dateOb.slice(0, dateOb.indexOf('T'))}
        {typeof (this.state.timesheetRecordsObj.data) !== 'undefined' ? siftStatsMH(dateOb) : []}

,
        );

    return (

Field Staff {
            this.props.whichView.toUpperCase()} by date.

              {staffListNames}

            {staffListMH}

    );
  }
}

export default withStyles(s)(HoursMiles);


text: __all__ = ["spec_pserver", "spec_master", "spec_trainer"]


text:
package ru.hh.oauth.subscribe.apis;

import ru.hh.oauth.subscribe.core.builder.api.DefaultApi20;
import ru.hh.oauth.subscribe.core.extractors.AccessTokenExtractor;
import ru.hh.oauth.subscribe.core.extractors.JsonTokenExtractor;
import ru.hh.oauth.subscribe.core.model.OAuthConfig;
import ru.hh.oauth.subscribe.core.model.OAuthConstants;
import ru.hh.oauth.subscribe.core.model.Verb;
import ru.hh.oauth.subscribe.core.utils.OAuthEncoder;

/**
 * SinaWeibo OAuth 2.0 api.
 */
public class SinaWeiboApi20 extends DefaultApi20 {

    private static final String AUTHORIZE_URL = "https://api.weibo.com/oauth2/authorize?client_id=%s&redirect_uri=%s&response_type=code";
    private static final String SCOPED_AUTHORIZE_URL = AUTHORIZE_URL + "&scope=%s";

    @Override
    public Verb getAccessTokenVerb() {
        return Verb.POST;
    }

    @Override
    public AccessTokenExtractor getAccessTokenExtractor() {
        return new JsonTokenExtractor();
    }

    @Override
    public String getAccessTokenEndpoint() {
        return "https://api.weibo.com/oauth2/access_token?grant_type=" + OAuthConstants.AUTHORIZATION_CODE;
    }

    @Override
    public String getAuthorizationUrl(OAuthConfig config) {
        // Append scope if present
        if (config.hasScope()) {
            return String.format(SCOPED_AUTHORIZE_URL, config.getApiKey(), OAuthEncoder.encode(config.getCallback()), OAuthEncoder.encode(config.
                    getScope()));
        } else {
            return String.format(AUTHORIZE_URL, config.getApiKey(), OAuthEncoder.encode(config.getCallback()));
        }
    }
}


text:
#include "PlayOnlineScene.h"

#include <ClanLib/gui.h>
#include "clanlib/display/2d.h"

#include "common.h"
#include "controllers/PlayOnlineSceneController.h"
#include "gfx/widgets/Header.h"

static const int MARGIN = 10;

const CL_String COL_NAME = "name";
const CL_String COL_GAMEMODE = "gamemode";
const CL_String COL_MAP = "map";
const CL_String COL_PLAYERS = "players";
const CL_String COL_PING = "ping";

class PlayOnlineSceneImpl
{
	public:

		PlayOnlineScene *m_parent;

		Gfx::Header m_sceneTitleHeader;
		CL_Label m_statusLabel;
		CL_ListView m_serverList;

		CL_PushButton m_mainMenuButton;
		CL_PushButton m_refreshButton;
		CL_PushButton m_connectButton;

		PlayOnlineSceneController m_controller;

		CL_Callback_v1<const PlayOnlineScene::Entry&> m_serverEntrySelected;

		PlayOnlineSceneImpl(PlayOnlineScene *p_parent);
		~PlayOnlineSceneImpl();

		void configureListViewWidget();
		void configureButtons();

		void addServerEntry(const PlayOnlineScene::Entry &p_entry);
		void clearServerEntries();

		void onServerListSelectionChanged(CL_ListViewSelection p_selection);
};

PlayOnlineScene::PlayOnlineScene(CL_GUIComponent *p_parent) :
		GuiScene(p_parent),
		m_impl(new PlayOnlineSceneImpl(this))
{
	m_impl->m_controller.initialize();
}

PlayOnlineSceneImpl::PlayOnlineSceneImpl(PlayOnlineScene *p_parent) :
		m_parent(p_parent),
		m_sceneTitleHeader(p_parent),
		m_statusLabel(p_parent),
		m_serverList(p_parent),
		m_mainMenuButton(p_parent),
		m_refreshButton(p_parent),
		m_connectButton(p_parent),
		m_controller(p_parent)
{
	const int stageWidth = m_parent->get_width();

	m_sceneTitleHeader.set_geometry(CL_Rect(10, 30, 300, 80));
	m_sceneTitleHeader.setText(_("Play Online"));
	m_sceneTitleHeader.setTextSize(58);

	m_statusLabel.set_geometry(CL_Rect(stageWidth - 300, 80, stageWidth, 100));
	m_statusLabel.set_text(_("Press the refresh button"));

	configureListViewWidget();
	configureButtons();

	m_serverList.func_selection_changed().set(
			this, &PlayOnlineSceneImpl::onServerListSelectionChanged);
}

void PlayOnlineSceneImpl::configureListViewWidget()
{
	static const float COL_NAME_SIZE = 0.4f;
	static const float COL_GAMEMODE_SIZE = 0.2f;
	static const float COL_MAP_SIZE = 0.2f;
	static const float COL_PLAYERS_SIZE = 0.1f;
	static const float COL_PING_SIZE = 0.1f;

	static const int BOTTOM_MARGIN = 50;

	const int stageWidth = m_parent->get_width();
	const int stageHeight = m_parent->get_height();
	const int listWidth = stageWidth - 2 * MARGIN;

	m_serverList.set_geometry(CL_Rect(10, 100, stageWidth - MARGIN, stageHeight - BOTTOM_MARGIN));
	m_serverList.set_display_mode(listview_mode_details);
	m_serverList.set_select_whole_row(true);

	// add headers
	CL_ListViewHeader *header = m_serverList.get_header();

	CL_ListViewColumnHeader colName = header->create_column(COL_NAME, _("Server name"));
	colName.set_width(listWidth * COL_NAME_SIZE);
	header->append(colName);

	CL_ListViewColumnHeader colGameMode = header->create_column(COL_GAMEMODE, _("Gamemode"));
	colGameMode.set_width(listWidth * COL_GAMEMODE_SIZE);
	header->append(colGameMode);

	CL_ListViewColumnHeader colMap = header->create_column(COL_MAP, _("Map"));
	colMap.set_width(listWidth * COL_MAP_SIZE);
	header->append(colMap);

	CL_ListViewColumnHeader colPlayers = header->create_column(COL_PLAYERS, _("Players"));
	colPlayers.set_width(listWidth * COL_PLAYERS_SIZE);
	header->append(colPlayers);

	CL_ListViewColumnHeader colPing = header->create_column(COL_PING, _("Ping"));
	colPing.set_width(listWidth * COL_PING_SIZE);
	header->append(colPing);
}

void PlayOnlineSceneImpl::configureButtons()
{
	const int stageWidth = m_parent->get_width();
	const int stageHeight = m_parent->get_height();

	static const int BUTTON_HEIGHT = 30;
	static const int BUTTON_WIDTH = 100;
	const int buttonTop = stageHeight - MARGIN - BUTTON_HEIGHT;
	const int buttonBottom = stageHeight - MARGIN;

	CL_Rect mainMenuButtonRect(MARGIN, buttonTop, MARGIN + BUTTON_WIDTH, buttonBottom);
	m_mainMenuButton.set_geometry(mainMenuButtonRect);
	m_mainMenuButton.set_text(_("Main menu"));

	CL_Rect refreshButtonRect(
			stageWidth - (MARGIN + BUTTON_WIDTH) * 2, buttonTop,
			stageWidth - (MARGIN * 2 + BUTTON_WIDTH), buttonBottom);
	m_refreshButton.set_geometry(refreshButtonRect);
	m_refreshButton.set_text(_("Refresh"));

	CL_Rect connectButtonRect(
			stageWidth - (MARGIN + BUTTON_WIDTH), buttonTop,
			stageWidth - MARGIN, buttonBottom);
	m_connectButton.set_geometry(connectButtonRect);
	m_connectButton.set_text(_("Connect"));
}

PlayOnlineScene::~PlayOnlineScene()
{
	// empty
}

PlayOnlineSceneImpl::~PlayOnlineSceneImpl()
{
	// empty
}

void PlayOnlineScene::draw(CL_GraphicContext &p_gc)
{
	CL_Draw::fill(p_gc, 0.0f, 0.0f, get_width(), get_height(), CL_Colorf::white);
}

void PlayOnlineScene::addServerEntry(const Entry &p_entry)
{
	m_impl->addServerEntry(p_entry);
}

void PlayOnlineSceneImpl::addServerEntry(const PlayOnlineScene::Entry &p_entry)
{
	CL_ListViewItem item = m_serverList.create_item();
	item.set_column_text(COL_NAME, p_entry.serverName);
	item.set_column_text(COL_GAMEMODE, p_entry.gamemode);
	item.set_column_text(COL_MAP, p_entry.mapName);
	item.set_column_text(
			COL_PLAYERS, cl_format("%1/%2", p_entry.playerCountCurrent, p_entry.playerCountLimit));
	item.set_column_text(COL_PING, CL_StringHelp::int_to_text(p_entry.ping));

	CL_ListViewItem docItem = m_serverList.get_document_item();
	docItem.append_child(item);

	item.set_userdata(CL_SharedPtr<PlayOnlineScene::Entry>(new PlayOnlineScene::Entry(p_entry)));
}

void PlayOnlineScene::clearServerEntries()
{
	m_impl->clearServerEntries();
}

void PlayOnlineSceneImpl::clearServerEntries()
{
	CL_ListViewItem docItem = m_serverList.get_document_item();
	docItem.remove_children();
}

void PlayOnlineScene::setStatusText(const CL_String &p_statusText)
{
	m_impl->m_statusLabel.set_text(p_statusText);
}

void PlayOnlineSceneImpl::onServerListSelectionChanged(CL_ListViewSelection p_selection)
{
	CL_ListViewSelectedItem selectedItem = p_selection.get_first();

	if (!selectedItem.is_null()) {
		CL_ListViewItem item = selectedItem.get_item();
		PlayOnlineScene::Entry *serverEntry =
				reinterpret_cast<PlayOnlineScene::Entry*>(item.get_userdata().get());

		m_serverEntrySelected.invoke(*serverEntry);
	}
}

CL_Callback_v0 &PlayOnlineScene::refreshButtonClicked()
{
	return m_impl->m_refreshButton.func_clicked();
}

CL_Callback_v0 &PlayOnlineScene::mainMenuButtonClicked()
{
	return m_impl->m_mainMenuButton.func_clicked();
}

CL_Callback_v0 &PlayOnlineScene::connectButtonClicked()
{
	return m_impl->m_connectButton.func_clicked();
}

CL_Callback_v1<const PlayOnlineScene::Entry&> &PlayOnlineScene::serverEntrySelected()
{
	return m_impl->m_serverEntrySelected;
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
    <context:component-scan base-package="com.spring.mvc"/>
    <mvc:annotation-driven/>
    <bean class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
        <property name="defaultContentType" value="text/html"/>
        <property name="favorPathExtension" value="true"/>
        <property name="ignoreAcceptHeader" value="true"/>
        <property name="useJaf" value="false"/>
        <property name="mediaTypes">
            <map>
                <entry key="html" value="text/html"/>
                <entry key="json" value="application/json"/>
                <entry key="xml" value="application/xml"/>
            </map>
        </property>
    </bean>
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <context:property-placeholder ignore-unresolvable="true" location="jdbc.properties"/>

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${driverClassName}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${user}"/>
        <property name="password" value="${password}"/>
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager"/>
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
</beans>


text:
$current = $PSScriptRoot
$computerName = $Env:COMPUTERNAME

$password = "changeit"
$days = "365"
# /C=US/ST=CA/L=Cupertino/O=YourCompany/OU=YourApp/CN=MyRootCA
$caPublisher = "/C=JP/S=TOKYO/L=MINATO-KU/O=Demo CA Corporation/CN=Demo CA"
# /C=US/ST=CA/L=Cupertino/O=YourCompany/OU=YourApp/CN=%COMPUTERNAME%
$serverPublisher = "/C=JP/S=TOKYO/L=MINATO-KU/O=Demo Server Corporation/CN=localhost"
# /C=US/ST=CA/L=Cupertino /O=YourCompany /OU=YourApp/CN=%CLIENT-COMPUTERNAME%
$clientPublisher = "/C=JP/S=TOKYO/L=MINATO-KU/O=Demo Client Corporation/CN=${computerName}"
$openSSLVersion = "1.0.2u"

$opensslRoot = Join-Path "${current}" "tools" | `
               Join-Path -ChildPath "openssl" | `
               Join-Path -ChildPath "${openSSLVersion}"
$openssl = Join-Path "${opensslRoot}" "openssl.exe"
$opensslConf = Join-Path "${current}" "tools" | `
               Join-Path -ChildPath "openssl" | `
               Join-Path -ChildPath "openssl.cnf"
if (!(Test-Path("${opensslConf}")))
{
    Write-Host "openssl.cnf: ${opensslConf} is missing" -ForegroundColor Red
    exit -1
}
if (!(Test-Path("${openssl}")))
{
    Write-Host "openssl.cnf: ${openssl} is missing" -ForegroundColor Red
    exit -1
}

$env:OPENSSL_CONF="${opensslConf}"

Write-Host "Generate CA key:" -ForegroundColor Green
& "${openssl}" genrsa -passout pass:"${password}" -des3 -out ca.key 4096

Write-Host "Generate CA certificate:" -ForegroundColor Green
& "${openssl}" req -passin pass:"${password}" -new -x509 -days $days -key ca.key -out ca.crt -subj "${caPublisher}"

Write-Host "Generate server key:" -ForegroundColor Green
& "${openssl}" genrsa -passout pass:"${password}" -des3 -out server.key 4096

Write-Host "Generate server signing request:" -ForegroundColor Green
& "${openssl}" req -passin pass:"${password}" -new -key server.key -out server.csr -subj "${serverPublisher}"

Write-Host "Self-sign server certificate:" -ForegroundColor Green
& "${openssl}" x509 -req -passin pass:"${password}" -days $days -in server.csr -CA ca.crt -CAkey ca.key -set_serial 01 -out server.crt -extfile san.csx

Write-Host "Remove passphrase from server key:" -ForegroundColor Green
& "${openssl}" rsa -passin pass:"${password}" -in server.key -out server.key

Write-Host "Generate client key" -ForegroundColor Green
& "${openssl}" genrsa -passout pass:"${password}" -des3 -out client.key 4096

Write-Host "Generate client signing request:" -ForegroundColor Green
& "${openssl}" req -passin pass:"${password}" -new -key client.key -out client.csr -subj "${clientPublisher}"

Write-Host "Self-sign client certificate:" -ForegroundColor Green
& "${openssl}" x509 -passin pass:"${password}" -req -days $days -in client.csr -CA ca.crt -CAkey ca.key -set_serial 01 -out client.crt

Write-Host "Remove passphrase from client key:" -ForegroundColor Green
& "${openssl}" rsa -passin pass:"${password}" -in client.key -out client.key

Write-Host "Generate pfx:" -ForegroundColor Green
& "${openssl}" pkcs12 -export -out server.pfx -inkey server.key -in server.crt -password pass:"${password}"

$clients = @(
    "Client",
    "LegacyClient"
)

$sourceRoot = Join-Path $current "sources"

foreach ($client in $clients)
{
    $outputDir = Join-Path $sourceRoot $client
    $outputCertificatesDir = Join-Path $outputDir "certificates"
    New-Item -Type Directory -Force "${outputCertificatesDir}" | Out-Null
    Write-Host "Output: ${outputCertificatesDir}" -ForegroundColor Green

    $certificates = @(
        "ca.crt",
        "client.key",
        "client.crt"
    )

    foreach ($certificate in $certificates)
    {
        $srcFile = Join-Path $current $certificate
        $dstFile = Join-Path $outputCertificatesDir $certificate
        Copy-Item $srcFile $dstFile -Force
    }
}

$servers = @(
    "Server"
)

foreach ($server in $servers)
{
    $outputDir = Join-Path $sourceRoot $server
    $outputCertificatesDir = Join-Path $outputDir "certificates"
    New-Item -Type Directory -Force "${outputCertificatesDir}" | Out-Null
    Write-Host "Output: ${outputCertificatesDir}" -ForegroundColor Green

    $certificates = @(
        "ca.crt",
        "server.key",
        "server.crt",
        "server.pfx"
    )

    foreach ($certificate in $certificates)
    {
        $srcFile = Join-Path $current $certificate
        $dstFile = Join-Path $outputCertificatesDir $certificate
        Copy-Item $srcFile $dstFile -Force
    }
}


text:
namespace JustOrderIt.Services.Web
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    public class IdentifierProvider : IIdentifierProvider
    {
        private const string Salt = "khhdw6WDmn-sk!kj8m";

        public static int? DecodeToIntStatic(string encodedId)
        {
            if (string.IsNullOrWhiteSpace(encodedId))
            {
                return null;
            }

            var base64EncodedBytes = Convert.FromBase64String(encodedId);
            var baseAsString = Encoding.UTF8
                .GetString(base64EncodedBytes)
                .Substring(0, base64EncodedBytes.Length - Salt.Length);
            return int.Parse(baseAsString);
        }

        public static string DecodeIdToStringStatic(string encodedId)
        {
            if (string.IsNullOrWhiteSpace(encodedId))
            {
                return null;
            }

            var base64EncodedBytes = Convert.FromBase64String(encodedId);
            var baseAsString = Encoding.UTF8
                .GetString(base64EncodedBytes)
                .Substring(0, base64EncodedBytes.Length - Salt.Length);
            return baseAsString;
        }

        public static string EncodeIntIdStatic(int id)
        {
            var plainTextBytes = Encoding.UTF8.GetBytes(id.ToString() + Salt);
            return Convert.ToBase64String(plainTextBytes);
        }

        public static string EncodeStringIdStatic(string id)
        {
            if (string.IsNullOrWhiteSpace(id))
            {
                return null;
            }

            var plainTextBytes = Encoding.UTF8.GetBytes(id + Salt);
            return Convert.ToBase64String(plainTextBytes);
        }

        public int? DecodeToIntId(string encodedId)
        {
            return DecodeToIntStatic(encodedId);
        }

        public string DecodeToStringId(string encodedId)
        {
            return DecodeIdToStringStatic(encodedId);
        }

        public string EncodeIntId(int id)
        {
            return EncodeIntIdStatic(id);
        }

        public string EncodeStringId(string id)
        {
            return EncodeStringIdStatic(id);
        }
    }
}


text:
<?php

/*
* <auto-generated>
*     This code was generated by a Codezu.
*
*     Changes to this file may cause incorrect behavior and will be lost if
*     the code is regenerated.
* </auto-generated>
*/

namespace Mozu\Api\Contracts\CommerceRuntime\Commerce;

/**
*	Dimensions of the packaged product.
*/
class PackageMeasurements
{
	/**
	*Height of the package in imperial units of feet and inches.
	*/
	public $height;

	/**
	*Length of the package in imperial units of feet and inches.
	*/
	public $length;

	/**
	*Weight of the package in imperial units of pounds and ounces.
	*/
	public $weight;

	/**
	*Width of the package in imperial units of feet and inches.
	*/
	public $width;

}

?>


text:
<?php

namespace Lthrt\ContactBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * DemographicType.
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="Lthrt\ContactBundle\Repository\DemographicTypeRepository")
 *
 * eg gender, race, ethnicity
 */
class DemographicType implements \Lthrt\EntityBundle\Entity\EntityLedger, \JsonSerializable
{
    use \Lthrt\EntityBundle\Entity\DoctrineEntityTrait;
    use \Lthrt\EntityBundle\Entity\JsonTrait;
    // use \Lthrt\EntityBundle\Entity\LoggingDisabledTrait;

    use \Lthrt\EntityBundle\Entity\ActiveTrait;
    use \Lthrt\EntityBundle\Entity\NameTrait;
}


text:
package org.springframework.security.oauth2.client.authentication;

import org.springframework.security.crypto.keygen.StringKeyGenerator;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.core.endpoint.AuthorizationRequestAttributes;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.util.Assert;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.UriComponentsBuilder;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URI;

import static org.springframework.security.oauth2.client.authentication.AuthorizationCodeAuthenticationProcessingFilter.AUTHORIZE_BASE_URI;

/**
 * This Filter initiates the authorization code grant flow by redirecting
 * the end-user's user-agent to the authorization server's Authorization Endpoint.
 *
 *

 * It uses an {@link AuthorizationRequestUriBuilder} to build the OAuth 2.0 Authorization Request,
 * which is used as the redirect URI to the Authorization Endpoint.
 * The redirect URI will include the client identifier, requested scope(s), state, response type, and a redirection URI
 * which the authorization server will send the user-agent back to (handled by {@link AuthorizationCodeAuthenticationProcessingFilter})
 * once access is granted (or denied) by the end-user (resource owner).
 *
 * @author Joe Grandja
 * @since 5.0
 * @see AuthorizationRequestAttributes
 * @see AuthorizationRequestRepository
 * @see AuthorizationRequestUriBuilder
 * @see ClientRegistration
 * @see ClientRegistrationRepository
 * @see AuthorizationCodeAuthenticationProcessingFilter
 * @see Section 4.1 Authorization Code Grant Flow
 * @see Section 4.1.1 Authorization Request
 */
public class AuthorizationCodeRequestRedirectFilter extends OncePerRequestFilter {
	public static final String AUTHORIZATION_BASE_URI = "/oauth2/authorization/code";
	private static final String CLIENT_ALIAS_VARIABLE_NAME = "clientAlias";
	private static final String AUTHORIZATION_URI = AUTHORIZATION_BASE_URI + "/{" + CLIENT_ALIAS_VARIABLE_NAME + "}";
	private static final String DEFAULT_REDIRECT_URI_TEMPLATE = "{scheme}://{serverName}:{serverPort}{baseAuthorizeUri}/{clientAlias}";
	private final AntPathRequestMatcher authorizationRequestMatcher;
	private final ClientRegistrationRepository clientRegistrationRepository;
	private final AuthorizationRequestUriBuilder authorizationUriBuilder;
	private final RedirectStrategy authorizationRedirectStrategy = new DefaultRedirectStrategy();
	private final StringKeyGenerator stateGenerator = new DefaultStateGenerator();
	private AuthorizationRequestRepository authorizationRequestRepository = new HttpSessionAuthorizationRequestRepository();

	public AuthorizationCodeRequestRedirectFilter(ClientRegistrationRepository clientRegistrationRepository,
													AuthorizationRequestUriBuilder authorizationUriBuilder) {

		Assert.notNull(clientRegistrationRepository, "clientRegistrationRepository cannot be null");
		Assert.notNull(authorizationUriBuilder, "authorizationUriBuilder cannot be null");
		this.authorizationRequestMatcher = new AntPathRequestMatcher(AUTHORIZATION_URI);
		this.clientRegistrationRepository = clientRegistrationRepository;
		this.authorizationUriBuilder = authorizationUriBuilder;
	}

	public final void setAuthorizationRequestRepository(AuthorizationRequestRepository authorizationRequestRepository) {
		Assert.notNull(authorizationRequestRepository, "authorizationRequestRepository cannot be null");
		this.authorizationRequestRepository = authorizationRequestRepository;
	}

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {

		if (this.requiresAuthorization(request, response)) {
			try {
				this.sendRedirectForAuthorization(request, response);
			} catch (Exception failed) {
				this.unsuccessfulAuthorization(request, response, failed);
			}
			return;
		}

		filterChain.doFilter(request, response);
	}

	protected boolean requiresAuthorization(HttpServletRequest request, HttpServletResponse response) {
		return this.authorizationRequestMatcher.matches(request);
	}

	protected void sendRedirectForAuthorization(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {

		String clientAlias = this.authorizationRequestMatcher
				.extractUriTemplateVariables(request).get(CLIENT_ALIAS_VARIABLE_NAME);
		ClientRegistration clientRegistration = this.clientRegistrationRepository.getRegistrationByClientAlias(clientAlias);
		if (clientRegistration == null) {
			throw new IllegalArgumentException("Invalid Client Identifier (Alias): " + clientAlias);
		}

		String redirectUriStr;
		if (isDefaultRedirectUri(clientRegistration)) {
			redirectUriStr = this.expandDefaultRedirectUri(request, clientRegistration);
		} else {
			redirectUriStr = clientRegistration.getRedirectUri();
		}

		AuthorizationRequestAttributes authorizationRequestAttributes =
			AuthorizationRequestAttributes.withAuthorizationCode()
				.clientId(clientRegistration.getClientId())
				.authorizeUri(clientRegistration.getProviderDetails().getAuthorizationUri())
				.redirectUri(redirectUriStr)
				.scopes(clientRegistration.getScopes())
				.state(this.stateGenerator.generateKey())
				.build();

		this.authorizationRequestRepository.saveAuthorizationRequest(authorizationRequestAttributes, request);

		URI redirectUri = this.authorizationUriBuilder.build(authorizationRequestAttributes);
		this.authorizationRedirectStrategy.sendRedirect(request, response, redirectUri.toString());
	}

	protected void unsuccessfulAuthorization(HttpServletRequest request, HttpServletResponse response,
												Exception failed) throws IOException, ServletException {

		if (logger.isDebugEnabled()) {
			logger.debug("Authorization Request failed: " + failed.toString(), failed);
		}
		response.sendError(HttpServletResponse.SC_BAD_REQUEST, failed.getMessage());
	}

	static boolean isDefaultRedirectUri(ClientRegistration clientRegistration) {
		return DEFAULT_REDIRECT_URI_TEMPLATE.equals(clientRegistration.getRedirectUri());
	}

	private String expandDefaultRedirectUri(HttpServletRequest request, ClientRegistration clientRegistration) {
		return UriComponentsBuilder.fromUriString(DEFAULT_REDIRECT_URI_TEMPLATE)
			.buildAndExpand(request.getScheme(), request.getServerName(), request.getServerPort(),
				AUTHORIZE_BASE_URI, clientRegistration.getClientAlias())
			.encode()
			.toUriString();
	}
}


text:
<!DOCTYPE html>

    <title>Aloy's portfolio</title>
    <link href='https://fonts.googleapis.com/css?family=Crete+Round' rel='stylesheet' type='text/css'>
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/styles.css" rel="stylesheet">

Home

                    About Me

                    Work History

Wang Weili Aloysius

 Year 2 Computing Science Student

 National University of Singapore

Featured Works


text:
struct NXT_guid
{
    struct NXT_str H;
    char guid[128 - sizeof(struct NXT_str)];
};

struct NXT_trade { uint64_t price,quantity,askorder,bidorder,blockbits,assetid; int32_t timestamp,decimals; };
union _asset_price { uint64_t assetoshis,price; };

struct NXT_assettxid
{
    struct NXT_str H;
    uint64_t AMtxidbits,txidbits,assetbits,senderbits,receiverbits,quantity,redeemtxid;
    union _asset_price U; // price 0 -> not buy/sell but might be deposit amount
    //struct NXT_guid *duplicatehash;
    uint32_t coinblocknum,cointxind,coinv;
    char *cointxid;
    char *comment;//*guid,
    int32_t completed,timestamp,vout;
};

struct NXT_assettxid_list
{
    struct NXT_assettxid **txids;
    int32_t num,max;
};

struct NXT_asset
{
    struct NXT_str H;
    uint64_t issued,mult,assetbits,issuer;
    char *description,*name;
    struct NXT_assettxid **txids;   // all transactions for this asset
    int32_t max,num,decimals,exdiv_height;
};

struct udp_info { uint64_t nxt64bits; uint32_t ipbits; uint16_t port; };
#define SET_UDPINFO(up,bits,addr) ((up)->nxt64bits = bits, (up)->ipbits = calc_ipbits(inet_ntoa((addr)->sin_addr)), (up)->port = ntohs((addr)->sin_port))

struct other_addr
{
    uint64_t modified,nxt64bits;
    char addr[128];
};

struct acct_coin { char name[16],*acctcoinaddr,*pubkey; };

struct NXT_acct
{
    struct NXT_str H;
    struct NXT_asset **assets;
    uint64_t *quantities,bestbits,quantity;
    struct NXT_assettxid_list **txlists;    // one list for each asset in acct
    int32_t maxassets,numassets,bestdist,numcoins;//numcoinaccts
    int64_t buyqty,buysum,sellqty,sellsum;
    double profits;
    uint32_t timestamps[64];
    struct acct_coin *coins[64];
    //struct coin_acct *coinaccts;
    // fields for NXTorrent
    //double hisfeedbacks[6],myfb_tohim[6];    // stats on feedbacks given
    //queue_t incomingQ;
    //uint16_t udp_port;
    //uv_stream_t *tcp,*connect;
    //char dispname[128];//,udp_sender[64];//,tcp_sender[64];
    struct nodestats stats;
    char *signedtx,NXTACCTSECRET[128];
};
struct NXT_acct **get_assetaccts(int32_t *nump,char *assetidstr,int32_t maxtimestamp);

#endif


text:
package kafka

import (
	"errors"
	"fmt"
	"strings"
	"time"

	"github.com/elastic/beats/libbeat/outputs"
)

type kafkaConfig struct {
	Hosts           []string           `config:"hosts"               validate:"required"`
	TLS             *outputs.TLSConfig `config:"tls"`
	Timeout         time.Duration      `config:"timeout"             validate:"min=1"`
	Worker          int                `config:"worker"              validate:"min=1"`
	UseType         bool               `config:"use_type"`
	Topic           string             `config:"topic"`
	KeepAlive       time.Duration      `config:"keep_alive"          validate:"min=0"`
	MaxMessageBytes *int               `config:"max_message_bytes"   validate:"min=1"`
	RequiredACKs    *int               `config:"required_acks"       validate:"min=-1"`
	BrokerTimeout   time.Duration      `config:"broker_timeout"      validate:"min=1"`
	Compression     string             `config:"compression"`
	MaxRetries      int                `config:"max_retries"         validate:"min=-1,nonzero"`
	ClientID        string             `config:"client_id"`
	ChanBufferSize  int                `config:"channel_buffer_size" validate:"min=1"`
}

var (
	defaultConfig = kafkaConfig{
		Hosts:           nil,
		TLS:             nil,
		Timeout:         30 * time.Second,
		Worker:          1,
		UseType:         false,
		Topic:           "",
		KeepAlive:       0,
		MaxMessageBytes: nil, // use library default
		RequiredACKs:    nil, // use library default
		BrokerTimeout:   10 * time.Second,
		Compression:     "gzip",
		MaxRetries:      3,
		ClientID:        "beats",
		ChanBufferSize:  256,
	}
)

func (c *kafkaConfig) Validate() error {
	if len(c.Hosts) == 0 {
		return errors.New("no hosts configured")
	}

	if c.UseType == false && c.Topic == "" {
		return errors.New("use_type must be true or topic must be set")
	}

	if _, ok := compressionModes[strings.ToLower(c.Compression)]; !ok {
		return fmt.Errorf("compression mode '%v' unknown", c.Compression)
	}

	return nil
}


text:
package com.athena.meerkat.controller.web.tomcat;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.athena.meerkat.controller.MeerkatConstants;
import com.athena.meerkat.controller.web.common.code.CommonCodeHandler;
import com.athena.meerkat.controller.web.common.model.GridJsonResponse;
import com.athena.meerkat.controller.web.common.model.SimpleJsonResponse;
import com.athena.meerkat.controller.web.entities.CommonCode;
import com.athena.meerkat.controller.web.entities.TaskHistory;
import com.athena.meerkat.controller.web.entities.TomcatConfigFile;
import com.athena.meerkat.controller.web.entities.TomcatDomain;
import com.athena.meerkat.controller.web.entities.TomcatInstance;
import com.athena.meerkat.controller.web.provisioning.TomcatProvisioningService;
import com.athena.meerkat.controller.web.tomcat.services.TaskHistoryService;
import com.athena.meerkat.controller.web.tomcat.services.TomcatConfigFileService;
import com.athena.meerkat.controller.web.tomcat.services.TomcatDomainService;
import com.athena.meerkat.controller.web.tomcat.services.TomcatInstanceService;

@Controller
@RequestMapping("/configfile")
public class TomcatConfigFileController {

	@Autowired
	private TomcatDomainService domainService;

	@Autowired
	private CommonCodeHandler commonHandler;

	@Autowired
	private TomcatInstanceService tomcatService;

	@Autowired
	private TomcatConfigFileService tomcatConfigFileService;

	@Autowired
	private TomcatProvisioningService proviService;

	@Autowired
	private TaskHistoryService taskService;

	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public @ResponseBody SimpleJsonResponse saveConfigFile(SimpleJsonResponse json, String content, String confType, String objType, int id, int objId) {
		TomcatDomain td = null;
		TomcatInstance tcinst = null;
		TomcatConfigFile conf = new TomcatConfigFile();

		if (objType.equals(MeerkatConstants.OBJ_TYPE_DOMAIN)) {
			td = domainService.getDomain(objId);
			conf.setTomcatDomain(td);

		} else if (objType.equals(MeerkatConstants.OBJ_TYPE_TOMCAT)) {
			tcinst = tomcatService.findOne(objId);
			conf.setTomcatInstance(tcinst);
			conf.setTomcatDomain(tcinst.getTomcatDomain());//don't delete.
		}

		CommonCode code = commonHandler.getCode(confType);
		if (code != null) {
			conf.setFileTypeCdId(code.getId());
		}

		TomcatConfigFile latestVersion = tomcatConfigFileService.getLatestConfVersion(td, tcinst, conf.getFileTypeCdId());

		if (latestVersion != null) {
			conf.setVersion(latestVersion.getVersion() + 1);
		} else {
			conf.setVersion(1);
		}

		conf.setContent(content);
		if (td != null) {
			conf = tomcatConfigFileService.saveConfigXmlFile(conf, td.getDomainTomcatConfig());
		} else {
			conf = tomcatConfigFileService.saveConfigXmlFile(conf, tcinst.getTomcatDomain().getDomainTomcatConfig());
		}

		// create task
		TaskHistory task = taskService.createConfigXmlUpdateTask(conf.getTomcatDomain().getId(), conf.getFileTypeCdId());
		if (td != null) {
			proviService.updateXml(td.getId(), conf.getId(), task.getId(), td.getTomcatInstances());
		} else if (tcinst != null) {
			proviService.updateXml(tcinst.getId(), conf.getId(), task.getId());
		}
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("configFileId", conf.getId());
		resultMap.put("task", task);
		json.setData(resultMap);

		return json;
	}

	@RequestMapping(value = "{type}/domain/{domainId}", method = RequestMethod.GET)
	public @ResponseBody GridJsonResponse getConfigVersionList(GridJsonResponse json, @PathVariable int domainId, @PathVariable String type) {
		TomcatDomain td = domainService.getDomain(domainId);

		List<TomcatConfigFile> confVersions = tomcatConfigFileService.getConfigFileVersions(td.getId(), type);
		json.setList(confVersions);
		json.setTotal(confVersions.size());
		json.setSuccess(true);
		return json;
	}

	@RequestMapping(value = "/{configFileId}", method = RequestMethod.GET)
	public @ResponseBody SimpleJsonResponse getConfigFileContents(SimpleJsonResponse json, @PathVariable Integer configFileId) {

		json.setData(tomcatConfigFileService.getConfigFileContents(configFileId));

		return json;
	}

	@RequestMapping("/diff/{firstId}/{secondId}")
	public String diff(Map<String, String> model, @PathVariable Integer firstId, @PathVariable Integer secondId) {

		TomcatConfigFile firstConfig = tomcatConfigFileService.getTomcatConfigFileById(firstId);
		TomcatConfigFile secondConfig = tomcatConfigFileService.getTomcatConfigFileById(secondId);

		String content = "";
		if (firstConfig != null) {

			content = tomcatConfigFileService.getConfigFileContents(firstConfig.getFilePath());
			model.put("firstConfig", content);
			model.put("firstConfigVersion", firstConfig.getVersionAndTimeAndTomcat());
		}
		if (secondConfig != null) {
			content = tomcatConfigFileService.getConfigFileContents(secondConfig.getFilePath());
			model.put("secondConfig", content);
			model.put("secondConfigVersion", secondConfig.getVersionAndTimeAndTomcat());
		}
		return "configdiff";
	}

	@RequestMapping(value = "/{type}/domain/{domainId}/tomcat/{tomcatId}", method = RequestMethod.GET)
	@ResponseBody
	public GridJsonResponse getConfigFileVersions(GridJsonResponse json, @PathVariable Integer domainId, @PathVariable Integer tomcatId,
			@PathVariable String type) {
		List<TomcatConfigFile> confVersions = new ArrayList<TomcatConfigFile>();
		TomcatInstance tomcat = null;
		TomcatDomain td = null;
		if (tomcatId > 0) {
			tomcat = tomcatService.findOne(tomcatId);
		}
		if (domainId > 0) {
			td = domainService.getDomain(domainId);
		}
		if (tomcat != null) {
			// list of config files modified in domain level
			confVersions = tomcatConfigFileService.getConfigFileVersions(tomcat.getDomainId(), type);
			List<TomcatConfigFile> modifiedConfigVersions = tomcatConfigFileService.getConfigFileVersions(tomcat, commonHandler.getCode(type).getId());
			if (modifiedConfigVersions != null) {
				confVersions.addAll(modifiedConfigVersions);
			}
		} else if (td != null) {
			confVersions = tomcatConfigFileService.getConfigFileVersions(domainId, type);
		}
		json.setList(confVersions);
		json.setTotal(confVersions.size());
		return json;
	}

	@RequestMapping(value = "/{type}/latest/domain/{domainId}/tomcat/{tomcatId}", method = RequestMethod.GET)
	@ResponseBody
	public SimpleJsonResponse getLatestVersionConfigFile(SimpleJsonResponse json, @PathVariable Integer domainId, @PathVariable Integer tomcatId,
			@PathVariable String type) {
		TomcatConfigFile conf = null;

		int fileTypeCdId = commonHandler.getCode(type).getId();//TODO tran : temporary code. don't do this.

		if (tomcatId > 0) {
			TomcatInstance tc = tomcatService.findOne(tomcatId);
			conf = tomcatConfigFileService.getLatestConfVersion(null, tc, fileTypeCdId);
		} else if (domainId > 0) {
			TomcatDomain td = domainService.getDomain(domainId);
			conf = tomcatConfigFileService.getLatestConfVersion(td, null, fileTypeCdId);
		}

		if (conf != null) {
			String content = tomcatConfigFileService.getConfigFileContents(conf.getId());
			conf.setContent(content);
			json.setData(conf);
		}
		return json;
	}

}


text:
using System;

using CompositeC1Contrib.Email.GoogleAnalytics;

namespace CompositeC1Contrib.Email
{
    public static class BootstrapperConfigurationExtensions
    {
        private static GoogleAnalyticsEventsProcessor _processor;

        public static void UseGoogleAnalytics(this IBootstrapperConfiguration config, GoogleAnalyticsEventsProcessorOptions options)
        {
            if (_processor != null)
            {
                throw new InvalidOperationException("Processor already initialized");
            }

            _processor = new GoogleAnalyticsEventsProcessor(config, options);
        }
    }
}


text:
package com.faforever.client.login;

import com.faforever.client.fx.Controller;
import com.faforever.client.i18n.I18n;
import com.faforever.client.util.TimeService;
import javafx.scene.control.Label;
import javafx.scene.layout.Pane;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.time.temporal.TemporalAccessor;

@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@RequiredArgsConstructor
public class AnnouncementController implements Controller<Pane> {

  public Pane loginAnnouncementRoot;
  public Label titleLabel;
  public Label messageLabel;
  public Label timeLabel;

  private final TimeService timeService;
  private final I18n i18n;

  @Override
  public Pane getRoot() {
    return loginAnnouncementRoot;
  }

  public void setTitle(String title) {
    titleLabel.setText(title);
  }

  public void setMessage(String message) {
    messageLabel.setText(message);
  }

  public void setTime(TemporalAccessor start, TemporalAccessor end) {
    timeLabel.setText(i18n.get("temporalRange", timeService.asDateTime(start), timeService.asDateTime(end)));
  }
}


text:
extern tinfra::module_tracer json_mo_parser_tracer;

class json_mo_parser {
    tinfra::json_lexer& lexer;

    tinfra::json_token  current;
    bool        finished;
    std::vector<std::string> name_stack;

public:
    json_mo_parser(tinfra::json_lexer& lexer);

    // MO visitor contract
    template <typename S, typename T>
    void record(S sym, T& v)
    {
        if( !match_name(sym) || finished ) {
            return;
        }
        expect(tinfra::json_token::OBJECT_BEGIN);
        next_or_fail("expected } or \"key\":value when parsing object but EOF found");

        if( current.type == tinfra::json_token::OBJECT_END ) {
            // short circuit for {}
            next();
            return;
        }

        while( true ) {
            // 'foo'
            expect(tinfra::json_token::STRING);
            std::string key(current.value.str());
            next();
            // 'foo' :
            expect(tinfra::json_token::COLON);
            next_or_fail("expected value after ':'");

            // try to parse matching field
            push_expected_name(key);
            tinfra::mo_mutate(v, *this);
            pop_expected_name();

            // now decide: next or end
            if( current.type == tinfra::json_token::COMMA ) {
                // , -> continue
                next();
                continue;
            }
            if( current.type == tinfra::json_token::OBJECT_END ) {
                // } -> break
                next();
                break;
            }
            fail("expected ',' or '}' after value when parsing dictionary");
        }
        tinfra::mo_mutate(v, *this);
    }

    template <typename S, typename T>
    void sequence(S sym, T& array)
    {
        if( !match_name(sym) || finished ) {
            return;
        }
        expect(tinfra::json_token::ARRAY_BEGIN);
        next_or_fail("expected ] or value when parsing array but EOF found");

        if( current.type == tinfra::json_token::ARRAY_END ) {
            // short circuit for []
            next();
            return;
        }
        while( true ) {
            {
                // ANYTHING
                typename T::value_type tmp;
                push_expected_name("!foo");
                tinfra::mo_mutate("!foo", tmp, *this);
                pop_expected_name();

                using std::swap;
                array.push_back(tmp);
            }

            // now decide: next or end
            if( current.type == tinfra::json_token::COMMA ) {
                // , -> continue
                next_or_fail("expected value after ','");
                continue;
            }
            if( current.type == tinfra::json_token::ARRAY_END ) {
                // ] -> break
                next();
                break;
            }
            fail("expected ',' or ']' after value when parsing array");
        }
    }
    template <typename S>
    void leaf(S sym, std::string& v)
        // std::string leaf
        // store any value as string, even integers and doubles
    {
        if( !match_name(sym) || finished ) {
            return;
        }

        switch( current.type ) {
        case tinfra::json_token::STRING:
        case tinfra::json_token::INTEGER:
        case tinfra::json_token::DOUBLE:
            v = current.value.str();
            next();
            break;
        default:
            fail(tsprintf("expected string for field '%s' but found (found %s)", get_full_field_name(sym), current.type));
        }
    }

    template <typename S, typename I>
    void integer_leaf(S sym, I& v)
        // integer type leaf leaf
        // store any value as string, even integers and doubles
    {
        if( !match_name(sym) || finished ) {
            return;
        }

        if( current.type == tinfra::json_token::INTEGER ) {
            v = tinfra::from_string<I>(current.value.str());
            next();
        } else {
            fail(tsprintf("expected integer for field '%s' but found (found %s)", get_full_field_name(sym), current.type));
        }
    }
    template <typename S>
    void leaf(S sym, int& v) {
        this->integer_leaf<int>(sym, v);
    }
    template <typename S>
    void leaf(S sym, long& v) {
        this->integer_leaf<long>(sym, v);
    }
    template <typename S>
    void leaf(S sym, long long& v) {
        this->integer_leaf<long long>(sym, v);
    }
private:
    void push_expected_name(std::string const& str);
    void pop_expected_name();
    bool match_name(tinfra::tstring const& name);

    bool next();
    void next_or_fail(const char* message);
    void fail(std::string const& message);
    void expect(tinfra::json_token::token_type tt);
    std::string get_full_field_name(tinfra::tstring sym);
};

// namespace tinfra

#endif // json_mo_parser_h_included

// jedit: :tabSize=8:indentSize=4:noTabs=true:mode=c++:


text:
package com.box.boxjavalibv2.jsonparsing;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import com.box.boxjavalibv2.dao.BoxObject;
import com.box.boxjavalibv2.interfaces.IBoxResourceHub;
import com.box.boxjavalibv2.interfaces.IBoxType;

public abstract class BaseBoxResourceHub implements IBoxResourceHub {

    // As a performance optimization, set up string values for all types.
    private static final Map<String, IBoxType> lowercaseStringToType = new HashMap<String, IBoxType>();

    public BaseBoxResourceHub() {
        initializeTypes();
    }

    @Override
    @SuppressWarnings("rawtypes")
    public Class getClass(IBoxType type) {
        return BoxObject.class;
    }

    protected Map<String, IBoxType> getLowerCaseStringToTypeMap() {
        return lowercaseStringToType;
    }

    /**
     * Get the concrete class for IBoxType
     *
     * @return
     */
    @SuppressWarnings("rawtypes")
    protected abstract Class getConcreteClassForIBoxType();

    /**
     * Get class for a certain type, assuming the input type is an object of the concrete class of IBoxType defined in this resource hub.
     *
     * @param <T>
     *
     * @param type
     * @return
     */
    @SuppressWarnings("rawtypes")
    protected abstract Class getObjectClassGivenConcreteIBoxType(IBoxType type);

    /**
     * Do call super.initializeTypes() when overriding this.
     */
    protected void initializeTypes() {
        // Make it non-abstract so children can call super. This way makes it more explicit that super should be called.
    }

    protected void initializeEnumTypes(Class<? extends Enum> cls) {
        Map<String, IBoxType> map = getLowerCaseStringToTypeMap();
        Enum[] types = cls.getEnumConstants();
        for (Enum type : types) {
            String str = type.name().toLowerCase(Locale.ENGLISH);
            map.put(str, (IBoxType) type);
        }
    }
}