text:
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Xml.Serialization;

using FluentAssertions.Equivalency;
using FluentAssertions.Execution;
using FluentAssertions.Primitives;

namespace FluentAssertions
{
    public static class ObjectAssertionsExtensions
    {
        ///
        /// Asserts that an object can be serialized and deserialized using the binary serializer and that it stills retains
        /// the values of all members.
        ///
        /// <param name="because">
        /// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
        /// is needed. If the phrase does not start with the word because, it is prepended automatically.
        /// </param>
        /// <param name="becauseArgs">
        /// Zero or more objects to format using the placeholders in <see cref="because" />.
        /// </param>
        public static AndConstraint<ObjectAssertions> BeBinarySerializable(this ObjectAssertions assertions, string because = "",
            params object[] becauseArgs)
        {
            return BeBinarySerializable<object>(assertions, options => options, because, becauseArgs);
        }

        ///
        /// Asserts that an object can be serialized and deserialized using the binary serializer and that it stills retains
        /// the values of all members.
        ///
        /// <param name="because">
        /// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
        /// is needed. If the phrase does not start with the word because, it is prepended automatically.
        /// </param>
        /// <param name="becauseArgs">
        /// Zero or more objects to format using the placeholders in <see cref="because" />.
        /// </param>
        public static AndConstraint<ObjectAssertions> BeBinarySerializable<T>(this ObjectAssertions assertions,
            Func<EquivalencyAssertionOptions<T>, EquivalencyAssertionOptions<T>> options, string because = "",
            params object[] becauseArgs)
        {
            try
            {
                object deserializedObject = CreateCloneUsingBinarySerializer(assertions.Subject);

                EquivalencyAssertionOptions<T> defaultOptions = AssertionOptions.CloneDefaults<T>()
                    .RespectingRuntimeTypes().IncludingFields().IncludingProperties();

                ((T)deserializedObject).ShouldBeEquivalentTo(assertions.Subject, _ => options(defaultOptions));
            }
            catch (Exception exc)
            {
                Execute.Assertion
                    .BecauseOf(because, becauseArgs)
                    .FailWith("Expected {0} to be serializable{reason}, but serialization failed with:\r\n\r\n{1}",
                        assertions.Subject,
                        exc.Message);
            }

            return new AndConstraint<ObjectAssertions>(assertions);
        }

        ///
        /// Asserts that an object can be serialized and deserialized using the data contract serializer and that it stills retains
        /// the values of all members.
        ///
        /// <param name="because">
        /// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
        /// is needed. If the phrase does not start with the word because, it is prepended automatically.
        /// </param>
        /// <param name="becauseArgs">
        /// Zero or more objects to format using the placeholders in <see cref="because" />.
        /// </param>
        public static AndConstraint<ObjectAssertions> BeDataContractSerializable(this ObjectAssertions assertions,
            string because = "", params object[] becauseArgs)
        {
            return BeDataContractSerializable<object>(assertions, because, becauseArgs);
        }

        ///
        /// Asserts that an object can be serialized and deserialized using the data contract serializer and that it stills retains
        /// the values of all members.
        ///
        /// <param name="because">
        /// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
        /// is needed. If the phrase does not start with the word because, it is prepended automatically.
        /// </param>
        /// <param name="becauseArgs">
        /// Zero or more objects to format using the placeholders in <see cref="because" />.
        /// </param>
        public static AndConstraint<ObjectAssertions> BeDataContractSerializable<T>(this ObjectAssertions assertions,
            string because = "", params object[] becauseArgs)
        {
            try
            {
                var deserializedObject = CreateCloneUsingDataContractSerializer(assertions.Subject);

                deserializedObject.ShouldBeEquivalentTo(assertions.Subject,
                        options => options.RespectingRuntimeTypes().IncludingFields().IncludingProperties());
            }
            catch (Exception exc)
            {
                Execute.Assertion
                    .BecauseOf(because, becauseArgs)
                    .FailWith("Expected {0} to be serializable{reason}, but serialization failed with:\r\n\r\n{1}",
                        assertions.Subject,
                        exc.Message);
            }

            return new AndConstraint<ObjectAssertions>(assertions);
        }

        private static object CreateCloneUsingBinarySerializer(object subject)
        {
            var stream = new MemoryStream();
            var binaryFormatter = new BinaryFormatter();
            binaryFormatter.Serialize(stream, subject);

            stream.Position = 0;
            return binaryFormatter.Deserialize(stream);
        }

        private static object CreateCloneUsingDataContractSerializer(object subject)
        {
            using (var stream = new MemoryStream())
            {
                var serializer = new DataContractSerializer(subject.GetType());
                serializer.WriteObject(stream, subject);
                stream.Position = 0;
                return serializer.ReadObject(stream);
            }
        }

        ///
        /// Asserts that an object can be serialized and deserialized using the XML serializer and that it stills retains
        /// the values of all members.
        ///
        /// <param name="because">
        /// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
        /// is needed. If the phrase does not start with the word because, it is prepended automatically.
        /// </param>
        /// <param name="becauseArgs">
        /// Zero or more objects to format using the placeholders in <see cref="because" />.
        /// </param>
        public static AndConstraint<ObjectAssertions> BeXmlSerializable(this ObjectAssertions assertions, string because = "",
            params object[] becauseArgs)
        {
            try
            {
                object deserializedObject = CreateCloneUsingXmlSerializer(assertions.Subject);

                deserializedObject.ShouldBeEquivalentTo(assertions.Subject,
                    options => options.RespectingRuntimeTypes().IncludingFields().IncludingProperties());
            }
            catch (Exception exc)
            {
                Execute.Assertion
                    .BecauseOf(because, becauseArgs)
                    .FailWith("Expected {0} to be serializable{reason}, but serialization failed with:\r\n\r\n{1}",
                        assertions.Subject,
                        exc.Message);
            }

            return new AndConstraint<ObjectAssertions>(assertions);
        }

        private static object CreateCloneUsingXmlSerializer(object subject)
        {
            var stream = new MemoryStream();
            var binaryFormatter = new XmlSerializer(subject.GetType());
            binaryFormatter.Serialize(stream, subject);

            stream.Position = 0;
            return binaryFormatter.Deserialize(stream);
        }
    }
}


text:
import { html } from 'lit-element'

export const theme = html`
<style>
    :host {
        /* Material Components Web Components */
        --mdc-theme-primary: var(--paper-blue-grey-700);
        --mdc-theme-secondary: var(--paper-green-700);
        --mdc-theme-background: var(--paper-grey-900);
        --mdc-theme-surface: var(--paper-grey-300);
        --mdc-theme-on-primary: #fff;
        --mdc-theme-on-secondary: #fff;
        --mdc-theme-on-surface: var(--paper-grey-900);

        /* Luminave Custom */
        --padding-basic: .5em;
        --focus-color: #ddd;
        --default-warning-color: #da4453;
        --default-success-color: var(--google-green-500);
        --warning-text-color: var(--text-primary-color);

        /* Google Material Design */
        /* This is the surface-color in mdc */
        --primary-background-color: var(--mdc-theme-surface);
        --primary-color: var(--mdc-theme-on-primary);
        --dark-primary-color: var(--mdc-theme-primary);
        --text-primary-color: var(--mdc-theme-on-primary);

        --light-primary-color: #f5f5f5;

        --accent-color: #ff4081;
        --primary-text-color: #ffffff;
        --secondary-text-color: #ffffff;
        --disabled-text-color: black;
        --divider-color: #e0e0e0;

        /* Polymer Elements */
        --app-drawer-scrim-background: rgba(0, 0, 0, 0.8);
/*
        --paper-checkbox-checked-color: var(--default-primary-color);
        --paper-checkbox-checked-ink-color: var(--default-primary-color);
        --paper-checkbox-unchecked-color: var(--dark-primary-color);
        --paper-checkbox-unchecked-ink-color: var(--dark-primary-color);
        --paper-checkbox-label-color: var(--text-primary-color);
        --paper-fab-background: var(--default-primary-color);
        --paper-fab-disabled-background: #4e5151;
        --paper-fab-disabled-text: var(--disabled-text-color);
        --paper-icon-button-disabled-text: #4e5151;
        --paper-input-container-color: #888;
        --paper-input-container-focus-color: var(--focus-color);
        --paper-input-container-invalid-color: red;
        --paper-input-container-input-color: #888;
        --paper-menu-background-color: #2c2f2f;
        --paper-menu-color: var(--text-primary-color);
        --paper-menu-disabled-color: #4e5151;
        --paper-progress-active-color: var(--default-primary-color);
        --paper-progress-secondary-color: #4db6ac;
        --paper-radio-button-checked-color: white;
        --paper-radio-button-checked-ink-color: #f5fbfb;
        --paper-radio-button-unchecked-color: var(--text-primary-color);
        --paper-radio-button-unchecked-ink-color: var(--text-primary-color);
        --paper-radio-button-label-color: var(--text-primary-color);
        --paper-slider-knob-color: var(--default-primary-color);
        --paper-slider-active-color: var(--default-primary-color);
        --paper-slider-pin-color: var(--default-primary-color);
        --paper-spinner-layer-1-color: var(--default-primary-color);
        --paper-spinner-layer-2-color: var(--default-primary-color);
        --paper-spinner-layer-3-color: var(--default-primary-color);
        --paper-spinner-layer-4-color: var(--default-primary-color);
        --paper-tabs-selection-bar-color: var(--default-primary-color);
        --paper-tab-ink: var(--default-primary-color);
        --paper-toggle-button-checked-bar-color: var(--dark-primary-color);
        --paper-toggle-button-checked-button-color: white;
        --paper-toggle-button-checked-ink-color: white;
        --paper-toggle-button-unchecked-bar-color: var(--text-primary-color);
        --paper-toggle-button-unchecked-button-color: var(--dark-primary-color);
        --paper-toggle-button-unchecked-ink-color: var(--dark-primary-color);
        --paper-toolbar-background: var(--dark-primary-color);
        --paper-toolbar-color: #bdced7;
*/

        color: #fff;
    }
</style>
`

