text:
// GUI Animator FREE
// Version: 1.0.1
// Unity 4.7.1 or higher and Unity 5.3.4 or higher compatilble, see more info in Readme.txt file.
//
// Author:				Gold Experience Team (http://www.ge-team.com)
//
// Unity Asset Store:					https://www.assetstore.unity3d.com/en/#!/content/58843
// GE Store:							http://www.ge-team.com/store/en/products/gui-animator-free/
// Full version on Unity Asset Store:	https://www.assetstore.unity3d.com/en/#!/content/28709
// Full version on GE Store:			http://www.ge-team.com/store/en/products/gui-animator-for-unity-ui/
//
// Please direct any bugs/comments/suggestions to geteamdev@gmail.com

#region Namespaces

using UnityEngine;
using System.Collections;

#endregion // Namespaces

// ######################################################################
// GA_FREE_Demo06a class
// - Animates all GUIAnimFREE elements in the scene.
// - Responds to user mouse click or tap on buttons.
//
// Note this class is attached with "-SceneController-" object in "GA FREE - Demo06 (960x600px)" scene.
// ######################################################################

public class GA_FREE_Demo06a : MonoBehaviour
{

	// ########################################
	// Variables
	// ########################################

	#region Variables

	// Canvas
	public Canvas m_Canvas;

	// GUIAnimFREE objects of title text
	public GUIAnimFREE m_Title1;
	public GUIAnimFREE m_Title2;

	// GUIAnimFREE objects of top and bottom bars
	public GUIAnimFREE m_TopBar;
	public GUIAnimFREE m_BottomBar;

	// GUIAnimFREE objects of primary buttons
	public GUIAnimFREE m_PrimaryButton1;
	public GUIAnimFREE m_PrimaryButton2;
	public GUIAnimFREE m_PrimaryButton3;
	public GUIAnimFREE m_PrimaryButton4;
	public GUIAnimFREE m_PrimaryButton5;

	// GUIAnimFREE objects of secondary buttons
	public GUIAnimFREE m_SecondaryButton1;
	public GUIAnimFREE m_SecondaryButton2;
	public GUIAnimFREE m_SecondaryButton3;
	public GUIAnimFREE m_SecondaryButton4;
	public GUIAnimFREE m_SecondaryButton5;
    public GUIAnimFREE m_Button5_Tertiary1;
    public GUIAnimFREE m_Button5_Tertiary2;
    public GUIAnimFREE m_Button5_Tertiary3;
    public GUIAnimFREE m_Button5_Tertiary4;
    public GUIAnimFREE m_Button5_Tertiary5;

    // Toggle state of buttons
    bool m_Button1_IsOn = false;
	bool m_Button2_IsOn = false;
	bool m_Button3_IsOn = false;
	bool m_Button4_IsOn = false;
	bool m_Button5_IsOn = false;
    bool m_Button5_Tertiary1_IsOn = false;
    bool m_Button5_Tertiary2_IsOn = false;
    bool m_Button5_Tertiary3_IsOn = false;
    bool m_Button5_Tertiary4_IsOn = false;
    bool m_Button5_Tertiary5_IsOn = false;

    #endregion // Variables

    // ########################################
    // MonoBehaviour Functions
    // http://docs.unity3d.com/ScriptReference/MonoBehaviour.html
    // ########################################

    #region MonoBehaviour

    // Awake is called when the script instance is being loaded.
    // http://docs.unity3d.com/ScriptReference/MonoBehaviour.Awake.html
    void Awake ()
	{
		if(enabled)
		{
			// Set GUIAnimSystemFREE.Instance.m_AutoAnimation to false in Awake() will let you control all GUI Animator elements in the scene via scripts.
			GUIAnimSystemFREE.Instance.m_AutoAnimation = false;
		}
	}

	// Start is called on the frame when a script is enabled just before any of the Update methods is called the first time.
	// http://docs.unity3d.com/ScriptReference/MonoBehaviour.Start.html
	void Start ()
	{
		// MoveIn m_TopBar and m_BottomBar
		//m_TopBar.MoveIn(GUIAnimSystemFREE.eGUIMove.SelfAndChildren);
		//m_BottomBar.MoveIn(GUIAnimSystemFREE.eGUIMove.SelfAndChildren);

		// MoveIn m_Title1 m_Title2
		StartCoroutine(MoveInTitleGameObjects());

		// Disable all scene switch buttons
		// http://docs.unity3d.com/Manual/script-GraphicRaycaster.html
		GUIAnimSystemFREE.Instance.SetGraphicRaycasterEnable(m_Canvas, false);
	}

	// Update is called every frame, if the MonoBehaviour is enabled.
	// http://docs.unity3d.com/ScriptReference/MonoBehaviour.Update.html
	void Update ()
	{

	}

	#endregion // MonoBehaviour

	// ########################################
	// MoveIn/MoveOut functions
	// ########################################

	#region MoveIn/MoveOut

	// Move In m_Title1 and m_Title2
	IEnumerator MoveInTitleGameObjects()
	{
		yield return new WaitForSeconds(1.0f);

		// Move In m_Title1 and m_Title2
		//m_Title1.MoveIn(GUIAnimSystemFREE.eGUIMove.Self);
		//m_Title2.MoveIn(GUIAnimSystemFREE.eGUIMove.Self);

		// MoveIn dialogs
		StartCoroutine(MoveInPrimaryButtons());

		// Enable all scene switch buttons
		// http://docs.unity3d.com/Manual/script-GraphicRaycaster.html
		GUIAnimSystemFREE.Instance.SetGraphicRaycasterEnable(m_Canvas, true);
	}

	// MoveIn all primary buttons
	IEnumerator MoveInPrimaryButtons()
	{
		yield return new WaitForSeconds(1.0f);

		// MoveIn all primary buttons
//		m_PrimaryButton1.MoveIn(GUIAnimSystemFREE.eGUIMove.Self);
//		m_PrimaryButton2.MoveIn(GUIAnimSystemFREE.eGUIMove.Self);
//		m_PrimaryButton3.MoveIn(GUIAnimSystemFREE.eGUIMove.Self);
//		m_PrimaryButton4.MoveIn(GUIAnimSystemFREE.eGUIMove.Self);

		m_PrimaryButton5.MoveIn(GUIAnimSystemFREE.eGUIMove.Self);

		// Enable all scene switch buttons
		StartCoroutine(EnableAllDemoButtons());
	}

	// MoveOut all primary buttons
	public void HideAllGUIs()
	{
		// MoveOut all primary buttons
		m_PrimaryButton1.MoveOut(GUIAnimSystemFREE.eGUIMove.SelfAndChildren);
		m_PrimaryButton2.MoveOut(GUIAnimSystemFREE.eGUIMove.SelfAndChildren);
		m_PrimaryButton3.MoveOut(GUIAnimSystemFREE.eGUIMove.SelfAndChildren);
		m_PrimaryButton4.MoveOut(GUIAnimSystemFREE.eGUIMove.SelfAndChildren);
		m_PrimaryButton5.MoveOut(GUIAnimSystemFREE.eGUIMove.SelfAndChildren);

		// MoveOut all secondary buttons
		if(m_Button1_IsOn == true)
			m_SecondaryButton1.MoveOut(GUIAnimSystemFREE.eGUIMove.SelfAndChildren);
		if(m_Button2_IsOn == true)
			m_SecondaryButton2.MoveOut(GUIAnimSystemFREE.eGUIMove.SelfAndChildren);
		if(m_Button3_IsOn == true)
			m_SecondaryButton3.MoveOut(GUIAnimSystemFREE.eGUIMove.SelfAndChildren);
		if(m_Button4_IsOn == true)
			m_SecondaryButton4.MoveOut(GUIAnimSystemFREE.eGUIMove.SelfAndChildren);
		if(m_Button5_IsOn == true)
			m_SecondaryButton5.MoveOut(GUIAnimSystemFREE.eGUIMove.SelfAndChildren);

        if (m_Button5_Tertiary1_IsOn == true)
            m_Button5_Tertiary1.MoveOut(GUIAnimSystemFREE.eGUIMove.SelfAndChildren);
        if (m_Button5_Tertiary2_IsOn == true)
            m_Button5_Tertiary2.MoveOut(GUIAnimSystemFREE.eGUIMove.SelfAndChildren);
        if (m_Button5_Tertiary3_IsOn == true)
            m_Button5_Tertiary3.MoveOut(GUIAnimSystemFREE.eGUIMove.SelfAndChildren);
        if (m_Button5_Tertiary4_IsOn == true)
            m_Button5_Tertiary4.MoveOut(GUIAnimSystemFREE.eGUIMove.SelfAndChildren);
        if (m_Button5_Tertiary5_IsOn == true)
            m_Button5_Tertiary5.MoveOut(GUIAnimSystemFREE.eGUIMove.SelfAndChildren);

        // MoveOut m_Title1 and m_Title2
        StartCoroutine(HideTitleTextMeshes());
	}

	// MoveOut m_Title1 and m_Title2
	IEnumerator HideTitleTextMeshes()
	{
		yield return new WaitForSeconds(1.0f);

		// MoveOut m_Title1 and m_Title2
		m_Title1.MoveOut(GUIAnimSystemFREE.eGUIMove.Self);
		m_Title2.MoveOut(GUIAnimSystemFREE.eGUIMove.Self);

		// MoveOut m_TopBar and m_BottomBar
		m_TopBar.MoveOut(GUIAnimSystemFREE.eGUIMove.SelfAndChildren);
		m_BottomBar.MoveOut(GUIAnimSystemFREE.eGUIMove.SelfAndChildren);
	}

	#endregion // MoveIn/MoveOut

	// ########################################
	// Enable/Disable button functions
	// ########################################

	#region Enable/Disable buttons

	// Enable/Disable all scene switch Coroutine
	IEnumerator EnableAllDemoButtons()
	{
		yield return new WaitForSeconds(1.0f);

		// Enable all scene switch buttons
		// http://docs.unity3d.com/Manual/script-GraphicRaycaster.html
		GUIAnimSystemFREE.Instance.SetGraphicRaycasterEnable(m_Canvas, true);
	}

	// Disable all buttons for a few seconds
	IEnumerator DisableAllButtonsForSeconds(float DisableTime)
	{
		// Disable all buttons
		GUIAnimSystemFREE.Instance.EnableAllButtons(false);

		yield return new WaitForSeconds(DisableTime);

		// Enable all buttons
		GUIAnimSystemFREE.Instance.EnableAllButtons(true);
	}

	#endregion // Enable/Disable buttons

	// ########################################
	// UI Responder functions
	// ########################################

	#region UI Responder

	public void OnButton_1()
	{
		// Disable all buttons for a few seconds
		StartCoroutine(DisableAllButtonsForSeconds(0.45f));

		// Toggle m_Button1
		ToggleButton_1();

		// Toggle other buttons
		if(m_Button2_IsOn==true)
		{
			ToggleButton_2();
		}
		if(m_Button3_IsOn==true)
		{
			ToggleButton_3();
		}
		if(m_Button4_IsOn==true)
		{
			ToggleButton_4();
		}
		if(m_Button5_IsOn==true)
		{
			ToggleButton_5();
		}
	}

	public void OnButton_2()
	{
		// Disable all buttons for a few seconds
		StartCoroutine(DisableAllButtonsForSeconds(0.45f));

		// Toggle m_Button2
		ToggleButton_2();

		// Toggle other buttons
		if(m_Button1_IsOn==true)
		{
			ToggleButton_1();
		}
		if(m_Button3_IsOn==true)
		{
			ToggleButton_3();
		}
		if(m_Button4_IsOn==true)
		{
			ToggleButton_4();
		}
		if(m_Button5_IsOn==true)
		{
			ToggleButton_5();
		}
	}

	public void OnButton_3()
	{
		// Disable all buttons for a few seconds
		StartCoroutine(DisableAllButtonsForSeconds(0.45f));

		// Toggle m_Button3
		ToggleButton_3();

		// Toggle other buttons
		if(m_Button1_IsOn==true)
		{
			ToggleButton_1();
		}
		if(m_Button2_IsOn==true)
		{
			ToggleButton_2();
		}
		if(m_Button4_IsOn==true)
		{
			ToggleButton_4();
		}
		if(m_Button5_IsOn==true)
		{
			ToggleButton_5();
		}
	}

