text:
if VOTING then VOTING = VOTING
else VOTING = {} end

VOTING.CurrentHeight = 50
include('cl_votingfonts.lua')
include('sh_votingconfig.lua')
--Include panels
include('panels/cl_votingpanel.lua')
include('panels/cl_playericon.lua')

function VOTING.OpenVoteScreen( settings )
	if not LocalPlayer() then return end
	VOTING.MainWindowOpen = true
	if !VotingMainWindow then
		VotingMainWindow = vgui.Create( "DFrame" )
		VotingMainWindow:SetSize( ScrW(), 300 )
		VotingMainWindow:SetDraggable( false )
		VotingMainWindow:ShowCloseButton( false )
		VotingMainWindow:SetTitle( "" )
		VotingMainWindow:SetBackgroundBlur( true )
		VotingMainWindow.VoteTime = settings.time
		VOTING.CanCloseTime = CurTime() + settings.time
		VotingMainWindow.Paint = VOTING.PaintMainWindow
		VOTING.VoteManager = {}

		//Voting panels list
		local VotingPanelsList = vgui.Create( "DPanelList", VotingMainWindow )
		VotingPanelsList:SetPadding( 0 )
		VotingPanelsList:SetSpacing( 5 )
		VotingPanelsList:SetAutoSize( true )
		VotingPanelsList:SetNoSizing( false )
		VotingPanelsList:EnableHorizontal( true )
		VotingPanelsList:EnableVerticalScrollbar( false )
		VotingPanelsList.Paint = function() end
		VotingPanelsList:SetWide(ScrW() - (ScrW() / 10))
		VotingPanelsList:SetPos((ScrW() / 10) / 2, 70)

		//Create voting panels
		for k,v in pairs(settings.Candidates) do
			local VotingPanel = vgui.Create( "PlayerVotingPanel" )
			if IsValid(v.player) then
			VotingPanel:SetPlayer(v.player)
			VotingPanel:SetColor(VOTING.NewVotingPanelColor())
			VotingPanel.DoClick = function()
				if LocalPlayer().HasVoted then return end
				local player = VotingPanel:GetPlayer()
				if player then
				LocalPlayer():ConCommand("mayor_vote "..k)
				VotingPanel:ToggleSelect(true)
				LocalPlayer().HasVoted = true
				if (VOTING.Settings.ForceMouseCursor) then gui.EnableScreenClicker(false) end
				end
			end
			else
			VotingPanel:SetColor(VOTING.NewVotingPanelColor())
			VotingPanel:SetNoActionEnbaled(true)
			VotingPanel:SetText("Disconnected")
			end
			table.insert(VOTING.VoteManager, VotingPanel)
			VotingPanelsList:AddItem(VotingPanel)
		end

		local maxwidth = VotingPanelsList:GetWide()
		local curwidth  = 0
		local items = 0
		for k,v in pairs(VotingPanelsList:GetItems()) do
			curwidth = curwidth + (v.CurrentWidth) + 5
			if (curwidth > maxwidth) then break
			else items = (items + 1) end
		end
		VotingPanelsList:SetWide(355 * items)
		VotingPanelsList:SetPos((ScrW() - VotingPanelsList:GetWide()) / 2, 70)
		local rows = 0
		local panelheight = 0
		rows = math.ceil(#VOTING.VoteManager / items)

		VOTING.MaxHeight = 130 + (70 * rows)
		VotingMainWindow:SetSize( ScrW(), VOTING.MaxHeight )
		if VOTING.Settings.ForceMouseCursor then gui.EnableScreenClicker(true) end
	else
		VOTING.CloseVoteScreen()
	end
end
//concommand.Add("voting", VOTING.OpenVoteScreen)
//usermessage.Hook("VOTING_Open", VOTING.OpenVoteScreen)

local FKeyReleased = false

function VOTING.PaintMainWindow()
	//Paint window itself
	surface.SetDrawColor(VOTING.Theme.WindowColor)

	VOTING.CurrentHeight = math.Approach( VOTING.CurrentHeight, VOTING.MaxHeight, FrameTime() * 400 )
	surface.DrawRect(0, 0, ScrW(), VOTING.CurrentHeight)

	//Banner heading
	local time = math.Clamp(VOTING.CanCloseTime - CurTime(), 0, VotingMainWindow.VoteTime)
	local timetext = string.FormattedTime(time, "%02i:%02i")
	local text = VOTING.Settings.VotingTitle .. " (" .. timetext  ..")"
	if VOTING.ResultsScreen then text = VOTING.Settings.ResultsTitle end
	draw.DrawText(text, "Bebas40Font", (ScrW() / 2), 10, VOTING.Theme.TitleTextColor, TEXT_ALIGN_CENTER )

	//Vote ticker
	if VOTING.VoteTickerAlpha > -1 then
		VOTING.VoteTickerAlpha = math.Clamp(VOTING.VoteTickerAlpha + FrameTime() * VOTING.NotificationDirFT * 300, 0, 190)

		local c = VOTING.VoteTickerColor
		local r,g,b = c.r,c.g,c.b
		local w,h = surface.GetTextSize(VOTING.VoteTickerMessage)

		local ypos = (ScrW() / 2) - (w / 4)
		draw.WordBox(2, ypos, (VOTING.MaxHeight - 30), VOTING.VoteTickerMessage, "OpenSans18Font", Color(r,g,b,VOTING.VoteTickerAlpha), color_white)
	end

end

function VOTING.CloseVoteScreen()
	if VotingMainWindow then
		VotingMainWindow:Remove()
		VotingMainWindow = nil
		VOTING.CanCloseTime = nil
		VOTING.LastPanelNumber = nil
		VOTING.VoteTickerAlpha = -1
		VOTING.VoteTickerMessage = "A vote has been placed in the election."
		VOTING.ResultsScreen = nil
		LocalPlayer().HasVoted = nil
		FKeyReleased = false
	end
	VOTING.MainWindowOpen = false
end

--NewVote Network Message
net.Receive("Voting_NewVote", function(l,c)
	 local votedata = net.ReadTable()
	 local votetime = VOTING.VoteTime
	 local settings = {}
	 settings.Candidates = votedata
	 settings.time = votetime
	 VOTING.OpenVoteScreen( settings )
	 if VOTING.Settings.MenuSounds then surface.PlaySound(VOTING.Settings.NewVoteSound) end
end)

--EndVote Network Message
net.Receive("Voting_EndVote", function(l,c)
	 local winningplayer = net.ReadEntity()

	 if winningplayer and not (winningplayer == NULL) then
			VOTING.ResultsScreen = true
			for k,v in pairs(VOTING.VoteManager) do
				if not (v:GetPlayer() == winningplayer) then
					v:SetNoActionEnbaled(true)
				else
					VOTING.VoteTickerAlpha = 0
					VOTING.VoteTickerMessage = string.format("Congratulations to the winner, %s!", winningplayer:Nick())
					VOTING.VoteTickerColor = v:GetColor()
				end
			end
	 else
	 end
	 if VOTING.Settings.MenuSounds then surface.PlaySound(VOTING.Settings.VoteResultsSound) end
	 timer.Simple(VOTING.Settings.CloseTimeAfterVoteEnds, VOTING.CloseVoteScreen)
end)

--Vote Cast Network Message
net.Receive("Voting_VoteCast", function(l,c)
	 local candidate = net.ReadEntity()
	 local player = net.ReadEntity()

	 if not VOTING.MainWindowOpen then return end
	 for k,v in pairs(VOTING.VoteManager) do
		if (v:GetPlayer() == candidate) then
			v:IncreaseVote(1)

			--Show vote ticker update
			if VOTING.Settings.ShowVoteTickerUpdates then
				VOTING.VoteTickerAlpha = 0
				VOTING.VoteTickerMessage = string.format("%s has voted for %s", player:Nick(), candidate:Nick())
				VOTING.VoteTickerColor = v:GetColor()
			end
		end
	 end
end)

VOTING.VoteTickerAlpha = -1
VOTING.VoteTickerMessage = "A vote has been placed in the election."
VOTING.VoteTickerColor = Color(26,83,255)
VOTING.NotificationDirFT = 1

VOTING.VotingStaticColors = {Color(26,83,255),Color(255,77,77),Color(230,184,0),Color(0,179,54)}

local ConfirmMenuVisible = false
function VOTING.ConfirmCandidacy()
	if ConfirmMenuVisible then return end
	ConfirmMenuVisible = true
	Derma_Query("Would you like to enter the next election " .. LocalPlayer():Nick() .. " ?", "Mayors Secretary",
			"Yes " .. (CUR or GAMEMODE.Config.currency or "$") .. tostring(VOTING.CandidateCost), function() LocalPlayer():ConCommand("mayor_vote_enter") ConfirmMenuVisible = false end,
			"Cancel", function() ConfirmMenuVisible = false end
			)
end
usermessage.Hook("VOTING_Confirm", VOTING.ConfirmCandidacy)

function VOTING.NewVotingPanelColor()
	if not VOTING.LastPanelNumber then VOTING.LastPanelNumber = 1
	else VOTING.LastPanelNumber = (VOTING.LastPanelNumber + 1) end

	if VOTING.VotingStaticColors[VOTING.LastPanelNumber] then
	return VOTING.VotingStaticColors[VOTING.LastPanelNumber]
	else
		local part = math.random(1,3)
		if part == 1 then return Color(255,math.random(1,255),math.random(1,255) )
		elseif part == 2 then return Color(math.random(1,255),255,math.random(1,255) )
		else return Color(math.random(1,255),math.random(1,255),255 ) end
	end
end

local function MayorVotingChatNotice(msg)
	local text = msg:ReadString() or "No message."
	chat.AddText(VOTING.Theme.NoticePrefixColor, VOTING.Settings.NoticePrefix .. " ", VOTING.Theme.NoticeTextColor, text )
end
usermessage.Hook("Voting_ChatNotice", MayorVotingChatNotice)


text:
using Artemis;
using Artemis.Attributes;
using Artemis.Interface;
using Fred.Components;
namespace Fred.Templates
{
    [ArtemisEntityTemplate(Name)]
    class WallAttackTemplate : IEntityTemplate
    {
        public const string Name = "WallAttackTemplate";

        public Entity BuildEntity(Entity entity, EntityWorld world, params object[] args)
        {
            entity.AddComponentFromPool<TransformComponent>();
            entity.AddComponent(new SpatialFormComponent("WallAttack"));
            entity.AddComponent(new ExpirationComponent(500));

            return entity;
        }

    }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using Android.App;
using Android.Content.PM;
using KinderChat.Infrastructure;

namespace KinderChat
{

	[Activity (Label = "@string/app_name", ScreenOrientation = ScreenOrientation.Portrait, MainLauncher = true, NoHistory=true, Icon = "@drawable/ic_launcher", LaunchMode = Android.Content.PM.LaunchMode.SingleTop)]
	public class WelcomeActivity : BaseActivity
	{
		protected override int LayoutResource {
			get {
				return Resource.Layout.activity_welcome;
			}
		}

		SignUpViewModel viewModel;
		protected override void OnCreate (Android.OS.Bundle bundle)
		{
			base.OnCreate (bundle);

            ServiceContainer.Register<IUIThreadDispacher>(() => new UIThreadDispacher());
            ServiceContainer.Register<ILiveConnection>(() => new WebSocketConnection());
			App.Init ();

			//don't need to do this every time unless testing
			if (Settings.IsLoggedIn && !App.ForceSignup) {
				StartActivity (typeof(MainActivity));
				return;
			}

			// Create the transaction
			var fts = SupportFragmentManager.BeginTransaction();
			fts.SetCustomAnimations(Resource.Animation.enter, Resource.Animation.exit, Resource.Animation.pop_enter, Resource.Animation.pop_exit);

			// Replace the content of the container
			fts.Replace(Android.Resource.Id.Content, WelcomeFragment.NewInstance());
			// Commit the changes
			fts.Commit();

			SupportActionBar.Title = "Welcome";
			SupportActionBar.SetDisplayHomeAsUpEnabled (false);
			SupportActionBar.SetHomeButtonEnabled (false);

			viewModel = App.SignUpViewModel;
			viewModel.PropertyChanged += ViewModelPropertyChanged;
		}

		void ViewModelPropertyChanged (object sender, System.ComponentModel.PropertyChangedEventArgs e)
		{
			RunOnUiThread (() => {
				switch (e.PropertyName) {
				case BaseViewModel.IsBusyPropertyName:
					if (viewModel.IsBusy)
						AndroidHUD.AndHUD.Shared.Show (this, maskType: AndroidHUD.MaskType.Clear);
					else
						AndroidHUD.AndHUD.Shared.Dismiss (this);
					break;
				}
			});
		}

		public void GoToGetStarted()
		{
			// Create the transaction
			var fts = SupportFragmentManager.BeginTransaction();
			fts.SetCustomAnimations(Resource.Animation.enter, Resource.Animation.exit, Resource.Animation.pop_enter, Resource.Animation.pop_exit);

			// Replace the content of the container
			fts.Replace(Android.Resource.Id.Content, GetStartedFragment.NewInstance());
			// Append this transaction to the backstack
			fts.AddToBackStack("get_started");
			// Commit the changes
			fts.Commit();

			SupportActionBar.SetDisplayHomeAsUpEnabled (true);
			SupportActionBar.SetHomeButtonEnabled (true);

			SupportActionBar.Title = "Sign Up";
		}

		public void GoToConfirmation()
		{
			// Create the transaction
			var fts = SupportFragmentManager.BeginTransaction();
			fts.SetCustomAnimations(Resource.Animation.enter, Resource.Animation.exit, Resource.Animation.pop_enter, Resource.Animation.pop_exit);

			// Replace the content of the container
			fts.Replace(Android.Resource.Id.Content, ConfirmationFragment.NewInstance());
			// Append this transaction to the backstack
			fts.AddToBackStack("confirmation");
			// Commit the changes
			fts.Commit();

			SupportActionBar.SetDisplayHomeAsUpEnabled (true);
			SupportActionBar.SetHomeButtonEnabled (true);
		}

		public override void OnBackPressed ()
		{
			base.OnBackPressed ();
			var showUp = SupportFragmentManager.BackStackEntryCount > 0;
			SupportActionBar.SetDisplayHomeAsUpEnabled (showUp);
			SupportActionBar.SetHomeButtonEnabled (showUp);
		}

		public override bool OnOptionsItemSelected (Android.Views.IMenuItem item)
		{
			if (item.ItemId == Android.Resource.Id.Home) {
				if (SupportFragmentManager.BackStackEntryCount > 0) {
					SupportFragmentManager.PopBackStack ();
				}

				var showUp = SupportFragmentManager.BackStackEntryCount > 0;
				SupportActionBar.SetDisplayHomeAsUpEnabled (showUp);
				SupportActionBar.SetHomeButtonEnabled (showUp);
			}
			return base.OnOptionsItemSelected (item);
		}

		protected override void OnDestroy ()
		{
			base.OnDestroy ();
			if(viewModel != null)
				viewModel.PropertyChanged -= ViewModelPropertyChanged;
		}
	}
}


text:
  Têche est
       un village
       localisé dans le département de l'Isère en Rhône-Alpes. Elle comptait 505 habitants en 2008.

Le nombre de logements, à Têche, se décomposait en 2011 en dix appartements et 228 maisons soit
 un marché plutôt équilibré.

Si vous pensez demenager à Têche, vous pourrez aisément trouver une maison à acheter.

À Têche, la valeur moyenne à la vente d'un appartement s'évalue à 1 988 € du m² en vente. La valeur moyenne d'une maison à l'achat se situe à 2 291 € du m². À la location le prix moyen se situe à 8,39 € du m² mensuel.

À coté de Têche sont situées les villes de
Saint-Marcellin située à 5 km, 7 694 habitants,
L'Albenc à 6 km, 1 059 habitants,
Cognin-les-Gorges à 2 km, 626 habitants,
Vinay à 3 km, 3 803 habitants,
Saint-Vérand située à 3 km, 1 730 habitants,
Malleval à 5 km, 55 habitants,
 entre autres. De plus, Têche est située à seulement 27 km de Grenoble.


text:
namespace blink {

// Suppress warning: global constructors, because struct WrapperTypeInfo is trivial
// and does not depend on another global objects.
#if defined(COMPONENT_BUILD) && defined(WIN32) && COMPILER(CLANG)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wglobal-constructors"
#endif
const WrapperTypeInfo V8TestInterfaceConstructor::wrapperTypeInfo = { gin::kEmbedderBlink, V8TestInterfaceConstructor::domTemplate, V8TestInterfaceConstructor::trace, V8TestInterfaceConstructor::traceWrappers, 0, 0, V8TestInterfaceConstructor::preparePrototypeAndInterfaceObject, nullptr, "TestInterfaceConstructor", 0, WrapperTypeInfo::WrapperTypeObjectPrototype, WrapperTypeInfo::ObjectClassId, WrapperTypeInfo::NotInheritFromEventTarget, WrapperTypeInfo::Independent };
#if defined(COMPONENT_BUILD) && defined(WIN32) && COMPILER(CLANG)
#pragma clang diagnostic pop
#endif

// This static member must be declared by DEFINE_WRAPPERTYPEINFO in TestInterfaceConstructor.h.
// For details, see the comment of DEFINE_WRAPPERTYPEINFO in
// bindings/core/v8/ScriptWrappable.h.
const WrapperTypeInfo& TestInterfaceConstructor::s_wrapperTypeInfo = V8TestInterfaceConstructor::wrapperTypeInfo;

namespace TestInterfaceConstructorV8Internal {

static void constructor1(const v8::FunctionCallbackInfo<v8::Value>& info)
{
    ExceptionState exceptionState(ExceptionState::ConstructionContext, "TestInterfaceConstructor", info.Holder(), info.GetIsolate());
    ScriptState* scriptState = ScriptState::forReceiverObject(info);
    ExecutionContext* executionContext = currentExecutionContext(info.GetIsolate());
    Document& document = *toDocument(currentExecutionContext(info.GetIsolate()));
    TestInterfaceConstructor* impl = TestInterfaceConstructor::create(scriptState, executionContext, document, exceptionState);
    if (exceptionState.hadException()) {
        exceptionState.throwIfNeeded();
        return;
    }
    v8::Local<v8::Object> wrapper = info.Holder();
    wrapper = impl->associateWithWrapper(info.GetIsolate(), &V8TestInterfaceConstructor::wrapperTypeInfo, wrapper);
    v8SetReturnValue(info, wrapper);
}

static void constructor2(const v8::FunctionCallbackInfo<v8::Value>& info)
{
    ExceptionState exceptionState(ExceptionState::ConstructionContext, "TestInterfaceConstructor", info.Holder(), info.GetIsolate());
    double doubleArg;
    V8StringResource<> stringArg;
    TestInterfaceEmpty* testInterfaceEmptyArg;
    Dictionary dictionaryArg;
    Vector<String> sequenceStringArg;
    Vector<Dictionary> sequenceDictionaryArg;
    HeapVector<LongOrTestDictionary> sequenceLongOrTestDictionaryArg;
    Dictionary optionalDictionaryArg;
    TestInterfaceEmpty* optionalTestInterfaceEmptyArg;
    {
        doubleArg = toRestrictedDouble(info.GetIsolate(), info[0], exceptionState);
        if (exceptionState.throwIfNeeded())
            return;
        stringArg = info[1];
        if (!stringArg.prepare())
            return;
        testInterfaceEmptyArg = V8TestInterfaceEmpty::toImplWithTypeCheck(info.GetIsolate(), info[2]);
        if (!testInterfaceEmptyArg) {
            exceptionState.throwTypeError("parameter 3 is not of type 'TestInterfaceEmpty'.");
            exceptionState.throwIfNeeded();
            return;
        }
        if (!isUndefinedOrNull(info[3]) && !info[3]->IsObject()) {
            exceptionState.throwTypeError("parameter 4 ('dictionaryArg') is not an object.");
            exceptionState.throwIfNeeded();
            return;
        }
        dictionaryArg = Dictionary(info[3], info.GetIsolate(), exceptionState);
        if (exceptionState.throwIfNeeded())
            return;
        sequenceStringArg = toImplArray<Vector<String>>(info[4], 5, info.GetIsolate(), exceptionState);
        if (exceptionState.throwIfNeeded())
            return;
        sequenceDictionaryArg = toImplArray<Vector<Dictionary>>(info[5], 6, info.GetIsolate(), exceptionState);
        if (exceptionState.throwIfNeeded())
            return;
        sequenceLongOrTestDictionaryArg = toImplArray<HeapVector<LongOrTestDictionary>>(info[6], 7, info.GetIsolate(), exceptionState);
        if (exceptionState.throwIfNeeded())
            return;
        if (!isUndefinedOrNull(info[7]) && !info[7]->IsObject()) {
            exceptionState.throwTypeError("parameter 8 ('optionalDictionaryArg') is not an object.");
            exceptionState.throwIfNeeded();
            return;
        }
        optionalDictionaryArg = Dictionary(info[7], info.GetIsolate(), exceptionState);
        if (exceptionState.throwIfNeeded())
            return;
        optionalTestInterfaceEmptyArg = V8TestInterfaceEmpty::toImplWithTypeCheck(info.GetIsolate(), info[8]);
        if (!optionalTestInterfaceEmptyArg) {
            exceptionState.throwTypeError("parameter 9 is not of type 'TestInterfaceEmpty'.");
            exceptionState.throwIfNeeded();
            return;
        }
    }
    ScriptState* scriptState = ScriptState::forReceiverObject(info);
    ExecutionContext* executionContext = currentExecutionContext(info.GetIsolate());
    Document& document = *toDocument(currentExecutionContext(info.GetIsolate()));
    TestInterfaceConstructor* impl = TestInterfaceConstructor::create(scriptState, executionContext, document, doubleArg, stringArg, testInterfaceEmptyArg, dictionaryArg, sequenceStringArg, sequenceDictionaryArg, sequenceLongOrTestDictionaryArg, optionalDictionaryArg, optionalTestInterfaceEmptyArg, exceptionState);
    if (exceptionState.hadException()) {
        exceptionState.throwIfNeeded();
        return;
    }
    v8::Local<v8::Object> wrapper = info.Holder();
    wrapper = impl->associateWithWrapper(info.GetIsolate(), &V8TestInterfaceConstructor::wrapperTypeInfo, wrapper);
    v8SetReturnValue(info, wrapper);
}

static void constructor3(const v8::FunctionCallbackInfo<v8::Value>& info)
{
    ExceptionState exceptionState(ExceptionState::ConstructionContext, "TestInterfaceConstructor", info.Holder(), info.GetIsolate());
    V8StringResource<> arg;
    V8StringResource<> optArg;
    {
        int numArgsPassed = info.Length();
        while (numArgsPassed > 0) {
            if (!info[numArgsPassed - 1]->IsUndefined())
                break;
            --numArgsPassed;
        }
        arg = info[0];
        if (!arg.prepare())
            return;
        if (UNLIKELY(numArgsPassed <= 1)) {
            ScriptState* scriptState = ScriptState::forReceiverObject(info);
            ExecutionContext* executionContext = currentExecutionContext(info.GetIsolate());
            Document& document = *toDocument(currentExecutionContext(info.GetIsolate()));
            TestInterfaceConstructor* impl = TestInterfaceConstructor::create(scriptState, executionContext, document, arg, exceptionState);
            if (exceptionState.hadException()) {
                exceptionState.throwIfNeeded();
                return;
            }
            v8::Local<v8::Object> wrapper = info.Holder();
            wrapper = impl->associateWithWrapper(info.GetIsolate(), &V8TestInterfaceConstructor::wrapperTypeInfo, wrapper);
            v8SetReturnValue(info, wrapper);
            return;
        }
        optArg = info[1];
        if (!optArg.prepare())
            return;
    }
    ScriptState* scriptState = ScriptState::forReceiverObject(info);
    ExecutionContext* executionContext = currentExecutionContext(info.GetIsolate());
    Document& document = *toDocument(currentExecutionContext(info.GetIsolate()));
    TestInterfaceConstructor* impl = TestInterfaceConstructor::create(scriptState, executionContext, document, arg, optArg, exceptionState);
    if (exceptionState.hadException()) {
        exceptionState.throwIfNeeded();
        return;
    }
    v8::Local<v8::Object> wrapper = info.Holder();
    wrapper = impl->associateWithWrapper(info.GetIsolate(), &V8TestInterfaceConstructor::wrapperTypeInfo, wrapper);
    v8SetReturnValue(info, wrapper);
}

static void constructor4(const v8::FunctionCallbackInfo<v8::Value>& info)
{
    ExceptionState exceptionState(ExceptionState::ConstructionContext, "TestInterfaceConstructor", info.Holder(), info.GetIsolate());
    V8StringResource<> arg;
    V8StringResource<> arg2;
    V8StringResource<> arg3;
    {
        arg = info[0];
        if (!arg.prepare())
            return;
        arg2 = info[1];
        if (!arg2.prepare())
            return;
        arg3 = info[2];
        if (!arg3.prepare())
            return;
    }
    ScriptState* scriptState = ScriptState::forReceiverObject(info);
    ExecutionContext* executionContext = currentExecutionContext(info.GetIsolate());
    Document& document = *toDocument(currentExecutionContext(info.GetIsolate()));
    TestInterfaceConstructor* impl = TestInterfaceConstructor::create(scriptState, executionContext, document, arg, arg2, arg3, exceptionState);
    if (exceptionState.hadException()) {
        exceptionState.throwIfNeeded();
        return;
    }
    v8::Local<v8::Object> wrapper = info.Holder();
    wrapper = impl->associateWithWrapper(info.GetIsolate(), &V8TestInterfaceConstructor::wrapperTypeInfo, wrapper);
    v8SetReturnValue(info, wrapper);
}

static void constructor(const v8::FunctionCallbackInfo<v8::Value>& info)
{
    ExceptionState exceptionState(ExceptionState::ConstructionContext, "TestInterfaceConstructor", info.Holder(), info.GetIsolate());
    switch (std::min(9, info.Length())) {
    case 0:
        if (true) {
            TestInterfaceConstructorV8Internal::constructor1(info);
            return;
        }
        break;
    case 1:
        if (true) {
            TestInterfaceConstructorV8Internal::constructor3(info);
            return;
        }
        break;
    case 2:
        if (true) {
            TestInterfaceConstructorV8Internal::constructor3(info);
            return;
        }
        break;
    case 3:
        if (true) {
            TestInterfaceConstructorV8Internal::constructor4(info);
            return;
        }
        break;
    case 7:
        if (true) {
            TestInterfaceConstructorV8Internal::constructor2(info);
            return;
        }
        break;
    case 8:
        if (true) {
            TestInterfaceConstructorV8Internal::constructor2(info);
            return;
        }
        break;
    case 9:
        if (true) {
            TestInterfaceConstructorV8Internal::constructor2(info);
            return;
        }
        break;
    default:
        if (info.Length() >= 0) {
            setArityTypeError(exceptionState, "[0, 1, 2, 3, 7, 8, 9]", info.Length());
            exceptionState.throwIfNeeded();
            return;
        }
        exceptionState.throwTypeError(ExceptionMessages::notEnoughArguments(0, info.Length()));
        exceptionState.throwIfNeeded();
        return;
    }
    exceptionState.throwTypeError("No matching constructor signature.");
    exceptionState.throwIfNeeded();
}

} // namespace TestInterfaceConstructorV8Internal

// Suppress warning: global constructors, because struct WrapperTypeInfo is trivial
// and does not depend on another global objects.
#if defined(COMPONENT_BUILD) && defined(WIN32) && COMPILER(CLANG)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wglobal-constructors"
#endif
const WrapperTypeInfo V8TestInterfaceConstructorConstructor::wrapperTypeInfo = { gin::kEmbedderBlink, V8TestInterfaceConstructorConstructor::domTemplate, V8TestInterfaceConstructor::trace, V8TestInterfaceConstructor::traceWrappers, 0, 0, V8TestInterfaceConstructor::preparePrototypeAndInterfaceObject, nullptr, "TestInterfaceConstructor", 0, WrapperTypeInfo::WrapperTypeObjectPrototype, WrapperTypeInfo::ObjectClassId, WrapperTypeInfo::NotInheritFromEventTarget, WrapperTypeInfo::Independent };
#if defined(COMPONENT_BUILD) && defined(WIN32) && COMPILER(CLANG)
#pragma clang diagnostic pop
#endif

static void V8TestInterfaceConstructorConstructorCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
    if (!info.IsConstructCall()) {
        V8ThrowException::throwTypeError(info.GetIsolate(), ExceptionMessages::constructorNotCallableAsFunction("Audio"));
        return;
    }

    if (ConstructorMode::current(info.GetIsolate()) == ConstructorMode::WrapExistingObject) {
        v8SetReturnValue(info, info.Holder());
        return;
    }
    ExceptionState exceptionState(ExceptionState::ConstructionContext, "TestInterfaceConstructor", info.Holder(), info.GetIsolate());
    if (UNLIKELY(info.Length() < 1)) {
        setMinimumArityTypeError(exceptionState, 1, info.Length());
        exceptionState.throwIfNeeded();
        return;
    }
    V8StringResource<> arg;
    V8StringResource<> optArg;
    {
        int numArgsPassed = info.Length();
        while (numArgsPassed > 0) {
            if (!info[numArgsPassed - 1]->IsUndefined())
                break;
            --numArgsPassed;
        }
        arg = info[0];
        if (!arg.prepare())
            return;
        if (UNLIKELY(numArgsPassed <= 1)) {
            ScriptState* scriptState = ScriptState::forReceiverObject(info);
            ExecutionContext* executionContext = currentExecutionContext(info.GetIsolate());
            Document& document = *toDocument(currentExecutionContext(info.GetIsolate()));
            TestInterfaceConstructor* impl = TestInterfaceConstructor::createForJSConstructor(scriptState, executionContext, document, arg, exceptionState);
            if (exceptionState.hadException()) {
                exceptionState.throwIfNeeded();
                return;
            }
            v8::Local<v8::Object> wrapper = info.Holder();
            wrapper = impl->associateWithWrapper(info.GetIsolate(), &V8TestInterfaceConstructorConstructor::wrapperTypeInfo, wrapper);
            v8SetReturnValue(info, wrapper);
            return;
        }
        optArg = info[1];
        if (!optArg.prepare())
            return;
    }
    ScriptState* scriptState = ScriptState::forReceiverObject(info);
    ExecutionContext* executionContext = currentExecutionContext(info.GetIsolate());
    Document& document = *toDocument(currentExecutionContext(info.GetIsolate()));
    TestInterfaceConstructor* impl = TestInterfaceConstructor::createForJSConstructor(scriptState, executionContext, document, arg, optArg, exceptionState);
    if (exceptionState.hadException()) {
        exceptionState.throwIfNeeded();
        return;
    }
    v8::Local<v8::Object> wrapper = info.Holder();
    wrapper = impl->associateWithWrapper(info.GetIsolate(), &V8TestInterfaceConstructorConstructor::wrapperTypeInfo, wrapper);
    v8SetReturnValue(info, wrapper);
}

v8::Local<v8::FunctionTemplate> V8TestInterfaceConstructorConstructor::domTemplate(v8::Isolate* isolate, const DOMWrapperWorld& world)
{
    static int domTemplateKey; // This address is used for a key to look up the dom template.
    V8PerIsolateData* data = V8PerIsolateData::from(isolate);
    v8::Local<v8::FunctionTemplate> result = data->findInterfaceTemplate(world, &domTemplateKey);
    if (!result.IsEmpty())
        return result;

    result = v8::FunctionTemplate::New(isolate, V8TestInterfaceConstructorConstructorCallback);
    v8::Local<v8::ObjectTemplate> instanceTemplate = result->InstanceTemplate();
    instanceTemplate->SetInternalFieldCount(V8TestInterfaceConstructor::internalFieldCount);
    result->SetClassName(v8AtomicString(isolate, "TestInterfaceConstructor"));
    result->Inherit(V8TestInterfaceConstructor::domTemplate(isolate, world));
    data->setInterfaceTemplate(world, &domTemplateKey, result);
    return result;
}

void V8TestInterfaceConstructor::constructorCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
    UseCounter::countIfNotPrivateScript(info.GetIsolate(), currentExecutionContext(info.GetIsolate()), UseCounter::TestFeature);
    if (!info.IsConstructCall()) {
        V8ThrowException::throwTypeError(info.GetIsolate(), ExceptionMessages::constructorNotCallableAsFunction("TestInterfaceConstructor"));
        return;
    }

    if (ConstructorMode::current(info.GetIsolate()) == ConstructorMode::WrapExistingObject) {
        v8SetReturnValue(info, info.Holder());
        return;
    }

    TestInterfaceConstructorV8Internal::constructor(info);
}

static void installV8TestInterfaceConstructorTemplate(v8::Isolate* isolate, const DOMWrapperWorld& world, v8::Local<v8::FunctionTemplate> interfaceTemplate)
{
    // Initialize the interface object's template.
    V8DOMConfiguration::initializeDOMInterfaceTemplate(isolate, interfaceTemplate, V8TestInterfaceConstructor::wrapperTypeInfo.interfaceName, v8::Local<v8::FunctionTemplate>(), V8TestInterfaceConstructor::internalFieldCount);
    interfaceTemplate->SetCallHandler(V8TestInterfaceConstructor::constructorCallback);
    interfaceTemplate->SetLength(0);
    v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interfaceTemplate);
    ALLOW_UNUSED_LOCAL(signature);
    v8::Local<v8::ObjectTemplate> instanceTemplate = interfaceTemplate->InstanceTemplate();
    ALLOW_UNUSED_LOCAL(instanceTemplate);
    v8::Local<v8::ObjectTemplate> prototypeTemplate = interfaceTemplate->PrototypeTemplate();
    ALLOW_UNUSED_LOCAL(prototypeTemplate);
    // Register DOM constants, attributes and operations.
}