redpajama_set_name: RedPajamaGithub


text:
/*
 * Message.cpp
 *
 *  Created on: May 18, 2017
 *      Author: kurt
 */

#include <cassert>
#include <cstdint>
#include <cstdlib>
#include <ctime>
#include <cstring>
#include <stdexcept>
#include <iostream>
#include <iomanip>
#include <boost/endian/conversion.hpp>
#include <boost/endian/buffers.hpp>

#include "Message.h"

namespace kcmsg {

/*
 *                            HEADER FORMAT
 *                            =============
 *
 *  | 00 01 02 03 | 04 05 | 06 07 08 09 | 0A 0B | 0C 0D | 0E 0F |
 *  |   src_id    |src_org|   tgt_id    |tgt_org| trn_id|trn_app|
 *
 *  | 10 11 | 12 13 14 15 | 16 17 | 18 19 1A 1B 1C 1D 1E 1F ....
 *  |trn_org|     ttl     | flags |msg_len|  user data ....
 *
 */
const size_t MESSAGE_LENGTH_OFFSET = 0x18;

const size_t HEADER_SOURCE_IDENT_OFFSET = 0x00;
const size_t HEADER_SOURCE_ORGANIZATION_OFFSET = 0x04;
const size_t HEADER_TARGET_IDENT_OFFSET = 0x06;
const size_t HEADER_TARGET_ORGANIZATION_OFFSET = 0x0A;
const size_t HEADER_TRANSACTION_IDENT_OFFSET = 0x0C;
const size_t HEADER_TRANSACTION_APPLICATION_OFFSET = 0x0E;
const size_t HEADER_TRANSACTION_ORGANIZATION_OFFSET = 0x10;
const size_t HEADER_TTL_OFFSET = 0x12;
const size_t HEADER_FLAGS_OFFSET = 0x16;

/* Supported Data Type Identifiers */
const uint8_t DATA_TYPE = 0x00;
const uint8_t DATA_TYPE_BOOL = 0x01;
const uint8_t DATA_TYPE_BYTE = 0x02;
const uint8_t DATA_TYPE_SHORT = 0x03;
const uint8_t DATA_TYPE_INT = 0x04;
const uint8_t DATA_TYPE_LONG = 0x05;
const uint8_t DATA_TYPE_LONG_LONG = 0x06;
const uint8_t DATA_TYPE_FLOAT = 0x07;
const uint8_t DATA_TYPE_DOUBLE = 0x08;
const uint8_t DATA_TYPE_CHAR = 0x09;
const uint8_t DATA_TYPE_WCHAR = 0x0A;
const uint8_t DATA_TYPE_STRING_1 = 0x0B;
const uint8_t DATA_TYPE_STRING_2 = 0x0C;
const uint8_t DATA_TYPE_WSTRING_1 = 0x0D;
const uint8_t DATA_TYPE_WSTRING_2 = 0x0E;
const uint8_t DATA_TYPE_TIME = 0x0F;
const uint8_t DATA_TYPE_DURATION = 0x10;
const uint8_t DATA_TYPE_BOOL_ARRAY = 0x11;
const uint8_t DATA_TYPE_BYTE_ARRAY = 0x12;
const uint8_t DATA_TYPE_SHORT_ARRAY = 0x13;
const uint8_t DATA_TYPE_INT_ARRAY = 0x14;
const uint8_t DATA_TYPE_LONG_ARRAY = 0x15;
const uint8_t DATA_TYPE_LONG_LONG_ARRAY = 0x16;
const uint8_t DATA_TYPE_FLOAT_ARRAY = 0x17;
const uint8_t DATA_TYPE_DOUBLE_ARRAY = 0x18;
const uint8_t DATA_TYPE_STRING_ARRAY = 0x19;
const uint8_t DATA_TYPE_WSTRING_ARRAY = 0x1A;
const uint8_t DATA_TYPE_TIME_ARRAY = 0x1B;
const uint8_t DATA_TYPE_DURRATION_ARRAY = 0x1C;

/* Private Methods */

void Message::readHeader(void)
{
	boost::endian::little_uint32_buf_t src_id;
	boost::endian::little_uint16_buf_t src_org;
	boost::endian::little_uint32_buf_t tgt_id;
	boost::endian::little_uint16_buf_t tgt_org;
	boost::endian::little_uint16_buf_t trans_id;
	boost::endian::little_uint16_buf_t trans_app;
	boost::endian::little_uint16_buf_t trans_org;
	boost::endian::little_uint32_buf_t ttl;
	boost::endian::little_uint16_buf_t flags;

	memcpy(&src_id, &data[HEADER_SOURCE_IDENT_OFFSET], sizeof(src_id));
	memcpy(&src_org, &data[HEADER_SOURCE_ORGANIZATION_OFFSET], sizeof(src_org));
	memcpy(&tgt_id, &data[HEADER_TARGET_IDENT_OFFSET], sizeof(tgt_id));
	memcpy(&tgt_org, &data[HEADER_TARGET_ORGANIZATION_OFFSET], sizeof(tgt_org));
	memcpy(&trans_id, &data[HEADER_TRANSACTION_IDENT_OFFSET], sizeof(trans_id));
	memcpy(&trans_app, &data[HEADER_TRANSACTION_APPLICATION_OFFSET], sizeof(trans_app));
	memcpy(&trans_org, &data[HEADER_TRANSACTION_ORGANIZATION_OFFSET], sizeof(trans_org));
	memcpy(&ttl, &data[HEADER_TTL_OFFSET], sizeof(ttl));
	memcpy(&flags, &data[HEADER_FLAGS_OFFSET], sizeof(flags));

	hdr.source_ident = src_id.value();
	hdr.source_organization = src_org.value();
	hdr.target_ident = tgt_id.value();
	hdr.target_organization = tgt_org.value();
	hdr.transaction_ident = trans_id.value();
	hdr.transaction_application = trans_app.value();
	hdr.transaction_organization = trans_org.value();
	hdr.ttl = ttl.value();
	hdr.flags = flags.value();
}

void Message::writeHeader(void)
{

	boost::endian::little_uint32_buf_t src_id;
	boost::endian::little_uint16_buf_t src_org;
	boost::endian::little_uint32_buf_t tgt_id;
	boost::endian::little_uint16_buf_t tgt_org;
	boost::endian::little_uint16_buf_t trans_id;
	boost::endian::little_uint16_buf_t trans_app;
	boost::endian::little_uint16_buf_t trans_org;
	boost::endian::little_uint32_buf_t ttl;
	boost::endian::little_uint16_buf_t flags;

	src_id = hdr.source_ident;
	src_org = hdr.source_organization;
	tgt_id = hdr.target_ident;
	tgt_org = hdr.target_organization;
	trans_id = hdr.transaction_ident;
	trans_app = hdr.transaction_application;
	trans_org = hdr.transaction_organization;
	ttl = hdr.ttl;
	flags = hdr.flags;

	memcpy(&data[HEADER_SOURCE_IDENT_OFFSET], &src_id, sizeof(src_id));
	memcpy(&data[HEADER_SOURCE_ORGANIZATION_OFFSET], &src_org, sizeof(src_org));
	memcpy(&data[HEADER_TARGET_IDENT_OFFSET], &tgt_id, sizeof(tgt_id));
	memcpy(&data[HEADER_TARGET_ORGANIZATION_OFFSET], &tgt_org, sizeof(tgt_org));
	memcpy(&data[HEADER_TRANSACTION_IDENT_OFFSET], &trans_id, sizeof(trans_id));
	memcpy(&data[HEADER_TRANSACTION_APPLICATION_OFFSET], &trans_app, sizeof(trans_app));
	memcpy(&data[HEADER_TRANSACTION_ORGANIZATION_OFFSET], &trans_org, sizeof(trans_org));
	memcpy(&data[HEADER_TTL_OFFSET], &ttl, sizeof(ttl));
	memcpy(&data[HEADER_FLAGS_OFFSET], &flags, sizeof(flags));
}

void Message::readMessageLength(void)
{
	boost::endian::little_uint16_buf_t msg_len;

	memcpy(&msg_len, &data[MESSAGE_LENGTH_OFFSET], sizeof(msg_len));
	data_length = msg_len.value();
}

void Message::updateDataLength(std::size_t delta)
{
	boost::endian::little_uint16_buf_t ndl;
	data_length += delta;
	ndl = data_length;
	memcpy(&data[MESSAGE_LENGTH_OFFSET], &ndl, sizeof(ndl));
}

/* Public Methods */

Message::Message()
{
	int maxdata = MAX_MSG_DATA;
	data = (char *) malloc(maxdata);
	assert(data);
	boost::endian::little_uint16_buf_t ndl;

	// zero out the message space
	memset(data, 0, maxdata);

	// set user data in message to end of message header
	data_length = offset = (std::size_t) MESSAGE_LENGTH_OFFSET + 2;

	// store the current length of the message, header plus a two byte length field
	// into the data.  This forces message size max to not be greater than 64K
	ndl = (boost::endian::little_uint16_buf_t) data_length;
	memcpy(&data[MESSAGE_LENGTH_OFFSET], &ndl, sizeof(ndl));
}

Message::~Message()
{
	if ( data )
		free( data );
}

void Message::setSourceIdentifier(uint32_t id)
{
	hdr.source_ident = id;
}

uint32_t Message::getSourceIdentifier(void)
{
	return ( hdr.source_ident );
}

void Message::setSourceOrganization(uint16_t id)
{
	hdr.source_organization = id;
}

uint16_t Message::getSourceOrganization(void)
{
	return ( hdr.source_organization );
}

void Message::setTargetIdentifier(uint32_t id)
{
	hdr.target_ident = id;
}

uint32_t Message::getTargetIdentifier(void)
{
	return ( hdr.target_ident );
}

void Message::setTargetOrganization(uint16_t id)
{
	hdr.target_organization = id;
}

uint16_t Message::getTargetOrganization(void)
{
	return ( hdr.target_organization );
}

void Message::setTransactionIdentifier(uint16_t id)
{
	hdr.transaction_ident = id;
}

uint16_t Message::getTransactionIdentifier(void)
{
	return ( hdr.transaction_ident );
}

void Message::setTransactionApplication(uint16_t id)
{
	hdr.transaction_application = id;
}

uint16_t Message::getTransactionApplication(void)
{
	return ( hdr.transaction_application );
}

void Message::setTransactionOrganization(uint16_t id)
{
	hdr.transaction_organization = id;
}

uint16_t Message::getTransactionOrganization(void)
{
	return ( hdr.transaction_organization );
}

void Message::setTTL(uint32_t val)
{
	hdr.ttl = val;
}

uint32_t Message::getTTL(void)
{
	return ( hdr.ttl );
}

void Message::setOnceAndOnlyOnce(bool val)
{
	if ( val )
		hdr.flags = hdr.flags | MSG_FLAG_ONCE_AND_ONLY_ONCE;
	else
		hdr.flags = hdr.flags & ~MSG_FLAG_ONCE_AND_ONLY_ONCE;
}

bool Message::isOnceAndOnlyOnce(void)
{
	return (hdr.flags & MSG_FLAG_ONCE_AND_ONLY_ONCE) > 0 ? true : false;
}

void Message::setQuickDeath(bool val)
{
	if ( val )
		hdr.flags = hdr.flags | MSG_FLAG_QUICK_DEATH;
	else
		hdr.flags = hdr.flags & ~MSG_FLAG_QUICK_DEATH;
}

bool Message::isQuickDeath(void)
{
	return (hdr.flags & MSG_FLAG_QUICK_DEATH) > 0 ? true : false;
}

void Message::setMessageFragment(bool val)
{
	if ( val )
		hdr.flags = hdr.flags | MSG_FLAG_FRAGMENT;
	else
		hdr.flags = hdr.flags & ~MSG_FLAG_FRAGMENT;
}

bool Message::isMessageFragment(void)
{
	return (hdr.flags & MSG_FLAG_FRAGMENT) > 0 ? true : false;
}

size_t Message::getMessageLength(void)
{
	return ( data_length );
}

void Message::debugMessageSerialize(std::string fo)
{
	FILE *fd;
	if ( ( fd = fopen(fo.c_str(), "wb") ) != nullptr)
	{
		fwrite(&data, data_length, 1, fd);
		fclose(fd);
	}
}

uint8_t Message::getDataType(void)
{
	//  uint8_t don't worry about endianess
	uint8_t val;
	memcpy(&val, &data[offset], sizeof(DATA_TYPE));
	return val;
}

void Message::debugMessagePrint(void)
{
	int dt;
	std::string s;

	std::cout << "Debug message printout" << std::endl;
	std::cout << "======================" << std::endl;
	std::cout << "<message>" << std::endl;
	std::cout << "    <header>" << std::endl;
	std::cout << "        <source_identifier>" << getSourceIdentifier() << "</source_identifier>" << std::endl;
	std::cout << "        <source_organization>" << getSourceOrganization() << "</source_organization>" << std::endl;
	std::cout << "        <target_identifier>" << getTargetIdentifier() << "</target_identifier>" << std::endl;
	std::cout << "        <target_organization>" << getTargetOrganization() << "</target_organization>" << std::endl;
	std::cout << "        <transaction_identifier>" << getTransactionIdentifier() << "</transaction_identifier>" << std::endl;
	std::cout << "        <transaction_application>" << getTransactionApplication() << "</transaction_application>" << std::endl;
	std::cout << "        <transaction_organization>" << getTransactionOrganization() << "</transaction_organization>" << std::endl;
	std::cout << "        <ttl>" << getTTL() << "</ttl>" << std::endl;
	std::cout << "        <is_once>" << ((isOnceAndOnlyOnce())?"true":"false") << "</is_once>" << std::endl;
	std::cout << "        <is_quick_death>" << ((isQuickDeath())?"true":"false") << "</is_quick_death>" << std::endl;
	std::cout << "        <is_fragment>" << ((isMessageFragment())?"true":"false") << "</is_fragment>" << std::endl;
	std::cout << "    </header>" << std::endl;
	std::cout << "    <data>" << std::endl;

	while ( offset < data_length)
	{
		dt = (int) getDataType();
		switch ( dt )
		{
		case DATA_TYPE_BOOL :
			std::cout << "        <bool>" << std::boolalpha << getBool() << "</bool>" << std::endl;
			break;
		case DATA_TYPE_BYTE :
			std::cout << "        <byte>" << std::hex << getByte() << "</byte>" << std::endl;
			break;
		case DATA_TYPE_SHORT :
			std::cout << "        <short>" << getShort() << "</short>" << std::endl;
			break;
		case DATA_TYPE_INT :
			std::cout << "        <int>" << getInt() << "</int>" << std::endl;
			break;
		case DATA_TYPE_LONG :
			std::cout << "        <long>" << getLong() << "</long>" << std::endl;
			break;
		case DATA_TYPE_LONG_LONG :
			std::cout << "        <long_long>" << getLongLong() << "</long_long>" << std::endl;
			break;
		case DATA_TYPE_FLOAT :
			std::cout << "        <float>" << std::fixed << std::setprecision(3) << getFloat() << "</float>" << std::endl;
			break;
		case DATA_TYPE_DOUBLE :
			std::cout << "        <double>" << getDouble() << "</double>" << std::endl;
			break;
		case DATA_TYPE_CHAR :
			std::cout << "        <char>" << getChar() << "</char>" << std::endl;
			break;
		case DATA_TYPE_WCHAR :
			std::cout << "        <wchar>" << getWChar() << "</wchar>" << std::endl;
			break;
		case DATA_TYPE_STRING_1 :
		case DATA_TYPE_STRING_2 :
			std::cout << "        <string>" << getString() << "</string>" << std::endl;
			break;
		case DATA_TYPE_WSTRING_1 :
		case DATA_TYPE_WSTRING_2 :
			std::wcout << "        <wstring>" << getWString() << "</wstring>" << std::endl;
			break;
		case DATA_TYPE_TIME :
			struct tm *time_info;
			time_t t;
			t = getTime();
			time_info = gmtime(&t);
			std::cout << "        <time>" << std::endl;
			std::cout << "            <seconds>" << time_info->tm_sec << "</seconds>" << std::endl;
			std::cout << "            <minutes>" << time_info->tm_min << "</minutes>" << std::endl;
			std::cout << "            <hours>" << time_info->tm_hour << "</hours>" << std::endl;
			std::cout << "            <day_of_month>" << time_info->tm_mday << "</day_of_month>" << std::endl;
			std::cout << "            <month>" << time_info->tm_mon << "</month>" << std::endl;
			std::cout << "            <day_of_week>" << time_info->tm_wday << "</day_of_week>" << std::endl;
			std::cout << "            <day_of_year>" << time_info->tm_yday << "</day_of_year>" << std::endl;
			std::cout << "            <year>" << time_info->tm_year << "</year>" << std::endl;
			std::cout << "            <time_zone>" << time_info->tm_zone << "</time_zone>" << std::endl;
			std::cout << "            <is_dst>" << ((time_info->tm_isdst) ? "true" : "false") << "</is_dst>" << std::endl;
			std::cout << "        </time>" << std::endl;
			break;
		case DATA_TYPE_DURATION :
			std::cout << "        <duration>" << getDuration() << "</duration>" << std::endl;
			break;
		case DATA_TYPE_BOOL_ARRAY :
			break;
		case DATA_TYPE_BYTE_ARRAY :
			break;
		case DATA_TYPE_SHORT_ARRAY :
			break;
		case DATA_TYPE_INT_ARRAY :
			break;
		case DATA_TYPE_LONG_ARRAY :
			break;
		case DATA_TYPE_LONG_LONG_ARRAY :
			break;
		case DATA_TYPE_FLOAT_ARRAY :
			break;
		case DATA_TYPE_DOUBLE_ARRAY :
			break;
		case DATA_TYPE_STRING_ARRAY :
			break;
		case DATA_TYPE_WSTRING_ARRAY :
			break;
		case DATA_TYPE_TIME_ARRAY :
			break;
		case DATA_TYPE_DURRATION_ARRAY :
			break;
		default :
			throw std::domain_error( "Unknown Data Type;" );
		}
	}

	std::cout << "    </data>" << std::endl;
	std::cout << "</message>" << std::endl;
}

/* Protected Methods */

void Message::putBool(bool val)
{
	if ( data_length + sizeof(DATA_TYPE) + sizeof(uint8_t) <= MAX_MSG_DATA )
	{
		memcpy( &data[data_length], &DATA_TYPE_BOOL, sizeof(DATA_TYPE));
		updateDataLength( sizeof( DATA_TYPE ) );

		uint8_t v = ( val ) ? 1 : 0;
		memcpy( &data[data_length], &v, sizeof(v) );
		updateDataLength( sizeof( v ) );
	}
	else
	{
		throw std::domain_error( "exceeded maximum message size" );
	}
}

void Message::putByte(int8_t val)
{
	if ( data_length + sizeof(DATA_TYPE) + sizeof(val) <= MAX_MSG_DATA )
	{
		memcpy( &data[data_length], &DATA_TYPE_BYTE, sizeof(DATA_TYPE));
		updateDataLength( sizeof( DATA_TYPE ) );

		memcpy( &data[data_length], &val, sizeof(val) );
		updateDataLength( sizeof( val ) );
	}
	else
	{
		throw std::domain_error( "exceeded maximum message size" );
	}
}

void Message::putShort(int16_t val)
{
	boost::endian::little_int16_buf_t nval;

	if ( data_length + sizeof(DATA_TYPE) + sizeof(val) <= MAX_MSG_DATA )
	{
		memcpy( &data[data_length], &DATA_TYPE_SHORT, sizeof(DATA_TYPE));
		updateDataLength( sizeof( DATA_TYPE ) );

		nval = val;
		memcpy( &data[data_length], &nval, sizeof(nval) );
		updateDataLength( sizeof( nval ) );
	}
	else
	{
		throw std::domain_error( "exceeded maximum message size" );
	}
}

void Message::putInt(int32_t val)
{
	boost::endian::little_int32_buf_t nval;
	if ( data_length + sizeof(DATA_TYPE) + sizeof(val) <= MAX_MSG_DATA )
	{
		memcpy( &data[data_length], &DATA_TYPE_INT, sizeof(DATA_TYPE));
		updateDataLength( sizeof( DATA_TYPE ) );

		nval = val;
		memcpy( &data[data_length], &nval, sizeof(nval) );
		updateDataLength( sizeof( nval ) );
	}
	else
	{
		throw std::domain_error( "exceeded maximum message size" );
	}
}

void Message::putLong(int32_t val)
{
	boost::endian::little_int32_buf_t nval;
	if ( data_length + sizeof(DATA_TYPE) + sizeof(val) <= MAX_MSG_DATA )
	{
		memcpy( &data[data_length], &DATA_TYPE_LONG, sizeof(DATA_TYPE));
		updateDataLength( sizeof( DATA_TYPE ) );

		nval = val;
		memcpy( &data[data_length], &nval, sizeof(nval) );
		updateDataLength( sizeof( nval ) );
	}
	else
	{
		throw std::domain_error( "exceeded maximum message size" );
	}
}

void Message::putLongLong(int64_t val)
{
	boost::endian::little_int64_buf_t nval;
	if ( data_length + sizeof(DATA_TYPE) + sizeof(val) <= MAX_MSG_DATA )
	{
		memcpy( &data[data_length], &DATA_TYPE_LONG_LONG, sizeof(DATA_TYPE));
		updateDataLength( sizeof( DATA_TYPE ) );

		nval = val;
		memcpy( &data[data_length], &nval, sizeof(nval) );
		updateDataLength( sizeof( nval ) );
	}
	else
	{
		throw std::domain_error( "exceeded maximum message size" );
	}
}

void Message::putFloat(float val)
{
	if ( data_length + sizeof(DATA_TYPE) + sizeof(val) <= MAX_MSG_DATA )
	{
		memcpy( &data[data_length], &DATA_TYPE_FLOAT, sizeof(DATA_TYPE));
		updateDataLength( sizeof( DATA_TYPE ) );

		memcpy( &data[data_length], &val, sizeof(val) );
		updateDataLength( sizeof( val ) );
	}
	else
	{
		throw std::domain_error( "exceeded maximum message size" );
	}
}

void Message::putDouble(double val)
{
	if ( data_length + sizeof(DATA_TYPE) + sizeof(val) <= MAX_MSG_DATA )
	{
		memcpy( &data[data_length], &DATA_TYPE_DOUBLE, sizeof(DATA_TYPE));
		updateDataLength( sizeof( DATA_TYPE ) );

		memcpy( &data[data_length], &val, sizeof(val) );
		updateDataLength( sizeof( val ) );
	}
	else
	{
		throw std::domain_error( "exceeded maximum message size" );
	}
}

void Message::putChar(char val)
{
	if ( data_length + sizeof(DATA_TYPE) + sizeof(val) <= MAX_MSG_DATA )
	{
		memcpy( &data[data_length], &DATA_TYPE_CHAR, sizeof(DATA_TYPE));
		updateDataLength( sizeof( DATA_TYPE ) );

		memcpy( &data[data_length], &val, sizeof(val) );
		updateDataLength( sizeof( val ) );
	}
	else
	{
		throw std::domain_error( "exceeded maximum message size" );
	}
}

void Message::putWChar(wchar_t val)
{
	if ( data_length + sizeof(DATA_TYPE) + sizeof(val) <= MAX_MSG_DATA )
	{
		memcpy( &data[data_length], &DATA_TYPE_WCHAR, sizeof(DATA_TYPE));
		updateDataLength( sizeof( DATA_TYPE ) );

		memcpy( &data[data_length], &val, sizeof(val) );
		updateDataLength( sizeof( val ) );
	}
	else
	{
		throw std::domain_error( "exceeded maximum message size" );
	}
}

void Message::putString(std::string val)
{
	size_t l = val.length();
	uint8_t dt =  l > 255 ? DATA_TYPE_STRING_2 : DATA_TYPE_STRING_1;
	size_t elem_size = (size_t) l * sizeof(char);

	switch ( dt )
	{
	case DATA_TYPE_STRING_1 :
		if ( data_length + sizeof(DATA_TYPE) + sizeof(uint8_t) + elem_size <= MAX_MSG_DATA )
		{
			memcpy( &data[data_length], &dt, sizeof( DATA_TYPE ) );
			updateDataLength( sizeof( DATA_TYPE ) );

			memcpy( &data[data_length], &l, sizeof( uint8_t ) );
			updateDataLength( sizeof( uint8_t ) );

			memcpy( &data[data_length], val.c_str(), elem_size );
			updateDataLength( elem_size );
		}
		else
		{
			throw std::domain_error( "exceeded maximum message size" );
		}
		break;

	case DATA_TYPE_STRING_2 :
		if ( data_length + sizeof(DATA_TYPE) + sizeof(uint16_t) + l * sizeof(char) <= MAX_MSG_DATA )
		{
			boost::endian::little_uint16_buf_t nval;

			memcpy( &data[data_length], &dt, sizeof(DATA_TYPE));
			updateDataLength( sizeof( DATA_TYPE ) );

			nval = (uint16_t) l;
			memcpy( &data[data_length], &nval, sizeof( nval ) );
			updateDataLength( sizeof( nval ) );

			memcpy( &data[data_length], val.c_str(), (size_t)(l * sizeof(char)) );
			updateDataLength( ( l * sizeof( char ) ) );
		}
		else
		{
			throw std::domain_error( "exceeded maximum message size" );
		}
		break;
	default:
		throw std::domain_error( "exceeded maximum message size" );
	}
}

void Message::putWString(std::wstring val)
{
	size_t l = (size_t) val.length();
	uint8_t dt =  l > 255 ? DATA_TYPE_WSTRING_2 : DATA_TYPE_WSTRING_1;

	switch ( dt )
	{
	case DATA_TYPE_WSTRING_1 :
		if ( data_length + sizeof(DATA_TYPE) + sizeof(uint8_t) + l * sizeof(wchar_t) <= MAX_MSG_DATA )
		{
			memcpy( &data[data_length], &dt, sizeof(DATA_TYPE));
			updateDataLength( sizeof( DATA_TYPE ) );

			uint8_t l1 = ( uint8_t ) l;
			memcpy( &data[data_length], &l1, sizeof( l1 ) );
			updateDataLength( sizeof( l1 ) );

			memcpy( &data[data_length], val.c_str(), (size_t)(l * sizeof(wchar_t)) );
			updateDataLength( ( l * sizeof(wchar_t) ) );
		}
		else
		{
			throw std::domain_error( "exceeded maximum message size" );
		}
		break;

	case DATA_TYPE_WSTRING_2 :
		if ( data_length + sizeof(DATA_TYPE) + sizeof(uint16_t) + l * sizeof(wchar_t) <= MAX_MSG_DATA )
		{
			boost::endian::little_uint16_buf_t nval;

			memcpy( &data[data_length], &dt, sizeof(DATA_TYPE));
			updateDataLength( sizeof( DATA_TYPE ) );

			nval = (uint16_t) l;
			memcpy( &data[data_length], &nval, sizeof( nval ) );
			updateDataLength( sizeof( nval ) );

			memcpy( &data[data_length], val.c_str(), (size_t)(l * sizeof(wchar_t)) );
			updateDataLength( ( l * sizeof( wchar_t ) ) );

			data_length += (l * sizeof(wchar_t));
		}
		else
		{
			throw std::domain_error( "exceeded maximum message size" );
		}
		break;
	default:
		throw std::domain_error( "exceeded maximum message size" );
	}
}

void Message::putTime(time_t val)
{
	if ( data_length + sizeof(DATA_TYPE) + sizeof(val) <= MAX_MSG_DATA )
	{
		boost::endian::little_uint64_buf_t nval;

		memcpy( &data[data_length], &DATA_TYPE_TIME, sizeof(DATA_TYPE));
		updateDataLength( sizeof( DATA_TYPE ) );

		nval = val;
		memcpy( &data[data_length], &nval, sizeof(nval) );
		updateDataLength( sizeof( nval ) );
	}
	else
	{
		throw std::domain_error( "exceeded maximum message size" );
	}
}

void Message::putDuration(uint32_t val)
{
	if ( data_length + sizeof(DATA_TYPE) + sizeof(val) <= MAX_MSG_DATA )
	{
		boost::endian::little_uint32_buf_t nval;

		memcpy( &data[data_length], &DATA_TYPE_DURATION, sizeof(DATA_TYPE));
		updateDataLength( sizeof( DATA_TYPE ) );

		nval = val;
		memcpy( &data[data_length], &nval, sizeof(nval) );
		updateDataLength( sizeof( nval ) );
	}
	else
	{
		throw std::domain_error( "exceeded maximum message size" );
	}
}

void Message::putBoolArray(bool *arr)
{

}

void Message::putByteArray(int8_t *arr)
{

}

void Message::putShortArray(int16_t *arr)
{

}

void Message::putIntArray(int32_t *arr)
{

}

void Message::putLongArray(int32_t *arr)
{

}

void Message::putLongLongArray(int64_t *arr)
{

}

void Message::putFloatArray(int32_t *arr)
{

}

void Message::putDoubleArray(int64_t *arr)
{

}

void Message::putStringArray(std::string *arr)
{

}

void Message::putTimeArray(time_t *arr)
{

}

void Message::putDurationArray(uint32_t *arr)
{

}

bool Message::getBool(void)
{
	int8_t data_type = 0;
	int8_t val = 0;
	bool ret_val;

	memcpy( &data_type, &data[offset], sizeof( DATA_TYPE ));
	offset += sizeof( DATA_TYPE );
	assert ( data_type == DATA_TYPE_BOOL );

	memcpy( &val, &data[offset], sizeof( val ) );
	offset += sizeof( val );
	ret_val = (bool) ( val != 0 ) ? true : false;

	return ret_val;
}

int8_t Message::getByte(void)
{
	int8_t data_type = 0;
	int8_t val = 0;

	memcpy( &data_type, &data[offset], sizeof( DATA_TYPE ));
	offset += sizeof( DATA_TYPE );
	assert ( data_type == DATA_TYPE_BYTE );

	memcpy( &val, &data[offset], sizeof( val ) );
	offset += sizeof( val );

	return val;
}

int16_t Message::getShort(void)
{
	int8_t data_type = 0;
	boost::endian::little_int16_buf_t nval;

	memcpy( &data_type, &data[offset], sizeof( DATA_TYPE ));
	offset += sizeof( DATA_TYPE );
	assert ( data_type == DATA_TYPE_SHORT );

	memcpy( &nval, &data[offset], sizeof( nval ) );
	offset += sizeof( nval );

	return ( nval.value() );
}

int32_t Message::getInt(void)
{
	int8_t data_type = 0;
	boost::endian::little_int32_buf_t nval;

	memcpy( &data_type, &data[offset], sizeof( DATA_TYPE ));
	offset += sizeof( DATA_TYPE );
	assert ( data_type == DATA_TYPE_INT );

	memcpy( &nval, &data[offset], sizeof( nval ) );
	offset += sizeof( nval );

	return ( nval.value() );
}

int32_t Message::getLong(void)
{
	int8_t data_type = 0;
	boost::endian::little_int16_buf_t nval;

	memcpy( &data_type, &data[offset], sizeof( DATA_TYPE ));
	offset += sizeof( DATA_TYPE );
	assert ( data_type == DATA_TYPE_LONG );

	memcpy( &nval, &data[offset], sizeof( nval ) );
	offset += sizeof( nval );

	return ( nval.value() );
}

int64_t Message::getLongLong(void)
{
	int8_t data_type = 0;
	boost::endian::little_int64_buf_t nval;

	memcpy( &data_type, &data[offset], sizeof( DATA_TYPE ));
	offset += sizeof( DATA_TYPE );
	assert ( data_type == DATA_TYPE_LONG_LONG );

	memcpy( &nval, &data[offset], sizeof( nval ) );
	offset += sizeof( nval );

	return ( nval.value() );
}

float Message::getFloat(void)
{
	int8_t data_type = 0;
	float val = 0;

	memcpy( &data_type, &data[offset], sizeof( DATA_TYPE ));
	offset += sizeof( DATA_TYPE );
	assert ( data_type == DATA_TYPE_FLOAT );

	memcpy( &val, &data[offset], sizeof( val ) );
	offset += sizeof( val );

	return val;
}

double Message::getDouble(void)
{
	int8_t data_type = 0;
	double val = 0;

	memcpy( &data_type, &data[offset], sizeof( DATA_TYPE ));
	offset += sizeof( DATA_TYPE );
	assert ( data_type == DATA_TYPE_DOUBLE );

	memcpy( &val, &data[offset], sizeof( val ) );
	offset += sizeof( val );

	return val;
}

char Message::getChar(void)
{
	int8_t data_type = 0;
	char val = '\0';

	memcpy( &data_type, &data[offset], sizeof( DATA_TYPE ));
	offset += sizeof( DATA_TYPE );
	assert ( data_type == DATA_TYPE_CHAR );

	memcpy( &val, &data[offset], sizeof( val ) );
	offset += sizeof( val );

	return val;
}

wchar_t Message::getWChar(void)
{
	int8_t data_type = 0;
	wchar_t val = L'\0';

	memcpy( &data_type, &data[offset], sizeof( DATA_TYPE ));
	offset += sizeof( DATA_TYPE );
	assert ( data_type == DATA_TYPE_WCHAR );

	memcpy( &val, &data[offset], sizeof( val ) );
	offset += sizeof( val );

	return val;
}

std::string Message::getString(void)
{
	int8_t data_type = 0;
	boost::endian::little_int8_buf_t s1len;
	boost::endian::little_int16_buf_t s2len;
	size_t string_len = 0;
	size_t elem_size = 0;
	int sv = 0;
	char *ptr = nullptr;
	std::string val;

	memcpy( &data_type, &data[offset], sizeof( DATA_TYPE ));
	offset += sizeof( DATA_TYPE );
	assert ( (data_type == DATA_TYPE_STRING_1) | (data_type == DATA_TYPE_STRING_2) );

	sv = (int) data_type;
	switch (sv)
	{
	case DATA_TYPE_STRING_1 :
		memcpy( &s1len, &data[offset], sizeof( s1len ));
		offset += sizeof( s1len );
		string_len = (size_t) s1len.value();
		break;
	case DATA_TYPE_STRING_2 :
		memcpy( &s2len, &data[offset], sizeof( s2len ));
		offset += sizeof( s2len );
		string_len = (size_t) s2len.value();
		break;
	default :
		break;
	}

	ptr = (char *) malloc( ((string_len + 1)*sizeof(char)) );
	assert ( ptr != nullptr );
	memset( ptr, 0, ((string_len + 1)*sizeof(char)) );

	elem_size = string_len * sizeof(char);
	memcpy( ptr, &data[offset], elem_size );
	offset += elem_size;

	val.assign(ptr);
	return val;
}

std::wstring Message::getWString(void)
{
	int8_t data_type = 0;
	boost::endian::little_int8_buf_t s1len;
	boost::endian::little_int16_buf_t s2len;

	size_t wstring_len;
	int sv = 0;
	wchar_t *ptr = nullptr;
	std::wstring val;

	memcpy( &data_type, &data[offset], sizeof( DATA_TYPE ));
	offset += sizeof( DATA_TYPE );
	assert ( (data_type == DATA_TYPE_WSTRING_1) | (data_type == DATA_TYPE_WSTRING_2) );

	sv = (int) data_type;
	switch (sv)
	{
	case DATA_TYPE_WSTRING_1 :
		memcpy( &s1len, &data[offset], sizeof( s1len ));

		offset += sizeof( s1len );
		wstring_len = (size_t) s1len.value();
		break;
	case DATA_TYPE_WSTRING_2 :
		memcpy( &s2len, &data[offset], sizeof( s2len ));

		offset += sizeof( s2len );
		wstring_len = (size_t) s2len.value();
		break;
	default :
		wstring_len = 0;
		break;
	}

	ptr = (wchar_t *) malloc( ((wstring_len + 1)*sizeof(wchar_t)) );
	memset( ptr, 0, ((wstring_len + 1)*sizeof(char)) );
	assert( ptr != nullptr );

	memcpy( ptr, &data[offset], (size_t)(wstring_len * sizeof(wchar_t)) );
	offset += (wstring_len * sizeof(wchar_t));

	val.assign( ptr );
	return val;
}

time_t Message::getTime(void)
{
	int8_t data_type = 0;
	boost::endian::little_int64_buf_t nval;
	time_t val = 0;

	memcpy( &data_type, &data[offset], sizeof( DATA_TYPE ));
	offset += sizeof( DATA_TYPE );
	assert ( data_type == DATA_TYPE_TIME );

	memcpy( &nval, &data[offset], sizeof( nval ) );
	offset += sizeof( nval );

	val = (time_t) nval.value();
	return val;
}

uint32_t Message::getDuration(void)
{
	int8_t data_type = 0;
	boost::endian::little_int32_buf_t nval;

	memcpy( &data_type, &data[offset], sizeof( DATA_TYPE ));
	offset += sizeof( DATA_TYPE );
	assert ( data_type == DATA_TYPE_DURATION );

	memcpy( &nval, &data[offset], sizeof( nval ) );
	offset += sizeof( nval );

	return ( nval.value() );
}

} /* namespace kcmsg */