	public void OnButton_4()
	{
		// Disable all buttons for a few seconds
		StartCoroutine(DisableAllButtonsForSeconds(0.45f));

		// Toggle m_Button4
		ToggleButton_4();

		// Toggle other buttons
		if(m_Button1_IsOn==true)
		{
			ToggleButton_1();
		}
		if(m_Button2_IsOn==true)
		{
			ToggleButton_2();
		}
		if(m_Button3_IsOn==true)
		{
			ToggleButton_3();
		}
		if(m_Button5_IsOn==true)
		{
			ToggleButton_5();
		}
	}

	public void OnButton_5()
	{
		// Disable all buttons for a few seconds
		StartCoroutine(DisableAllButtonsForSeconds(0.45f));

		// Toggle m_Button5
		ToggleButton_5();

		// Toggle other buttons
		if(m_Button1_IsOn==true)
		{
			ToggleButton_1();
		}
		if(m_Button2_IsOn==true)
		{
			ToggleButton_2();
		}
		if(m_Button3_IsOn==true)
		{
			ToggleButton_3();
		}
		if(m_Button4_IsOn==true)
		{
			ToggleButton_4();
		}
    }

    public void OnButton_5_tertiary1()
    {
        // Disable all buttons for a few seconds
        StartCoroutine(DisableAllButtonsForSeconds(0.45f));

        // Toggle m_Button5_Tertiary1
        ToggleButton_5_Tertiary1();

        // Toggle other tertiary buttons
        if (m_Button5_Tertiary2_IsOn == true)
        {
            ToggleButton_5_Tertiary2();
        }
        if (m_Button5_Tertiary3_IsOn == true)
        {
            ToggleButton_5_Tertiary3();
        }
        if (m_Button5_Tertiary4_IsOn == true)
        {
            ToggleButton_5_Tertiary4();
        }
        if (m_Button5_Tertiary5_IsOn == true)
        {
            ToggleButton_5_Tertiary5();
        }
    }

    public void OnButton_5_tertiary2()
    {
        // Disable all buttons for a few seconds
        StartCoroutine(DisableAllButtonsForSeconds(0.45f));

        // Toggle m_Button5_Tertiary2
        ToggleButton_5_Tertiary2();

        // Toggle other tertiary buttons
        if (m_Button5_Tertiary1_IsOn == true)
        {
            ToggleButton_5_Tertiary1();
        }
        if (m_Button5_Tertiary3_IsOn == true)
        {
            ToggleButton_5_Tertiary3();
        }
        if (m_Button5_Tertiary4_IsOn == true)
        {
            ToggleButton_5_Tertiary4();
        }
        if (m_Button5_Tertiary5_IsOn == true)
        {
            ToggleButton_5_Tertiary5();
        }
    }

    public void OnButton_5_tertiary3()
    {
        // Disable all buttons for a few seconds
        StartCoroutine(DisableAllButtonsForSeconds(0.45f));

        // Toggle m_Button5_Tertiary3
        ToggleButton_5_Tertiary3();

        // Toggle other tertiary buttons
        if (m_Button5_Tertiary1_IsOn == true)
        {
            ToggleButton_5_Tertiary1();
        }
        if (m_Button5_Tertiary2_IsOn == true)
        {
            ToggleButton_5_Tertiary2();
        }
        if (m_Button5_Tertiary4_IsOn == true)
        {
            ToggleButton_5_Tertiary4();
        }
        if (m_Button5_Tertiary5_IsOn == true)
        {
            ToggleButton_5_Tertiary5();
        }
    }

    public void OnButton_5_tertiary4()
    {
        // Disable all buttons for a few seconds
        StartCoroutine(DisableAllButtonsForSeconds(0.45f));

        // Toggle m_Button5_Tertiary4
        ToggleButton_5_Tertiary4();

        // Toggle other tertiary buttons
        if (m_Button5_Tertiary1_IsOn == true)
        {
            ToggleButton_5_Tertiary1();
        }
        if (m_Button5_Tertiary2_IsOn == true)
        {
            ToggleButton_5_Tertiary2();
        }
        if (m_Button5_Tertiary3_IsOn == true)
        {
            ToggleButton_5_Tertiary3();
        }
        if (m_Button5_Tertiary5_IsOn == true)
        {
            ToggleButton_5_Tertiary5();
        }
    }

    public void OnButton_5_tertiary5()
    {
        // Disable all buttons for a few seconds
        StartCoroutine(DisableAllButtonsForSeconds(0.45f));

        // Toggle m_Button5_Tertiary5
        ToggleButton_5_Tertiary5();

        // Toggle other tertiary buttons
        if (m_Button5_Tertiary1_IsOn == true)
        {
            ToggleButton_5_Tertiary1();
        }
        if (m_Button5_Tertiary2_IsOn == true)
        {
            ToggleButton_5_Tertiary2();
        }
        if (m_Button5_Tertiary3_IsOn == true)
        {
            ToggleButton_5_Tertiary3();
        }
        if (m_Button5_Tertiary4_IsOn == true)
        {
            ToggleButton_5_Tertiary4();
        }
    }

    #endregion // UI Responder

    // ########################################
    // Toggle button functions
    // ########################################

    #region Toggle Button

    // Toggle m_Button1
    void ToggleButton_1()
	{
		m_Button1_IsOn = !m_Button1_IsOn;
		if(m_Button1_IsOn==true)
		{
			// MoveIn m_SecondaryButton1
			m_SecondaryButton1.MoveIn(GUIAnimSystemFREE.eGUIMove.SelfAndChildren);
		}
		else
		{
			// MoveOut m_SecondaryButton1
			m_SecondaryButton1.MoveOut(GUIAnimSystemFREE.eGUIMove.SelfAndChildren);
		}
	}

	// Toggle m_Button2
	void ToggleButton_2()
	{
		m_Button2_IsOn = !m_Button2_IsOn;
		if(m_Button2_IsOn==true)
		{
			// MoveIn m_SecondaryButton2
			m_SecondaryButton2.MoveIn(GUIAnimSystemFREE.eGUIMove.SelfAndChildren);
		}
		else
		{
			// MoveOut m_SecondaryButton2
			m_SecondaryButton2.MoveOut(GUIAnimSystemFREE.eGUIMove.SelfAndChildren);
		}
	}

	// Toggle m_Button3
	void ToggleButton_3()
	{
		m_Button3_IsOn = !m_Button3_IsOn;
		if(m_Button3_IsOn==true)
		{
			// MoveIn m_SecondaryButton3
			m_SecondaryButton3.MoveIn(GUIAnimSystemFREE.eGUIMove.SelfAndChildren);
		}
		else
		{
			// MoveOut m_SecondaryButton3
			m_SecondaryButton3.MoveOut(GUIAnimSystemFREE.eGUIMove.SelfAndChildren);
		}
	}

	// Toggle m_Button4
	void ToggleButton_4()
	{
		m_Button4_IsOn = !m_Button4_IsOn;
		if(m_Button4_IsOn==true)
		{
			// MoveIn m_SecondaryButton4
			m_SecondaryButton4.MoveIn(GUIAnimSystemFREE.eGUIMove.SelfAndChildren);
		}
		else
		{
			// MoveOut m_SecondaryButton4
			m_SecondaryButton4.MoveOut(GUIAnimSystemFREE.eGUIMove.SelfAndChildren);
		}
	}

	// Toggle m_Button5
	void ToggleButton_5()
	{
		m_Button5_IsOn = !m_Button5_IsOn;
		if(m_Button5_IsOn==true)
		{
			// MoveIn m_SecondaryButton5
			m_SecondaryButton5.MoveIn(GUIAnimSystemFREE.eGUIMove.SelfAndChildren);
		}
		else
		{
			// MoveOut m_SecondaryButton5
			m_SecondaryButton5.MoveOut(GUIAnimSystemFREE.eGUIMove.SelfAndChildren);

            if (m_Button5_Tertiary1_IsOn)
                ToggleButton_5_Tertiary1();
            if (m_Button5_Tertiary2_IsOn)
                ToggleButton_5_Tertiary2();
            if (m_Button5_Tertiary3_IsOn)
                ToggleButton_5_Tertiary3();
            if (m_Button5_Tertiary4_IsOn)
                ToggleButton_5_Tertiary4();
            if (m_Button5_Tertiary5_IsOn)
                ToggleButton_5_Tertiary5();
        }
    }

    // Toggle m_Button5_Tertiary1
    void ToggleButton_5_Tertiary1()
    {
        m_Button5_Tertiary1_IsOn = !m_Button5_Tertiary1_IsOn;
        if (m_Button5_Tertiary1_IsOn == true)
        {
            // MoveIn m_Button5_Tertiary1
            m_Button5_Tertiary1.MoveIn(GUIAnimSystemFREE.eGUIMove.SelfAndChildren);
        }
        else
        {
            // MoveOut m_Button5_Tertiary1
            m_Button5_Tertiary1.MoveOut(GUIAnimSystemFREE.eGUIMove.SelfAndChildren);
        }
    }

    // Toggle m_Button5_Tertiary2
    void ToggleButton_5_Tertiary2()
    {
        m_Button5_Tertiary2_IsOn = !m_Button5_Tertiary2_IsOn;
        if (m_Button5_Tertiary2_IsOn == true)
        {
            // MoveIn m_Button5_Tertiary2
            m_Button5_Tertiary2.MoveIn(GUIAnimSystemFREE.eGUIMove.SelfAndChildren);
        }
        else
        {
            // MoveOut m_Button5_Tertiary2
            m_Button5_Tertiary2.MoveOut(GUIAnimSystemFREE.eGUIMove.SelfAndChildren);
        }
    }

    // Toggle m_Button5_Tertiary3
    void ToggleButton_5_Tertiary3()
    {
        m_Button5_Tertiary3_IsOn = !m_Button5_Tertiary3_IsOn;
        if (m_Button5_Tertiary3_IsOn == true)
        {
            // MoveIn m_Button5_Tertiary3
            m_Button5_Tertiary3.MoveIn(GUIAnimSystemFREE.eGUIMove.SelfAndChildren);
        }
        else
        {
            // MoveOut m_Button5_Tertiary3
            m_Button5_Tertiary3.MoveOut(GUIAnimSystemFREE.eGUIMove.SelfAndChildren);
        }
    }

    // Toggle m_Button5_Tertiary4
    void ToggleButton_5_Tertiary4()
    {
        m_Button5_Tertiary4_IsOn = !m_Button5_Tertiary4_IsOn;
        if (m_Button5_Tertiary4_IsOn == true)
        {
            // MoveIn m_Button5_Tertiary4
            m_Button5_Tertiary4.MoveIn(GUIAnimSystemFREE.eGUIMove.SelfAndChildren);
        }
        else
        {
            // MoveOut m_Button5_Tertiary4
            m_Button5_Tertiary4.MoveOut(GUIAnimSystemFREE.eGUIMove.SelfAndChildren);
        }
    }

    // Toggle m_Button5_Tertiary5
    void ToggleButton_5_Tertiary5()
    {
        m_Button5_Tertiary5_IsOn = !m_Button5_Tertiary5_IsOn;
        if (m_Button5_Tertiary5_IsOn == true)
        {
            // MoveIn m_Button5_Tertiary5
            m_Button5_Tertiary5.MoveIn(GUIAnimSystemFREE.eGUIMove.SelfAndChildren);
        }
        else
        {
            // MoveOut m_Button5_Tertiary5
            m_Button5_Tertiary5.MoveOut(GUIAnimSystemFREE.eGUIMove.SelfAndChildren);
        }
    }

    #endregion // Toggle Button
}


text:
<?php

namespace Shopery\DateTime\Listener\PHPUnit;

use DateTime as NativeDateTime;
use Shopery\DateTime\DateTime;

class DateTimeListenerTest extends \PHPUnit_Framework_TestCase
{
    const SLEEP_TIME = 2;

    /**
     * @freezeTime
     *
     * @group slow_test
     */
    public function test_annotation()
    {
        $expected = DateTime::now();
        sleep(self::SLEEP_TIME);

        $now = DateTime::now();

        $this->assertEquals($expected, $now);
    }