v8::Local<v8::FunctionTemplate> V8TestInterfaceConstructor::domTemplate(v8::Isolate* isolate, const DOMWrapperWorld& world)
{
    return V8DOMConfiguration::domClassTemplate(isolate, world, const_cast<WrapperTypeInfo*>(&wrapperTypeInfo), installV8TestInterfaceConstructorTemplate);
}

bool V8TestInterfaceConstructor::hasInstance(v8::Local<v8::Value> v8Value, v8::Isolate* isolate)
{
    return V8PerIsolateData::from(isolate)->hasInstance(&wrapperTypeInfo, v8Value);
}

v8::Local<v8::Object> V8TestInterfaceConstructor::findInstanceInPrototypeChain(v8::Local<v8::Value> v8Value, v8::Isolate* isolate)
{
    return V8PerIsolateData::from(isolate)->findInstanceInPrototypeChain(&wrapperTypeInfo, v8Value);
}

TestInterfaceConstructor* V8TestInterfaceConstructor::toImplWithTypeCheck(v8::Isolate* isolate, v8::Local<v8::Value> value)
{
    return hasInstance(value, isolate) ? toImpl(v8::Local<v8::Object>::Cast(value)) : nullptr;
}

} // namespace blink


text:
package org.michaelgorski.kinetic;