text:
"""Integration tests for custom attribute definitions model."""

from sqlalchemy.exc import IntegrityError

from ggrc import db
from ggrc.app import app
from ggrc.models import all_models as models
from integration.ggrc import TestCase
from integration.ggrc.models import factories

CAD = factories.CustomAttributeDefinitionFactory

class TestCAD(TestCase):
  """Tests for basic functionality of cad model."""

  def test_setting_reserved_words(self):
    """Test setting any of the existing attribute names."""

    with self.assertRaises(ValueError):
      cad = models.CustomAttributeDefinition()
      cad.definition_type = "section"
      cad.title = "title"

    with self.assertRaises(ValueError):
      cad = models.CustomAttributeDefinition()
      cad.title = "title"
      cad.definition_type = "section"

    with self.assertRaises(ValueError):
      models.CustomAttributeDefinition(
          title="title",
          definition_type="Assessment",
      )

    with self.assertRaises(ValueError):
      models.CustomAttributeDefinition(
          title="TITLE",
          definition_type="program",
      )

    cad = models.CustomAttributeDefinition(
        title="non existing title",
        definition_type="program",
    )
    self.assertEqual(cad.title, "non existing title")

  def test_setting_global_cad_names(self):
    """Test duplicates with global attribute names."""

    db.session.add(models.CustomAttributeDefinition(
        title="global cad",
        definition_type="section",
        attribute_type="Text",
    ))
    db.session.add(models.CustomAttributeDefinition(
        title="non existing title",
        definition_type="section",
        definition_id=1,
        attribute_type="Text",
    ))
    db.session.add(models.CustomAttributeDefinition(
        title="non existing title",
        definition_type="section",
        definition_id=2,
        attribute_type="Text",
    ))
    db.session.add(models.AccessControlRole(
        name="a name for a role",
        object_type="Section",
    ))
    db.session.commit()

    with self.assertRaises(IntegrityError):
      db.session.add(models.CustomAttributeDefinition(
          title="non existing title",
          definition_type="section",
          definition_id=2,
          attribute_type="Text",
      ))
      db.session.commit()
    db.session.rollback()

    with self.assertRaises(ValueError):
      db.session.add(models.CustomAttributeDefinition(
          title="global cad",
          definition_type="section",
          definition_id=2,
          attribute_type="Text",
      ))
      db.session.commit()

    with self.assertRaises(ValueError):
      db.session.add(models.CustomAttributeDefinition(
          title="a name for a role",
          definition_type="section",
          definition_id=2,
          attribute_type="Text",
      ))
      db.session.commit()

  def test_different_models(self):
    """Test unique names over on different models."""
    db.session.add(models.CustomAttributeDefinition(
        title="my custom attribute title",
        definition_type="section",
        attribute_type="Text",
    ))
    db.session.commit()
    db.session.add(models.AccessControlRole(
        name="my custom attribute title",
        object_type="Contract",
    ))
    db.session.commit()
    cad = models.CustomAttributeDefinition(
        title="my custom attribute title",
        definition_type="program",
        attribute_type="Text",
    )
    self.assertEqual(cad.title, "my custom attribute title")

  def test_setting_same_name(self):
    """Setting an already existing title should pass the validator."""

    db.session.add(models.CustomAttributeDefinition(
        title="my custom attribute title",
        definition_type="section",
        attribute_type="Text",
    ))
    db.session.commit()
    cad = models.CustomAttributeDefinition.query.first()
    cad.title = "my custom attribute title"
    cad.attribute_type = "Rich Text"
    db.session.commit()
    cad = models.CustomAttributeDefinition.query.first()
    self.assertEqual(cad.title, "my custom attribute title")
    self.assertEqual(cad.attribute_type, "Rich Text")

  def test_assessment(self):
    """Test collisions between assessment template and assessments.

    Assessment template is not allowed to have local CAD that match Assessment
    global CAD, because that will cause collisions when assessments are
    generated when using the mentioned template.
    """
    with app.app_context():
      CAD(
          title="assessment CAD",
          definition_type="assessment_template",
          definition_id=1,
      )

    with app.app_context():
      # check that local assessment local CAD can match AT CAD.
      CAD(
          title="assessment CAD",
          definition_type="assessment",
          definition_id=1,
      )
    with app.app_context():
      with self.assertRaises(ValueError):
        CAD(
            title="assessment CAD",
            definition_type="assessment",
        )

  def test_assessment_template(self):
    """Test collisions between assessment template and assessments.

    Assessment template is not allowed to have local CAD that match Assessment
    global CAD, because that will cause collisions when assessments are
    generated when using the mentioned template.
    """
    with app.app_context():
      CAD(
          title="global title",
          definition_type="assessment",
      )
      CAD(
          title="local title",
          definition_type="assessment",
          definition_id=1,
      )
    with app.app_context():
      # check that assessment template CAD can match an assessment local CAD.
      CAD(
          title="local title",
          definition_type="assessment_template",
          definition_id=1,
      )
    with app.app_context():
      with self.assertRaises(ValueError):
        CAD(
            title="global title",
            definition_type="assessment_template",
            definition_id=1,
        )

  def test_role_attribute(self):
    """Test access control role collisions with attributes & CADs"""
    db.session.add(models.CustomAttributeDefinition(
        title="my custom attribute title",
        definition_type="section",
        attribute_type="Text",
    ))
    db.session.commit()

    with self.assertRaises(ValueError):
      db.session.add(models.AccessControlRole(
          name="title",
          object_type="Market",
      ))
      db.session.commit()

    with self.assertRaises(ValueError):
      db.session.add(models.AccessControlRole(
          name="my custom attribute title",
          object_type="Section",
      ))
      db.session.commit()