    /**
     * @freezeTime 2015-01-01
     */
    public function test_annotation_with_date()
    {
        $expected = new NativeDateTime('2015-01-01');
        $now = DateTime::now();

        $this->assertEquals($expected, $now);
    }

    /**
     * @freezeTime yesterday
     */
    public function test_annotation_with_relative_date()
    {
        $expected = new NativeDateTime('yesterday');
        $now = DateTime::now();

        $this->assertEquals($expected, $now);
    }
}

redpajama_set_name: RedPajamaGithub


text:
import os
from typing import cast

import pytest

from pants.base.build_root import BuildRoot
from pants.core.goals.run import Run, RunFieldSet, RunRequest, RunSubsystem, run
from pants.engine.addresses import Address
from pants.engine.fs import CreateDigest, Digest, FileContent, Workspace
from pants.engine.process import InteractiveProcess, InteractiveProcessResult
from pants.engine.target import (
    Target,
    TargetRootsToFieldSets,
    TargetRootsToFieldSetsRequest,
    WrappedTarget,
)
from pants.option.global_options import GlobalOptions
from pants.testutil.option_util import create_goal_subsystem, create_subsystem
from pants.testutil.rule_runner import (
    MockEffect,
    MockGet,
    RuleRunner,
    mock_console,
    run_rule_with_mocks,
)

@pytest.fixture
def rule_runner() -> RuleRunner:
    return RuleRunner()

def create_mock_run_request(rule_runner: RuleRunner, program_text: bytes) -> RunRequest:
    digest = rule_runner.request(
        Digest,
        [CreateDigest([FileContent(path="program.py", content=program_text, is_executable=True)])],
    )
    return RunRequest(digest=digest, args=(os.path.join("{chroot}", "program.py"),))

def single_target_run(
    rule_runner: RuleRunner,
    address: Address,
    *,
    program_text: bytes,
) -> Run:
    workspace = Workspace(rule_runner.scheduler, _enforce_effects=False)

    class TestRunFieldSet(RunFieldSet):
        required_fields = ()

    class TestBinaryTarget(Target):
        alias = "binary"
        core_fields = ()

    target = TestBinaryTarget({}, address)
    field_set = TestRunFieldSet.create(target)

    with mock_console(rule_runner.options_bootstrapper) as (console, _):
        res = run_rule_with_mocks(
            run,
            rule_args=[
                create_goal_subsystem(RunSubsystem, args=[]),
                create_subsystem(GlobalOptions, pants_workdir=rule_runner.pants_workdir),
                console,
                workspace,
                BuildRoot(),
                rule_runner.environment,
            ],
            mock_gets=[
                MockGet(
                    output_type=TargetRootsToFieldSets,
                    input_type=TargetRootsToFieldSetsRequest,
                    mock=lambda _: TargetRootsToFieldSets({target: [field_set]}),
                ),
                MockGet(
                    output_type=WrappedTarget,
                    input_type=Address,
                    mock=lambda _: WrappedTarget(target),
                ),
                MockGet(
                    output_type=RunRequest,
                    input_type=TestRunFieldSet,
                    mock=lambda _: create_mock_run_request(rule_runner, program_text),
                ),
                MockEffect(
                    output_type=InteractiveProcessResult,
                    input_type=InteractiveProcess,
                    mock=rule_runner.run_interactive_process,
                ),
            ],
        )
        return cast(Run, res)

def test_normal_run(rule_runner: RuleRunner) -> None:
    program_text = b'#!/usr/bin/python\nprint("hello")'
    res = single_target_run(
        rule_runner,
        Address("some/addr"),
        program_text=program_text,
    )
    assert res.exit_code == 0

def test_materialize_input_files(rule_runner: RuleRunner) -> None:
    program_text = b'#!/usr/bin/python\nprint("hello")'
    binary = create_mock_run_request(rule_runner, program_text)
    with mock_console(rule_runner.options_bootstrapper):
        result = rule_runner.run_interactive_process(
            InteractiveProcess(
                argv=("./program.py",),
                run_in_workspace=False,
                input_digest=binary.digest,
            )
        )
    assert result.exit_code == 0

def test_failed_run(rule_runner: RuleRunner) -> None:
    program_text = b'#!/usr/bin/python\nraise RuntimeError("foo")'
    res = single_target_run(rule_runner, Address("some/addr"), program_text=program_text)
    assert res.exit_code == 1


text:
#include <aws/inspector/model/UpdateApplicationRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Inspector::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

UpdateApplicationRequest::UpdateApplicationRequest() :
    m_applicationArnHasBeenSet(false),
    m_applicationNameHasBeenSet(false),
    m_resourceGroupArnHasBeenSet(false)
{
}

Aws::String UpdateApplicationRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_applicationArnHasBeenSet)
  {
   payload.WithString("applicationArn", m_applicationArn);

  }

  if(m_applicationNameHasBeenSet)
  {
   payload.WithString("applicationName", m_applicationName);

  }

  if(m_resourceGroupArnHasBeenSet)
  {
   payload.WithString("resourceGroupArn", m_resourceGroupArn);

  }

  return payload.WriteReadable();
}

Aws::Http::HeaderValueCollection UpdateApplicationRequest::GetRequestSpecificHeaders() const
{
  Aws::Http::HeaderValueCollection headers;
  headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "InspectorService.UpdateApplication"));
  return headers;

}


text:
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "DTD/xhtml1-transitional.dtd">

  <title>npyscreen.selectone.SelectOne</title>
  <link rel="stylesheet" href="epydoc.css" type="text/css" />

         Home

         Trees

         Indices

         Help

        Package npyscreen ::
        Module selectone ::
        Class SelectOne

[hide private]

[frames] | no frames]

Class SelectOne
source code

         object --+
                  |
widget.InputHandler --+
                      |
          widget.Widget --+
                          |
        multiline.MultiLine --+
                              |
                             SelectOne

Display a list of items to the user.  By overloading the display_value
  method, this widget can be made to display different kinds of
  objects.

        Nested Classes
        [hide private]

        _contained_widgets

        Instance Methods
        [hide private]

          update(self,
        clear=True)

      How should object display itself on the screen.

            source code

          h_select(self,
        ch)

            source code

          _print_line(self,
        line,
        value_indexer)

            source code

Inherited from multiline.MultiLine:
      __init__,
      calculate_area_needed,
      display_value,
      edit,
      h_cursor_beginning,
      h_cursor_end,
      h_cursor_line_down,
      h_cursor_line_up,
      h_cursor_page_down,
      h_cursor_page_up,
      h_exit,
      h_find_char,
      h_select_exit,
      set_up_handlers,
      t_input_isprint

Inherited from widget.Widget:
      clear,
      destroy,
      display,
      get_and_use_key_press,
      get_editable,
      safe_filter,
      safe_string,
      set_editable,
      set_size,
      space_available,
      try_adjust_widgets

Inherited from widget.InputHandler:
      add_complex_handlers,
      add_handlers,
      h_exit_down,
      h_exit_escape,
      h_exit_left,
      h_exit_right,
      h_exit_up,
      handle_input

Inherited from object:
      __delattr__,
      __getattribute__,
      __hash__,
      __new__,
      __reduce__,
      __reduce_ex__,
      __repr__,
      __setattr__,
      __str__

        Properties
        [hide private]

Inherited from object:
      __class__

        Method Details
        [hide private]

update(self,
        clear=True)

  	source code

  How should object display itself on the screen. Define here, but do
  not actually refresh the curses display, since this should be done as
  little as possible.  This base widget puts nothing on screen.

Overrides:
      multiline.MultiLine.update

h_select(self,
        ch)

  	source code

Overrides:
      multiline.MultiLine.h_select

_print_line(self,
        line,
        value_indexer)

  	source code

Overrides:
      multiline.MultiLine._print_line

         Home

         Trees

         Indices

         Help

    Generated by Epydoc 3.0beta1 on Thu Mar 29 15:58:54 2007

      http://epydoc.sourceforge.net


text:
package portmapper

import (
	"errors"
	"fmt"
	"net"
	"sync"

	"github.com/Sirupsen/logrus"
	"github.com/docker/docker/daemon/networkdriver/portallocator"
	"github.com/docker/docker/pkg/iptables"
)

type mapping struct {
	proto         string
	userlandProxy UserlandProxy
	host          net.Addr
	container     net.Addr
}

var NewProxy = NewProxyCommand

var (
	ErrUnknownBackendAddressType = errors.New("unknown container address type not supported")
	ErrPortMappedForIP           = errors.New("port is already mapped to ip")
	ErrPortNotMapped             = errors.New("port is not mapped")
)

type PortMapper struct {
	chain *iptables.Chain

	// udp:ip:port
	currentMappings map[string]*mapping
	lock            sync.Mutex

	Allocator *portallocator.PortAllocator
}

func New() *PortMapper {
	return NewWithPortAllocator(portallocator.New())
}

func NewWithPortAllocator(allocator *portallocator.PortAllocator) *PortMapper {
	return &PortMapper{
		currentMappings: make(map[string]*mapping),
		Allocator:       allocator,
	}
}

func (pm *PortMapper) SetIptablesChain(c *iptables.Chain) {
	pm.chain = c
}

func (pm *PortMapper) Map(container net.Addr, hostIP net.IP, hostPort int, useProxy bool) (host net.Addr, err error) {
	pm.lock.Lock()
	defer pm.lock.Unlock()

	var (
		m                 *mapping
		proto             string
		allocatedHostPort int
	)

	switch container.(type) {
	case *net.TCPAddr:
		proto = "tcp"
		if allocatedHostPort, err = pm.Allocator.RequestPort(hostIP, proto, hostPort); err != nil {
			return nil, err
		}

		m = &mapping{
			proto:     proto,
			host:      &net.TCPAddr{IP: hostIP, Port: allocatedHostPort},
			container: container,
		}

		if useProxy {
			m.userlandProxy = NewProxy(proto, hostIP, allocatedHostPort, container.(*net.TCPAddr).IP, container.(*net.TCPAddr).Port)
		}
	case *net.UDPAddr:
		proto = "udp"
		if allocatedHostPort, err = pm.Allocator.RequestPort(hostIP, proto, hostPort); err != nil {
			return nil, err
		}

		m = &mapping{
			proto:     proto,
			host:      &net.UDPAddr{IP: hostIP, Port: allocatedHostPort},
			container: container,
		}

		if useProxy {
			m.userlandProxy = NewProxy(proto, hostIP, allocatedHostPort, container.(*net.UDPAddr).IP, container.(*net.UDPAddr).Port)
		}
	default:
		return nil, ErrUnknownBackendAddressType
	}

	// release the allocated port on any further error during return.
	defer func() {
		if err != nil {
			pm.Allocator.ReleasePort(hostIP, proto, allocatedHostPort)
		}
	}()

	key := getKey(m.host)
	if _, exists := pm.currentMappings[key]; exists {
		return nil, ErrPortMappedForIP
	}

	containerIP, containerPort := getIPAndPort(m.container)
	if err := pm.forward(iptables.Append, m.proto, hostIP, allocatedHostPort, containerIP.String(), containerPort); err != nil {
		return nil, err
	}

	cleanup := func() error {
		// need to undo the iptables rules before we return
		if m.userlandProxy != nil {
			m.userlandProxy.Stop()
		}
		pm.forward(iptables.Delete, m.proto, hostIP, allocatedHostPort, containerIP.String(), containerPort)
		if err := pm.Allocator.ReleasePort(hostIP, m.proto, allocatedHostPort); err != nil {
			return err
		}

		return nil
	}

	if m.userlandProxy != nil {
		if err := m.userlandProxy.Start(); err != nil {
			if err := cleanup(); err != nil {
				return nil, fmt.Errorf("Error during port allocation cleanup: %v", err)
			}
			return nil, err
		}
	}

	pm.currentMappings[key] = m
	return m.host, nil
}

// re-apply all port mappings
func (pm *PortMapper) ReMapAll() {
	logrus.Debugln("Re-applying all port mappings.")
	for _, data := range pm.currentMappings {
		containerIP, containerPort := getIPAndPort(data.container)
		hostIP, hostPort := getIPAndPort(data.host)
		if err := pm.forward(iptables.Append, data.proto, hostIP, hostPort, containerIP.String(), containerPort); err != nil {
			logrus.Errorf("Error on iptables add: %s", err)
		}
	}
}