/**
 * FastLayer for ultra fast rendering. If you don't need node nesting,
* mouse and touch interactions, or event pub/sub, you should use FastLayer
* instead of Layer to create your layers. It renders about 2x faster than normal layers.
 * @author Michael Gorski
 *
 */
public class KFastLayer extends KContainer {

	protected KFastLayer() {}

}


text:
$traceurRuntime.ModuleStore.getAnonymousModule(function() {
  "use strict";
  angular.module("kao.crud.select", ["kao.crud.api"]).directive("kaoSelect", function() {
    return {
      restrict: "E",
      replace: true,
      scope: {
        model: "=",
        url: "@",
        displayField: "@"
      },
      controller: function($scope, $http) {
        $scope.records = [];
        $scope.getRecords = function() {
          $http.get($scope.url).success(function(data) {
            $scope.records = data.records;
          }).error(function(error) {
            console.log(error);
          });
        };
        $scope.getRecords();
      },
      template: "<select ng-options=\"record as record[displayField] for record in records track by record.id\" ng-model=\"model\" />"
    };
  }).directive("modelSelect", function() {
    return {
      restrict: "E",
      replace: true,
      scope: {
        model: "=",
        type: "@",
        displayField: "@"
      },
      controller: function($scope, CrudApiService) {
        var crudApi = CrudApiService.getApiFor($scope.type);
        $scope.records = [];
        $scope.getRecords = function() {
          crudApi.getAll().success(function(data) {
            $scope.records = data.records;
          }).error(function(error) {
            console.log(error);
          });
        };
        $scope.getRecords();
      },
      template: "<select ng-options=\"record as record[displayField] for record in records track by record.id\" ng-model=\"model\" />"
    };
  });
  return {};
});


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Class template recursive_wrapper</title>
<link rel="stylesheet" href="../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.76.1">
<link rel="home" href="../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset">
<link rel="up" href="../variant/reference.html#header.boost.variant.recursive_wrapper_hpp" title="Header <boost/variant/recursive_wrapper.hpp>">
<link rel="prev" href="make_recursive_v_id1583552.html" title="Class template make_recursive_variant_over">
<link rel="next" href="is_recursive_wrapper.html" title="Class template is_recursive_wrapper">