text:
CFLAGS=-g -O2 -Wall -Wextra -Isrc -rdynamic -DNDEBUG $(OPTFLAGS)
LDFLAGS=$(OPTLIBS)
PREFIX?=/usr/local

SOURCES=$(wildcard src/**/*.c src/*.c)
OBJECTS=$(patsubst %.c,%.o,$(SOURCES))

TEST_SRC=$(wildcard tests/*_tests.c)
TESTS=$(patsubst %.c,%,$(TEST_SRC))

TARGET=build/liblcthw.a

# The Target Build
all: $(TARGET) tests

dev: CFLAGS=-g -Wall -Isrc -Wall -Wextra $(OPTFLAGS)
dev: all

$(TARGET): CFLAGS += -fPIC
$(TARGET): build $(OBJECTS)
	ar rcs $@ $(OBJECTS)
	ranlib $@

build:
	@mkdir -p build
	@mkdir -p bin

# The Unit Tests
.PHONY: tests
tests: LDLIBS += $(TARGET)
tests: $(TESTS)
	sh ./tests/runtests.sh

valgrind:
	VALGRIND="valgrind --log-file=/tmp/valgrind-%p.log" $(MAKE)

# The Cleaner
clean:
	rm -rf build $(OBJECTS) $(TESTS)
	rm -f tests/tests.log
	find . -name "*.gc*" -exec rm {} \;
	rm -rf `find . -name "*.dSYM" -print`

# The Install
install: all
	install -d $(DESTDIR)/$(PREFIX)/lib/
	install $(TARGET) $(DESTDIR)/$(PREFIX)/lib/

# The Checker
check:
	@echo Files with potentially dangerous functions.
	@egrep '[^_.>a-zA-Z0-9](str(n?cpy|n?cat|xfrm|n?dup|str|pbrk|tok|_)|stpn?cpy|a?sn?printf|byte_)' $(SOURCES) || true


text:
package restaurant.restaurant_duvoisin;

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

/**
 * Restaurant Menu
 */
public class Menu {
	// Array of Items
	public Map<String, Double> menuItems = new HashMap<String, Double>();

	public Menu() {
		menuItems.put("salad", 5.99);
		menuItems.put("pizza", 8.99);
		menuItems.put("chicken", 10.99);
		menuItems.put("steak", 15.99);
	}

	public void removeMenuOption(String option) { menuItems.remove(option); }
}


text:
<?php

    // Cache plugin
    add_action( "plugin_loaded", "cache", "check" );

    class CachePlugin extends Plugin{

        static protected $cache_directory,
                         $cache_filepath;

        // check if there is a cache file
        static function check(){

            $request_uri = $_SERVER["REQUEST_URI"];
            self::$cache_directory = str_replace( '//', '/', CACHE_DIR . "html/" . $request_uri . "/" );

            if( $request_uri == "" )
                $request_uri = "index.php";

            self::$cache_filepath = self::$cache_directory . md5( $request_uri ) . ".php";

            if( file_exists( self::$cache_filepath ) ){

                $html = file_get_contents( self::$cache_filepath );

                // - BENCHMARK ------
                list( $timer, $memory ) = self::$context['loader']->get_benchmark();
                $script =   "<script>" .
                            "$('#execution_time').html('$timer');".
                            "$('#memory_used').html('$memory');".
                            "$('#included_files').html('".sizeof(get_included_files())."');".
                            "$('#n_query').html(0);".
                            "</script>";
                $html = preg_replace( "/<\/body>/", "$script</body>", $html );
                echo $html;
                load_actions( "after_draw", array("loader"=>self::$context['loader']) );
                die;
            }
            else{
                add_action( "before_draw", "cache", "save" );
            }

        }

        // save a new cache
        static function save(){

            if (self::$cache_directory && !is_dir(self::$cache_directory))
                mkdir(self::$cache_directory, 0755, $recursive = true);

            file_put_contents(self::$cache_filepath, self::$context['html'], $create_folder = true);

        }

    }

// -- end


text:
package mods.quiddity.redux.json.model;

import com.google.common.collect.ImmutableList;
import mods.quiddity.redux.Redux;
import net.minecraftforge.event.world.BlockEvent;
import net.minecraftforge.event.world.ChunkWatchEvent;
import net.minecraftforge.event.world.ExplosionEvent;
import net.minecraftforge.event.world.WorldEvent;
import net.minecraftforge.fml.common.eventhandler.Event;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.List;

/**
 * JSON Object model to represent Redux event triggers
 *
 * @author winsock on 2/5/15.
 */
@SuppressWarnings("all")
public class Trigger {

    /**
     *
Required

     * The name of the event to trigger on.
     * See: {@link mods.quiddity.redux.json.model.Trigger.TriggerEvent}
     */
    @Nonnull
    protected String trigger;

    /**
     * Trigger only when this block is the target of the event.
     * Defaults to true when this flag is not present.
     */
    @Nullable
    protected boolean on_cause = true;

    /**
     *
Required

     * Commands are an array of commands to execute in sequence.
     * Result of prior commands pushed onto a stack as well.
     * If a command has $(POP) it will pop off the last result on the stack and insert it.
     * If it has $(PEEK) it will peek at the top result and insert the value.
     * The value is not removed from the stack with peek.
     * You can pop/peek multiple times, it will pop from left to right.
     */
    @Nonnull
    protected List<String> commands;

    public TriggerEvent getTriggerEvent() {
        if (trigger == null || trigger.isEmpty()) {
            Redux.instance.getLogger().warn("A block tried to register a trigger that is either empty or null.");
            return null;
        }
        return TriggerEvent.valueOf(trigger);
    }

    public List<String> getCommands() {
        if (commands == null || commands.isEmpty()) {
            Redux.instance.getLogger().warn("A block tried to register a trigger that has no commands.");
            return null;
        }
        return ImmutableList.copyOf(commands);
    }

    public boolean blockHasToBeTheCause() {
        return on_cause;
    }

    public enum TriggerEvent {
        BlockHarvestDropsEvent(BlockEvent.HarvestDropsEvent.class),
        BlockBreakEvent(BlockEvent.BreakEvent.class),
        BlockPlaceEvent(BlockEvent.PlaceEvent.class),
        BlockMultiPlaceEvent(BlockEvent.MultiPlaceEvent.class),
        WorldLoad(WorldEvent.Load.class),
        WorldUnload(WorldEvent.Unload.class),
        WorldPotentialSpawns(WorldEvent.PotentialSpawns.class),
        WorldCreateSpawnPosition(WorldEvent.CreateSpawnPosition.class),
        ExplosionStart(ExplosionEvent.Start.class),
        ExplosionDetonate(ExplosionEvent.Detonate.class),
        ChunkWatch(ChunkWatchEvent.Watch.class),
        ChunkUnWatch(ChunkWatchEvent.UnWatch.class),
        ServerChatEvent(net.minecraftforge.event.ServerChatEvent.class),
        OnTick(Event.class),
        OnEntityCollide(Event.class),
        OnInteract(Event.class),
        OnRestoneStrengthChange(Event.class);

        private Class<? extends Event> forgeEventClass;
        private TriggerEvent(Class<? extends Event> forgeEvent) {
            this.forgeEventClass = forgeEvent;
        }

        public Class<? extends Event> getForgeEventClass() {
            return forgeEventClass;
        }

        public static TriggerEvent getTriggerEventFromForgeEvent(Class<? extends Event> forgeEvent) {
            for (TriggerEvent e: TriggerEvent.values()) {
                if (e.forgeEventClass == forgeEvent) {
                    return e;
                }
            }
            return null;
        }
    }
}


text:
import pygame

class Animation:
    def __init__(self, img, seq):
        #Attributes
        self.img = img
        self.seq = seq

    def __del__(self):
        pass

    def draw(self, screen, dest):
        screen.blit(self.img, dest)


text:
<?php

/**
 * Returns a result set listing primary keys for a table
 *
 * @phpstub
 *
 * @param resource $connection
 * @param string $qualifier
 * @param string $schema
 * @param string $table-name
 *
 * @return resource Returns a statement resource with a result set containing rows describing
 *                  the primary keys for the specified table. The result set is composed of the
 *                  following columns:
 */
function db2_primary_keys($connection, $qualifier, $schema, $table-name)
{
}


text:
import React from 'react'
import { Provider } from 'react-redux'
import { BrowserRouter, Switch, Route, Link } from 'react-router-dom'
import configureStore from '../configure-store'

// pages
import SignupPage from '../components/Authentication/SignupPage'
import LoginPage from '../components/Authentication/LoginPage'

import Header from '../components/Pages/Header'
import ContactsApp from '../components/ContactsApp'
import HomeWelcome from '../components/Pages/HomeWelcome'
import NotFound from '../components/Pages/NotFound'

const routes =
<Provider store={configureStore()}>
  <BrowserRouter>
    <div>
      <Header />
      <Switch>
        <Route exact path="/" component={HomeWelcome} />
        <Route path="/group/:filter" component={ContactsApp} />
        <Route exact path="/login" component={LoginPage}/>
        <Route exact path="/signup" component={SignupPage}/>
        <Route component={NotFound}/>
      </Switch>
    </div>
  </BrowserRouter>
</Provider>

export default routes


text:
NAME = armor-web
IMAGE = labstack/armor-web

build:
	rm -rf public
	hugo
	docker build -t $(IMAGE) .

push: build
	docker push $(IMAGE)

.PHONY: build push


text:
using v8::FunctionTemplate;
using v8::Local;
using v8::External;

Nan::Persistent<FunctionTemplate> SaneHandle::constructor_template;

NAN_MODULE_INIT(SaneHandle::Init) {
    Nan::HandleScope scope;

    // Prepare constructor template.
    Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(New);
    tpl->SetClassName(Nan::New("SaneHandle").ToLocalChecked());
    tpl->InstanceTemplate()->SetInternalFieldCount(1);

    constructor_template.Reset(tpl);
    target->Set(Nan::New("SaneHandle").ToLocalChecked(), tpl->GetFunction());
}

NAN_METHOD(SaneHandle::New) {
    Nan::HandleScope scope;

    if (!info.IsConstructCall()) {
        return Nan::ThrowTypeError("Use the new operator to create new SaneHandle objects");
    }

    if (info.Length() < 1 || !info[0]->IsExternal()) {
        return Nan::ThrowTypeError("SaneHandle object cannot be created directly");
    }

    SaneHandle* handle = new SaneHandle(static_cast<SANE_Handle>(
        External::Cast(*info[0])->Value()));
    handle->Wrap(info.This());
    info.GetReturnValue().Set(info.This());
}

SANE_Handle SaneHandle::getHandle() {
    return _handle;
}


text:
/**
 * SMTI06, M Haidar Hanif, 54411850
 * Part of Employ
 */

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.AbstractButton;
import javax.swing.ButtonGroup;
import javax.swing.ButtonModel;
import javax.swing.event.EventListenerList;

@SuppressWarnings("serial")
public class ButtonGroupListener extends ButtonGroup {

  private ActionListener btnGrpListener = new BtnGrpListener();
  private EventListenerList listenerList = new EventListenerList();

  @Override
  public void add(AbstractButton b) {
    b.addActionListener(btnGrpListener);
    super.add(b);
  }

  public void addActionListener(ActionListener listener) {
    listenerList.add(ActionListener.class, listener);
  }

  public void removeActionListener(ActionListener listener) {
    listenerList.remove(ActionListener.class, listener);
  }

  protected void fireActionListeners() {
    Object[] listeners = listenerList.getListenerList();
    String actionCommand = "";
    ButtonModel model = getSelection();
    if (model != null) {
      actionCommand = model.getActionCommand();
    }
    ActionEvent ae = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, actionCommand);
    for (int i = listeners.length - 2; i >= 0; i -= 2) {
      if (listeners[i] == ActionListener.class) {
        ((ActionListener) listeners[i + 1]).actionPerformed(ae);
      }
    }
  }

  private class BtnGrpListener implements ActionListener {

    public void actionPerformed(ActionEvent ae) {
      fireActionListeners();
    }
  }
}