func (pm *PortMapper) Unmap(host net.Addr) error {
	pm.lock.Lock()
	defer pm.lock.Unlock()

	key := getKey(host)
	data, exists := pm.currentMappings[key]
	if !exists {
		return ErrPortNotMapped
	}

	if data.userlandProxy != nil {
		data.userlandProxy.Stop()
	}

	delete(pm.currentMappings, key)

	containerIP, containerPort := getIPAndPort(data.container)
	hostIP, hostPort := getIPAndPort(data.host)
	if err := pm.forward(iptables.Delete, data.proto, hostIP, hostPort, containerIP.String(), containerPort); err != nil {
		logrus.Errorf("Error on iptables delete: %s", err)
	}

	switch a := host.(type) {
	case *net.TCPAddr:
		return pm.Allocator.ReleasePort(a.IP, "tcp", a.Port)
	case *net.UDPAddr:
		return pm.Allocator.ReleasePort(a.IP, "udp", a.Port)
	}
	return nil
}

func getKey(a net.Addr) string {
	switch t := a.(type) {
	case *net.TCPAddr:
		return fmt.Sprintf("%s:%d/%s", t.IP.String(), t.Port, "tcp")
	case *net.UDPAddr:
		return fmt.Sprintf("%s:%d/%s", t.IP.String(), t.Port, "udp")
	}
	return ""
}

func getIPAndPort(a net.Addr) (net.IP, int) {
	switch t := a.(type) {
	case *net.TCPAddr:
		return t.IP, t.Port
	case *net.UDPAddr:
		return t.IP, t.Port
	}
	return nil, 0
}

func (pm *PortMapper) forward(action iptables.Action, proto string, sourceIP net.IP, sourcePort int, containerIP string, containerPort int) error {
	if pm.chain == nil {
		return nil
	}
	return pm.chain.Forward(action, sourceIP, sourcePort, proto, containerIP, containerPort)
}


text:
/**
 *
 */
package net.freecoder.restdemo.dao;

import java.util.List;

import net.freecoder.restdemo.common.OrderedSpringJUnit4ClassRunner;
import net.freecoder.restdemo.dao.MwsDao;
import net.freecoder.restdemo.model.WlsMwsSiteConfig;
import net.freecoder.restdemo.model.WlsMwsSiteConfigId;
import net.freecoder.restdemo.util.UUIDUtil;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;

/**
 * @author JiTing
 */