Home
Libraries
People
FAQ
More

Class template recursive_wrapper

boost::recursive_wrapper — Solves circular dependencies, enabling recursive types.

Synopsis

// In header: <boost/variant/recursive_wrapper.hpp>

template<typename T>
class recursive_wrapper {
public:
  // types
  typedef T type;

  // construct/copy/destruct
  recursive_wrapper();
  recursive_wrapper(const recursive_wrapper &);
  recursive_wrapper(const T &);
  ~recursive_wrapper();

  // modifiers
  void swap(recursive_wrapper &);
  recursive_wrapper & operator=(const recursive_wrapper &);
  recursive_wrapper & operator=(const T &);

  // queries
  T & get();
  const T & get() const;
  T * get_pointer();
  const T * get_pointer() const;
};

Description

The recursive_wrapper class template has an
          interface similar to a simple value container, but its content is
          allocated dynamically. This allows recursive_wrapper to
          hold types T whose member data leads to a circular
          dependency (e.g., a data member of T has a data member
          of type T).

The application of recursive_wrapper is easiest
          understood in context. See
          the section called “Recursive types with recursive_wrapper” for a
          demonstration of a common use of the class template.

Notes:

Any type specified as the template argument to
            recursive_wrapper must be capable of construction via
            operator new. Thus, for instance, references are not
            supported.

recursive_wrapper
        public
       construct/copy/destruct

recursive_wrapper();
Default constructor.
Initializes *this by default construction of
            T.

<col align="left" valign="top">

Requires:

T must fulfill the requirements of the
            DefaultConstructible [20.1.4]
            concept.

Throws:

May fail with any exceptions arising from the default
            constructor of T or, in the event of
            insufficient memory, with std::bad_alloc.

recursive_wrapper(const recursive_wrapper & other);
Copy constructor.
Copies the content of other into
            *this.

<col align="left" valign="top">

Throws:

May fail with any exceptions arising from the
            copy constructor of T or, in the event of
            insufficient memory, with std::bad_alloc.

recursive_wrapper(const T & operand);
Value constructor.
Copies operand into
            *this.

<col align="left" valign="top">

Throws:

May fail with any exceptions arising from the
            copy constructor of T or, in the event of
            insufficient memory, with std::bad_alloc.

~recursive_wrapper();
Destructor.
Deletes the content of *this.

<col align="left" valign="top">

Throws:

Will not throw.

recursive_wrapper modifiers

void swap(recursive_wrapper & other);

Exchanges contents of *this and
              other.

<col align="left" valign="top">

Throws:

Will not throw.

recursive_wrapper & operator=(const recursive_wrapper & rhs);
Copy assignment operator.
Assigns the content of rhs to the content of
              *this.

<col align="left" valign="top">

Requires:

T must fulfill the requirements of
            the Assignable
            concept.

Throws:

May fail with any exceptions arising from the assignment
              operator of T.

recursive_wrapper & operator=(const T & rhs);
Value assignment operator.
Assigns rhs into the content of
              *this.

<col align="left" valign="top">

Requires:

T must fulfill the requirements of the
              Assignable
              concept.

Throws:

May fail with any exceptions arising from the assignment
              operator of T.

recursive_wrapper queries

T & get();
const T & get() const;

Returns a reference to the content of
              *this.

<col align="left" valign="top">

Throws:

Will not throw.

T * get_pointer();
const T * get_pointer() const;

Returns a pointer to the content of
              *this.

<col align="left" valign="top">

Throws:

Will not throw.