text:
$(function () {
    var localDate = new Date()
    var noticeData = null;
    var preventPopUps = false;
    var gu = new HabitUtilities();
    var selectedChoiceIndex = -1;

    $("button[name='story_intro_ok']").click(introCloseClick);
    $("button[name='zone_notice_ok']").click(zoneCloseClick);
    $("button[name='zone_choice_back']").click(zoneChoiceGoBackClick);
    $("button[name='zone_choice_ok']").click(zoneChoiceConfirm);
    $("#zone_choice_no_popups_check").click(blockPopupCheckForZoneChoiceClick);

    $("#story_notices").on('hidden.bs.modal', onStoryIntroHide);
    $("#zone_notices").on('hidden.bs.modal', onIntroZoneHide);

    $.ajax({
        url: "main/checkin",
        type: 'get',
        dataType: 'json',
        data: { 'utcElapsedTime': Date.now(), 'utcOffset': localDate.getTimezoneOffset() },
        success: onCheckInSuccess
    });

    function onStoryIntroHide() {
        /*
            this is called when the into message is closed and the user has
            chosen to continue allowing pop-ups.
        */
        if (preventPopUps) {
            return;
        }
        $("#zone_notice_content").html(noticeData['zoneNotice']);
        $('#zone_notices').modal('show');
    }

    function onCheckInSuccess(data) {
        /*
            this should be called whenever the paige loads.
        */
        noticeData = data;
        $("#story_notice_content").html(data['storyNotice']);
        $('#story_notices').modal('show');
    }

    function onRegisterZoneSuccess() {

    }

    function onIntroZoneHide() {
        /*
            this is called when the home zone description box is closed by the
            user.
        */
        var zones = noticeData['zonePrompt'];
        if (preventPopUps) {
            var item = gu.arrayRandomChoice(zones);
            //JPTODO: send info to sever
            return;
        }
        ko.applyBindings(new zoneViewModel(zones), document.getElementById("zone_choices"));
        $('#zone_choices').modal('show');
    }

    function generalAjaxSuccess() {
        /*
            mostly for testing purposes
        */
        console.log("success");
    }

    function introCloseClick() {
        /*
            when the user clicks on the next button for the intro message
        */
        checkPreventPopupsCheckbox();
        $('#story_notices').modal('hide');
    }

    function zoneCloseClick() {
        /*
            when the user clicks on the next button for the home zone description box
        */
        checkPreventPopupsCheckbox();
        $('#zone_notices').modal('hide');
    }

    function zoneChoiceGoBackClick() {
        /*
            when the user clicks on the go back button after the user has selected a zone.
        */
        selectedZone = null;
        $("#picked_zone_description").addClass("hidden");
        $("#zone_choice_list").removeClass("hidden");
        $("button[name='zone_choice_back']").addClass("hidden");
        $("button[name='zone_choice_ok']").addClass("hidden");
    }

    function zoneChoiceConfirm(){
        /*
            when the user clicks OK after a zone has been selected or if
            the user clicks OK after the block pop-ups checkbox has been
            marked.
        */
        checkPreventPopupsCheckbox();
        $('#zone_choices').modal('hide');
        if (selectedChoiceIndex > -1) {

            $.ajax({
                url: "main/register_zone",
                type: 'get',
                dataType: 'json',
                data: { 'selectedZoneIndex': selectedChoiceIndex },
                success: onRegisterZoneSuccess
            });
        }
        else {
            var zones = noticeData['zonePrompt'];
            var item = gu.arrayRandomChoice(zones);
            //JPTODO: send info to sever
            return;

        }

    }

    function blockPopupCheckForZoneChoiceClick() {
        /*
            if the user checks the no pop-up checkbox on the zone selection
            window.
        */
        preventPopUps = $('#zone_choice_no_popups_check').prop('checked');
        console.log("check checked");
        if (preventPopUps) {
            $("button[name='zone_choice_ok']").removeClass("hidden");
        }
        else {
            if ($("#picked_zone_description").hasClass("hidden")) {
                $("button[name='zone_choice_ok']").addClass("hidden");
            }
        }
    }

    function checkPreventPopupsCheckbox() {
        /*
            this should be called on most next screen clicks on the opening
            box. This sends a message to the server to not send anymore
            pop-ups for this user.
        */
        preventPopUps = $('#no_popups_check').prop('checked') ||
            $('#zone_choice_no_popups_check').prop('checked');
        if (preventPopUps) {
            $.ajax({
                url: "main/disable_popups",
                type: "get",
                success: generalAjaxSuccess
            });
        }
    }

    function zoneChoice(zoneItem) {
        /*
            js class to be a knockout.js zone item.
            args should be fed from noticeData object
            args:
                zoneItem:
        */
        var self = this;
        self.name = zoneItem['fullName'];
        self.lvl = zoneItem['lvl'];
        self.description = zoneItem['description'];
    }

    function zoneViewModel(zoneList) {
        /*
            knockout.js
            args:
                zoneList:
                    pass value for 'zonePrompt' from the global noticeData
        */
        var self = this;
        var transformedZoneList = [];
        for (var i = 0; i < zoneList.length; i++) {
            transformedZoneList.push(new zoneChoice(zoneList[i]));
        }

        self.onZoneChoiceClick = function (index,choice,e) {
            /*
                when the user clicks on any of the opening zone choices.
            */
            selectedChoiceIndex = index;
            $("#zone_choice_list").addClass("hidden");
            var $zoneDesc = $("#picked_zone_description")
            $zoneDesc.html("");
            $zoneDesc.removeClass("hidden");
            $zoneDesc.html(choice.description);
            $("button[name='zone_choice_back']").removeClass("hidden");
            $("button[name='zone_choice_ok']").removeClass("hidden");
        }

        self.choices = ko.observableArray(transformedZoneList);
    }

});