@RunWith(OrderedSpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:test-context-application.xml" })
public class MwsSiteConfigDaoTest {

	@Autowired
	MwsDao mwsDao;

	private static String wxAccountId = UUIDUtil.uuid8();

	@Test
	public void testCRUD() {
		String propName = "testProp";
		String propValue = String.valueOf(System.currentTimeMillis());

		WlsMwsSiteConfigId id = new WlsMwsSiteConfigId(propName, wxAccountId);
		WlsMwsSiteConfig configItem = new WlsMwsSiteConfig(id, propValue);
		WlsMwsSiteConfigId configId = mwsDao.saveConfig(configItem);

		// get
		WlsMwsSiteConfig dbItem = mwsDao.get(id);
		Assert.assertEquals(configId, id);

		// update
		String newValue = "new";
		dbItem.setPropValue(newValue);
		mwsDao.update(dbItem);

		// get by wxAccountId
		List<WlsMwsSiteConfig> configList = mwsDao
				.getListByWxAccountId(wxAccountId);
		Assert.assertEquals(1, configList.size());
		Assert.assertEquals(id, configList.get(0).getId());
		Assert.assertEquals(newValue, configList.get(0).getPropValue());

		// delete
		mwsDao.delete(dbItem);
		WlsMwsSiteConfig deletedDbItem = mwsDao.get(id);
		Assert.assertNull(deletedDbItem);
	}

}


text:
[![NPM version](http://img.shields.io/npm/v/hyperbole.svg?style=flat)](https://www.npmjs.org/package/hyperbole)
[![Dependency Status](http://img.shields.io/david/ksmithut/hyperbole.svg?style=flat)](https://david-dm.org/ksmithut/hyperbole)
[![Dev Dependency Status](http://img.shields.io/david/dev/ksmithut/hyperbole.svg?style=flat)](https://david-dm.org/ksmithut/hyperbole#info=devDependencies&view=table)
[![Code Climate](http://img.shields.io/codeclimate/github/ksmithut/hyperbole.svg?style=flat)](https://codeclimate.com/github/ksmithut/hyperbole)
[![Build Status](http://img.shields.io/travis/ksmithut/hyperbole/master.svg?style=flat)](https://travis-ci.org/ksmithut/hyperbole)
[![Coverage Status](http://img.shields.io/codeclimate/coverage/github/ksmithut/hyperbole.svg?style=flat)](https://codeclimate.com/github/ksmithut/hyperbole)

Hyperbole is a Promise wrapper around the core node `http` and `https` modules.

# Installation

```bash
npm install --save hyperbole
```

# Usage

With express or other connect-like server handlers

```js
var express = require('express');
var app     = require('app');
var server  = require('hyperbole')(app, 3000);

app.use(function (req, res) {
  res.json({hello: 'world'});
});

server.start()
  .then(function () {
    console.log('Server started on port %s', server.port);
  })
  .catch(function (err) {
    console.log(err);
  });

```

To make it an https server, pass in the required options as the third parameter.

```js
var fs      = require('fs');
var express = require('express');
var app     = require('app');
var server  = require('hyperbole')(app, 443, {
  key: fs.readFileSync('key.pem'),
  cert: fs.readFileSync('cert.pem')
});

app.use(function (req, res) {
  res.json({hello: 'world'});
});

server.start()
  .then(function () {
    console.log('HTTPS server started on port %s', server.port);
  })
  .catch(function (err) {
    console.log(err);
  });
```

You can also have multiple servers.

```js
var fs = require('fs');
var express = require('express');
var createServer = require('hyperbole');
var app = require('app');
var httpServer = createServer(app, 80);
var httpsServer = createServer(app, 443, {
  key: fs.readFileSync('key.pem'),
  cert: fs.readFileSync('cert.pem')
});

// Only redirect the root
app.get('/', function (req, res, next) {
  if (!req.secure) {
    return res.redirect('https://' + req.headers.host + req.url);
  }
  next();
});

// Send 426 "Upgrade Required" error to notify the user that they need to use
// https
app.use(function (req, res, next) {
  if (!req.secure) {
    return res.status(426).send('Switch to using https');
  }
  next();
});

app.use(function (req, res) {
  res.json({secure: true});
});

httpsServer.start()
  .then(httpServer.start)
  .then(function () {
    console.log('Both servers started');
  })
  .catch(function (err) {
    console.log(err);
  });
```

# API

The exported object is actually a `class`-like object, so technically, it's
probably better to do:

```js
var Server = require('hyperbole');
var server = new Server(app, port);
```

but for convenience, you can just use it as a function, and it will return the
new server instance.

It takes 3 arguments:

* `app` (Function) - The handler that takes in the request and response objects
to process each request. This is usually an express, koa, or connect app.
* `port` (Number/String) - The port to bind to.
* `secure` (Object) *optional* - If you want the server to be an https server,
then pass in the options object as described
[here](https://nodejs.org/api/https.html#https_https_createserver_options_requestlistener).

It returns a server instance.

Each instance has the following methods:

* `server.start()`

  Starts the server. Returns a promise with no arguments passed.

* `server.stop()`

  Stops the server. The server must have successfully started in order to stop it.

You can also access the http server object directly with `server.server` in case
you were using it for `socket.io` or something else.


text:
import { ComponentMeta, ComponentStory } from '@storybook/react';

import Icon from '.';

export default {
  argTypes: {
    defaultImage: { control: 'text' },
    imgSource: { control: 'text' },
    title: { control: 'text' },
    uploadedImage: { control: 'text' }
  },
  component: Icon,
  title: 'Icon/Attach'
} as ComponentMeta<typeof Icon>;

const TemplateIcon: ComponentStory<typeof Icon> = (args) => <Icon {...args} />;

export const PlaygroundIcon = TemplateIcon.bind({});

export const normal = (): JSX.Element => (
  <Icon
    defaultImage=""
    imgSource=""
    title="Attach"
    uploadedImage=""
    onClick={(): void => undefined}
  />
);


text:
package com.smarthome.screen;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Vector3;
import com.smarthome.SmartHome;
import com.smarthome.helpers.StaticSprites;

public class MainInterface extends Screen{

	private SmartHome home;
	private int width, height;
	private Vector3 translationVector;
	private SpriteBatch batcher;
	private float delta;

	public MainInterface(SmartHome home){
		this.home = home;
		width = home.width;
		height = home.height;
		batcher = new SpriteBatch();
		translationVector = new Vector3();

	}

	@Override
	public boolean keyDown(int keycode) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean keyUp(int keycode) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean keyTyped(char character) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean touchDown(int screenX, int screenY, int pointer, int button) {
		return false;
	}

	@Override
	public boolean touchUp(int screenX, int screenY, int pointer, int button) {
		translationVector.set(screenX, screenY, 0);
		Gdx.app.log("MainInterface.class", "X pos: " + Float.toString(translationVector.x));
		Gdx.app.log("MainInterface.class", "Y pos: " + Float.toString(translationVector.y));
		return false;
	}

	@Override
	public boolean touchDragged(int screenX, int screenY, int pointer) {
		Gdx.app.log("MainInterface.class", Float.toString(delta));
		return false;
	}

	@Override
	public boolean mouseMoved(int screenX, int screenY) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean scrolled(int amount) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void update() {
		delta = Math.min(Gdx.graphics.getDeltaTime(), 1/60f);

	}

	@Override
	public void render() {
		batcher.begin();
		batcher.draw(StaticSprites.test, 0, 0, width, height);

		batcher.end();

	}

	@Override
	public void enter() {
		Gdx.input.setCatchBackKey(true);
		Gdx.input.setInputProcessor(this);

		Gdx.app.log("MainInterface.class", "Screen Width: " + Integer.toString(width));
		Gdx.app.log("MainInterface.class", "Screen Height: " + Integer.toString(height));

	}

}


text:
package com.navercorp.pinpoint.web.vo.callstacks;

import com.navercorp.pinpoint.common.server.bo.MethodTypeEnum;
import com.navercorp.pinpoint.common.trace.ServiceType;

/**
 * @author jaehong.kim
 */
public class DefaultRecord extends BaseRecord {
    public DefaultRecord(int tab, int id, int parentId, boolean method, String title, String arguments,
                         long begin, long elapsed, long gap, String agentId, String agentName, String applicationName, ServiceType serviceType,
                         String destinationId, boolean hasChild, boolean hasException, String transactionId, long spanId,
                         long executionMilliseconds, MethodTypeEnum methodTypeEnum, boolean isAuthorized) {
        this.tab = tab;
        this.id = id;
        this.parentId = parentId;
        this.method = method;

        this.title = title;
        this.arguments = arguments;
        this.begin = begin;
        this.elapsed = elapsed;
        this.gap = gap;
        this.agentId = agentId;
        this.agentName = agentName;

        this.applicationName = applicationName;
        this.serviceType = serviceType;
        this.destinationId = destinationId;

        this.excludeFromTimeline = serviceType == null || serviceType.isInternalMethod();
        this.hasChild = hasChild;
        this.hasException = hasException;

        this.transactionId = transactionId;
        this.spanId = spanId;

        this.executionMilliseconds = executionMilliseconds;
        this.methodTypeEnum = methodTypeEnum;
        this.isAuthorized = isAuthorized;
    }

    public int getId() {
        return id;
    }

    public int getParentId() {
        return parentId;
    }

    public int getTab() {
        return tab;
    }

    public String getTabspace() {
        if(tab == 0) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        for(int i=0; i< tab; i++) {
            sb.append("&nbsp");
        }
        return sb.toString();
    }

    public boolean isMethod() {
        return method;
    }

    public String getTitle() {
        return title;
    }

    public String getArguments() {
        return arguments;
    }

    public long getBegin() {
        return begin;
    }

    public long getElapsed() {
        return elapsed;
    }

    public long getGap() {
        return gap;
    }

    public String getAgentId() {
        return agentId;
    }

    public String getApplicationName() {
        return applicationName;
    }

    public String getApiType() {
        if (destinationId == null) {
            if (serviceType == null) {
                // no ServiceType when parameter
                return "";
            }
            return serviceType.getDesc();
        }
        if (serviceType.isIncludeDestinationId()) {
            return serviceType.getDesc() + "(" + destinationId + ")";
        } else {
            return serviceType.getDesc();
        }

    }

    public boolean isExcludeFromTimeline() {
        return excludeFromTimeline;
    }

    public String getSimpleClassName() {
        return simpleClassName;
    }

    public void setSimpleClassName(String simpleClassName) {
        this.simpleClassName = simpleClassName;
    }

    public String getFullApiDescription() {
        return fullApiDescription;
    }

    public void setFullApiDescription(String fullApiDescription) {
        this.fullApiDescription = fullApiDescription;
    }

    public boolean isFocused() {
        return focused;
    }

    public void setFocused(boolean focused) {
        this.focused = focused;
    }

    public boolean getHasChild() {
        return hasChild;
    }

    public boolean getHasException() {
        return hasException;
    }

    public String getTransactionId() {
        return transactionId;
    }

    public long getSpanId() {
        return spanId;
    }

    public long getExecutionMilliseconds() {
        return executionMilliseconds;
    }

    public MethodTypeEnum getMethodTypeEnum() {
        return methodTypeEnum;
    }

    public boolean isAuthorized() {
        return this.isAuthorized;
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("{tab=");
        builder.append(tab);
        builder.append(", id=");
        builder.append(id);
        builder.append(", parentId=");
        builder.append(parentId);
        builder.append(", method=");
        builder.append(method);
        builder.append(", title=");
        builder.append(title);
        builder.append(", simpleClassName=");
        builder.append(simpleClassName);
        builder.append(", fullApiDescription=");
        builder.append(fullApiDescription);
        builder.append(", arguments=");
        builder.append(arguments);
        builder.append(", begin=");
        builder.append(begin);
        builder.append(", elapsed=");
        builder.append(elapsed);
        builder.append(", gap=");
        builder.append(gap);
        builder.append(", executionMilliseconds=");
        builder.append(executionMilliseconds);
        builder.append(", agentId=");
        builder.append(agentId);
        builder.append(", applicationName=");
        builder.append(applicationName);
        builder.append(", serviceType=");
        builder.append(serviceType);
        builder.append(", destinationId=");
        builder.append(destinationId);
        builder.append(", excludeFromTimeline=");
        builder.append(excludeFromTimeline);
        builder.append(", transactionId=");
        builder.append(transactionId);
        builder.append(", spanId=");
        builder.append(spanId);
        builder.append(", focused=");
        builder.append(focused);
        builder.append(", hasChild=");
        builder.append(hasChild);
        builder.append(", hasException=");
        builder.append(hasException);
        builder.append(", methodTypeEnum=");
        builder.append(methodTypeEnum);
        builder.append(", isAuthorized=");
        builder.append(isAuthorized);
        builder.append("}");
        return builder.toString();
    }
}


text:
#include "XMBullet/BulletCollision/NarrowPhaseCollision/btConvexCast.h"

btConvexCast::~btConvexCast()
{
}


text:
#import <Xcode3UI/PBXBuildPhaseWrapper.h>

@interface PBXShellScriptBuildPhaseWrapper : PBXBuildPhaseWrapper
{
}

- (void)removeFromOutputPathsAtIndex:(unsigned long long)arg1;
- (void)insertInOutputPaths:(id)arg1 atIndex:(unsigned long long)arg2;
- (void)removeFromInputPathsAtIndex:(unsigned long long)arg1;
- (void)insertInInputPaths:(id)arg1 atIndex:(unsigned long long)arg2;
- (id)newScriptingObjectOfClass:(Class)arg1 forValueForKey:(id)arg2 withContentsValue:(id)arg3 properties:(id)arg4;
- (id)outputPaths;
- (id)inputPaths;
- (void)setShowEnvironmentVariables:(BOOL)arg1;
- (BOOL)showEnvironmentVariables;
- (void)setShellScript:(id)arg1;
- (id)shellScript;
- (void)setShellPath:(id)arg1;
- (id)shellPath;

@end


text:
// Copyright 2012 Citrix Systems, Inc. Licensed under the
// Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License.  Citrix Systems, Inc.
// reserves all rights not expressly granted by the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Automatically generated by addcopyright.py at 04/02/2012
(function($) {
  /**
   * Convert table to be resizable and sortable
   *
   * @author Brian Federle
   */
  $.fn.dataTable = function(method, options) {
    var $table = this;

    /**
     * Check if position is in 'resize zone'
     *
     * @return boolean, true if position is within bounds
     */
    var withinResizeBounds = function($elem, posX) {
      var leftBound = $elem.offset().left + $elem.width() / 1.2;

      return posX > leftBound;
    };

    /**
     * Handles actual resizing of table headers
     */
    var resizeDragEvent = function(event) {
      var $elem = $(this);

      if (event.type == 'mousedown') {
        $elem.addClass('dragging');

        return false;
      } else if (event.type == 'mouseup') {
        $table.find('th').removeClass('dragging');

        return false;
      }

      var isDraggable = $elem.hasClass('dragging');

      if (!isDraggable) {
        return false;
      }

      var columnIndex = $elem.index();

      // Get all TDs from column
      var columnCells = [];
      $table.find('tbody tr:first').each(function() {
        var targetCell = $($(this).find('td')[columnIndex]);

        columnCells.push(targetCell);
      });

      var tolerance = 25;
      var targetWidth = event.pageX - $elem.offset().left + tolerance;
      $(columnCells).each(function() {
        $(this).css({
          width: targetWidth
        });
      });

      resizeHeaders();

      return true;
    };

    var splitTable = function() {
      var $mainContainer = $('<div>')
            .addClass('data-table')
            .appendTo($table.parent())
            .append(
              $table.remove()
            );
      $table = $mainContainer;
      var $theadContainer = $('<div>').addClass('fixed-header').prependTo($table);
      var $theadTable = $('<table>').appendTo($theadContainer).attr('nowrap', 'nowrap');
      var $thead = $table.find('thead').remove().appendTo($theadTable);

      return $thead;
    };

    /**
     * Event to set resizable appearance on hover
     */
    var hoverResizableEvent = function(event) {
      var $elem = $(this);
      var posX = event.pageX;

      if (event.type != 'mouseout' && withinResizeBounds($elem, posX)) {
        $elem.addClass('resizable');
      } else {
        $elem.removeClass('resizable');
      }

      return true;
    };

    /**
     * Make row at specified index selected or unselected
     *
     * @param rowIndex Row's index, starting at 1
     */
    var toggleSelectRow = function(rowIndex) {
      var $rows = $table.find('tbody tr');
      var $row = $($rows[rowIndex]);

      $row.siblings().removeClass('selected');
      return $row.addClass('selected');
    };

    var computeEvenOddRows = function() {
      var currentRowType = 'even';
      $table.find('tbody tr').each(function() {
        var $row = $(this);

        $row.removeClass('even').removeClass('odd');
        $row.addClass(currentRowType);

        if (currentRowType == 'even') currentRowType = 'odd';
        else currentRowType = 'even';
      });
    };

    /**
     * Sort table by column
     *
     * @param columnIndex Index of column (starting at 0) to sort by
     */
    var sortTable = function(columnIndex) {
      return false;
      var direction = 'asc';

      if ($table.find('thead th').hasClass('sorted ' + direction)) {
        direction = 'desc';
      }

      $table.find('thead th').removeClass('sorted desc asc');
      $($table.find('thead th')[columnIndex]).addClass('sorted').addClass(direction);

      var $elems = $table.find('tbody td').filter(function() {
        return $(this).index() == columnIndex;
      });

      var sortData = [];
      $elems.each(function() {
        sortData.push($(this).html());
        sortData.sort();

        if (direction == 'asc') {
          sortData.reverse();
        }
      });

      $(sortData).each(function() {
        var sortKey = this;
        var $targetCell = $elems.filter(function() {
          return $(this).html() == sortKey;
        });
        var $targetContainer = $targetCell.parent();

        $targetContainer.remove().appendTo($table.find('tbody'));
      });

      computeEvenOddRows();
    };

    var resizeHeaders = function() {
      var $thead = $table.closest('div.data-table').find('thead');
      var $tbody = $table.find('tbody');
      var $ths = $thead.find('th');
      var $tds = $tbody.find('tr:first td');

      if ($ths.size() > $tds.size()) {
        $ths.width(
          $table.width() / $ths.size()
        );
        return false;
      }

      $ths.each(function() {
        var $th = $(this);

        var $td = $tds.filter(function() {
          return $(this).index() == $th.index();
        });

        $th.width($td.width());

        return true;
      });

      return $ths;
    };

    var methods = {
      removeRow: function(rowIndex) {
        var $row = $($table.find('tbody tr')[rowIndex]);

        $row.fadeOut(function() {
          $row.remove();
          computeEvenOddRows();
        });

        return $row;
      },

      refresh: function() {
        resizeHeaders();
        computeEvenOddRows();
      },

      selectRow: function(rowIndex) {
        var $row = $($table.find('tbody tr')[rowIndex]);

        $row.siblings().removeClass('selected');
        $row.addClass('selected');
      }
    };

    var init = function() {
      var noSelect = options && options.noSelect == true ? true : false;
      if (!$table.closest('div.data-table').size() && !$table.hasClass('no-split')) {
        splitTable();
        $table.find('tbody').closest('table').addClass('body');
      }

      $table.find('th').bind('mousemove mouseout', hoverResizableEvent);
      $table.find('th').bind('mousedown mousemove mouseup mouseout', resizeDragEvent);
      $table.find('th').bind('click', function(event) {
        if ($(this).hasClass('resizable')) {
          return false;
        }

        sortTable($(event.target).index());

        return false;
      });

      $table.bind('click', function(event) {
        var $tr = $(event.target).closest('tr');

        if (!$tr.size() || noSelect) return true;
        var rowIndex = $tr.index();

        toggleSelectRow(rowIndex);

        return true;
      });

      computeEvenOddRows();
      resizeHeaders();
    };

    if (methods[method]) {
      return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
    } else if (!method) {
      init();
    } else {
      $.error('Method ' + method + ' does not exist on jQuery.dataTable');
    }

    return $table;
  };
}(jQuery));


text:
namespace _06.Animals.Animals.Kinds
{
    public class Cat : Animal
    {
        public Cat(string name, int age, string gender) : base(name, age, gender)
        {
        }

        public override string ProduceSound()
        {
            return "MiauMiau";
        }
    }
}


text:
package gex.newsml.g2;

import lombok.ToString;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAnyAttribute;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlID;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import javax.xml.namespace.QName;

/**
 * The type for an internationalized and unrestricted string, where the language
 * and directionality in which the information is writte are indirected
 *
 *

 * Java class for IntlStringType2 complex type.
 *
 *

 * The following schema fragment specifies the expected content contained within
 * this class.
 *
 *

 * <complexType name="IntlStringType2">
 *   <simpleContent>
 *     <extension base="<http://www.w3.org/2001/XMLSchema>string">
 *       <attGroup ref="{http://iptc.org/std/nar/2006-10-01/}commonPowerAttributes"/>
 *       <attGroup ref="{http://iptc.org/std/nar/2006-10-01/}i18nAttributes"/>
 *       <anyAttribute processContents='lax' namespace='##other'/>
 *     </extension>
 *   </simpleContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "IntlStringType2", propOrder = { "value" })
@XmlSeeAlso({ AltId.class })
@ToString
public class IntlStringType2 {

	@XmlValue
	protected String value;
	@XmlAttribute(name = "id")
	@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
	@XmlID
	@XmlSchemaType(name = "ID")
	protected String id;
	@XmlAttribute(name = "creator")
	protected String creator;
	@XmlAttribute(name = "creatoruri")
	protected String creatoruri;
	@XmlAttribute(name = "modified")
	protected String modified;
	@XmlAttribute(name = "custom")
	protected Boolean custom;
	@XmlAttribute(name = "how")
	protected String how;
	@XmlAttribute(name = "howuri")
	protected String howuri;
	@XmlAttribute(name = "why")
	protected String why;
	@XmlAttribute(name = "whyuri")
	protected String whyuri;
	@XmlAttribute(name = "pubconstraint")
	protected List<String> pubconstraint;
	@XmlAttribute(name = "pubconstrainturi")
	protected List<String> pubconstrainturi;
	@XmlAttribute(name = "lang", namespace = "http://www.w3.org/XML/1998/namespace")
	protected String lang;
	@XmlAttribute(name = "dir")
	@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
	protected String dir;
	@XmlAnyAttribute
	private Map<QName, String> otherAttributes = new HashMap<QName, String>();

	/**
	 * Gets the value of the value property.
	 *
	 * @return possible object is {@link String }
	 *
	 */
	public String getValue() {
		return value;
	}

	/**
	 * Sets the value of the value property.
	 *
	 * @param value
	 *            allowed object is {@link String }
	 *
	 */
	public void setValue(String value) {
		this.value = value;
	}

	/**
	 * Gets the value of the id property.
	 *
	 * @return possible object is {@link String }
	 *
	 */
	public String getId() {
		return id;
	}

	/**
	 * Sets the value of the id property.
	 *
	 * @param value
	 *            allowed object is {@link String }
	 *
	 */
	public void setId(String value) {
		this.id = value;
	}

	/**
	 * Gets the value of the creator property.
	 *
	 * @return possible object is {@link String }
	 *
	 */
	public String getCreator() {
		return creator;
	}

	/**
	 * Sets the value of the creator property.
	 *
	 * @param value
	 *            allowed object is {@link String }
	 *
	 */
	public void setCreator(String value) {
		this.creator = value;
	}

	/**
	 * Gets the value of the creatoruri property.
	 *
	 * @return possible object is {@link String }
	 *
	 */
	public String getCreatoruri() {
		return creatoruri;
	}

	/**
	 * Sets the value of the creatoruri property.
	 *
	 * @param value
	 *            allowed object is {@link String }
	 *
	 */
	public void setCreatoruri(String value) {
		this.creatoruri = value;
	}

	/**
	 * Gets the value of the modified property.
	 *
	 * @return possible object is {@link String }
	 *
	 */
	public String getModified() {
		return modified;
	}

	/**
	 * Sets the value of the modified property.
	 *
	 * @param value
	 *            allowed object is {@link String }
	 *
	 */
	public void setModified(String value) {
		this.modified = value;
	}

	/**
	 * Gets the value of the custom property.
	 *
	 * @return possible object is {@link Boolean }
	 *
	 */
	public Boolean isCustom() {
		return custom;
	}

	/**
	 * Sets the value of the custom property.
	 *
	 * @param value
	 *            allowed object is {@link Boolean }
	 *
	 */
	public void setCustom(Boolean value) {
		this.custom = value;
	}

	/**
	 * Gets the value of the how property.
	 *
	 * @return possible object is {@link String }
	 *
	 */
	public String getHow() {
		return how;
	}

	/**
	 * Sets the value of the how property.
	 *
	 * @param value
	 *            allowed object is {@link String }
	 *
	 */
	public void setHow(String value) {
		this.how = value;
	}

	/**
	 * Gets the value of the howuri property.
	 *
	 * @return possible object is {@link String }
	 *
	 */
	public String getHowuri() {
		return howuri;
	}

	/**
	 * Sets the value of the howuri property.
	 *
	 * @param value
	 *            allowed object is {@link String }
	 *
	 */
	public void setHowuri(String value) {
		this.howuri = value;
	}

	/**
	 * Gets the value of the why property.
	 *
	 * @return possible object is {@link String }
	 *
	 */
	public String getWhy() {
		return why;
	}

	/**
	 * Sets the value of the why property.
	 *
	 * @param value
	 *            allowed object is {@link String }
	 *
	 */
	public void setWhy(String value) {
		this.why = value;
	}

	/**
	 * Gets the value of the whyuri property.
	 *
	 * @return possible object is {@link String }
	 *
	 */
	public String getWhyuri() {
		return whyuri;
	}

	/**
	 * Sets the value of the whyuri property.
	 *
	 * @param value
	 *            allowed object is {@link String }
	 *
	 */
	public void setWhyuri(String value) {
		this.whyuri = value;
	}

	/**
	 * Gets the value of the pubconstraint property.
	 *
	 *

	 * This accessor method returns a reference to the live list, not a
	 * snapshot. Therefore any modification you make to the returned list will
	 * be present inside the JAXB object. This is why there is not a
	 * set method for the pubconstraint property.
	 *
	 *

	 * For example, to add a new item, do as follows:
	 *
	 *

	 * getPubconstraint().add(newItem);
	 *

	 *
	 *
	 *

	 * Objects of the following type(s) are allowed in the list {@link String }
	 *
	 *
	 */
	public List<String> getPubconstraint() {
		if (pubconstraint == null) {
			pubconstraint = new ArrayList<String>();
		}
		return this.pubconstraint;
	}

	/**
	 * Gets the value of the pubconstrainturi property.
	 *
	 *

	 * This accessor method returns a reference to the live list, not a
	 * snapshot. Therefore any modification you make to the returned list will
	 * be present inside the JAXB object. This is why there is not a
	 * set method for the pubconstrainturi property.
	 *
	 *

	 * For example, to add a new item, do as follows:
	 *
	 *

	 * getPubconstrainturi().add(newItem);
	 *

	 *
	 *
	 *

	 * Objects of the following type(s) are allowed in the list {@link String }
	 *
	 *
	 */
	public List<String> getPubconstrainturi() {
		if (pubconstrainturi == null) {
			pubconstrainturi = new ArrayList<String>();
		}
		return this.pubconstrainturi;
	}

	/**
	 * Specifies the language of this property and potentially all descendant
	 * properties. xml:lang values of descendant properties override this value.
	 * Values are determined by Internet BCP 47.
	 *
	 * @return possible object is {@link String }
	 *
	 */
	public String getLang() {
		return lang;
	}

	/**
	 * Sets the value of the lang property.
	 *
	 * @param value
	 *            allowed object is {@link String }
	 *
	 */
	public void setLang(String value) {
		this.lang = value;
	}

	/**
	 * Gets the value of the dir property.
	 *
	 * @return possible object is {@link String }
	 *
	 */
	public String getDir() {
		return dir;
	}

	/**
	 * Sets the value of the dir property.
	 *
	 * @param value
	 *            allowed object is {@link String }
	 *
	 */
	public void setDir(String value) {
		this.dir = value;
	}

	/**
	 * Gets a map that contains attributes that aren't bound to any typed
	 * property on this class.
	 *
	 *

	 * the map is keyed by the name of the attribute and the value is the string
	 * value of the attribute.
	 *
	 * the map returned by this method is live, and you can add new attribute by
	 * updating the map directly. Because of this design, there's no setter.
	 *
	 *
	 * @return always non-null
	 */
	public Map<QName, String> getOtherAttributes() {
		return otherAttributes;
	}

}


text:
using System;
using System.Linq;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using SolidworksAddinFramework.Events;
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using Weingartner.WeinCad.Interfaces;
using Weingartner.WeinCad.Interfaces.Monads;

namespace SolidworksAddinFramework
{
    public static class SldWorksExtensions
    {

        public static IObservable<IModelDoc2> DocOpenObservable(this SldWorks swApp)
        {
            return swApp.DocumentLoadNotify2Observable()
                .Select(args => swApp
                    .GetDocuments()
                    .CastArray<IModelDoc2>()
                    .Single(doc => doc.GetTitle() == args.docTitle && doc.GetPathName() == args.docPath)
                );
        }

        public static IDisposable DoWithOpenDoc(this SldWorks swApp, Func<IModelDoc2, IDisposable> action)
        {
            var d = new CompositeDisposable();
            swApp.DocOpenObservable()
                .SelectDisposable(d, action, (doc, disposable) => doc
                    .DestroyNotify2Observable()
                    .FirstAsync()
                    .Select(_ => disposable)
                )
                .SelectMany(p => p)
                .Subscribe(disposable => disposable.Dispose())
                .DisposeWith(d);
            return d;
        }

        public static IDisposable DoWithOpenDoc(this SldWorks swApp, Action<IModelDoc2, Action<IDisposable>> action)
        {
            Func<IModelDoc2, IDisposable> func = doc =>
            {
                var disposables = new CompositeDisposable();
                action(doc, disposables.Add);
                return disposables;
            };
            return swApp.DoWithOpenDoc(func);
        }

        /// <summary>
        /// Open a document invisibly. It will not be shown to the user but you will be
        /// able to interact with it through the API as if it is loaded.
        /// </summary>
        /// <param name="sldWorks"></param>
        /// <param name="toolFile"></param>
        /// <returns></returns>
        public static ModelDoc2 OpenInvisibleReadOnly(this ISldWorks sldWorks, string toolFile, bool visible = false, swDocumentTypes_e type = swDocumentTypes_e.swDocPART)
        {
            try
            {
                if (!visible)
                    sldWorks.DocumentVisible(false, (int)type);
                var spec = (IDocumentSpecification)sldWorks.GetOpenDocSpec(toolFile);
                if (!visible)
                {
                    spec.Silent = true;
                    spec.ReadOnly = true;
                }
                var doc = SwAddinBase.Active.SwApp.OpenDoc7(spec);

                doc.Visible = visible;
                return doc;
            }
            finally
            {
                if (!visible)
                    sldWorks.DocumentVisible
                        (true,
                            (int)
                                type);

            }
        }

        /// <summary>
        /// Tries to load an iges file invisibly. Throws an exception if it doesn't work.
        /// </summary>
        /// <param name="sldWorks"></param>
        /// <param name="igesFile"></param>
        /// <param name="visible"></param>
        /// <returns></returns>
        public static ModelDoc2 LoadIgesInvisible(this ISldWorks sldWorks, string igesFile, bool visible = false)
        {
            var swDocPart = (int)swDocumentTypes_e.swDocPART;

            try
            {
                if (!visible)
                    sldWorks.DocumentVisible(false, swDocPart);

                ImportIgesData swImportData =
                    (ImportIgesData)SwAddinBase.Active.SwApp.GetImportFileData(igesFile);

                int err = 0;
                var newDoc = SwAddinBase.Active.SwApp.LoadFile4(igesFile, "r", swImportData, ref err);
                if (err != 0)
                    throw new Exception(@"Unable to load file {igesFile");

                return newDoc;
            }
            finally
            {
                if (!visible)
                    sldWorks.DocumentVisible
                        (true,
                            swDocPart);

            }
        }

        public static ModelDoc2 CreateHiddenDocument
            (this ISldWorks sldWorks, bool hidden = true, swDocumentTypes_e type = swDocumentTypes_e.swDocPART)
        {
            try
            {

                if (hidden)
                    sldWorks.DocumentVisible(false, (int)type);

                var partTemplateName = sldWorks.GetUserPreferenceStringValue((int)swUserPreferenceStringValue_e.swDefaultTemplatePart);
                var doc = (ModelDoc2)sldWorks.NewDocument(partTemplateName, (int)swDwgPaperSizes_e.swDwgPaperA4size, 1, 1);
                doc.Visible = false;

                /*
                ModelView myModelView = null;
                myModelView = ((ModelView)(doc.ActiveView));
                myModelView.FrameLeft = 0;
                myModelView.FrameTop = 0;
                myModelView = ((ModelView)(doc.ActiveView));

                myModelView.FrameState = ((int)(swWindowState_e.swWindowMinimized));
                */
                return doc;
            }
            finally
            {
                if (hidden)
                    sldWorks.DocumentVisible
                        (true,
                            (int)
                                type);

            }

        }
    }
}


text:
* The start method now runs its life cycle methods synchronously if all defined methods are synchronous.
    * This allows certain simplifications, for example:

        ```javascript
        synchronousView.start()
            .done(function() {
                doSomethingThatReliesOnTheViewBeingStarted();
            });
        ```

    * can now optionally be simplified to synchronous code:

        ```javascript
        synchronousView.start();
        doSomethingThatReliesOnTheViewBeingStarted();
        ```

    * but any code that was listening for progress on a synchronous view has to be modified to use the built in events:

        ```javascript
        # cannot notify on promises that are resolved, so the following has to be changed:
        synchView.start().progress(function(event) { if ("..." === event) ...

        # to:
        synchView.on("...", ...);
        synchView.start();
        ```


text:
{% extends "blog/base_blog.html" %}
{% load cache i18n archive %}

{% block body_class %}{{ block.super }} category_detail{% endblock %}
{% block body_id %}category_{{ category.id }}{% endblock %}

{% block content %}

{% trans "Posts for" %} {{ year }}

{% get_post_archive as months %}

    {% for date in months %}

{{ date|date:"F Y" }}

    {% endfor %}

    {% for post in object_list %}
        {% include "blog/includes/post_list.html" %}
    {% endfor %}

{% endblock %}


text:
//---------------------------------------------------------------------
// Author: Keith Hill
//
// Description: Class to implement the Get-DriveInfo cmdlet.
//
// Creation Date: Feb 12, 2008
//---------------------------------------------------------------------
using System;
using System.IO;
using System.Management.Automation;
using Microsoft.PowerShell.Commands;

namespace Pscx.Commands.IO
{
    [Cmdlet(VerbsCommon.Get, PscxNouns.DriveInfo)]
    [OutputType(new[] {typeof(DriveInfo)})]
    [ProviderConstraint(typeof(FileSystemProvider))]
    public class GetDriveInfoCommand : PscxCmdlet
    {
        protected override void EndProcessing()
        {
            object target = null;
            try
            {
                DriveInfo[] drives = DriveInfo.GetDrives();
                foreach (DriveInfo driveInfo in drives)
                {
                    target = driveInfo;
                    if (driveInfo.IsReady &&
                        (driveInfo.DriveType != DriveType.Network) &&
                        (driveInfo.DriveType != DriveType.CDRom))
                    {
                        WriteObject(driveInfo);
                    }
                }
            }
            catch (PipelineStoppedException)
            {
                throw;
            }
            catch (Exception ex)
            {
                WriteError(new ErrorRecord(ex, "Get-DriveInfo", ErrorCategory.NotSpecified, target));
            }
        }
    }
}


text:
from collections import namedtuple
import unittest
import tempfile
import shutil
import numpy as np

from ray.tune.logger import JsonLogger, CSVLogger, TBXLogger

Trial = namedtuple("MockTrial", ["evaluated_params", "trial_id"])

def result(t, rew, **kwargs):
    results = dict(
        time_total_s=t,
        episode_reward_mean=rew,
        mean_accuracy=rew * 2,
        training_iteration=int(t))
    results.update(kwargs)
    return results

class LoggerSuite(unittest.TestCase):
    """Test built-in loggers."""

    def setUp(self):
        self.test_dir = tempfile.mkdtemp()

    def tearDown(self):
        shutil.rmtree(self.test_dir, ignore_errors=True)

    def testCSV(self):
        config = {"a": 2, "b": 5, "c": {"c": {"D": 123}, "e": None}}
        t = Trial(evaluated_params=config, trial_id="csv")
        logger = CSVLogger(config=config, logdir=self.test_dir, trial=t)
        logger.on_result(result(2, 4))
        logger.on_result(result(2, 4))
        logger.on_result(result(2, 4, score=[1, 2, 3], hello={"world": 1}))
        logger.close()

    def testJSON(self):
        config = {"a": 2, "b": 5, "c": {"c": {"D": 123}, "e": None}}
        t = Trial(evaluated_params=config, trial_id="json")
        logger = JsonLogger(config=config, logdir=self.test_dir, trial=t)
        logger.on_result(result(0, 4))
        logger.on_result(result(1, 4))
        logger.on_result(result(2, 4, score=[1, 2, 3], hello={"world": 1}))
        logger.close()

    def testTBX(self):
        config = {
            "a": 2,
            "b": [1, 2],
            "c": {
                "c": {
                    "D": 123
                }
            },
            "d": np.int64(1),
            "e": np.bool8(True)
        }
        t = Trial(evaluated_params=config, trial_id="tbx")
        logger = TBXLogger(config=config, logdir=self.test_dir, trial=t)
        logger.on_result(result(0, 4))
        logger.on_result(result(1, 4))
        logger.on_result(result(2, 4, score=[1, 2, 3], hello={"world": 1}))
        logger.close()

    def testBadTBX(self):
        config = {"b": (1, 2, 3)}
        t = Trial(evaluated_params=config, trial_id="tbx")
        logger = TBXLogger(config=config, logdir=self.test_dir, trial=t)
        logger.on_result(result(0, 4))
        logger.on_result(result(2, 4, score=[1, 2, 3], hello={"world": 1}))
        with self.assertLogs("ray.tune.logger", level="INFO") as cm:
            logger.close()
        assert "INFO" in cm.output[0]

        config = {"None": None}
        t = Trial(evaluated_params=config, trial_id="tbx")
        logger = TBXLogger(config=config, logdir=self.test_dir, trial=t)
        logger.on_result(result(0, 4))
        logger.on_result(result(2, 4, score=[1, 2, 3], hello={"world": 1}))
        with self.assertLogs("ray.tune.logger", level="INFO") as cm:
            logger.close()
        assert "INFO" in cm.output[0]

if __name__ == "__main__":
    import pytest
    import sys
    sys.exit(pytest.main(["-v", __file__]))


text:
package org.gmod.gbol.simpleObject;

import java.util.ArrayList;
import java.util.Collection;

/*
 * Autogenerated extension of org.gmod.gbol.simpleObject.generated.FeaturePhenotype.
 * Add custom code to this file.
 *
 * Author: Robert Bruggner, rbruggner@berkeleybop.org
 *
*/

public class FeaturePhenotype extends org.gmod.gbol.simpleObject.generated.AbstractFeaturePhenotype {

	private static final long serialVersionUID = 1L;

	public FeaturePhenotype(){
		super();
	}

//	@Override
//	public Collection<AbstractSimpleObject> getWriteObjects() {
//		ArrayList<AbstractSimpleObject> writeObjects = new ArrayList<AbstractSimpleObject>();
//		// Have to write yourself
//		writeObjects.add(this);
//
//		// Singletons
//		writeObjects.addAll(this.getPhenotype().getWriteObjects());
//
//		return writeObjects;
//	}

	public AbstractSimpleObjectIterator getWriteableObjects()
	{
		return new SimpleObjectIterator(this);
	}

	private static class SimpleObjectIterator extends AbstractSimpleObjectIterator
	{

		private static class Status extends AbstractSimpleObjectIterator.Status
		{
			public final static int phenotype = 1;
		}

		public SimpleObjectIterator(FeaturePhenotype featurePhenotype)
		{
			super(featurePhenotype);
		}

		public AbstractSimpleObject next()
		{
			FeaturePhenotype featurePhenotype = (FeaturePhenotype)object;
			AbstractSimpleObject retVal = null;
			if (status == Status.self) {
				retVal = peek();
				processSingletonIterator(Status.phenotype, featurePhenotype.getPhenotype());
			}
			else {
				if (status == Status.phenotype) {
					retVal = soIter.next();
				}
			}
			current = retVal;
			return retVal;
		}
	}

}


text:
const express = require("express");
const app = express();

app.use(express.static("./public", {
    maxAge : "365 days"
}));
// TODO Add cache control support

const port = process.env.PORT || 8080 ;
app.listen(port, () => {
    console.log(`The server is now running at port ${port}...`);
});


text:
package com.strongloop.android.loopback.guide.lessons;

import java.util.List;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.strongloop.android.loopback.Model;
import com.strongloop.android.loopback.ModelRepository;
import com.strongloop.android.loopback.RestAdapter;
import com.strongloop.android.loopback.guide.GuideApplication;
import com.strongloop.android.loopback.guide.R;
import com.strongloop.android.loopback.guide.util.HtmlFragment;

/**
 * Implementation for Lesson Two: Existing Data? No Problem.
 */
public class LessonTwoFragment extends HtmlFragment {

    /**
     * Unlike Lesson One, our CarModel class is based _entirely_ on an existing schema.
     *
     * In this case, every field in Oracle that's defined as a NUMBER type becomes a Number,
     * and each field defined as a VARCHAR2 becomes a String.
     *
     * When we load these models from Oracle, LoopBack uses these property setters and getters
     * to know what data we care about. If we left off `extras`, for example, LoopBack would
     * simply omit that field.
     */
    public static class CarModel extends Model {
    	private String vin;
    	private int year;
    	private String make;
    	private String model;
    	private String image;
    	private String carClass;
    	private String color;

    	public String getVin() {
			return vin;
		}
		public void setVin(String vin) {
			this.vin = vin;
		}
		public int getYear() {
			return year;
		}
		public void setYear(int year) {
			this.year = year;
		}
		public String getMake() {
			return make;
		}
		public void setMake(String make) {
			this.make = make;
		}
		public String getModel() {
			return model;
		}
		public void setModel(String model) {
			this.model = model;
		}
		public String getImage() {
			return image;
		}
		public void setImage(String image) {
			this.image = image;
		}
		public String getCarClass() {
			return carClass;
		}
		public void setCarClass(String carClass) {
			this.carClass = carClass;
		}
		public String getColor() {
			return color;
		}
		public void setColor(String color) {
			this.color = color;
		}
    }

    /**
     * Our custom ModelRepository subclass. See Lesson One for more information.
     */
    public static class CarRepository extends ModelRepository<CarModel> {
        public CarRepository() {
            super("car", CarModel.class);
        }
    }

    /**
     * Loads all Car models from the server. To make full use of this, return to your (running)
     * Sample Application and restart it with the DB environment variable set to "oracle".
     * For example, on most *nix flavors (including Mac OS X), that looks like:
     *
     * 1. Stop the current server with Ctrl-C.
     * 2. DB=oracle slc run app
     *
     * What does this do, you ask? Without that environment variable, the Sample Application uses
     * simple, in-memory storage for all models. With the environment variable, it uses a custom-made
     * Oracle adapter with a demo Oracle database we host for this purpose. If you have existing
     * data, it's that easy to pull into LoopBack. No need to leave it behind.
     *
     * Advanced users: LoopBack supports multiple data sources simultaneously, albeit on a per-model
     * basis. In your next project, try connecting a schema-less model (e.g. our Note example)
     * to a Mongo data source, while connecting a legacy model (e.g. this Car example) to
     * an Oracle data source.
     */
    private void sendRequest() {
        // 1. Grab the shared RestAdapter instance.
        GuideApplication app = (GuideApplication)getActivity().getApplication();
        RestAdapter adapter = app.getLoopBackAdapter();

        // 2. Instantiate our CarRepository.See LessonOneView for further discussion.
        CarRepository repository = adapter.createRepository(CarRepository.class);

        // 3. Rather than instantiate a model directly like we did in Lesson One, we'll query
        //    the server for all Cars, filling out our ListView with the results. In this case,
        //    the Repository is really the workhorse; the Model is just a simple container.

        repository.findAll(new ModelRepository.FindAllCallback<LessonTwoFragment.CarModel>() {
            @Override
            public void onSuccess(List<CarModel> models) {
                list.setAdapter(new CarListAdapter(getActivity(), models));
            }

            @Override
            public void onError(Throwable t) {
                Log.e(getTag(), "Cannot save Note model.", t);
                showResult("Failed.");
            }
        });
    }

    private void showResult(String message) {
        Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
    }

    /**
     * Basic ListAdapter implementation using our custom Model type.
     */
    private static class CarListAdapter extends ArrayAdapter<CarModel> {
        public CarListAdapter(Context context, List<CarModel> list) {
            super(context, 0, list);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(getContext()).inflate(
                        android.R.layout.simple_list_item_1, null);
            }

            CarModel model = getItem(position);
            if (model == null) return convertView;

            TextView textView = (TextView)convertView.findViewById(
                    android.R.id.text1);
            textView.setText(
                    model.getModel() + " - " + model.getYear());

            return convertView;
        }
    }

    //
    // GUI glue
    //
    private ListView list;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        setRootView((ViewGroup) inflater.inflate(
                R.layout.fragment_lesson_two, container, false));

        list = (ListView)getRootView().findViewById(R.id.list);

        setHtmlText(R.id.content, R.string.lessonTwo_content);

        installButtonClickHandler();

        return getRootView();
    }

    private void installButtonClickHandler() {
        final Button button = (Button) getRootView().findViewById(R.id.sendRequest);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                sendRequest();
            }
        });
    }
}


text:
Create a application using these controls:
* ContentControl
* HeaderedContentControl
* ItemsControl
* HeaderedItemsControl
* Frame (navigate to a Web page)
* Use bubbling and tunneling events with different Button controls

## Create a WPF Editor

* Create a WPF application WPFEditor
* Add a TextBox control that allows multiple text lines
* Add a Menu control with File -> Open, File -> Save, File -> Close, and Edit -> Cut, Copy, Paste, Undo
* Add command handlers to read and save files
* Define menus for Cut/Copy/Paste/Undo
* Create a custom command for the WPFEditor


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>ClassInfo.ClassInfoAction (Groovy 2.4.4)</title>
<meta name="date" content="2015-07-09">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.codehaus.groovy.reflection

Interface ClassInfo.ClassInfoAction

Enclosing class:

ClassInfo

public static interface ClassInfo.ClassInfoAction

Method Summary

Methods

Modifier and Type
Method and Description

void
onClassInfo(ClassInfo classInfo)

Method Detail

onClassInfo

void onClassInfo(ClassInfo classInfo)

Overview

Package

Class

Tree

Deprecated

Index

Help

Copyright © 2003-2015 The Apache Software Foundation. All rights reserved.

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
from __future__ import unicode_literals
from moto.core.responses import BaseResponse

class SpotFleets(BaseResponse):

    def cancel_spot_fleet_requests(self):
        spot_fleet_request_ids = self._get_multi_param("SpotFleetRequestId.")
        terminate_instances = self._get_param("TerminateInstances")
        spot_fleets = self.ec2_backend.cancel_spot_fleet_requests(
            spot_fleet_request_ids, terminate_instances)
        template = self.response_template(CANCEL_SPOT_FLEETS_TEMPLATE)
        return template.render(spot_fleets=spot_fleets)

    def describe_spot_fleet_instances(self):
        spot_fleet_request_id = self._get_param("SpotFleetRequestId")

        spot_requests = self.ec2_backend.describe_spot_fleet_instances(
            spot_fleet_request_id)
        template = self.response_template(
            DESCRIBE_SPOT_FLEET_INSTANCES_TEMPLATE)
        return template.render(spot_request_id=spot_fleet_request_id, spot_requests=spot_requests)

    def describe_spot_fleet_requests(self):
        spot_fleet_request_ids = self._get_multi_param("SpotFleetRequestId.")

        requests = self.ec2_backend.describe_spot_fleet_requests(
            spot_fleet_request_ids)
        template = self.response_template(DESCRIBE_SPOT_FLEET_TEMPLATE)
        return template.render(requests=requests)

    def modify_spot_fleet_request(self):
        spot_fleet_request_id = self._get_param("SpotFleetRequestId")
        target_capacity = self._get_int_param("TargetCapacity")
        terminate_instances = self._get_param("ExcessCapacityTerminationPolicy", if_none="Default")
        successful = self.ec2_backend.modify_spot_fleet_request(
            spot_fleet_request_id, target_capacity, terminate_instances)
        template = self.response_template(MODIFY_SPOT_FLEET_REQUEST_TEMPLATE)
        return template.render(successful=successful)

    def request_spot_fleet(self):
        spot_config = self._get_dict_param("SpotFleetRequestConfig.")
        spot_price = spot_config['spot_price']
        target_capacity = spot_config['target_capacity']
        iam_fleet_role = spot_config['iam_fleet_role']
        allocation_strategy = spot_config['allocation_strategy']

        launch_specs = self._get_list_prefix(
            "SpotFleetRequestConfig.LaunchSpecifications")

        request = self.ec2_backend.request_spot_fleet(
            spot_price=spot_price,
            target_capacity=target_capacity,
            iam_fleet_role=iam_fleet_role,
            allocation_strategy=allocation_strategy,
            launch_specs=launch_specs,
        )

        template = self.response_template(REQUEST_SPOT_FLEET_TEMPLATE)
        return template.render(request=request)

REQUEST_SPOT_FLEET_TEMPLATE = """<RequestSpotFleetResponse xmlns="http://ec2.amazonaws.com/doc/2016-09-15/">
    <requestId>60262cc5-2bd4-4c8d-98ed-example</requestId>
    <spotFleetRequestId>{{ request.id }}</spotFleetRequestId>
</RequestSpotFleetResponse>"""

MODIFY_SPOT_FLEET_REQUEST_TEMPLATE = """<ModifySpotFleetRequestResponse xmlns="http://ec2.amazonaws.com/doc/2016-09-15/">
    <requestId>21681fea-9987-aef3-2121-example</requestId>
    <return>{{ 'true' if successful else 'false' }}</return>
</ModifySpotFleetRequestResponse>"""

DESCRIBE_SPOT_FLEET_TEMPLATE = """<DescribeSpotFleetRequestsResponse xmlns="http://ec2.amazonaws.com/doc/2016-09-15/">
    <requestId>4d68a6cc-8f2e-4be1-b425-example</requestId>
    <spotFleetRequestConfigSet>
        {% for request in requests %}
        <item>
            <spotFleetRequestId>{{ request.id }}</spotFleetRequestId>
            <spotFleetRequestState>{{ request.state }}</spotFleetRequestState>
            <spotFleetRequestConfig>
                <spotPrice>{{ request.spot_price }}</spotPrice>
                <targetCapacity>{{ request.target_capacity }}</targetCapacity>
                <iamFleetRole>{{ request.iam_fleet_role }}</iamFleetRole>
                <allocationStrategy>{{ request.allocation_strategy }}</allocationStrategy>
                <fulfilledCapacity>{{ request.fulfilled_capacity }}</fulfilledCapacity>
                <launchSpecifications>
                    {% for launch_spec in request.launch_specs %}
                    <item>
                        <subnetId>{{ launch_spec.subnet_id }}</subnetId>
                        <ebsOptimized>{{ launch_spec.ebs_optimized }}</ebsOptimized>
                        <imageId>{{ launch_spec.image_id }}</imageId>
                        <instanceType>{{ launch_spec.instance_type }}</instanceType>
                        <iamInstanceProfile><arn>{{ launch_spec.iam_instance_profile }}</arn></iamInstanceProfile>
                        <keyName>{{ launch_spec.key_name }}</keyName>
                        <monitoring><enabled>{{ launch_spec.monitoring }}</enabled></monitoring>
                        <spotPrice>{{ launch_spec.spot_price }}</spotPrice>
                        <userData>{{ launch_spec.user_data }}</userData>
                        <weightedCapacity>{{ launch_spec.weighted_capacity }}</weightedCapacity>
                        <groupSet>
                            {% for group in launch_spec.group_set %}
                            <item>
                                <groupId>{{ group }}</groupId>
                            </item>
                            {% endfor %}
                        </groupSet>
                    </item>
                    {% endfor %}
                </launchSpecifications>
            </spotFleetRequestConfig>
        </item>
        {% endfor %}
    </spotFleetRequestConfigSet>
</DescribeSpotFleetRequestsResponse>"""

DESCRIBE_SPOT_FLEET_INSTANCES_TEMPLATE = """<DescribeSpotFleetInstancesResponse xmlns="http://ec2.amazonaws.com/doc/2016-09-15/">
    <requestId>cfb09950-45e2-472d-a6a9-example</requestId>
    <spotFleetRequestId>{{ spot_request_id }}</spotFleetRequestId>
    <activeInstanceSet>
        {% for spot_request in spot_requests %}
        <item>
            <instanceId>{{ spot_request.instance.id }}</instanceId>
            <spotInstanceRequestId>{{ spot_request.id }}</spotInstanceRequestId>
            <instanceType>{{ spot_request.instance.instance_type }}</instanceType>
        </item>
        {% endfor %}
    </activeInstanceSet>
</DescribeSpotFleetInstancesResponse>
"""

CANCEL_SPOT_FLEETS_TEMPLATE = """<CancelSpotFleetRequestsResponse xmlns="http://ec2.amazonaws.com/doc/2016-09-15/">
    <requestId>e12d2fe5-6503-4b4b-911c-example</requestId>
    <unsuccessfulFleetRequestSet/>
    <successfulFleetRequestSet>
        {% for spot_fleet in spot_fleets %}
        <item>
            <spotFleetRequestId>{{ spot_fleet.id }}</spotFleetRequestId>
            <currentSpotFleetRequestState>cancelled_terminating</currentSpotFleetRequestState>
            <previousSpotFleetRequestState>active</previousSpotFleetRequestState>
        </item>
        {% endfor %}
    </successfulFleetRequestSet>
</CancelSpotFleetRequestsResponse>"""


text:
![SignalTanh picture](SignalTanh.svg)

Contains a signal hyperbolic tangent function component

#### Input Variables
* **in** - Input value [-]

#### Output Variables
* **out** - Output value [-]

### Theory
<!---EQUATION out = \tanh(in) = \dfrac{e^{in}-e^{-in}}{e^{in}+e^{-in}} --->


text:
from __future__ import unicode_literals
import argparse
from glob import glob
from itertools import izip
from os.path import basename
import sys

from konlpy.tag import Hannanum # konlpy>=0.3.0
from pokr.database import transaction
from pokr.models.bill import Bill
from pokr.models.bill_keyword import bill_keyword
from pokr.models.keyword import Keyword
from popong_nlp.extractor.extract import keywords as extract_keywords
from utils.command import Command

class BillKeywordCommand(Command):
    __command__ = 'bill_keyword'

class UpdateBillKeywordsCommand(Command):
    __command__ = 'update'
    __parent__ = BillKeywordCommand

    @classmethod
    def init_parser_options(cls):
        cls.parser.add_argument('files')

    @classmethod
    def run(cls, files, **kwargs):
        insert_bill_keywords(files)

def insert_bill_keywords(files):
    hannanum = Hannanum()
    with transaction() as session:
        existing_bill_ids = set(r[0] for r in session.query(Bill.id))
        keyword_store = KeywordStore(session)
        for file_ in glob(files):
            filename = basename(file_)
            print 'processing %s,' % filename,
            bill_id = filename.split('.', 1)[0]
            if bill_id not in existing_bill_ids:
                continue
            with open(file_, 'r') as f:
                keywords = extract_keywords(f, hannanum)
            keyword_ids = [keyword_store.id(keyword[0]) for keyword in keywords]
            keyword_store.sync()
            existing_keywords_for_bill = set(r[0]
                    for r in session.query(bill_keyword.c.keyword_id)\
                                     .filter(bill_keyword.c.bill_id == bill_id)
            )

            new_bill_keywords = [
                {
                    'bill_id': bill_id,
                    'keyword_id': keyword_id,
                    'weight': weight,
                }
                for (_, weight), keyword_id in izip(keywords, keyword_ids)
                if keyword_id not in existing_keywords_for_bill
            ]

            if new_bill_keywords:
                # TODO(lucypark, 2014-12-13): delete existing keywords before insert
                session.execute(bill_keyword.insert(), new_bill_keywords)
                print 'done'
            else:
                print 'passed'

class KeywordStore(object):
    dict_ = {}
    last_id = 0
    last_id_in_db = 0

    def __init__(self, session=None):
        if session:
            self.init(session)

    def init(self, session):
        bss = session.query(Keyword.id, Keyword.name)\
                     .order_by(Keyword.id)\
                     .all()
        self.dict_ = {
            r[1]: r[0] for r in bss
        }
        self.last_id_in_db = self.last_id = bss[-1][0] if bss else 0
        self.session = session

    def id(self, name):
        if name not in self.dict_:
            self.last_id += 1
            self.dict_[name] = self.last_id
        return self.dict_[name]

    def sync(self):
        keywords = [{
                        'id': id,
                        'name': name
                    } for name, id in self.dict_.items()
                      if id > self.last_id_in_db]
        if keywords:
            self.session.execute(Keyword.__table__.insert(), keywords)
            self.session.flush()
        self.last_id_in_db = self.last_id