Copyright © 2002, 2003 Eric Friedman, Itay Maman
Distributed under the Boost Software License, Version 1.0.
    (See accompanying file LICENSE_1_0.txt or copy at
    http://www.boost.org/LICENSE_1_0.txt)


text:
/*!
 * \file cudnn_batch_norm.h
 * \brief
 * \author Junyuan Xie
 */

#ifndef MXNET_OPERATOR_NN_CUDNN_CUDNN_BATCH_NORM_H_
#define MXNET_OPERATOR_NN_CUDNN_CUDNN_BATCH_NORM_H_

#include <mxnet/base.h>
#include <vector>
#include "../batch_norm-inl.h"

namespace mxnet {
namespace op {

#if MXNET_USE_CUDNN == 1

STATIC_ASSERT_CUDNN_VERSION_GE(7401);

bool CudnnBatchNormSupports(const BatchNormParam& param, const TBlob& x);

void CudnnBatchNormForward(const BatchNormParam& param,
                           const OpContext& ctx,
                           const std::vector<TBlob>& inputs,
                           const std::vector<OpReqType>& req,
                           const std::vector<TBlob>& outputs);

void CudnnBatchNormBackward(const BatchNormParam& param,
                            const OpContext& ctx,
                            const std::vector<TBlob>& inputs,
                            const std::vector<OpReqType>& req,
                            const std::vector<TBlob>& outputs);

#endif  // MXNET_USE_CUDNN == 1

}  // namespace op
}  // namespace mxnet

#endif  // MXNET_OPERATOR_NN_CUDNN_CUDNN_BATCH_NORM_H_


text:
package ru.job4j.tracker;

import org.junit.Test;

import org.junit.Assert;

import static org.hamcrest.Matchers.is;

/**.
 * Test TrackerSql
 *
 * @author Anton Vasilyuk
 * @version 1.0.
 * @since 0.1.
 */
public class TrackerSQLTest {

    /**.
     * Test created connection
     */
    @Test
    public void checkConnection() {
        TrackerSQL sql = new TrackerSQL();
        Assert.assertThat(sql.init(), is(true));
    }
}


text:
package gengorums

import (
	"github.com/relab/gorums"
	"google.golang.org/protobuf/compiler/protogen"
)

var qspecInterface = `
{{$genFile := .GenFile}}
{{$configOpt := use "gorums.ConfigOption" .GenFile}}
{{- range qspecServices .Services}}
// QuorumSpec is the interface of quorum functions for {{.GoName}}.
type QuorumSpec interface {
	{{$configOpt}}

{{range qspecMethods .Methods -}}
	{{/* Below . is the method object */}}
	{{$method := .GoName}}
	{{$in := in $genFile .}}
	{{$out := out $genFile .}}
	{{$customOut := customOut $genFile .}}
	// {{$method}}QF is the quorum function for the {{$method}}
	// {{docName .}} call method. The in parameter is the request object
	// supplied to the {{$method}} method at call time, and may or may not
	// be used by the quorum function. If the in parameter is not needed
	// you should implement your quorum function with '_ *{{$in}}'.
	{{$method}}QF(in *{{$in}}, replies map[uint32]*{{$out}}) (*{{$customOut}}{{withCorrectable . ", int"}}, bool)
{{end}}
}
{{end}}
`

// qspecMethods returns all Gorums methods that require
// a quorum function; that is, all except multicast and plain gRPC methods.
func qspecMethods(methods []*protogen.Method) (s []*protogen.Method) {
	for _, method := range methods {
		if hasMethodOption(method, gorums.E_Multicast, gorums.E_Unicast) || !hasGorumsCallType(method) {
			// ignore multicast and non-Gorums methods
			continue
		}
		s = append(s, method)
	}
	return s
}

// qspecServices returns all services that have Gorums methods.
func qspecServices(services []*protogen.Service) (s []*protogen.Service) {
	for _, service := range services {
		for _, method := range service.Methods {
			if !hasGorumsCallType(method) {
				// ignore services without Gorums methods
				continue
			}
		}
		s = append(s, service)
	}
	return s
}


text:
<?php

namespace Righteous\Validator\Url;

use Righteous\Validator\Url;

/**
 * @author Massimo Lombardo <unwiredbrain@gmail.com>
 */
class WithQuery extends Url
{

    /**
     * {@inheritdoc}
     */
    public function validate()
    {
        return false !== filter_var($this->input, FILTER_VALIDATE_URL, FILTER_FLAG_QUERY_REQUIRED);
    }

}


text:
module Viget
  module TestExtensions
    module ActionController
      module ClassMethods
        attr_reader :controller_options

        %w(get post put delete).each do |method|
          class_eval %{
            def #{method}(action, &block)
              @options = {
                :method  => :#{method},
                :action  => action
              }
              block.call if block_given?

              self
            end
          }
        end

        def with(params = {}, session = {}, &block)
          @options[:params]  = params
          @options[:session] = session
          block.call if block_given?
          self
        end

        def should_assign(variable, value = nil, &block)
          add_controller_test "#{variable} should be assigned in [method] [action]" do |myself|
            myself.instance_eval do
              assert assigns(variable), "#{variable} was not assigned"
            end
          end

          add_controller_test "#{variable} should match expected in [method] [action]" do |myself|
            myself.instance_eval do
              if block_given?
                assert block.call(assigns(variable)), "#{variable} does not have expected value"
              elsif !value.nil?
                if value.is_a?(Regexp)
                  assert_match value, assigns(variable)
                else
                  assert_equal value, assigns(variable)
                end

                assert_equal value, assigns(variable), "#{variable} does not have expected value"
              end
            end
          end if !value.nil? || block_given?
          self
        end

        def should_not_assign(variable)
          add_controller_test "#{variable} should not be assigned in [method] [action]" do |myself|
            myself.instance_eval do
              assert assigns(variable).nil?, "#{variable} was assigned"
            end
          end
          self
        end

        def should_use_filter(filter_name)
          add_controller_test "[method] [action] should hit #{filter_name} filter" do |myself|
            klass.any_instance.expects(filter_name).raises(StandardError)
            myself.instance_eval do
              assert_raises(StandardError) do
                myself.send(@method, @action, @params, @session)
              end
            end
          end
          self
        end

        def should_not_use_filter(filter_name)
          add_controller_test "[method] [action] should not hit #{filter_name} filter" do |myself|
            klass.any_instance.expects(filter_name).never
            myself.instance_eval do
              myself.send(@method, @action, @params, @session)
            end
          end
          self
        end

        def should_render(template = nil)
          add_controller_test "[method] [action] should succeed" do |myself|
            myself.instance_eval do
              assert_response :success, "#{@method.to_s.upcase} #{@action}  failed"
            end
          end

          add_controller_test "correct template should be rendered in [method] [action]" do |myself|
            myself.instance_eval do
              template ||= @action
              assert_template template.to_s, "#{template} was not rendered"
            end
          end
          self
        end

        def should_set_flash(key, value = nil, &block)
          add_controller_test "flash for #{key} should be assigned in [method] [action]" do |myself|
            myself.instance_eval do
              assert flash[key], "#{key} was not assigned in flash"
            end
          end

          add_controller_test "flash #{key} should match expected in [method] [action]" do |myself|
            myself.instance_eval do
              if block_given?
                assert block.call(flash[key]), "#{key} in flash does not have expected value"
              elsif !value.nil?
                if value.is_a?(Regexp)
                  assert_match value, flash[key]
                else
                  assert_equal value, flash[key]
                end
              end
            end
          end if !value.nil? || block_given?
          self
        end

        def should_set_session(key, value = nil, &block)
          add_controller_test "session #{key} should be assigned in [method] [action]" do |myself|
            myself.instance_eval do
              assert session[key], "#{key} was not assigned in session"
            end
          end

          add_controller_test "session #{key} should match expected in [method] [action]" do |myself|
            myself.instance_eval do
              if block_given?
                assert block.call(session[key]), "#{key} in session does not have expected value"
              elsif !value.nil?
                if value.is_a?(Regexp)
                  assert_match value, session[key]
                else
                  assert_equal value, session[key]
                end
              end
            end
          end if !value.nil? || block_given?
          self
        end

        def should_redirect_to(target)
          add_controller_test "[method] [action] should redirect" do |myself|
            myself.instance_eval do
              assert_response :redirect, "#{@method.to_s.upcase} #{@action} was not a redirect"
            end
          end

          add_controller_test "[method] [action] should redirect to expected target" do |myself|
            if target.is_a?(Symbol)
              myself.instance_eval do
                assert_redirected_to target
              end
            else
              myself.instance_eval do
                assert_redirected_to eval(target)
              end
            end
          end
          self
        end

        private
        def extract_from_options()
          method  = @options[:method]
          action  = @options[:action]
          params  = @options[:params]
          session = @options[:session]
          return method, action, params, session
        end

        def add_controller_test(name, &block)
          method, action, params, session = extract_from_options

          test_name = name.gsub(/\s+/, '_').sub('[method]', method.to_s.upcase).sub('[action]', action.to_s)
          @dynamic_tests ||= {}
          @dynamic_tests[test_name.to_sym] = {
            :block   => block,
            :method  => method,
            :action  => action,
            :params  => params,
            :session => session
            }

          # TODO: merge passed-in session data with anything set in setup (e.g., login_as)
          class_eval %{
            def test_#{test_name}_#{@dynamic_tests.size.to_s.rjust(5, '0')}
              this_test = self.class.dynamic_tests[:#{test_name}]
              @method, @action, @params, @session = this_test[:method], this_test[:action], this_test[:params], this_test[:session]
              setup_and_submit_request(@method, @action, @params, @session)
              this_test[:block].call(self)
            end
          }
        end
      end

      module InstanceMethods
        def setup_and_submit_request(method, params, *extra)
          local_setup if respond_to?(:local_setup)
          send(method, params, *extra)
        end
      end
    end
  end
end


text:
package logging

import (
	"github.com/ccding/go-config-reader/config"
	"io"
	"os"
	"strconv"
	"sync"
	"sync/atomic"
	"time"
)

// Pre-defined formats
const (
	DefaultFileName   = "logging.log"                   // default logging filename
	DefaultConfigFile = "logging.conf"                  // default logging configuration file
	DefaultTimeFormat = "2006-01-02 15:04:05.999999999" // defaulttime format
	bufSize           = 1000                            // buffer size for writer
	queueSize         = 10000                           // chan queue size in async logging
	reqSize           = 10000                           // chan queue size in async logging
)

// Logger is the logging struct.
type Logger struct {

	// Be careful of the alignment issue of the variable seqid because it
	// uses the sync/atomic.AddUint64() operation. If the alignment is
	// wrong, it will cause a panic. To solve the alignment issue in an
	// easy way, we put seqid to the beginning of the structure.
	// seqid is only visiable internally.
	seqid uint64 // last used sequence number in record

	// These variables can be configured by users.
	name         string    // logger name
	level        Level     // record level higher than this will be printed
	recordFormat string    // format of the record
	recordArgs   []string  // arguments to be used in the recordFormat
	out          io.Writer // writer
	sync         bool      // use sync or async way to record logs
	timeFormat   string    // format for time

	// These variables are visible to users.
	startTime time.Time // start time of the logger

	// Internally used variables, which don't have get and set functions.
	wlock   sync.Mutex   // writer lock
	queue   chan string  // queue used in async logging
	request chan request // queue used in non-runtime logging
	flush   chan bool    // flush signal for the watcher to write
	quit    chan bool    // quit signal for the watcher to quit
	fd      *os.File     // file handler, used to close the file on destroy
	runtime bool         // with runtime operation or not
}

// SimpleLogger creates a new logger with simple configuration.
func SimpleLogger(name string) (*Logger, error) {
	return createLogger(name, WARNING, BasicFormat, DefaultTimeFormat, os.Stdout, false)
}

// BasicLogger creates a new logger with basic configuration.
func BasicLogger(name string) (*Logger, error) {
	return FileLogger(name, WARNING, BasicFormat, DefaultTimeFormat, DefaultFileName, false)
}

// RichLogger creates a new logger with simple configuration.
func RichLogger(name string) (*Logger, error) {
	return FileLogger(name, NOTSET, RichFormat, DefaultTimeFormat, DefaultFileName, false)
}

// FileLogger creates a new logger with file output.
func FileLogger(name string, level Level, format string, timeFormat string, file string, sync bool) (*Logger, error) {
	out, err := os.Create(file)
	if err != nil {
		return nil, err
	}
	logger, err := createLogger(name, level, format, timeFormat, out, sync)
	if err == nil {
		logger.fd = out
		return logger, nil
	} else {
		return nil, err
	}
}

// WriterLogger creates a new logger with a writer
func WriterLogger(name string, level Level, format string, timeFormat string, out io.Writer, sync bool) (*Logger, error) {
	return createLogger(name, level, format, timeFormat, out, sync)
}

// WriterLogger creates a new logger from a configuration file
func ConfigLogger(filename string) (*Logger, error) {
	conf := config.NewConfig(filename)
	err := conf.Read()
	if err != nil {
		return nil, err
	}
	name := conf.Get("", "name")
	slevel := conf.Get("", "level")
	if slevel == "" {
		slevel = "0"
	}
	l, err := strconv.Atoi(slevel)
	if err != nil {
		return nil, err
	}
	level := Level(l)
	format := conf.Get("", "format")
	if format == "" {
		format = BasicFormat
	}
	timeFormat := conf.Get("", "timeFormat")
	if timeFormat == "" {
		timeFormat = DefaultTimeFormat
	}
	ssync := conf.Get("", "sync")
	if ssync == "" {
		ssync = "0"
	}
	file := conf.Get("", "file")
	if file == "" {
		file = DefaultFileName
	}
	sync := true
	if ssync == "0" {
		sync = false
	} else if ssync == "1" {
		sync = true
	} else {
		return nil, err
	}
	return FileLogger(name, level, format, timeFormat, file, sync)
}

// createLogger create a new logger
func createLogger(name string, level Level, format string, timeFormat string, out io.Writer, sync bool) (*Logger, error) {
	logger := new(Logger)

	err := logger.parseFormat(format)
	if err != nil {
		return nil, err
	}

	// asign values to logger
	logger.name = name
	logger.level = level
	logger.out = out
	logger.seqid = 0
	logger.sync = sync
	logger.queue = make(chan string, queueSize)
	logger.request = make(chan request, reqSize)
	logger.flush = make(chan bool)
	logger.quit = make(chan bool)
	logger.startTime = time.Now()
	logger.fd = nil
	logger.timeFormat = timeFormat

	// start watcher to write logs if it is async or no runtime field
	if !logger.sync {
		go logger.watcher()
	}

	return logger, nil
}

// Destroy sends quit signal to watcher and releases all the resources.
func (logger *Logger) Destroy() {
	if !logger.sync {
		// quit watcher
		logger.quit <- true
		// wait for watcher quit
		<-logger.quit
	}
	// clean up
	if logger.fd != nil {
		logger.fd.Close()
	}
}

// Flush the writer
func (logger *Logger) Flush() {
	if !logger.sync {
		// send flush signal
		logger.flush <- true
		// wait for flush finish
		<-logger.flush
	}
}

// Getter functions

func (logger *Logger) Name() string {
	return logger.name
}

func (logger *Logger) StartTime() int64 {
	return logger.startTime.UnixNano()
}

func (logger *Logger) TimeFormat() string {
	return logger.timeFormat
}

func (logger *Logger) Level() Level {
	return Level(atomic.LoadInt32((*int32)(&logger.level)))
}

func (logger *Logger) RecordFormat() string {
	return logger.recordFormat
}

func (logger *Logger) RecordArgs() []string {
	return logger.recordArgs
}

func (logger *Logger) Writer() io.Writer {
	return logger.out
}

func (logger *Logger) Sync() bool {
	return logger.sync
}

// Setter functions

func (logger *Logger) SetLevel(level Level) {
	atomic.StoreInt32((*int32)(&logger.level), int32(level))
}

func (logger *Logger) SetWriter(out ...io.Writer) {
	logger.out = io.MultiWriter(out...)
}


text:
/*
 * @file
 */
#include "modules/planning/open_space/trajectory_smoother/distance_approach_ipopt_fixed_dual_interface.h"
namespace apollo {
namespace planning {

DistanceApproachIPOPTFixedDualInterface::
    DistanceApproachIPOPTFixedDualInterface(
        const size_t horizon, const double ts, const Eigen::MatrixXd& ego,
        const Eigen::MatrixXd& xWS, const Eigen::MatrixXd& uWS,
        const Eigen::MatrixXd& l_warm_up, const Eigen::MatrixXd& n_warm_up,
        const Eigen::MatrixXd& x0, const Eigen::MatrixXd& xf,
        const Eigen::MatrixXd& last_time_u, const std::vector<double>& XYbounds,
        const Eigen::MatrixXi& obstacles_edges_num, const size_t obstacles_num,
        const Eigen::MatrixXd& obstacles_A, const Eigen::MatrixXd& obstacles_b,
        const PlannerOpenSpaceConfig& planner_open_space_config)
    : ts_(ts),
      ego_(ego),
      xWS_(xWS),
      uWS_(uWS),
      l_warm_up_(l_warm_up),
      n_warm_up_(n_warm_up),
      x0_(x0),
      xf_(xf),
      last_time_u_(last_time_u),
      XYbounds_(XYbounds),
      obstacles_edges_num_(obstacles_edges_num),
      obstacles_A_(obstacles_A),
      obstacles_b_(obstacles_b) {
  CHECK(horizon < std::numeric_limits<int>::max())
      << "Invalid cast on horizon in open space planner";
  horizon_ = static_cast<int>(horizon);
  ADEBUG << "horizon length: " << horizon_;
  CHECK(obstacles_num < std::numeric_limits<int>::max())
      << "Invalid cast on obstacles_num in open space planner";

  obstacles_num_ = static_cast<int>(obstacles_num);
  w_ev_ = ego_(1, 0) + ego_(3, 0);
  l_ev_ = ego_(0, 0) + ego_(2, 0);
  g_ = {l_ev_ / 2, w_ev_ / 2, l_ev_ / 2, w_ev_ / 2};
  offset_ = (ego_(0, 0) + ego_(2, 0)) / 2 - ego_(2, 0);
  obstacles_edges_sum_ = obstacles_edges_num_.sum();
  state_result_ = Eigen::MatrixXd::Zero(4, horizon_ + 1);
  dual_l_result_ = Eigen::MatrixXd::Zero(obstacles_edges_sum_, horizon_ + 1);
  dual_n_result_ = Eigen::MatrixXd::Zero(4 * obstacles_num_, horizon_ + 1);
  control_result_ = Eigen::MatrixXd::Zero(2, horizon_);
  time_result_ = Eigen::MatrixXd::Zero(1, horizon_);

  state_start_index_ = 0;
  control_start_index_ = 4 * (horizon_ + 1);
  time_start_index_ = control_start_index_ + 2 * horizon_;
  l_start_index_ = time_start_index_ + (horizon_ + 1);
  n_start_index_ = l_start_index_ + obstacles_edges_sum_ * (horizon_ + 1);

  distance_approach_config_ =
      planner_open_space_config.distance_approach_config();
  weight_state_x_ = distance_approach_config_.weight_x();
  weight_state_y_ = distance_approach_config_.weight_y();
  weight_state_phi_ = distance_approach_config_.weight_phi();
  weight_state_v_ = distance_approach_config_.weight_v();
  weight_input_steer_ = distance_approach_config_.weight_steer();
  weight_input_a_ = distance_approach_config_.weight_a();
  weight_rate_steer_ = distance_approach_config_.weight_steer_rate();
  weight_rate_a_ = distance_approach_config_.weight_a_rate();
  weight_stitching_steer_ = distance_approach_config_.weight_steer_stitching();
  weight_stitching_a_ = distance_approach_config_.weight_a_stitching();
  weight_first_order_time_ =
      distance_approach_config_.weight_first_order_time();
  weight_second_order_time_ =
      distance_approach_config_.weight_second_order_time();
  min_safety_distance_ = distance_approach_config_.min_safety_distance();
  max_steer_angle_ =
      vehicle_param_.max_steer_angle() / vehicle_param_.steer_ratio();
  max_speed_forward_ = distance_approach_config_.max_speed_forward();
  max_speed_reverse_ = distance_approach_config_.max_speed_reverse();
  max_acceleration_forward_ =
      distance_approach_config_.max_acceleration_forward();
  max_acceleration_reverse_ =
      distance_approach_config_.max_acceleration_reverse();
  min_time_sample_scaling_ =
      distance_approach_config_.min_time_sample_scaling();
  max_time_sample_scaling_ =
      distance_approach_config_.max_time_sample_scaling();
  max_steer_rate_ =
      vehicle_param_.max_steer_angle_rate() / vehicle_param_.steer_ratio();
  use_fix_time_ = distance_approach_config_.use_fix_time();
  wheelbase_ = vehicle_param_.wheel_base();
  enable_constraint_check_ =
      distance_approach_config_.enable_constraint_check();
  enable_jacobian_ad_ = distance_approach_config_.enable_jacobian_ad();
}

bool DistanceApproachIPOPTFixedDualInterface::get_nlp_info(
    int& n, int& m, int& nnz_jac_g, int& nnz_h_lag,
    IndexStyleEnum& index_style) {
  ADEBUG << "get_nlp_info";
  // n1 : states variables, 4 * (N+1)
  int n1 = 4 * (horizon_ + 1);
  ADEBUG << "n1: " << n1;
  // n2 : control inputs variables
  int n2 = 2 * horizon_;
  ADEBUG << "n2: " << n2;
  // n3 : sampling time variables
  int n3 = horizon_ + 1;
  ADEBUG << "n3: " << n3;
  // n4 : dual multiplier associated with obstacle shape
  lambda_horizon_ = 0;
  // n5 : dual multipier associated with car shape, obstacles_num*4 * (N+1)
  miu_horizon_ = 0;

  // m1 : dynamics constatins
  int m1 = 4 * horizon_;
  // m2 : control rate constraints (only steering)
  int m2 = horizon_;
  // m3 : sampling time equality constraints
  int m3 = horizon_;
  // m4 : obstacle constraints
  // int m4 = 4 * obstacles_num_ * (horizon_ + 1);

  num_of_variables_ = n1 + n2 + n3;
  num_of_constraints_ = m1 + m2 + m3 + (num_of_variables_ - (horizon_ + 1) + 2);

  // number of variables
  n = num_of_variables_;
  ADEBUG << "num_of_variables_ " << num_of_variables_;
  // number of constraints
  m = num_of_constraints_;
  ADEBUG << "num_of_constraints_ " << num_of_constraints_;

  generate_tapes(n, m, &nnz_jac_g, &nnz_h_lag);

  index_style = IndexStyleEnum::C_STYLE;
  return true;
}

bool DistanceApproachIPOPTFixedDualInterface::get_bounds_info(
    int n, double* x_l, double* x_u, int m, double* g_l, double* g_u) {
  ADEBUG << "get_bounds_info";
  CHECK(XYbounds_.size() == 4)
      << "XYbounds_ size is not 4, but" << XYbounds_.size();

  // Variables: includes state, u, sample time and lagrange multipliers
  // 1. state variables, 4 * [0, horizon]
  // start point pose
  int variable_index = 0;
  for (int i = 0; i < 4; ++i) {
    x_l[i] = -2e19;
    x_u[i] = 2e19;
  }
  variable_index += 4;

  // During horizons, 2 ~ N-1
  for (int i = 1; i < horizon_; ++i) {
    // x
    x_l[variable_index] = -2e19;
    x_u[variable_index] = 2e19;

    // y
    x_l[variable_index + 1] = -2e19;
    x_u[variable_index + 1] = 2e19;

    // phi
    x_l[variable_index + 2] = -2e19;
    x_u[variable_index + 2] = 2e19;

    // v
    x_l[variable_index + 3] = -2e19;
    x_u[variable_index + 3] = 2e19;

    variable_index += 4;
  }

  // end point pose
  for (int i = 0; i < 4; ++i) {
    x_l[variable_index + i] = -2e19;
    x_u[variable_index + i] = 2e19;
  }
  variable_index += 4;
  ADEBUG << "variable_index after adding state variables : " << variable_index;

  // 2. control variables, 2 * [0, horizon_-1]
  for (int i = 0; i < horizon_; ++i) {
    // steer
    x_l[variable_index] = -2e19;
    x_u[variable_index] = 2e19;

    // a
    x_l[variable_index + 1] = -2e19;
    x_u[variable_index + 1] = 2e19;

    variable_index += 2;
  }
  ADEBUG << "variable_index after adding control variables : "
         << variable_index;

  // 3. sampling time variables, 1 * [0, horizon_]
  for (int i = 0; i < horizon_ + 1; ++i) {
    x_l[variable_index] = -2e19;
    x_u[variable_index] = 2e19;
    ++variable_index;
  }
  ADEBUG << "variable_index after adding sample time : " << variable_index;
  ADEBUG << "sample time fix time status is : " << use_fix_time_;

  // Constraints: includes four state Euler forward constraints, three
  // Obstacle related constraints

  // 1. dynamics constraints 4 * [0, horizons-1]
  int constraint_index = 0;
  for (int i = 0; i < 4 * horizon_; ++i) {
    g_l[i] = 0.0;
    g_u[i] = 0.0;
  }
  constraint_index += 4 * horizon_;

  ADEBUG << "constraint_index after adding Euler forward dynamics constraints: "
         << constraint_index;

  // 2. Control rate limit constraints, 1 * [0, horizons-1], only apply
  // steering rate as of now
  for (int i = 0; i < horizon_; ++i) {
    g_l[constraint_index] = -max_steer_rate_;
    g_u[constraint_index] = max_steer_rate_;
    ++constraint_index;
  }

  ADEBUG << "constraint_index after adding steering rate constraints: "
         << constraint_index;

  // 3. Time constraints 1 * [0, horizons-1]
  for (int i = 0; i < horizon_; ++i) {
    g_l[constraint_index] = 0.0;
    g_u[constraint_index] = 0.0;
    ++constraint_index;
  }

  ADEBUG << "constraint_index after adding time constraints: "
         << constraint_index;

  // 4. Three obstacles related equal constraints, one equality constraints,
  // [0, horizon_] * [0, obstacles_num_-1] * 4

  // 5. load variable bounds as constraints
  // start configuration
  g_l[constraint_index] = x0_(0, 0);
  g_u[constraint_index] = x0_(0, 0);
  g_l[constraint_index + 1] = x0_(1, 0);
  g_u[constraint_index + 1] = x0_(1, 0);
  g_l[constraint_index + 2] = x0_(2, 0);
  g_u[constraint_index + 2] = x0_(2, 0);
  g_l[constraint_index + 3] = x0_(3, 0);
  g_u[constraint_index + 3] = x0_(3, 0);
  constraint_index += 4;

  for (int i = 1; i < horizon_; ++i) {
    g_l[constraint_index] = XYbounds_[0];
    g_u[constraint_index] = XYbounds_[1];
    g_l[constraint_index + 1] = XYbounds_[2];
    g_u[constraint_index + 1] = XYbounds_[3];
    g_l[constraint_index + 2] = -max_speed_reverse_;
    g_u[constraint_index + 2] = max_speed_forward_;
    constraint_index += 3;
  }

  // end configuration
  g_l[constraint_index] = xf_(0, 0);
  g_u[constraint_index] = xf_(0, 0);
  g_l[constraint_index + 1] = xf_(1, 0);
  g_u[constraint_index + 1] = xf_(1, 0);
  g_l[constraint_index + 2] = xf_(2, 0);
  g_u[constraint_index + 2] = xf_(2, 0);
  g_l[constraint_index + 3] = xf_(3, 0);
  g_u[constraint_index + 3] = xf_(3, 0);
  constraint_index += 4;

  for (int i = 0; i < horizon_; ++i) {
    g_l[constraint_index] = -max_steer_angle_;
    g_u[constraint_index] = max_steer_angle_;
    g_l[constraint_index + 1] = -max_acceleration_reverse_;
    g_u[constraint_index + 1] = max_acceleration_forward_;
    constraint_index += 2;
  }

  for (int i = 0; i < horizon_ + 1; ++i) {
    if (!use_fix_time_) {
      g_l[constraint_index] = min_time_sample_scaling_;
      g_u[constraint_index] = max_time_sample_scaling_;
    } else {
      g_l[constraint_index] = 1.0;
      g_u[constraint_index] = 1.0;
    }
    constraint_index++;
  }

  ADEBUG << "constraint_index after adding obstacles constraints: "
         << constraint_index;
  ADEBUG << "get_bounds_info_ out";
  return true;
}

bool DistanceApproachIPOPTFixedDualInterface::get_starting_point(
    int n, bool init_x, double* x, bool init_z, double* z_L, double* z_U, int m,
    bool init_lambda, double* lambda) {
  ADEBUG << "get_starting_point";
  CHECK(init_x) << "Warm start init_x setting failed";

  CHECK_EQ(horizon_, uWS_.cols());
  CHECK_EQ(horizon_ + 1, xWS_.cols());

  // 1. state variables 4 * (horizon_ + 1)
  for (int i = 0; i < horizon_ + 1; ++i) {
    int index = i * 4;
    for (int j = 0; j < 4; ++j) {
      x[index + j] = xWS_(j, i);
    }
  }

  // 2. control variable initialization, 2 * horizon_
  for (int i = 0; i < horizon_; ++i) {
    int index = i * 2;
    x[control_start_index_ + index] = uWS_(0, i);
    x[control_start_index_ + index + 1] = uWS_(1, i);
  }

  // 3. time scale variable initialization, horizon_ + 1
  for (int i = 0; i < horizon_ + 1; ++i) {
    x[time_start_index_ + i] =
        0.5 * (min_time_sample_scaling_ + max_time_sample_scaling_);
  }

  // check initial states
  if (distance_approach_config_.enable_check_initial_state()) {
    int kM = m;
    double g[kM];
    eval_g(n, x, true, m, g);
    check_g(n, x, m, g);
  }

  ADEBUG << "get_starting_point out";
  return true;
}

bool DistanceApproachIPOPTFixedDualInterface::eval_f(int n, const double* x,
                                                     bool new_x,
                                                     double& obj_value) {
  eval_obj(n, x, &obj_value);
  return true;
}

bool DistanceApproachIPOPTFixedDualInterface::eval_grad_f(int n,
                                                          const double* x,
                                                          bool new_x,
                                                          double* grad_f) {
  gradient(tag_f, n, x, grad_f);
  return true;
}

bool DistanceApproachIPOPTFixedDualInterface::eval_g(int n, const double* x,
                                                     bool new_x, int m,
                                                     double* g) {
  eval_constraints(n, x, m, g);
  // if (enable_constraint_check_) check_g(n, x, m, g);
  return true;
}

bool DistanceApproachIPOPTFixedDualInterface::eval_jac_g(int n, const double* x,
                                                         bool new_x, int m,
                                                         int nele_jac,
                                                         int* iRow, int* jCol,
                                                         double* values) {
  if (values == nullptr) {
    ADEBUG << "nnz_jac: " << nnz_jac;
    // return the structure of the jacobian
    for (int idx = 0; idx < nnz_jac; idx++) {
      iRow[idx] = rind_g[idx];
      jCol[idx] = cind_g[idx];
    }
  } else {
    // return the values of the jacobian of the constraints
    sparse_jac(tag_g, m, n, 1, x, &nnz_jac, &rind_g, &cind_g, &jacval,
               options_g);
    for (int idx = 0; idx < nnz_jac; idx++) {
      values[idx] = jacval[idx];
    }
  }
  return true;
}

bool DistanceApproachIPOPTFixedDualInterface::eval_jac_g_ser(
    int n, const double* x, bool new_x, int m, int nele_jac, int* iRow,
    int* jCol, double* values) {
  AERROR << "not ready ATM!";
  return false;
}

bool DistanceApproachIPOPTFixedDualInterface::eval_h(
    int n, const double* x, bool new_x, double obj_factor, int m,
    const double* lambda, bool new_lambda, int nele_hess, int* iRow, int* jCol,
    double* values) {
  if (values == nullptr) {
    // return the structure. This is a symmetric matrix, fill the lower left
    // triangle only.

    for (int idx = 0; idx < nnz_L; idx++) {
      iRow[idx] = rind_L[idx];
      jCol[idx] = cind_L[idx];
    }
  } else {
    // return the values. This is a symmetric matrix, fill the lower left
    // triangle only

    obj_lam[0] = obj_factor;

    for (int idx = 0; idx < m; idx++) {
      obj_lam[1 + idx] = lambda[idx];
    }

    set_param_vec(tag_L, m + 1, obj_lam);
    sparse_hess(tag_L, n, 1, const_cast<double*>(x), &nnz_L, &rind_L, &cind_L,
                &hessval, options_L);

    for (int idx = 0; idx < nnz_L; idx++) {
      values[idx] = hessval[idx];
    }
  }

  return true;
}

void DistanceApproachIPOPTFixedDualInterface::finalize_solution(
    Ipopt::SolverReturn status, int n, const double* x, const double* z_L,
    const double* z_U, int m, const double* g, const double* lambda,
    double obj_value, const Ipopt::IpoptData* ip_data,
    Ipopt::IpoptCalculatedQuantities* ip_cq) {
  int state_index = state_start_index_;
  int control_index = control_start_index_;
  int time_index = time_start_index_;
  int dual_l_index = l_start_index_;
  int dual_n_index = n_start_index_;

  // enable_constraint_check_: for debug only
  if (enable_constraint_check_) {
    ADEBUG << "final resolution constraint checking";
    check_g(n, x, m, g);
  }
  // 1. state variables, 4 * [0, horizon]
  // 2. control variables, 2 * [0, horizon_-1]
  // 3. sampling time variables, 1 * [0, horizon_]
  // 4. dual_l obstacles_edges_sum_ * [0, horizon]
  // 5. dual_n obstacles_num * [0, horizon]
  for (int i = 0; i < horizon_; ++i) {
    state_result_(0, i) = x[state_index];
    state_result_(1, i) = x[state_index + 1];
    state_result_(2, i) = x[state_index + 2];
    state_result_(3, i) = x[state_index + 3];
    control_result_(0, i) = x[control_index];
    control_result_(1, i) = x[control_index + 1];
    time_result_(0, i) = ts_ * x[time_index];
    for (int j = 0; j < obstacles_edges_sum_; ++j) {
      dual_l_result_(j, i) = x[dual_l_index + j];
    }
    for (int k = 0; k < 4 * obstacles_num_; k++) {
      dual_n_result_(k, i) = x[dual_n_index + k];
    }
    state_index += 4;
    control_index += 2;
    time_index++;
    dual_l_index += obstacles_edges_sum_;
    dual_n_index += 4 * obstacles_num_;
  }
  state_result_(0, 0) = x0_(0, 0);
  state_result_(1, 0) = x0_(1, 0);
  state_result_(2, 0) = x0_(2, 0);
  state_result_(3, 0) = x0_(3, 0);
  // push back last horizon for states
  state_result_(0, horizon_) = xf_(0, 0);
  state_result_(1, horizon_) = xf_(1, 0);
  state_result_(2, horizon_) = xf_(2, 0);
  state_result_(3, horizon_) = xf_(3, 0);

  for (int j = 0; j < obstacles_edges_sum_; ++j) {
    dual_l_result_(j, horizon_) = 0.0;
  }
  for (int k = 0; k < 4 * obstacles_num_; k++) {
    dual_n_result_(k, horizon_) = 0.0;
  }
  // memory deallocation of ADOL-C variables
  delete[] obj_lam;

  free(rind_g);
  free(cind_g);
  free(jacval);

  free(rind_L);
  free(cind_L);
  free(hessval);
}

void DistanceApproachIPOPTFixedDualInterface::get_optimization_results(
    Eigen::MatrixXd* state_result, Eigen::MatrixXd* control_result,
    Eigen::MatrixXd* time_result, Eigen::MatrixXd* dual_l_result,
    Eigen::MatrixXd* dual_n_result) const {
  ADEBUG << "get_optimization_results";
  *state_result = state_result_;
  *control_result = control_result_;
  *time_result = time_result_;
  *dual_l_result = dual_l_result_;
  *dual_n_result = dual_n_result_;

  if (!distance_approach_config_.enable_initial_final_check()) return;
  CHECK_EQ(state_result_.cols(), xWS_.cols());
  CHECK_EQ(state_result_.rows(), xWS_.rows());
  double state_diff_max = 0.0;
  for (int i = 0; i < horizon_ + 1; ++i) {
    for (int j = 0; j < 4; ++j) {
      state_diff_max =
          std::max(std::abs(xWS_(j, i) - state_result_(j, i)), state_diff_max);
    }
  }

  // 2. control variable initialization, 2 * horizon_
  CHECK_EQ(control_result_.cols(), uWS_.cols());
  CHECK_EQ(control_result_.rows(), uWS_.rows());
  double control_diff_max = 0.0;
  for (int i = 0; i < horizon_; ++i) {
    control_diff_max = std::max(std::abs(uWS_(0, i) - control_result_(0, i)),
                                control_diff_max);
    control_diff_max = std::max(std::abs(uWS_(1, i) - control_result_(1, i)),
                                control_diff_max);
  }

  // 2. time scale variable initialization, horizon_ + 1

  // 3. lagrange constraint l, obstacles_edges_sum_ * (horizon_+1)
  CHECK_EQ(dual_l_result_.cols(), l_warm_up_.cols());
  CHECK_EQ(dual_l_result_.rows(), l_warm_up_.rows());
  double l_diff_max = 0.0;
  for (int i = 0; i < horizon_ + 1; ++i) {
    for (int j = 0; j < obstacles_edges_sum_; ++j) {
      l_diff_max = std::max(std::abs(l_warm_up_(j, i) - dual_l_result_(j, i)),
                            l_diff_max);
    }
  }

  // 4. lagrange constraint m, 4*obstacles_num * (horizon_+1)
  CHECK_EQ(n_warm_up_.cols(), dual_n_result_.cols());
  CHECK_EQ(n_warm_up_.rows(), dual_n_result_.rows());
  double n_diff_max = 0.0;
  for (int i = 0; i < horizon_ + 1; ++i) {
    for (int j = 0; j < 4 * obstacles_num_; ++j) {
      n_diff_max = std::max(std::abs(n_warm_up_(j, i) - dual_n_result_(j, i)),
                            n_diff_max);
    }
  }

  ADEBUG << "state_diff_max: " << state_diff_max;
  ADEBUG << "control_diff_max: " << control_diff_max;
  ADEBUG << "dual_l_diff_max: " << l_diff_max;
  ADEBUG << "dual_n_diff_max: " << n_diff_max;
}

//***************    start ADOL-C part ***********************************
template <class T>
void DistanceApproachIPOPTFixedDualInterface::eval_obj(int n, const T* x,
                                                       T* obj_value) {
  // Objective is :
  // min control inputs
  // min input rate
  // min time (if the time step is not fixed)
  // regularization wrt warm start trajectory
  DCHECK(ts_ != 0) << "ts in distance_approach_ is 0";
  int control_index = control_start_index_;
  int time_index = time_start_index_;
  int state_index = state_start_index_;

  // TODO(QiL): Initial implementation towards earlier understanding and debug
  // purpose, later code refine towards improving efficiency

  *obj_value = 0.0;
  // 1. objective to minimize state diff to warm up
  for (int i = 0; i < horizon_ + 1; ++i) {
    T x1_diff = x[state_index] - xWS_(0, i);
    T x2_diff = x[state_index + 1] - xWS_(1, i);
    T x3_diff = x[state_index + 2] - xWS_(2, i);
    T x4_abs = x[state_index + 3];
    *obj_value += weight_state_x_ * x1_diff * x1_diff +
                  weight_state_y_ * x2_diff * x2_diff +
                  weight_state_phi_ * x3_diff * x3_diff +
                  weight_state_v_ * x4_abs * x4_abs;
    state_index += 4;
  }

  // 2. objective to minimize u square
  for (int i = 0; i < horizon_; ++i) {
    *obj_value += weight_input_steer_ * x[control_index] * x[control_index] +
                  weight_input_a_ * x[control_index + 1] * x[control_index + 1];
    control_index += 2;
  }

  // 3. objective to minimize input change rate for first horizon
  control_index = control_start_index_;
  T last_time_steer_rate =
      (x[control_index] - last_time_u_(0, 0)) / x[time_index] / ts_;
  T last_time_a_rate =
      (x[control_index + 1] - last_time_u_(1, 0)) / x[time_index] / ts_;
  *obj_value +=
      weight_stitching_steer_ * last_time_steer_rate * last_time_steer_rate +
      weight_stitching_a_ * last_time_a_rate * last_time_a_rate;

  // 4. objective to minimize input change rates, [0- horizon_ -2]
  time_index++;
  for (int i = 0; i < horizon_ - 1; ++i) {
    T steering_rate =
        (x[control_index + 2] - x[control_index]) / x[time_index] / ts_;
    T a_rate =
        (x[control_index + 3] - x[control_index + 1]) / x[time_index] / ts_;
    *obj_value += weight_rate_steer_ * steering_rate * steering_rate +
                  weight_rate_a_ * a_rate * a_rate;
    control_index += 2;
    time_index++;
  }

  // 5. objective to minimize total time [0, horizon_]
  time_index = time_start_index_;
  for (int i = 0; i < horizon_ + 1; ++i) {
    T first_order_penalty = weight_first_order_time_ * x[time_index];
    T second_order_penalty =
        weight_second_order_time_ * x[time_index] * x[time_index];
    *obj_value += first_order_penalty + second_order_penalty;
    time_index++;
  }
}

template <class T>
void DistanceApproachIPOPTFixedDualInterface::eval_constraints(int n,
                                                               const T* x,
                                                               int m, T* g) {
  // state start index
  int state_index = state_start_index_;

  // control start index.
  int control_index = control_start_index_;

  // time start index
  int time_index = time_start_index_;

  int constraint_index = 0;

  // 1. state constraints 4 * [0, horizons-1]
  for (int i = 0; i < horizon_; ++i) {
    // x1
    g[constraint_index] =
        x[state_index + 4] -
        (x[state_index] +
         ts_ * x[time_index] *
             (x[state_index + 3] +
              ts_ * x[time_index] * 0.5 * x[control_index + 1]) *
             cos(x[state_index + 2] + ts_ * x[time_index] * 0.5 *
                                          x[state_index + 3] *
                                          tan(x[control_index]) / wheelbase_));

    // x2
    g[constraint_index + 1] =
        x[state_index + 5] -
        (x[state_index + 1] +
         ts_ * x[time_index] *
             (x[state_index + 3] +
              ts_ * x[time_index] * 0.5 * x[control_index + 1]) *
             sin(x[state_index + 2] + ts_ * x[time_index] * 0.5 *
                                          x[state_index + 3] *
                                          tan(x[control_index]) / wheelbase_));

    // x3
    g[constraint_index + 2] =
        x[state_index + 6] -
        (x[state_index + 2] +
         ts_ * x[time_index] *
             (x[state_index + 3] +
              ts_ * x[time_index] * 0.5 * x[control_index + 1]) *
             tan(x[control_index]) / wheelbase_);

    // x4
    g[constraint_index + 3] =
        x[state_index + 7] -
        (x[state_index + 3] + ts_ * x[time_index] * x[control_index + 1]);

    control_index += 2;
    constraint_index += 4;
    time_index++;
    state_index += 4;
  }

  ADEBUG << "constraint_index after adding Euler forward dynamics constraints "
            "updated: "
         << constraint_index;

  // 2. Control rate limit constraints, 1 * [0, horizons-1], only apply
  // steering rate as of now
  control_index = control_start_index_;
  time_index = time_start_index_;

  // First rate is compare first with stitch point
  g[constraint_index] =
      (x[control_index] - last_time_u_(0, 0)) / x[time_index] / ts_;
  control_index += 2;
  constraint_index++;
  time_index++;

  for (int i = 1; i < horizon_; ++i) {
    g[constraint_index] =
        (x[control_index] - x[control_index - 2]) / x[time_index] / ts_;
    constraint_index++;
    control_index += 2;
    time_index++;
  }

  // 3. Time constraints 1 * [0, horizons-1]
  time_index = time_start_index_;
  for (int i = 0; i < horizon_; ++i) {
    g[constraint_index] = x[time_index + 1] - x[time_index];
    constraint_index++;
    time_index++;
  }

  ADEBUG << "constraint_index after adding time constraints "
            "updated: "
         << constraint_index;

  // 4. Three obstacles related equal constraints, one equality constraints,
  // [0, horizon_] * [0, obstacles_num_-1] * 4
  state_index = state_start_index_;

  // 5. load variable bounds as constraints
  state_index = state_start_index_;
  control_index = control_start_index_;
  time_index = time_start_index_;

  // start configuration
  g[constraint_index] = x[state_index];
  g[constraint_index + 1] = x[state_index + 1];
  g[constraint_index + 2] = x[state_index + 2];
  g[constraint_index + 3] = x[state_index + 3];
  constraint_index += 4;
  state_index += 4;

  // constraints on x,y,v
  for (int i = 1; i < horizon_; ++i) {
    g[constraint_index] = x[state_index];
    g[constraint_index + 1] = x[state_index + 1];
    g[constraint_index + 2] = x[state_index + 3];
    constraint_index += 3;
    state_index += 4;
  }

  // end configuration
  g[constraint_index] = x[state_index];
  g[constraint_index + 1] = x[state_index + 1];
  g[constraint_index + 2] = x[state_index + 2];
  g[constraint_index + 3] = x[state_index + 3];
  constraint_index += 4;
  state_index += 4;

  for (int i = 0; i < horizon_; ++i) {
    g[constraint_index] = x[control_index];
    g[constraint_index + 1] = x[control_index + 1];
    constraint_index += 2;
    control_index += 2;
  }

  for (int i = 0; i < horizon_ + 1; ++i) {
    g[constraint_index] = x[time_index];
    constraint_index++;
    time_index++;
  }

  ADEBUG << "constraint_index after adding variable box constraints "
            "updated: "
         << constraint_index;
}

bool DistanceApproachIPOPTFixedDualInterface::check_g(int n, const double* x,
                                                      int m, const double* g) {
  int kN = n;
  int kM = m;
  double x_u_tmp[kN];
  double x_l_tmp[kN];
  double g_u_tmp[kM];
  double g_l_tmp[kM];

  get_bounds_info(n, x_l_tmp, x_u_tmp, m, g_l_tmp, g_u_tmp);

  const double delta_v = 1e-4;
  for (int idx = 0; idx < n; ++idx) {
    x_u_tmp[idx] = x_u_tmp[idx] + delta_v;
    x_l_tmp[idx] = x_l_tmp[idx] - delta_v;
    if (x[idx] > x_u_tmp[idx] || x[idx] < x_l_tmp[idx]) {
      AINFO << "x idx unfeasible: " << idx << ", x: " << x[idx]
            << ", lower: " << x_l_tmp[idx] << ", upper: " << x_u_tmp[idx];
    }
  }

  // m1 : dynamics constatins
  int m1 = 4 * horizon_;

  // m2 : control rate constraints (only steering)
  int m2 = m1 + horizon_;

  // m3 : sampling time equality constraints
  int m3 = m2 + horizon_;

  // m4 : obstacle constraints
  // int m4 = m3 + 4 * obstacles_num_ * (horizon_ + 1);

  // 5. load variable bounds as constraints
  // start configuration
  int m5 = m3 + 3 + 1;

  // constraints on x,y,v
  int m6 = m5 + 3 * (horizon_ - 1);

  // end configuration
  int m7 = m6 + 3 + 1;

  // control variable bnd
  int m8 = m7 + 2 * horizon_;

  // time interval variable bnd
  int m9 = m8 + (horizon_ + 1);

  // lambda_horizon_
  // int m10 = m9 + lambda_horizon_;

  // miu_horizon_
  // int m11 = m10 + miu_horizon_;

  CHECK_EQ(m9, num_of_constraints_);

  AINFO << "dynamics constatins to: " << m1;
  AINFO << "control rate constraints (only steering) to: " << m2;
  AINFO << "sampling time equality constraints to: " << m3;
  AINFO << "start conf constraints to: " << m5;
  AINFO << "constraints on x,y,v to: " << m6;
  AINFO << "end constraints to: " << m7;
  AINFO << "control bnd to: " << m8;
  AINFO << "time interval constraints to: " << m9;
  AINFO << "total constraints: " << num_of_constraints_;

  for (int idx = 0; idx < m; ++idx) {
    if (g[idx] > g_u_tmp[idx] + delta_v || g[idx] < g_l_tmp[idx] - delta_v) {
      AINFO << "constratins idx unfeasible: " << idx << ", g: " << g[idx]
            << ", lower: " << g_l_tmp[idx] << ", upper: " << g_u_tmp[idx];
    }
  }
  return true;
}

void DistanceApproachIPOPTFixedDualInterface::generate_tapes(int n, int m,
                                                             int* nnz_jac_g,
                                                             int* nnz_h_lag) {
  std::vector<double> xp(n);
  std::vector<double> lamp(m);
  std::vector<double> zl(m);
  std::vector<double> zu(m);
  std::vector<adouble> xa(n);
  std::vector<adouble> g(m);
  std::vector<double> lam(m);

  double sig;
  adouble obj_value;
  double dummy = 0.0;
  obj_lam = new double[m + 1];
  get_starting_point(n, 1, &xp[0], 0, &zl[0], &zu[0], m, 0, &lamp[0]);

  trace_on(tag_f);
  for (int idx = 0; idx < n; idx++) {
    xa[idx] <<= xp[idx];
  }
  eval_obj(n, &xa[0], &obj_value);
  obj_value >>= dummy;
  trace_off();

  trace_on(tag_g);
  for (int idx = 0; idx < n; idx++) {
    xa[idx] <<= xp[idx];
  }
  eval_constraints(n, &xa[0], m, &g[0]);
  for (int idx = 0; idx < m; idx++) {
    g[idx] >>= dummy;
  }
  trace_off();

  trace_on(tag_L);
  for (int idx = 0; idx < n; idx++) {
    xa[idx] <<= xp[idx];
  }
  for (int idx = 0; idx < m; idx++) {
    lam[idx] = 1.0;
  }
  sig = 1.0;
  eval_obj(n, &xa[0], &obj_value);
  obj_value *= mkparam(sig);
  eval_constraints(n, &xa[0], m, &g[0]);
  for (int idx = 0; idx < m; idx++) {
    obj_value += g[idx] * mkparam(lam[idx]);
  }
  obj_value >>= dummy;

  trace_off();

  rind_g = nullptr;
  cind_g = nullptr;
  jacval = nullptr;
  options_g[0] = 0; /* sparsity pattern by index domains (default) */
  options_g[1] = 0; /*                         safe mode (default) */
  options_g[2] = 0;
  options_g[3] = 0; /*                column compression (default) */

  sparse_jac(tag_g, m, n, 0, &xp[0], &nnz_jac, &rind_g, &cind_g, &jacval,
             options_g);
  *nnz_jac_g = nnz_jac;

  rind_L = nullptr;
  cind_L = nullptr;
  hessval = nullptr;
  options_L[0] = 0;
  options_L[1] = 1;

  sparse_hess(tag_L, n, 0, &xp[0], &nnz_L, &rind_L, &cind_L, &hessval,
              options_L);
  *nnz_h_lag = nnz_L;
}
//***************    end   ADOL-C part ***********************************

}  // namespace planning
}  // namespace apollo


text:
<!doctype html>

		<meta charset="utf-8">
		<title>VanillaJS • TodoMVC</title>
		<link rel="stylesheet" href="node_modules/todomvc-common/base.css">
		<link rel="stylesheet" href="node_modules/todomvc-app-css/index.css">

todos

				<input class="new-todo" placeholder="What needs to be done?" autofocus>

				<input class="toggle-all" type="checkbox">
				Mark all as complete

						All

						Active

						Completed

				<button class="clear-completed">Clear completed</button>

Double-click to edit a todo

Created by Oscar Godson

Refactored by Christoph Burgmer

Part of TodoMVC