//$(function(){

    //$.ajax({
    //    url: "/hero",
    //    type: 'get',
    //    dataType: 'json',
    //    error: function (p1,p2,p3) {
    //        //alert(p3);
    //    },
    //    success: function (data) {
    //        //heroFromJson = JSON.parse(data);

    //        //ko.applyBindings(new SpaceHabitModel(heroFromJson));
    //    }
    //});

//  function clearDailyEditInputs(){
//    $('#edit_daily_box input').val("");
//    $('#edit_daily_box textarea').val("");
//    $('#daily_urgency .selected_danger_radio').removeClass("selected_danger_radio");
//    $('#daily_urgency .danger_radio:nth-of-type(4)').addClass("selected_danger_radio");
//    $('#daily_difficulty .selected_danger_radio').removeClass("selected_danger_radio");
//    $('#daily_difficulty .danger_radio:nth-of-type(4)').addClass("selected_danger_radio");
//    $('#daily_rate input').val("1");
//    $('.day_check').prop('checked','true');

//  }

//  function clearHabitEditInputs(){

//  }

//  function clearTodoEditInputs(){}

//  function clearGoodsEditInputs(){}

//  var SpaceHabitModel = function(heroModel){

//    var self = this;

//    self.hero = {'name': ko.observable(heroModel.name),
//      'lvl': ko.observable(heroModel.lvl),
//      'gold': ko.observable(heroModel.gold),
//      'maxHp':ko.observable(heroModel.maxHp),
//      'nowHp': ko.observable(heroModel.nowHp),
//      'maxXp': ko.observable(heroModel.maxHp),
//      'nowXp': ko.observable(heroModel.nowXp),
//    };

//    //self.dailies = ko.observableArray(GetDailies());
//    //self.finishedDailies = ko.observableArray(GetFinishedDailies());
//    //self.habits = ko.observableArray(GetHabits());
//    //self.todos = ko.observableArray(GetTodos());
//    //self.IRLGoods = ko.observableArray(GetIRLPrizes());
//    //self.disposableGoods = ko.observableArray(GetDisposableGoods());
//    //self.armsGoods = ko.observableArray(GetArmsPrizes());
//	//self.items = ko.observableArray(GetDisposableGoods());

//    self.doDaily = function(daily){
//    };
//    self.undoDaily = function(daily){};
//    self.dohabit = function(habit){};
//    self.doTodo = function(todo){};
//    self.buyGood = function(good){};
//	self.useItem = function(item){};

//    self.getHeroHealthPercent = function(){
//      var percent = Math.round((self.hero.nowHp()/self.hero.maxHp())*100);
//      return percent +"%";
//    };

//    self.getHeroXpPercent = function(){
//      var percent = Math.round((self.hero.nowXp()/self.hero.maxXp())*100);
//      return percent + "%";
//    };

//    self.getMonsterHealthPercent = function(){
//        //var percent = Math.round((self.monster.nowHp()/self.monster.maxHp())*100);
//        percent = 75;
//      return percent + "%";
//    };

//    self.getDaysUntilTodoEnds = function(todo){
//      return todo.dueDate;
//    };

//    self.getDaysUntilTodoStarts = function(todo){
//      return todo.effectiveDate;
//    };

//    self.getDaysUntilDailyEnds = function(daily){
//      return daily.daysLeft;
//    };

//  };

//  $('button[name="open_add_daily"]').click(function(){
//    clearDailyEditInputs();
//    $('#edit_daily_box').modal('show');
//  });

//  $('button[name="open_add_habit"]').click(function(){
//    clearHabitEditInputs();
//    $('#edit_habit_box').modal('show');
//  });

//  $('button[name="open_add_todo"]').click(function(){
//    clearTodoEditInputs();
//    $('#edit_todo_box').modal('show');
//  });

//  $(".task_open_extra_options").click(function(){

//  });

//   $('.danger_radio:nth-of-type(4)').addClass("selected_danger_radio");

//   $('.danger_radio').click(function(){
//     $(this).siblings('.selected_danger_radio').removeClass("selected_danger_radio");
//     $(this).addClass("selected_danger_radio");
//   });

//});