text:
#ifdef USE_TI_UISCROLLVIEW

#import "TiUIScrollViewProxy.h"
#import "TiUIScrollView.h"

#import "TiUtils.h"

@implementation TiUIScrollViewProxy

static NSArray* scrollViewKeySequence;
-(NSArray *)keySequence
{
    if (scrollViewKeySequence == nil)
    {
        //URL has to be processed first since the spinner depends on URL being remote
        scrollViewKeySequence = [[NSArray arrayWithObjects:@"minZoomScale",@"maxZoomScale",@"zoomScale",nil] retain];
    }
    return scrollViewKeySequence;
}

-(void)_initWithProperties:(NSDictionary *)properties
{
    [self initializeProperty:@"minZoomScale" defaultValue:NUMFLOAT(1.0)];
    [self initializeProperty:@"maxZoomScale" defaultValue:NUMFLOAT(1.0)];
    [self initializeProperty:@"zoomScale" defaultValue:NUMFLOAT(1.0)];
    [self initializeProperty:@"canCancelEvents" defaultValue:NUMBOOL(YES)];
    [self initializeProperty:@"scrollingEnabled" defaultValue:NUMBOOL(YES)];
    [super _initWithProperties:properties];
}

-(NSString*)apiName
{
    return @"Ti.UI.ScrollView";
}

-(TiPoint *) contentOffset{
    if([self viewAttached]){
        TiThreadPerformOnMainThread(^{
                   contentOffset = [[TiPoint alloc] initWithPoint:CGPointMake(
                                        [(TiUIScrollView *)[self view] scrollView].contentOffset.x,
                                        [(TiUIScrollView *)[self view] scrollView].contentOffset.y)] ;
          }, YES);
    }
    else{
        contentOffset = [[TiPoint alloc] initWithPoint:CGPointMake(0,0)];
    }
    return [contentOffset autorelease];
}

-(void)windowWillOpen
{
    [super windowWillOpen];
    //Since layout children is overridden in scrollview need to make sure that
    //a full layout occurs atleast once if view is attached
    if ([self viewAttached]) {
        [self contentsWillChange];
    }
}

-(void)contentsWillChange
{
	if ([self viewAttached])
	{
		[(TiUIScrollView *)[self view] setNeedsHandleContentSize];
	}
	[super contentsWillChange];
}

-(void)willChangeSize
{
	if ([self viewAttached])
	{
		[(TiUIScrollView *)[self view] setNeedsHandleContentSizeIfAutosizing];
	}
	[super willChangeSize];
}

-(void)layoutChildren:(BOOL)optimize
{
	if (![self viewAttached])
	{
		return;
	}

	[(TiUIScrollView *)[self view] handleContentSizeIfNeeded];
}

-(void)layoutChildrenAfterContentSize:(BOOL)optimize
{
	[super layoutChildren:optimize];
}

-(CGFloat)autoWidthForSize:(CGSize)size
{
    BOOL flexibleContentWidth = YES;
    BOOL flexibleContentHeight = YES;
    CGSize contentSize = CGSizeMake(size.width,size.height);
    id cw = [self valueForUndefinedKey:@"contentWidth"];
    id ch = [self valueForUndefinedKey:@"contentHeight"];
    TiDimension contentWidth = TiDimensionUndefined;
    TiDimension contentHeight = TiDimensionUndefined;
    if (cw) {
        contentWidth = TiDimensionFromObject(cw);
    }
    if (ch) {
        contentHeight = TiDimensionFromObject(ch);
    }

    if (TiDimensionIsAutoFill(contentWidth)) {
        return size.width;
    }

    if (TiDimensionIsDip(contentWidth) || TiDimensionIsPercent(contentWidth)) {
        return TiDimensionCalculateValue(contentWidth, size.width);
    }

    if (TiDimensionIsAutoFill(contentHeight) || TiDimensionIsDip(contentHeight) || TiDimensionIsPercent(contentHeight)) {
        contentSize.height = MAX(TiDimensionCalculateValue(contentHeight, size.height), size.height);
    }

    CGFloat result = 0.0;

    if (TiLayoutRuleIsVertical(layoutProperties.layoutStyle)) {
        //Vertical layout. Just get the maximum child width
        CGFloat thisWidth = 0.0;
        NSArray* subproxies = [self children];
        for (TiViewProxy * thisChildProxy in subproxies) {
            thisWidth = [thisChildProxy minimumParentWidthForSize:contentSize];
            if (result < thisWidth) {
                result = thisWidth;
            }
        }
    }
    else if (TiLayoutRuleIsHorizontal(layoutProperties.layoutStyle)) {
        //Horizontal Layout with auto width. Stretch Indefinitely.
        NSArray* subproxies = [self children];
        for (TiViewProxy * thisChildProxy in subproxies) {
            if ([thisChildProxy widthIsAutoFill]) {
                //result += size.width;
                result += [thisChildProxy minimumParentWidthForSize:size];
            }
            else if (TiDimensionIsPercent(thisChildProxy->layoutProperties.width)){
                result += [thisChildProxy minimumParentWidthForSize:size];
            }
            else {
                result += [thisChildProxy minimumParentWidthForSize:contentSize];
            }
        }
    }
    else {
        result = [super autoWidthForSize:contentSize];
    }
    return result;
}

-(CGFloat)autoHeightForSize:(CGSize)size
{
    BOOL flexibleContentWidth = YES;
    BOOL flexibleContentHeight = YES;
    CGSize contentSize = CGSizeMake(size.width,size.height);
    id cw = [self valueForUndefinedKey:@"contentWidth"];
    id ch = [self valueForUndefinedKey:@"contentHeight"];
    TiDimension contentWidth = TiDimensionUndefined;
    TiDimension contentHeight = TiDimensionUndefined;
    if (cw) {
        contentWidth = TiDimensionFromObject(cw);
    }
    if (ch) {
        contentHeight = TiDimensionFromObject(ch);
    }

    if (TiDimensionIsAutoFill(contentHeight)) {
        return size.height;
    }
    if (TiDimensionIsDip(contentHeight) || TiDimensionIsPercent(contentHeight)) {
        return TiDimensionCalculateValue(contentHeight, size.height);
    }

    if (TiDimensionIsAutoFill(contentWidth) || TiDimensionIsDip(contentWidth) || TiDimensionIsPercent(contentWidth)) {
        contentSize.width = MAX(TiDimensionCalculateValue(contentWidth, size.width),size.width);
        flexibleContentWidth = NO;
    }
    else {
        contentSize.width = [self autoWidthForSize:size];
    }

    CGFloat result = 0.0;
    if (TiLayoutRuleIsVertical(layoutProperties.layoutStyle)) {
        NSArray* subproxies = [self children];
        for (TiViewProxy * thisChildProxy in subproxies) {
            if ([thisChildProxy heightIsAutoFill]) {
                //result += size.height;
                result += [thisChildProxy minimumParentHeightForSize:size];
            }
            else if (TiDimensionIsPercent(thisChildProxy->layoutProperties.height)){
                result += [thisChildProxy minimumParentHeightForSize:size];
            }
            else {
                result += [thisChildProxy minimumParentHeightForSize:contentSize];
            }
        }
    }
    else if (TiLayoutRuleIsHorizontal(layoutProperties.layoutStyle)) {
        if(flexibleContentWidth) {
            CGFloat thisHeight = 0;
            NSArray* subproxies = [self children];
            for (TiViewProxy * thisChildProxy in subproxies) {
                if ([thisChildProxy heightIsAutoFill]) {
                    //thisHeight = size.height;
                    thisHeight = [thisChildProxy minimumParentHeightForSize:contentSize];
                }
                else if (TiDimensionIsPercent(thisChildProxy->layoutProperties.height)){
                    thisHeight = [thisChildProxy minimumParentHeightForSize:size];
                }
                else {
                    thisHeight = [thisChildProxy minimumParentHeightForSize:contentSize];
                }
                if (result < thisHeight) {
                    result = thisHeight;
                }
            }
        }
        else {
            //Not flexible width and wraps
            result = [super autoHeightForSize:contentSize];
        }
    }
    else {
        result = [super autoHeightForSize:contentSize];
    }
    return result;
}

-(CGRect)computeChildSandbox:(TiViewProxy*)child withBounds:(CGRect)bounds
{
    CGRect viewBounds = CGRectMake(bounds.origin.x, bounds.origin.y, bounds.size.width, bounds.size.height);
    CGRect contentSize = CGRectMake(bounds.origin.x, bounds.origin.y, bounds.size.width, bounds.size.height);
    if ([self viewAttached]) {
        viewBounds = [[self view] bounds];
    }
    BOOL flexibleContentWidth = YES;
    BOOL flexibleContentHeight = YES;
    id cw = [self valueForUndefinedKey:@"contentWidth"];
    id ch = [self valueForUndefinedKey:@"contentHeight"];
    TiDimension contentWidth = TiDimensionUndefined;
    TiDimension contentHeight = TiDimensionUndefined;
    if (cw) {
        contentWidth = TiDimensionFromObject(cw);
    }
    if (ch) {
        contentHeight = TiDimensionFromObject(ch);
    }

    if (TiDimensionIsAutoFill(contentWidth) || TiDimensionIsDip(contentWidth) || TiDimensionIsPercent(contentWidth)) {
        flexibleContentWidth = NO;
    }
    if (TiDimensionIsAutoFill(contentHeight) || TiDimensionIsDip(contentHeight) || TiDimensionIsPercent(contentHeight)) {
        flexibleContentHeight = NO;
    }

    contentSize.size.width = MAX(contentSize.size.width,viewBounds.size.width);
    contentSize.size.height = MAX(contentSize.size.height,viewBounds.size.height);

    if (TiLayoutRuleIsVertical(layoutProperties.layoutStyle)) {
        if (TiDimensionIsPercent(child->layoutProperties.height)){
            bounds.origin.y = verticalLayoutBoundary;
            bounds.size.height = [child minimumParentHeightForSize:viewBounds.size];
            verticalLayoutBoundary += bounds.size.height;
            return bounds;
        }
        else if (flexibleContentHeight) {
            //Match autoHeight behavior
            if ([child heightIsAutoFill]) {
                bounds.origin.y = verticalLayoutBoundary;
                bounds.size.height = [child minimumParentHeightForSize:viewBounds.size];
                verticalLayoutBoundary += bounds.size.height;
            }
            else {
                bounds.origin.y = verticalLayoutBoundary;
                bounds.size.height = [child minimumParentHeightForSize:contentSize.size];
                verticalLayoutBoundary += bounds.size.height;
            }
            return bounds;
        }
        else {
            return [super computeChildSandbox:child withBounds:contentSize];
        }
    }
    else if (TiLayoutRuleIsHorizontal(layoutProperties.layoutStyle)) {
        if (flexibleContentWidth) {
            //Match autoWidth behavior
            bounds.origin.x = horizontalLayoutBoundary;
            bounds.size.width = [child minimumParentWidthForSize:viewBounds.size];
            horizontalLayoutBoundary += bounds.size.width;
            bounds.size.height = contentSize.size.height;
            return bounds;
        }
        else {
            return [super computeChildSandbox:child withBounds:contentSize];
        }

    }
}

-(void)childWillResize:(TiViewProxy *)child
{
	[super childWillResize:child];
	[(TiUIScrollView *)[self view] setNeedsHandleContentSizeIfAutosizing];
}

-(BOOL)optimizeSubviewInsertion
{
    return YES;
}

-(UIView *)parentViewForChild:(TiViewProxy *)child
{
	return [(TiUIScrollView *)[self view] wrapperView];
}

-(void)scrollTo:(id)args
{
	ENSURE_ARG_COUNT(args,2);
	TiPoint * offset = [[TiPoint alloc] initWithPoint:CGPointMake(
			[TiUtils floatValue:[args objectAtIndex:0]],
			[TiUtils floatValue:[args objectAtIndex:1]])];

	[self setContentOffset:offset withObject:Nil];
	[offset release];
}

-(void)scrollToBottom:(id)args
{
    TiThreadPerformOnMainThread(^{
        [(TiUIScrollView *)[self view] scrollToBottom];
    }, YES);
}

-(void) setContentOffset:(id)value withObject:(id)animated
{
    TiThreadPerformOnMainThread(^{
        [(TiUIScrollView *)[self view] setContentOffset_:value withObject:animated];
    }, YES);
}

-(void) setZoomScale:(id)value withObject:(id)animated
{
    TiThreadPerformOnMainThread(^{
        [(TiUIScrollView *)[self view] setZoomScale_:value withObject:animated];
    }, YES);
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView_               // scrolling has ended
{
	if ([self _hasListeners:@"scrollEnd"])
	{	//TODO: Deprecate old event.
		[self fireEvent:@"scrollEnd" withObject:nil];
	}
	if ([self _hasListeners:@"scrollend"])
	{
		[self fireEvent:@"scrollend" withObject:nil];
	}
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGPoint offset = [scrollView contentOffset];
    if ([self _hasListeners:@"scroll"]) {
        [self fireEvent:@"scroll" withObject:[NSDictionary dictionaryWithObjectsAndKeys:
                NUMFLOAT(offset.x),@"x",
                NUMFLOAT(offset.y),@"y",
                NUMFLOAT(scrollView.zoomScale),@"curZoomScale",
                NUMBOOL([scrollView isZooming]),@"zooming",
                NUMBOOL([scrollView isDecelerating]),@"decelerating",
                NUMBOOL([scrollView isDragging]),@"dragging",
                nil]];
    }
}

- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale
{
	[self replaceValue:NUMFLOAT(scale) forKey:@"zoomScale" notification:NO];

	if ([self _hasListeners:@"scale"])
	{
		[self fireEvent:@"scale" withObject:[NSDictionary dictionaryWithObjectsAndKeys:
											  NUMFLOAT(scale),@"scale",
											  nil]];
	}
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
	if([self _hasListeners:@"dragStart"])
	{	//TODO: Deprecate old event
		[self fireEvent:@"dragStart" withObject:nil];
	}
	if([self _hasListeners:@"dragstart"])
	{
		[self fireEvent:@"dragstart" withObject:nil];
	}
}

//listerner which tells when dragging ended in the scroll view.

-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
	if([self _hasListeners:@"dragEnd"])
	{	//TODO: Deprecate old event
		[self fireEvent:@"dragEnd" withObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:decelerate],@"decelerate",nil]]	;
	}
	if([self _hasListeners:@"dragend"])
	{
		[self fireEvent:@"dragend" withObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:decelerate],@"decelerate",nil]]	;
	}
}

DEFINE_DEF_PROP(scrollsToTop,[NSNumber numberWithBool:YES]);

@end

#endif


text:
#include "mitkMouseWheelEvent.h"

mitk::MouseWheelEvent::MouseWheelEvent(BaseRenderer* baseRenderer,
    const Point2D& mousePosition, const Point3D& worldPosition,
    MouseButtons buttonStates,
    ModifierKeys modifiers,
    int wheelDelta)
: InteractionPositionEvent(baseRenderer, mousePosition, worldPosition)
, m_WheelDelta(wheelDelta)
, m_ButtonStates(buttonStates)
, m_Modifiers(modifiers)
{
}

int mitk::MouseWheelEvent::GetWheelDelta() const
{
  return m_WheelDelta;
}

void mitk::MouseWheelEvent::SetWheelDelta(int delta)
{
  m_WheelDelta = delta;
}

mitk::InteractionEvent::ModifierKeys mitk::MouseWheelEvent::GetModifiers() const
{
  return m_Modifiers;
}

mitk::InteractionEvent::MouseButtons mitk::MouseWheelEvent::GetButtonStates() const
{
  return m_ButtonStates;
}

void mitk::MouseWheelEvent::SetModifiers(ModifierKeys modifiers)
{
  m_Modifiers = modifiers;
}

void mitk::MouseWheelEvent::SetButtonStates(MouseButtons buttons)
{
  m_ButtonStates = buttons;
}

mitk::MouseWheelEvent::~MouseWheelEvent()
{
}

bool mitk::MouseWheelEvent::IsEqual(const mitk::InteractionEvent& interactionEvent) const
{
  const mitk::MouseWheelEvent& mwe = static_cast<const MouseWheelEvent&>(interactionEvent);
  return ((this->GetWheelDelta() * mwe.GetWheelDelta() >= 0) // Consider WheelEvents to be equal if the scrolling is done in the same direction.
          && this->GetModifiers() == mwe.GetModifiers() && this->GetButtonStates() == mwe.GetButtonStates() &&
          Superclass::IsEqual(interactionEvent));
}

bool mitk::MouseWheelEvent::IsSuperClassOf(const InteractionEvent::Pointer& baseClass) const
{
  return (dynamic_cast<MouseWheelEvent*>(baseClass.GetPointer()) != NULL) ;
}

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Bot. Mater. Otd. Sporov. Rast. Bot. Inst. Komarova Akad. Nauk S. S. S. R. 7: (1951)

#### Original name
Sirosporonaemella strobilina Naumov, 1951

### Remarks
null


text:
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using System.ComponentModel;
using System.Windows.Forms.VisualStyles;

namespace WeifenLuo.WinFormsUI.Docking
{
	internal class VS2005DockPaneCaption : DockPaneCaptionBase
	{
        private sealed class InertButton : InertButtonBase
        {
            private Bitmap m_image, m_imageAutoHide;

            public InertButton(VS2005DockPaneCaption dockPaneCaption, Bitmap image, Bitmap imageAutoHide)
                : base()
            {
                m_dockPaneCaption = dockPaneCaption;
                m_image = image;
                m_imageAutoHide = imageAutoHide;
                RefreshChanges();
            }

            private VS2005DockPaneCaption m_dockPaneCaption;
            private VS2005DockPaneCaption DockPaneCaption
            {
                get { return m_dockPaneCaption; }
            }

            public bool IsAutoHide
            {
                get { return DockPaneCaption.DockPane.IsAutoHide; }
            }

            public override Bitmap Image
            {
                get { return IsAutoHide ? m_imageAutoHide : m_image; }
            }

            protected override void OnRefreshChanges()
            {
                if (DockPaneCaption.TextColor != ForeColor)
                {
                    ForeColor = DockPaneCaption.TextColor;
                    Invalidate();
                }
            }
        }

		#region consts
		private const int _TextGapTop = 2;
		private const int _TextGapBottom = 0;
		private const int _TextGapLeft = 3;
		private const int _TextGapRight = 3;
		private const int _ButtonGapTop = 2;
		private const int _ButtonGapBottom = 1;
		private const int _ButtonGapBetween = 1;
		private const int _ButtonGapLeft = 1;
		private const int _ButtonGapRight = 2;
		#endregion

        private static Bitmap _imageButtonClose;
        private static Bitmap ImageButtonClose
        {
            get
            {
                if (_imageButtonClose == null)
                    _imageButtonClose = Resources.DockPane_Close;

                return _imageButtonClose;
            }
        }

		private InertButton m_buttonClose;
        private InertButton ButtonClose
        {
            get
            {
                if (m_buttonClose == null)
                {
                    m_buttonClose = new InertButton(this, ImageButtonClose, ImageButtonClose);
                    m_toolTip.SetToolTip(m_buttonClose, ToolTipClose);
                    m_buttonClose.Click += new EventHandler(Close_Click);
                    Controls.Add(m_buttonClose);
                }

                return m_buttonClose;
            }
        }

        private static Bitmap _imageButtonAutoHide;
        private static Bitmap ImageButtonAutoHide
        {
            get
            {
                if (_imageButtonAutoHide == null)
                    _imageButtonAutoHide = Resources.DockPane_AutoHide;

                return _imageButtonAutoHide;
            }
        }

        private static Bitmap _imageButtonDock;
        private static Bitmap ImageButtonDock
        {
            get
            {
                if (_imageButtonDock == null)
                    _imageButtonDock = Resources.DockPane_Dock;

                return _imageButtonDock;
            }
        }

        private InertButton m_buttonAutoHide;
        private InertButton ButtonAutoHide
        {
            get
            {
                if (m_buttonAutoHide == null)
                {
                    m_buttonAutoHide = new InertButton(this, ImageButtonDock, ImageButtonAutoHide);
                    m_toolTip.SetToolTip(m_buttonAutoHide, ToolTipAutoHide);
                    m_buttonAutoHide.Click += new EventHandler(AutoHide_Click);
                    Controls.Add(m_buttonAutoHide);
                }

                return m_buttonAutoHide;
            }
        }

        private static Bitmap _imageButtonOptions;
        private static Bitmap ImageButtonOptions
        {
            get
            {
                if (_imageButtonOptions == null)
                    _imageButtonOptions = Resources.DockPane_Option;

                return _imageButtonOptions;
            }
        }

        private InertButton m_buttonOptions;
        private InertButton ButtonOptions
        {
            get
            {
                if (m_buttonOptions == null)
                {
                    m_buttonOptions = new InertButton(this, ImageButtonOptions, ImageButtonOptions);
                    m_toolTip.SetToolTip(m_buttonOptions, ToolTipOptions);
                    m_buttonOptions.Click += new EventHandler(Options_Click);
                    Controls.Add(m_buttonOptions);
                }
                return m_buttonOptions;
            }
        }

        private IContainer m_components;
        private IContainer Components
        {
            get { return m_components; }
        }

		private ToolTip m_toolTip;

		public VS2005DockPaneCaption(DockPane pane) : base(pane)
		{
			SuspendLayout();

            m_components = new Container();
            m_toolTip = new ToolTip(Components);

			ResumeLayout();
		}

        protected override void Dispose(bool disposing)
        {
            if (disposing)
                Components.Dispose();
            base.Dispose(disposing);
        }

		private static int TextGapTop
		{
			get	{	return _TextGapTop;	}
		}

        private static Font TextFont
        {
            get { return SystemInformation.MenuFont; }
        }

		private static int TextGapBottom
		{
			get	{	return _TextGapBottom;	}
		}

		private static int TextGapLeft
		{
			get	{	return _TextGapLeft;	}
		}

		private static int TextGapRight
		{
			get	{	return _TextGapRight;	}
		}

		private static int ButtonGapTop
		{
			get	{	return _ButtonGapTop;	}
		}

		private static int ButtonGapBottom
		{
			get	{	return _ButtonGapBottom;	}
		}

		private static int ButtonGapLeft
		{
			get	{	return _ButtonGapLeft;	}
		}

		private static int ButtonGapRight
		{
			get	{	return _ButtonGapRight;	}
		}

		private static int ButtonGapBetween
		{
			get	{	return _ButtonGapBetween;	}
		}

		private static string _toolTipClose;
		private static string ToolTipClose
		{
			get
			{
				if (_toolTipClose == null)
					_toolTipClose = Strings.DockPaneCaption_ToolTipClose;
				return _toolTipClose;
			}
		}

        private static string _toolTipOptions;
        private static string ToolTipOptions
        {
            get
            {
                if (_toolTipOptions == null)
                    _toolTipOptions = Strings.DockPaneCaption_ToolTipOptions;

                return _toolTipOptions;
            }
        }

		private static string _toolTipAutoHide;
		private static string ToolTipAutoHide
		{
			get
			{
				if (_toolTipAutoHide == null)
					_toolTipAutoHide = Strings.DockPaneCaption_ToolTipAutoHide;
				return _toolTipAutoHide;
			}
		}

        private static Blend _activeBackColorGradientBlend;
        private static Blend ActiveBackColorGradientBlend
        {
            get
            {
                if (_activeBackColorGradientBlend == null)
                {
                    Blend blend = new Blend(2);

                    blend.Factors = new float[]{0.5F, 1.0F};
                    blend.Positions = new float[]{0.0F, 1.0F};
                    _activeBackColorGradientBlend = blend;
                }

                return _activeBackColorGradientBlend;
            }
        }

		private static Color ActiveBackColorGradientBegin
		{
            get { return SystemColors.GradientActiveCaption; }
        }

        private static Color ActiveBackColorGradientEnd
        {
            get { return SystemColors.ActiveCaption; }
        }

		private static Color InactiveBackColor
		{
            get
            {
                string colorScheme = VisualStyleInformation.ColorScheme;

                if (colorScheme == "HomeStead" || colorScheme == "Metallic")
                    return SystemColors.GradientInactiveCaption;
                else
                    return SystemColors.GrayText;
            }
		}

		private static Color ActiveTextColor
		{
			get	{	return SystemColors.ActiveCaptionText;	}
		}

		private static Color InactiveTextColor
		{
			get	{	return SystemColors.ControlText;	}
		}

        private Color TextColor
        {
            get { return DockPane.IsActivated ? ActiveTextColor : InactiveTextColor; }
        }

		private static TextFormatFlags _textFormat =
            TextFormatFlags.SingleLine |
            TextFormatFlags.EndEllipsis |
            TextFormatFlags.VerticalCenter;
		private TextFormatFlags TextFormat
		{
            get
            {
                if (RightToLeft == RightToLeft.No)
                    return _textFormat;
                else
                    return _textFormat | TextFormatFlags.RightToLeft | TextFormatFlags.Right;
            }
		}

		protected internal override int MeasureHeight()
		{
			int height = TextFont.Height + TextGapTop + TextGapBottom;

			if (height < ButtonClose.Image.Height + ButtonGapTop + ButtonGapBottom)
				height = ButtonClose.Image.Height + ButtonGapTop + ButtonGapBottom;

			return height;
		}

		protected override void OnPaint(PaintEventArgs e)
		{
			base.OnPaint (e);
			DrawCaption(e.Graphics);
		}

		private void DrawCaption(Graphics g)
		{
            if (ClientRectangle.Width == 0 || ClientRectangle.Height == 0)
                return;

            if (DockPane.IsActivated)
            {
                using (LinearGradientBrush brush = new LinearGradientBrush(ClientRectangle, ActiveBackColorGradientBegin, ActiveBackColorGradientEnd, LinearGradientMode.Vertical))
                {
                    brush.Blend = ActiveBackColorGradientBlend;
                    g.FillRectangle(brush, ClientRectangle);
                }
            }
            else
            {
                using (SolidBrush brush = new SolidBrush(InactiveBackColor))
                {
                    g.FillRectangle(brush, ClientRectangle);
                }
            }

			Rectangle rectCaption = ClientRectangle;

			Rectangle rectCaptionText = rectCaption;
            rectCaptionText.X += TextGapLeft;
            rectCaptionText.Width -= TextGapLeft + TextGapRight;
            rectCaptionText.Width -= ButtonGapLeft + ButtonClose.Width + ButtonGapRight;
            if (ShouldShowAutoHideButton)
                rectCaptionText.Width -= ButtonAutoHide.Width + ButtonGapBetween;
            if (HasTabPageContextMenu)
                rectCaptionText.Width -= ButtonOptions.Width + ButtonGapBetween;
			rectCaptionText.Y += TextGapTop;
			rectCaptionText.Height -= TextGapTop + TextGapBottom;
            TextRenderer.DrawText(g, DockPane.CaptionText, TextFont, DrawHelper.RtlTransform(this, rectCaptionText), TextColor, TextFormat);
		}

		protected override void OnLayout(LayoutEventArgs levent)
		{
			SetButtonsPosition();
			base.OnLayout (levent);
		}

		protected override void OnRefreshChanges()
		{
			SetButtons();
			Invalidate();
		}

		private bool CloseButtonEnabled
		{
			get	{	return (DockPane.ActiveContent != null)? DockPane.ActiveContent.DockHandler.CloseButton : false;	}
		}

		private bool ShouldShowAutoHideButton
		{
			get	{	return !DockPane.IsFloat;	}
		}

		private void SetButtons()
		{
			ButtonClose.Enabled = CloseButtonEnabled;
			ButtonAutoHide.Visible = ShouldShowAutoHideButton;
            ButtonOptions.Visible = HasTabPageContextMenu;
            ButtonClose.RefreshChanges();
            ButtonAutoHide.RefreshChanges();
            ButtonOptions.RefreshChanges();

			SetButtonsPosition();
		}

		private void SetButtonsPosition()
		{
			// set the size and location for close and auto-hide buttons
			Rectangle rectCaption = ClientRectangle;
			int buttonWidth = ButtonClose.Image.Width;
			int buttonHeight = ButtonClose.Image.Height;
			int height = rectCaption.Height - ButtonGapTop - ButtonGapBottom;
			if (buttonHeight < height)
			{
				buttonWidth = buttonWidth * (height / buttonHeight);
				buttonHeight = height;
			}
			Size buttonSize = new Size(buttonWidth, buttonHeight);
			int x = rectCaption.X + rectCaption.Width - 1 - ButtonGapRight - m_buttonClose.Width;
			int y = rectCaption.Y + ButtonGapTop;
			Point point = new Point(x, y);
            ButtonClose.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize));
			point.Offset(-(buttonWidth + ButtonGapBetween), 0);
            ButtonAutoHide.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize));
            if (ShouldShowAutoHideButton)
                point.Offset(-(buttonWidth + ButtonGapBetween), 0);
            ButtonOptions.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize));
		}

		private void Close_Click(object sender, EventArgs e)
		{
			DockPane.CloseActiveContent();
		}

		private void AutoHide_Click(object sender, EventArgs e)
		{
			DockPane.DockState = DockHelper.ToggleAutoHideState(DockPane.DockState);
		}

        private void Options_Click(object sender, EventArgs e)
        {
            ShowTabPageContextMenu(PointToClient(Control.MousePosition));
        }

        protected override void OnRightToLeftChanged(EventArgs e)
        {
            base.OnRightToLeftChanged(e);
            PerformLayout();
        }
	}
}


text:
namespace renderer
{

template <size_t N>
class SampleCountHistory
{
  public:
    SampleCountHistory()
      : m_size(0)
      , m_first(0)
      , m_index(0)
    {
    }

    void insert(const double time, const foundation::uint64 value)
    {
        m_index = m_first;

        m_records[m_index].m_time = time;
        m_records[m_index].m_value = value;

        m_first = (m_first + 1) % N;

        if (m_size < N)
            ++m_size;
    }

    double get_samples_per_second() const
    {
        if (m_size == 0)
            return 0.0;

        const Record* first = &m_records[m_size < N ? 0 : m_first];
        const Record* last = &m_records[m_index];

        assert(last->m_value >= first->m_value);
        assert(last->m_time >= first->m_time);

        const foundation::uint64 delta_value = last->m_value - first->m_value;
        const double delta_time = last->m_time - first->m_time;

        return delta_time > 0.0 ? delta_value / delta_time : 0.0;
    }

  private:
    struct Record
    {
        double              m_time;
        foundation::uint64  m_value;
    };

    Record  m_records[N];
    size_t  m_size;
    size_t  m_first;
    size_t  m_index;
};

}       // namespace renderer

#endif  // !APPLESEED_RENDERER_KERNEL_RENDERING_PROGRESSIVE_SAMPLECOUNTHISTORY_H


text:
// .NAME vtkParametricRandomHills - Generate a surface covered with randomly placed hills.
// .SECTION Description
// vtkParametricRandomHills generates a surface covered with randomly placed hills.
//
// For further information about this surface, please consult the
// technical description "Parametric surfaces" in http://www.vtk.org/documents.php
// in the "VTK Technical Documents" section in the VTk.org web pages.
//
// .SECTION Thanks
// Andrew Maclean a.maclean@cas.edu.au for
// creating and contributing the class.
//
#ifndef __vtkParametricRandomHills_h
#define __vtkParametricRandomHills_h

#include "vtkCommonComputationalGeometryExport.h" // For export macro
#include "vtkParametricFunction.h"

class vtkDoubleArray;

class VTKCOMMONCOMPUTATIONALGEOMETRY_EXPORT vtkParametricRandomHills : public vtkParametricFunction
{

public:
  vtkTypeMacro(vtkParametricRandomHills,vtkParametricFunction);
  void PrintSelf(ostream& os, vtkIndent indent);

  // Description
  // Return the parametric dimension of the class.
  virtual int GetDimension() {return 2;}

  // Description:
  // Construct a surface of random hills with the following parameters:
  // MinimumU = -10, MaximumU = 10,
  // MinimumV = -10, MaximumV = 10,
  // JoinU = 0, JoinV = 0,
  // TwistU = 0, TwistV = 0;
  // ClockwiseOrdering = 1,
  // DerivativesAvailable = 0,
  // Number of hills = 30,
  // Variance of the hills 2.5 in both x- and y- directions,
  // Scaling factor for the variances 1/3 in both x- and y- directions,
  // Amplitude of each hill = 1,
  // Scaling factor for the amplitude = 1/3,
  // RandomSeed = 1,
  // AllowRandomGeneration = 1.
  static vtkParametricRandomHills *New();

  // Description:
  // Set/Get the number of hills.
  // Default is 30.
  vtkSetMacro(NumberOfHills,int);
  vtkGetMacro(NumberOfHills,int);

  // Description:
  // Set/Get the hill variance in the x-direction.
  // Default is 2.5.
  vtkSetMacro(HillXVariance,double);
  vtkGetMacro(HillXVariance,double);

  // Description:
  // Set/Get the hill variance in the y-direction.
  // Default is 2.5.
  vtkSetMacro(HillYVariance,double);
  vtkGetMacro(HillYVariance,double);

  // Description:
  // Set/Get the hill amplitude (height).
  // Default is 2.
  vtkSetMacro(HillAmplitude,double);
  vtkGetMacro(HillAmplitude,double);

  // Description:
  // Set/Get the Seed for the random number generator,
  // a value of 1 will initialize the random number generator,
  // a negative value will initialize it with the system time.
  // Default is 1.
  vtkSetMacro(RandomSeed,int);
  vtkGetMacro(RandomSeed,int);

  // Description:
  // Set/Get the random generation flag.
  // A value of 0 will disable the generation of random hills on the surface.
  // This allows a reproducible shape to be generated.
  // Any other value means that the generation of the hills will be done
  // randomly.
  // Default is 1.
  vtkSetMacro(AllowRandomGeneration,int);
  vtkGetMacro(AllowRandomGeneration,int);
  vtkBooleanMacro(AllowRandomGeneration,int);

  // Description:
  // Set/Get the scaling factor for the variance in the x-direction.
  // Default is 1/3.
  vtkSetMacro(XVarianceScaleFactor,double);
  vtkGetMacro(XVarianceScaleFactor,double);

  // Description:
  // Set/Get the scaling factor for the variance in the y-direction.
  // Default is 1/3.
  vtkSetMacro(YVarianceScaleFactor,double);
  vtkGetMacro(YVarianceScaleFactor,double);

  // Description:
  // Set/Get the scaling factor for the amplitude.
  // Default is 1/3.
  vtkSetMacro(AmplitudeScaleFactor,double);
  vtkGetMacro(AmplitudeScaleFactor,double);

  // Description:
  // Generate the centers of the hills, their standard deviations and
  // their amplitudes. This function creates a series of vectors representing
  // the u, v coordinates of each hill, its variance in the u, v directions and
  // the amplitude.
  //
  // NOTE: This function must be called whenever any of the parameters are changed.
  void GenerateTheHills( void );

  // Description:
  // Construct a terrain consisting of randomly placed hills on a surface.
  //
  // It is assumed that the function GenerateTheHills() has been executed
  // to build the vectors of coordinates required to generate the point Pt.
  // Pt represents the sum of all the amplitudes over the space.
  //
  // This function performs the mapping \f$f(u,v) \rightarrow (x,y,x)\f$, returning it
  // as Pt. It also returns the partial derivatives Du and Dv.
  // \f$Pt = (x, y, z), Du = (dx/du, dy/du, dz/du), Dv = (dx/dv, dy/dv, dz/dv)\f$ .
  // Then the normal is \f$N = Du X Dv\f$ .
  virtual void Evaluate(double uvw[3], double Pt[3], double Duvw[9]);

  // Description:
  // Calculate a user defined scalar using one or all of uvw, Pt, Duvw.
  //
  // uvw are the parameters with Pt being the the Cartesian point,
  // Duvw are the derivatives of this point with respect to u, v and w.
  // Pt, Duvw are obtained from Evaluate().
  //
  // This function is only called if the ScalarMode has the value
  // vtkParametricFunctionSource::SCALAR_FUNCTION_DEFINED
  //
  // If the user does not need to calculate a scalar, then the
  // instantiated function should return zero.
  //
  virtual double EvaluateScalar(double uvw[3], double Pt[3], double Duvw[9]);

protected:
  vtkParametricRandomHills();
  ~vtkParametricRandomHills();

  // Variables
  int NumberOfHills;
  double HillXVariance;
  double HillYVariance;
  double HillAmplitude;
  int RandomSeed;
  double XVarianceScaleFactor;
  double YVarianceScaleFactor;
  double AmplitudeScaleFactor;
  int AllowRandomGeneration;

private:
  vtkParametricRandomHills(const vtkParametricRandomHills&);  // Not implemented.
  void operator=(const vtkParametricRandomHills&);  // Not implemented.

  // Description:
  // Initialise the random number generator.
  void InitSeed ( int RandomSeed );

  // Description:
  // Return a random number between 0 and 1.
  double Rand ( void );

  // Description:
  // Center (x,y), variances (x,y) and amplitudes of the hills.
  vtkDoubleArray * hillData;
};

#endif


text:
package org.apache.hadoop.streaming;

import java.io.IOException;

import org.apache.hadoop.mapred.*;

import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.Path;

import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.io.Writable;

import org.apache.hadoop.util.Progressable;

/** Similar to org.apache.hadoop.mapred.TextOutputFormat,
 * but delimits key and value with a TAB.
 * @author Michel Tourn
 */
public class StreamOutputFormat implements OutputFormat {

  public RecordWriter getRecordWriter(FileSystem fs, JobConf job, String name, Progressable progr) throws IOException {

    Path file = new Path(job.getOutputPath(), name);

    final FSDataOutputStream out = fs.create(file);

    return new RecordWriter() {

      public synchronized void write(WritableComparable key, Writable value) throws IOException {
        out.write(key.toString().getBytes("UTF-8"));
        out.writeByte('\t');
        out.write(value.toString().getBytes("UTF-8"));
        out.writeByte('\n');
      }

      public synchronized void close(Reporter reporter) throws IOException {
        out.close();
      }
    };
  }

  /** Check whether the output specification for a job is appropriate.  Called
   * when a job is submitted.  Typically checks that it does not already exist,
   * throwing an exception when it already exists, so that output is not
   * overwritten.
   *
   * @param job the job whose output will be written
   * @throws IOException when output should not be attempted
   */
  public void checkOutputSpecs(FileSystem fs, JobConf job) throws IOException {
    // allow existing data (for app-level restartability)
  }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
 * (C) Copyright 2013 Uwe Schindler (Generics Policeman) and others.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with 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.
-->
<project xmlns:au="antlib:org.apache.ant.antunit">

  <pathconvert property="cp" refid="path.build"/>

  <target name="testBundledSignatures">
    <java jar="${jar-file}" failonerror="true" fork="true">
      <arg value="-c"/>
      <arg value="${cp}"/>
      <arg value="-d"/>
      <arg file="${antunit.main.classes}"/>
      <arg value="-b"/>
      <arg value="jdk-unsafe-${jdk.version},jdk-deprecated-${jdk.version}"/>
      <arg value="--internalruntimeforbidden"/>
    </java>
    <au:assertLogContains text=" 0 error(s)."/>
    <au:assertLogContains text="Reading bundled API signatures: jdk-deprecated-${jdk.version}"/>
    <au:assertLogContains text="Reading bundled API signatures: jdk-unsafe-${jdk.version}"/>
  </target>

  <target name="testExcludes">
    <java jar="${jar-file}" failonerror="true" fork="true">
      <arg value="-c"/>
      <arg value="${cp}"/>
      <arg value="-d"/>
      <arg file="${antunit.main.classes}"/>
      <arg value="-b"/>
      <arg value="jdk-unsafe-${jdk.version},jdk-deprecated-${jdk.version}"/>
      <arg value="--bundledsignatures"/>
      <arg value="jdk-system-out"/>
      <arg value="--excludes"/>
      <arg value="de/thetaphi/forbiddenapis/CliMain.class"/>
      <arg value="--internalruntimeforbidden"/>
    </java>
    <au:assertLogContains text=" 0 error(s)."/>
    <au:assertLogContains text="Reading bundled API signatures: jdk-deprecated-${jdk.version}"/>
    <au:assertLogContains text="Reading bundled API signatures: jdk-unsafe-${jdk.version}"/>
    <au:assertLogContains text="Reading bundled API signatures: jdk-system-out"/>
  </target>

  <target name="testSignatureFile">
    <au:expectfailure expectedMessage="Java returned: 1">
      <java jar="${jar-file}" failonerror="true" fork="true">
        <arg value="-c"/>
        <arg value="${cp}"/>
        <arg value="-d"/>
        <arg file="${antunit.main.classes}"/>
        <arg value="-f"/>
        <arg file="signatures1.txt"/>
      </java>
    </au:expectfailure>
    <au:assertLogContains text="java.lang.String#substring(int,int) [You are crazy that you disallow substrings]"/>
  </target>

</project>


text:
'use strict';

const assert = require('./../../assert');
const common = require('./../../common');

let battle;

describe('Most status moves', function () {
	afterEach(function () {
		battle.destroy();
	});

	it('should ignore natural type immunities', function () {
		battle = common.createBattle();
		battle.join('p1', 'Guest 1', 1, [{species: "Smeargle", ability: 'prankster', item: 'leftovers', moves: ['gastroacid', 'glare', 'confuseray', 'sandattack']}]);
		battle.join('p2', 'Guest 2', 1, [
			{species: "Klefki", ability: 'magician', happiness: 0, moves: ['return']},
			{species: "Dusknoir", ability: 'frisk', moves: ['shadowpunch']},
			{species: "Slaking", ability: 'truant', moves: ['shadowclaw']},
			{species: "Tornadus", ability: 'prankster', moves: ['tailwind']},
			{species: "Unown", ability: 'levitate', moves: ['hiddenpower']},
		]);
		battle.makeChoices('move gastroacid', 'move return');
		assert.false.holdsItem(battle.p2.active[0]); // Klefki's Magician suppressed by Gastro Acid.
		battle.makeChoices('move glare', 'switch 2'); // Dusknoir
		assert.strictEqual(battle.p2.active[0].status, 'par');
		battle.makeChoices('move confuseray', 'switch 3'); // Slaking
		assert.ok(battle.p2.active[0].volatiles['confusion']);
		battle.makeChoices('move sandattack', 'switch 4'); // Tornadus
		assert.statStage(battle.p2.active[0], 'accuracy', -1);
		battle.makeChoices('move sandattack', 'switch 5'); // Unown (Levitate)
		assert.statStage(battle.p2.active[0], 'accuracy', -1);
	});

	it('should fail when the opposing Pokemon is immune to the status effect it sets', function () {
		this.timeout(0);

		battle = common.createBattle();
		battle.join('p1', 'Guest 1', 1, [{species: "Smeargle", ability: 'noguard', item: 'laggingtail', moves: ['thunderwave', 'willowisp', 'poisongas', 'toxic']}]);
		battle.join('p2', 'Guest 2', 1, [
			{species: "Zapdos", ability: 'pressure', moves: ['charge']},
			{species: "Emboar", ability: 'blaze', moves: ['sleeptalk']},
			{species: "Muk", ability: 'stench', moves: ['shadowsneak']},
			{species: "Aron", ability: 'sturdy', moves: ['magnetrise']},
		]);

		battle.makeChoices('move thunderwave', 'move charge');
		assert.strictEqual(battle.p2.active[0].status, '');
		assert.ok(battle.log[battle.lastMoveLine + 1].startsWith('|-immune|'));

		battle.makeChoices('move willowisp', 'switch 2'); // Emboar
		assert.strictEqual(battle.p2.active[0].status, '');
		assert.ok(battle.log[battle.lastMoveLine + 1].startsWith('|-immune|'));

		battle.makeChoices('move poisongas', 'switch 3'); // Muk
		assert.strictEqual(battle.p2.active[0].status, '');
		assert.ok(battle.log[battle.lastMoveLine + 1].startsWith('|-immune|'));

		battle.makeChoices('move toxic', 'move shadowsneak');
		assert.strictEqual(battle.p2.active[0].status, '');
		assert.ok(battle.log[battle.lastMoveLine + 1].startsWith('|-immune|'));

		battle.makeChoices('move poisongas', 'switch 4'); // Aron
		assert.strictEqual(battle.p2.active[0].status, '');
		assert.ok(battle.log[battle.lastMoveLine + 1].startsWith('|-immune|'));

		battle.makeChoices('move toxic', 'move magnetrise');
		assert.strictEqual(battle.p2.active[0].status, '');
		assert.ok(battle.log[battle.lastMoveLine + 1].startsWith('|-immune|'));
	});
});

describe('Poison-inflicting status moves [Gen 2]', function () {
	const POISON_STATUS_MOVES = ['poisonpowder', 'poisongas', 'toxic'];

	afterEach(function () {
		battle.destroy();
	});

	it('should not ignore type immunities', function () {
		battle = common.gen(2).createBattle([
			[{species: "Smeargle", moves: POISON_STATUS_MOVES}],
			[{species: "Magneton", moves: ['sleeptalk']}],
		]);
		// Set all moves to perfect accuracy
		battle.onEvent('Accuracy', battle.getFormat(), true);

		const target = battle.p2.active[0];
		POISON_STATUS_MOVES.forEach(move => {
			assert.constant(() => target.status, () => battle.makeChoices('move ' + move, 'move sleeptalk'));
		});
	});
});


text:
using System;
using BohFoundation.Domain.Infrastructure;

namespace BohFoundation.TestHelpers
{
    public static class TestHelpersCommonFields
    {
        public static Guid GuidOne { get; set; }
        public static string DatabaseName { get; private set; }

        public static void InitializeFields()
        {
            GuidOne = Guid.NewGuid();
            GuidOneWithNoDashes = GuidOne.ToString().Replace("-", "");
            DatabaseName = IsLocalTest.LocalTest ? "LocalTest" : "CloudTest";
            AzureConnectionName = IsLocalTest.LocalTest ? "AzureStorageLocalTest" : "AzureStorageCloudTest";
        }

        public static string GuidOneWithNoDashes { get; set; }
        public static string AzureConnectionName { get; set; }

        public static string EmailDynamic() {
            return Guid.NewGuid() + "@email.com" ; }

        public static string GetRandomString()
        {
            return Guid.NewGuid().ToString();
        }

        public const string Email = "Email@email.com";
        public const string FirstName = "FirstName";
        public const string LastName = "LastName";
        public static string FullName { get { return FirstName + " " + LastName; } }
        public const string Password = "password";
        public const int GraduatingYear = 2013;
        public const string ExceptionMessage = "error";
        public const int Id = 123;
        public const string EssayTitle = "Are There Hats?";
        public const string EssayPrompt = "Explain: Are hats real?";

        public const string Paragraph =
            "Nullam quis risus eget urna mollis ornare vel eu leo. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nullam id dolor id nibh ultricies vehicula. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec ullamcorper nulla non metus auctor fringilla. Duis mollis, est non commodo luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Duis mollis, est non commodo luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit.";
    }
}


text:
UEdGraphPin* FGraphEditorDragDropAction::GetHoveredPin() const
{
	return HoveredPin.Get();
}

UEdGraphNode* FGraphEditorDragDropAction::GetHoveredNode() const
{
	return HoveredNode.IsValid() ? HoveredNode->GetNodeObj() : NULL;
}

UEdGraph* FGraphEditorDragDropAction::GetHoveredGraph() const
{
	// Note: We always want to report a graph even when hovering over a node or pin;
	// the same is not true for nodes when hovering over a pin (at least right now)
	if (HoveredGraph.IsValid())
	{
		return HoveredGraph->GetGraphObj();
	}
	else if (UEdGraphNode* Node = GetHoveredNode())
	{
		return Node->GetGraph();
	}
	else if (UEdGraphPin* Pin = GetHoveredPin())
	{
		return Pin->GetOwningNode()->GetGraph();
	}

	return NULL;
}

void FGraphEditorDragDropAction::SetHoveredPin(UEdGraphPin* InPin)
{
	if (HoveredPin != InPin)
	{
		HoveredPin = InPin;
		HoverTargetChanged();
	}
}

void FGraphEditorDragDropAction::SetHoveredNode(const TSharedPtr<SGraphNode>& InNode)
{
	if (HoveredNode != InNode)
	{
		HoveredNode = InNode;
		HoverTargetChanged();
	}
}

void FGraphEditorDragDropAction::SetHoveredGraph(const TSharedPtr<SGraphPanel>& InGraph)
{
	if (HoveredGraph != InGraph)
	{
		HoveredGraph = InGraph;
		HoverTargetChanged();
	}
}

void FGraphEditorDragDropAction::SetHoveredCategoryName(const FText& InHoverCategoryName)
{
	if(!HoveredCategoryName.EqualTo(InHoverCategoryName))
	{
		HoveredCategoryName = InHoverCategoryName;
		HoverTargetChanged();
	}
}

void FGraphEditorDragDropAction::SetHoveredAction(TSharedPtr<struct FEdGraphSchemaAction> Action)
{
	if(HoveredAction.Pin().Get() != Action.Get())
	{
		HoveredAction = Action;
		HoverTargetChanged();
	}
}

void FGraphEditorDragDropAction::Construct()
{
	// Create the drag-drop decorator window
	CursorDecoratorWindow = SWindow::MakeCursorDecorator();
	const bool bShowImmediately = false;
	FSlateApplication::Get().AddWindow(CursorDecoratorWindow.ToSharedRef(), bShowImmediately);

	HoverTargetChanged();
}

bool FGraphEditorDragDropAction::HasFeedbackMessage()
{
	return CursorDecoratorWindow->GetContent() != SNullWidget::NullWidget;
}

void FGraphEditorDragDropAction::SetFeedbackMessage(const TSharedPtr<SWidget>& Message)
{
	if (Message.IsValid())
	{
		CursorDecoratorWindow->ShowWindow();
		CursorDecoratorWindow->SetContent
		(
			SNew(SBorder)
			. BorderImage(FEditorStyle::GetBrush("Graph.ConnectorFeedback.Border"))
			[
				Message.ToSharedRef()
			]
		);
	}
	else
	{
		CursorDecoratorWindow->HideWindow();
		CursorDecoratorWindow->SetContent(SNullWidget::NullWidget);
	}
}

void FGraphEditorDragDropAction::SetSimpleFeedbackMessage(const FSlateBrush* Icon, const FSlateColor& IconColor, const FText& Message)
{
	// Let the user know the status of making this connection.

	// Use CreateRaw as we cannot using anything that will create a shared ptr from within an objects construction, this should be
	// safe though as we will destroy our window before we get destroyed.
	TAttribute<EVisibility> ErrorIconVisibility = TAttribute<EVisibility>::Create(TAttribute<EVisibility>::FGetter::CreateRaw(this, &FGraphEditorDragDropAction::GetErrorIconVisible));
	TAttribute<EVisibility> IconVisibility = TAttribute<EVisibility>::Create(TAttribute<EVisibility>::FGetter::CreateRaw(this, &FGraphEditorDragDropAction::GetIconVisible));

		SetFeedbackMessage(
		SNew(SHorizontalBox)
		+SHorizontalBox::Slot()
		.AutoWidth()
		.Padding(3.0f)
		[
			SNew(SScaleBox)
			.Stretch(EStretch::ScaleToFit)
			[
				SNew(SImage)
				.Visibility(ErrorIconVisibility)
				.Image( FEditorStyle::GetBrush( TEXT("Graph.ConnectorFeedback.Error") ))
				.ColorAndOpacity( FLinearColor::White )
			]
		]
		+SHorizontalBox::Slot()
		.AutoWidth()
		.Padding(3.0f)
		[
			SNew(SScaleBox)
			.Stretch(EStretch::ScaleToFit)
			[
				SNew(SImage)
				.Visibility(IconVisibility)
				.Image( Icon )
				.ColorAndOpacity( IconColor )
			]
		]
		+SHorizontalBox::Slot()
		.AutoWidth()
		.MaxWidth(500)
		.VAlign(VAlign_Center)
		[
			SNew(STextBlock)
			.WrapTextAt( 480 )
			.Text( Message )
		]
	);
}

EVisibility FGraphEditorDragDropAction::GetIconVisible() const
{
	return bDropTargetValid ? EVisibility::Visible : EVisibility::Collapsed;
}

EVisibility FGraphEditorDragDropAction::GetErrorIconVisible() const
{
	return bDropTargetValid ? EVisibility::Collapsed : EVisibility::Visible;
}

////////////////////////////////////////////////////////////

void FGraphSchemaActionDragDropAction::HoverTargetChanged()
{
	if(ActionNode.IsValid())
	{
		const FSlateBrush* StatusSymbol = FEditorStyle::GetBrush(TEXT("Graph.ConnectorFeedback.NewNode"));

		//Create feedback message with the function name.
		SetSimpleFeedbackMessage(StatusSymbol, FLinearColor::White, ActionNode->MenuDescription);
	}
}

FReply FGraphSchemaActionDragDropAction::DroppedOnPanel( const TSharedRef< SWidget >& Panel, FVector2D ScreenPosition, FVector2D GraphPosition, UEdGraph& Graph)
{
	if(ActionNode.IsValid())
	{
		TArray<UEdGraphPin*> DummyPins;
		ActionNode->PerformAction(&Graph, DummyPins, GraphPosition);

		return FReply::Handled();
	}
	return FReply::Unhandled();
}


text:
package com.ibatis.sqlmap.engine.cache;

import static org.junit.jupiter.api.Assertions.assertTrue;

import org.junit.jupiter.api.Test;

/**
 * CacheKey Tester.
 *
 * @author <Authors name>
 * @version 1.0
 * @since
 *
 *        <pre>
 *        08 / 29 / 2006
 *        </pre>
 */
public class CacheKeyTest {

  @Test
  public void testUpdate() {
    CacheKey key3 = new CacheKey();

    CacheKey key4 = new CacheKey();

    key3.update("AV");

    key4.update("B7");

    assertTrue(!key3.equals(key4));
    assertTrue(!key3.toString().equals(key4.toString()));

  }

}


text:
<?php

// autoload_classmap.php @generated by Composer

$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);

return array(
    'ClassMapBar' => $vendorDir . '/b/b/test.php',
    'ClassMapBaz' => $vendorDir . '/c/c/foo/test.php',
    'ClassMapFoo' => $vendorDir . '/a/a/src/a.php',
    'Composer\\InstalledVersions' => $vendorDir . '/composer/InstalledVersions.php',
);


text:
import logging
import click
from itertools import chain
from collections import namedtuple
import asyncio

from tornado.platform.asyncio import AsyncIOMainLoop
from streamz import Stream, union, combine_latest, zip_latest
import attr

from .events import PriceUpdate
from .collectors import Collector
from .feeds import Feed
from .config import config

logger = logging.getLogger(__name__)

AsyncIOMainLoop().install()

ENVVAR_PREFIX = 'NUMISMATIC'

class AliasedGroup(click.Group):

    def get_command(self, ctx, cmd_name):
        rv = click.Group.get_command(self, ctx, cmd_name)
        if rv is not None:
            return rv
        matches = [x for x in self.list_commands(ctx)
                   if x.startswith(cmd_name)]
        if not matches:
            return None
        elif len(matches) == 1:
            return click.Group.get_command(self, ctx, matches[0])
        ctx.fail('Too many matches: %s' % ', '.join(sorted(matches)))

pass_state = click.make_pass_decorator(dict, ensure=True)

@click.group(cls=AliasedGroup, chain=True)
@click.option('--cache-dir', '-d', default=None)
@click.option('--requester', '-r', default='base',
              type=click.Choice(['base', 'caching']))
@click.option('--log-level', '-l', default='info',
              type=click.Choice(['debug', 'info', 'warning', 'error',
                                 'critical']))
@click.option('--timeout', '-t', default=0)
@pass_state
def coin(state, cache_dir, requester, log_level, timeout):
    '''Numismatic Command Line Interface

    Examples:

        coin list

        coin info

        coin info -a ETH

        coin prices

        coin prices -a XMR,ZEC -c EUR,ZAR

        coin prices --raw

        coin prices -f luno

        coin tickers -f cryptocompare

        coin tickers -f cryptocompare --raw

        coin history

        coin history -a ETH -c BTC -o ETH-BTH-history.json

        coin subscribe collect

        coin -t 30 subscribe -a BTC,ETH,XMR,ZEC collect -t Trade

        coin subscribe -f bitfinex -f gdax collect

        coin subscribe -f bitfinex -f gdax collect --raw

        coin subscribe -f cryptocompare collect

        coin subscribe -f cryptocompare -e kraken collect

        coin subscribe -f bitfinex -f gdax compare

        coin sub -f cryptocompare -C tickers -e cexio sub -f \\
            cryptocompare -C prices -e kraken sub -f bitfinex sub -f gdax \\
            sub -f poloniex compare
    '''
    logging.basicConfig(level=getattr(logging, log_level.upper()))
    state['cache_dir'] = cache_dir
    state['requester'] = requester
    state['output_stream'] = Stream()
    state['subscriptions'] = {}

@coin.resultcallback()
def run(results, cache_dir, requester, log_level, timeout):
    """
    Run the asyncio event loop for a set amount of time. Set to 0 to run
    indefinitely.  Default is no-timeout."""
    if not timeout:
        # Allow to run indefinitely if timeout==0
        timeout = None
    loop = asyncio.get_event_loop()
    logger.debug('starting ...')
    tasks = asyncio.Task.all_tasks()
    try:
        if tasks:
            logger.info(f'Running {len(tasks)} tasks ...')
            completed, pending = \
                loop.run_until_complete(asyncio.wait(tasks, timeout=timeout))
        else:
            pass
    except KeyboardInterrupt:
        pass
    finally:
        tasks = asyncio.Task.all_tasks()
        pending = {task for task in tasks if not task.done()}
        if pending:
            logger.debug('Cancelling {len(pending)) tasks ...')
        for task in pending:
            logger.debug(f'Cancelling pending task {id(task)} ...')
            task.cancel()
        logger.debug('Done')

@coin.command(name='list')
@click.option('--feed', '-f', default=config['DEFAULT']['Feed'],
              type=click.Choice(Feed._get_subclasses().keys()))
@click.option('--output', '-o', type=click.File('wt'), default='-')
@pass_state
def list_all(state, feed, output):
    "List all available assets"
    feed_client = Feed.factory(feed, cache_dir=state['cache_dir'],
                               requester=state['requester'])
    assets_list = feed_client.get_list()
    # FIXME: This should a collector rather than write()
    write(assets_list, output, sep=' ')

@coin.command()
@click.option('--feed', '-f', default=config['DEFAULT']['Feed'],
              type=click.Choice(Feed._get_subclasses().keys()))
@click.option('--assets', '-a', multiple=True,
              envvar=f'{ENVVAR_PREFIX}_ASSETS')
@click.option('--output', '-o', type=click.File('wt'), default='-')
@pass_state
def info(state, feed, assets, output):
    "Info about the requested assets"
    feed_client = Feed.factory(feed, cache_dir=state['cache_dir'],
                               requester=state['requester'])
    assets_info = feed_client.get_info(assets)
    # FIXME: This should a collector rather than write()
    write(assets_info, output)

@coin.command()
@click.option('--feed', '-f', default=config['DEFAULT']['Feed'],
              type=click.Choice(Feed._get_subclasses().keys()))
@click.option('--exchange', '-e', default=None)
@click.option('--assets', '-a', multiple=True,
              envvar=f'{ENVVAR_PREFIX}_ASSETS')
@click.option('--currencies', '-c', multiple=True,
              envvar=f'{ENVVAR_PREFIX}_CURRENCIES')
@click.option('--raw', is_flag=True)
@click.option('--output', '-o', type=click.File('wt'), default='-')
@pass_state
def prices(state, feed, exchange, assets, currencies, raw, output):
    'Latest asset prices'
    feed_client = Feed.factory(feed, cache_dir=state['cache_dir'],
                               requester=state['requester'])
    prices = feed_client.get_prices(assets=assets, currencies=currencies,
                                    exchange=exchange, raw=raw)
    # FIXME: This should a collector rather than write()
    write(prices, output)

@coin.command()
@click.option('--feed', '-f', default=config['DEFAULT']['Feed'],
              type=click.Choice(Feed._get_subclasses().keys()))
@click.option('--exchange', '-e', default=None)
@click.option('--assets', '-a', multiple=True,
              envvar=f'{ENVVAR_PREFIX}_ASSETS')
@click.option('--currencies', '-c', multiple=True,
              envvar=f'{ENVVAR_PREFIX}_CURRENCIES')
@click.option('--raw', is_flag=True)
@click.option('--output', '-o', type=click.File('wt'), default='-')
@pass_state
def tickers(state, feed, exchange, assets, currencies, raw, output):
    'Latest asset tickers'
    feed_client = Feed.factory(feed, cache_dir=state['cache_dir'],
                               requester=state['requester'])
    tickers = feed_client.get_tickers(assets=assets, currencies=currencies,
                                      exchange=exchange, raw=raw)
    # FIXME: This should a collector rather than write()
    write(tickers, output)

@coin.command()
@click.option('--feed', '-f', default=config['DEFAULT']['Feed'],
              type=click.Choice(Feed._get_subclasses().keys()))
@click.option('--exchange', '-e', default=None)
@click.option('--freq', default='d', type=click.Choice(list('dhms')))
@click.option('--start-date', '-s', default=-30)
@click.option('--end-date', '-e', default=None)
@click.option('--assets', '-a', multiple=True,
              envvar=f'{ENVVAR_PREFIX}_ASSETS')
@click.option('--currencies', '-c', multiple=True,
              envvar=f'{ENVVAR_PREFIX}_CURRENCIES')
@click.option('--output', '-o', type=click.File('wt'), default='-')
@pass_state
def history(state, feed, exchange, assets, currencies, freq, start_date,
            end_date, output):
    'Historic asset prices and volumes'
    feed_client = Feed.factory(feed, cache_dir=state['cache_dir'],
                               requester=state['requester'])
    data = feed_client.get_historical_data(assets, currencies, freq=freq,
                                           start_date=start_date,
                                           end_date=end_date,
                                           exchange=exchange)
    # FIXME: This should a collector rather than write()
    write(data, output)

# FIXME: Do we still want this?
def tabulate(data):
    if isinstance(data, dict):
        data_iter = data.values()
    elif isinstance(data, list):
        data_iter = data
    else:
        raise TypeError(f'data: {data}')
    headers = set(chain(*map(lambda v: v.keys(), data_iter)))
    DataTuple = namedtuple('DataTuple', ' '.join(headers))
    DataTuple.__new__.__defaults__ = (None,) * len(headers)
    return map(lambda d: DataTuple(**d), data_iter)

@coin.command()
@click.option('--feed', '-f', default='bitfinex',
              type=click.Choice(Feed._get_subclasses().keys()))
@click.option('--exchange', '-e', default=None)
@click.option('--assets', '-a', multiple=True,
              envvar=f'{ENVVAR_PREFIX}_ASSETS')
@click.option('--currencies', '-c', multiple=True,
              envvar=f'{ENVVAR_PREFIX}_CURRENCIES')
@click.option('--interval', '-i', default=1.0, type=float,
              help='Interval between requests for RestClient subscriptions')
@click.option('--channels', '-C', multiple=True)
@pass_state
def subscribe(state, feed, exchange, assets, currencies, interval, channels):
    'Subscribe to live events from a feed'
    feed_client = Feed.factory(feed)
    subscriptions = feed_client.subscribe(assets, currencies, channels,
                                          exchange=exchange, interval=interval)
    state['subscriptions'].update(subscriptions)
    return subscriptions

@coin.command()
@click.option('--subscriptions', '-s', default=['all'], type=str, multiple=True)
@click.option('--event', 'stream', flag_value='event', default=True)
@click.option('--raw', 'stream', flag_value='raw')
@click.option('--collector', '-c', default='file',
              type=click.Choice(Collector._get_subclasses().keys()))
@click.option('--output', '-o', default='-', type=click.Path())
@click.option('--filters', '-f', default=None, type=str, multiple=True)
# FIXME: the types should be autogenerated from the Event types
@click.option('--types', '-t', default=None, multiple=True,
              type=click.Choice(['None', 'Heartbeat', 'PriceUpdate', 'Ticker',
                                 'Trade', 'Order']))
@click.option('--text', 'format', flag_value='text', default=True)
@click.option('--json', 'format', flag_value='json')
@click.option('--interval', '-i', default=None, type=float)
@pass_state
def collect(state, subscriptions, stream, collector, output, filters, types, format,
            interval):
    'Collect events and write them to an output sink'
    all_subscriptions = state['subscriptions']
    if stream=='event':
        stream_name = 'event_stream'
    elif stream=='raw':
        stream_name = 'raw_stream'
    else:
        raise ValueError(stream)
    if set(subscriptions)==set(['all']):
        subscriptions = all_subscriptions.keys()
    else:
        # allows filtering subscriptions that contain a pattern
        subscriptions = {sub_name for sub_pattern in subscriptions for sub_name
                         in all_subscriptions if sub_pattern in sub_name}
    collect_stream = union(*(getattr(all_subscriptions[sub], stream_name)
                             for sub in subscriptions))
    collector_name = collector
    collector = Collector.factory(collector_name, event_stream=collect_stream,
                                  path=output, format=format, types=types,
                                  filters=filters, interval=interval)
    return collector

@coin.command()
@click.option('--collector', '-c', default='file',
              type=click.Choice(Collector._get_subclasses().keys()))
@click.option('--output', '-o', default='-', type=click.Path())
@click.option('--interval', '-i', default=None, type=float)
@pass_state
def compare(state, collector, output, interval):
    'Compare prices events and write them to an output sink'
    subscriptions = state['subscriptions']
    streams = [sub.event_stream.filter(lambda ev: isinstance(ev, PriceUpdate))
               for sub in subscriptions.values()]
    compare_stream = combine_latest(*streams).map(
        lambda trades: {(t.exchange+'--'+t.asset+'/'+t.currency):t.price for t in trades})
    collector_name = collector
    collector = Collector.factory(collector_name, event_stream=compare_stream,
                                  path=output, interval=interval)
    return collector

def write(data, file, sep='\n'):
    for record in data:
        file.write(str(record)+sep)
    file.write('\n')

if __name__ == '__main__':
    coin()


text:
declare namespace echarts {
    namespace EChartOption {
        /**
         * Drawing grid in rectangular coordinate.
         * In a single grid, at most two X and Y axes each is allowed.
         * Line chart, bar chart, and scatter chart (bubble chart) can be drawn in grid.
         *
         * @see https://echarts.apache.org/en/option.html#grid
         */
        interface Grid {
            /**
             * Component ID, not specified by default.
             * If specified, it can be used to refer the component in option or API.
             */
            id?: string | undefined;
            /**
             * Whether to show the grid in rectangular coordinate.
             *
             * @default false
             */
            show?: boolean | undefined;
            /**
             * zlevel value of all graphical elements in.
             * zlevel is used to make layers with Canvas.
             * Graphical elements with different zlevel values will be placed in different Canvases,
             * which is a common optimization technique.
             * We can put those frequently changed elements (like those with animations) to a seperate zlevel.
             * Notice that too many Canvases will increase memory cost, and should be used carefully on mobile phones to avoid crash.
             * Canvases with bigger zlevel will be placed on Canvases with smaller zlevel.
             *
             * @default 0
             */
            zlevel?: number | undefined;
            /**
             * z value of all graphical elements in , which controls order of drawing graphical components.
             * Components with smaller z values may be overwritten by those with larger z values.
             * z has a lower priority to zlevel, and will not create new Canvas.
             *
             * @default 2
             */
            z?: number | undefined;
            /**
             * Distance between grid component and the left side of the container.
             * left value can be instant pixel value like 20;
             * it can also be percentage value relative to container width like '20%';
             * and it can also be 'left', 'center', or 'right'.
             * If the left value is set to be 'left', 'center', or 'right',
             * then the component will be aligned automatically based on position.
             *
             * @default '10%'
             */
            left?: number | string | undefined;
            /**
             * Distance between grid component and the top side of the container.
             * top value can be instant pixel value like 20;
             * it can also be percentage value relative to container width like '20%';
             * and it can also be 'top', 'middle', or 'bottom'.
             *
             * @default 60
             */
            top?: number | string | undefined;
            /**
             * Distance between grid component and the right side of the container.
             * right value can be instant pixel value like 20;
             * it can also be percentage value relative to container width like '20%'.
             *
             * @default '10%'
             */
            right?: number | string | undefined;
            /**
             * Distance between grid component and the bottom side of the container.
             * bottom value can be instant pixel value like 20; it can also be percentage value relative to container width like '20%'.
             *
             * @default 60
             */
            bottom?: number | string | undefined;
            /**
             * Width of grid component. Adaptive by default.
             *
             * @default 'auto'
             */
            width?: number | string | undefined;
            /**
             * Height of grid component. Adaptive by default.
             *
             * @default 'auto'
             */
            height?: number | string | undefined;
            /**
             * Whether the grid region contains axis tick label of axis.
             * When containLabel is false:
             * grid.left grid.right grid.top grid.bottom grid.width grid.height decide the location
             * and size of the rectangle that is made of by xAxis and yAxis.
             * Setting to false will help when multiple grids need to be aligned at their axes.
             * When containLabel is true:
             * grid.left grid.right grid.top grid.bottom grid.width grid.height decide the location
             * and size of the rectangle that contains the axes and the labels of the axes.
             * Setting to true will help when the length of axis labels is dynamic and is hard to approximate.
             * This will avoid labels from overflowing the container or overlapping other components.
             *
             * @default false
             */
            containLabel?: boolean | undefined;
            /**
             * Background color of grid, which is transparent by default.
             * Attention: Works only if show: true is set.
             *
             * @default 'transparent'
             */
            backgroundColor?: string | undefined;
            /**
             * Border color of grid. Support the same color format as backgroundColor.
             * Attention: Works only if show: true is set.
             *
             * @default '#ccc'
             */
            borderColor?: string | undefined;
            /**
             * Border width of grid.
             * Attention: Works only if show: true is set.
             *
             * @default 1
             */
            borderWidth?: number | undefined;
            /**
             * Size of shadow blur. This attribute should be used along with
             * shadowColor,shadowOffsetX, shadowOffsetY to set shadow to component.
             * Attention:
             * This property works only if show: true is configured and
             * backgroundColor is defined other than transparent.
             */
            shadowBlur?: number | undefined;
            /**
             * Shadow color. Support same format as color.
             * Attention: This property works only if show: true configured.
             */
            shadowColor?: string | undefined;
            /**
             * Offset distance on the horizontal direction of shadow.
             * Attention: This property works only if show: true configured.
             *
             * @default 0
             */
            shadowOffsetX?: number | undefined;
            /**
             * Offset distance on the vertical direction of shadow.
             * Attention: This property works only if show: true configured.
             *
             * @default 0
             */
            shadowOffsetY?: number | undefined;
            /**
             * tooltip settings in the coordinate system component.
             * @see https://echarts.apache.org/en/option.html#grid.tooltip
             */
            tooltip?: Tooltip | undefined;
        }
    }
}


text:
from webob import exc

import nova
from nova.api.openstack import common
from nova.api.openstack.compute.views import addresses as view_addresses
from nova.api.openstack import wsgi
from nova.api.openstack import xmlutil
from nova.i18n import _

def make_network(elem):
    elem.set('id', 0)

    ip = xmlutil.SubTemplateElement(elem, 'ip', selector=1)
    ip.set('version')
    ip.set('addr')

network_nsmap = {None: xmlutil.XMLNS_V11}

class NetworkTemplate(xmlutil.TemplateBuilder):
    def construct(self):
        sel = xmlutil.Selector(xmlutil.get_items, 0)
        root = xmlutil.TemplateElement('network', selector=sel)
        make_network(root)
        return xmlutil.MasterTemplate(root, 1, nsmap=network_nsmap)

class AddressesTemplate(xmlutil.TemplateBuilder):
    def construct(self):
        root = xmlutil.TemplateElement('addresses', selector='addresses')
        elem = xmlutil.SubTemplateElement(root, 'network',
                                          selector=xmlutil.get_items)
        make_network(elem)
        return xmlutil.MasterTemplate(root, 1, nsmap=network_nsmap)

class Controller(wsgi.Controller):
    """The servers addresses API controller for the OpenStack API."""

    _view_builder_class = view_addresses.ViewBuilder

    def __init__(self, **kwargs):
        super(Controller, self).__init__(**kwargs)
        self._compute_api = nova.compute.API()

    @wsgi.serializers(xml=AddressesTemplate)
    def index(self, req, server_id):
        context = req.environ["nova.context"]
        instance = common.get_instance(self._compute_api, context, server_id)
        networks = common.get_networks_for_instance(context, instance)
        return self._view_builder.index(networks)

    @wsgi.serializers(xml=NetworkTemplate)
    def show(self, req, server_id, id):
        context = req.environ["nova.context"]
        instance = common.get_instance(self._compute_api, context, server_id)
        networks = common.get_networks_for_instance(context, instance)
        if id not in networks:
            msg = _("Instance is not a member of specified network")
            raise exc.HTTPNotFound(explanation=msg)

        return self._view_builder.show(networks[id], id)

def create_resource():
    return wsgi.Resource(Controller())


text:
layout:         post
title:          "Installing Docker Toolbox on Windows OS"
description:    "Docker Toolbox provides front-end client of docker in Windows OS."
keywords:       [Docker, Docker Toolbox]
categories:     [Virtualization]
tags:           [Docker, VirtualBox]
---

WindowsでDockerを使うには、VirtualBoxなどを使用してDocker Engineを動作できるLinux環境を準備する必要があります。
VirtualBoxでLinux環境を利用するだけであればVagrantでも問題ありませんが、
Docker Toolboxを利用することで、Dockerすぐに使えるLinux環境を手に入れることができます。

<div class="notice">
Dockerは64bit OSでのみ動作します。
</div>

<!-- more -->

# Install Docker Toolbox

まずは[Docker Toolbox](https://www.docker.com/products/docker-toolbox)をダウンロードします。

ダウンロードしたらインストーラの案内に従って[Next > ]ボタンを押していきます。
{% include modal-image
    id="installer01"
    src="/images/posts/20160310/docker-toolbox-installer-01.png"
    class="half center"
%}

インストールパスはお好みで。
{% include modal-image
    id="installer02"
    src="/images/posts/20160310/docker-toolbox-installer-02.png"
    class="half center"
%}

Docker Tookboxでインストールされるコンポーネントを選択します。
私は、VirtualBoxとMsys2の環境を持っていたので、 __VirtualBox__ と __Git for Windows__ のチェックは外しました。
{% include modal-image
    id="installer03"
    src="/images/posts/20160310/docker-toolbox-installer-03.png"
    class="half center"
%}

ショートカット作成や`PATH`設定もお好みで。`PATH`設定しておいたほうが便利です。
{% include modal-image
    id="installer04"
    src="/images/posts/20160310/docker-toolbox-installer-04.png"
    class="half center"
%}

内容がOKであればインストールを開始します。
{% include modal-image
    id="installer05"
    src="/images/posts/20160310/docker-toolbox-installer-05.png"
    class="half center"
%}

# Usage Docker Toolbox

Windowsでは`docker-machine.exe`を使用します。
インストールフォルダ配下に`start.sh`があるので、Msys2など下記コマンドでdockerホストをVirtualBox上で起動することができます。

{% highlight raw %}
> bash --login start.sh
Running pre-create checks...
Creating machine...
(default) Copying C:\Users\${USER}\.docker\machine\cache\boot2docker.iso to C:\Users\${USER}\.docker\machine\machines\default\boot2docker.iso...
(default) Creating VirtualBox VM...
(default) Creating SSH key...
(default) Starting the VM...
(default) Check network to re-create if needed...
(default) Waiting for an IP...
Waiting for machine to be running, this may take a few minutes...
Detecting operating system of created instance...
Waiting for SSH to be available...
Detecting the provisioner...
Provisioning with boot2docker...
Copying certs to the local machine directory...
Copying certs to the remote machine...
Setting Docker configuration on the remote daemon...
Checking connection to Docker...
Docker is up and running!
To see how to connect your Docker Client to the Docker Engine running on this virtual machine, run: C:\Program Files\tools\DockerToolbox\docker-machine.exe env default

                        ##         .
                  ## ## ##        ==
               ## ## ## ## ##    ===
           /"""""""""""""""""\___/ ===
      ~~~ {~~ ~~~~ ~~~ ~~~~ ~~~ ~ /  ===- ~~~
           \______ o           __/
             \    \         __/
              \____\_______/

docker is configured to use the default machine with IP 192.168.99.100
For help getting started, check out the docs at https://docs.docker.com
{% endhighlight %}

ここまで表示されていれば、VirtualBox上で`default`というVM名でDockerホストが起動しています。

試しに、SSHでログインして、dockerの起動テストをしてみます。
SSHログインも`docker-machine.exe`からおこないます。

{% highlight raw %}
> docker-machine ssh default
                        ##         .
                  ## ## ##        ==
               ## ## ## ## ##    ===
           /"""""""""""""""""\___/ ===
      ~~~ {~~ ~~~~ ~~~ ~~~~ ~~~ ~ /  ===- ~~~
           \______ o           __/
             \    \         __/
              \____\_______/
 _                 _   ____     _            _
| |__   ___   ___ | |_|___ \ __| | ___   ___| | _____ _ __
| '_ \ / _ \ / _ \| __| __) / _` |/ _ \ / __| |/ / _ \ '__|
| |_) | (_) | (_) | |_ / __/ (_| | (_) | (__|   <  __/ |
|_.__/ \___/ \___/ \__|_____\__,_|\___/ \___|_|\_\___|_|
Boot2Docker version 1.10.2, build master : 611be10 - Mon Feb 22 22:47:06 UTC 2016
Docker version 1.10.2, build c3959b1
docker@default:~$
{% endhighlight %}

これで、VirtualBox上で動いているDockerホストにSSHログインできました。
続いてdockerを動かしてみます。サブコマンドに`run`を指定し、コンテナ名と実行コマンドを指定します。
ここではコンテナ名を`centos`としていますが、ここれはデフォルトで提供されているもののようです。
初回は、Dockerリポジトリからコンテナイメージをダウンロードしてきますので少々時間がかかります。

{% highlight raw %}
docker@default:~$ docker run centos /bin/echo Hello World
Unable to find image 'centos:latest' locally
latest: Pulling from library/centos
a3ed95caeb02: Pull complete
196355c4b639: Pull complete
Digest: sha256:381f21e4c7b3724c6f420b2bcfa6e13e47ed155192869a2a04fa10f944c78476
Status: Downloaded newer image for centos:latest
Hello World
docker@default:~$
{% endhighlight %}

無事`Hello World`と`echo`表示させることができました。


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.smb-tec.xo.query</groupId>
        <artifactId>xo-neo4j-query</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>

    <artifactId>xo-neo4j-lucene</artifactId>

    <name>eXtended Objects - Neo4j - Lucene Query Support</name>

</project>


text:
import { shallowMount, Wrapper } from '@vue/test-utils';
import Vue from 'vue';
import ModulDate from '../../utils/modul-date/modul-date';
import { DatePickerSupportedTypes } from './../datepicker/datepicker';
import PeriodpickerPlugin, { MDateRange, MPeriodpicker, MPeriodpickerFromSlotProps, MPeriodpickerToSlotProps } from './periodpicker';

let wrapper: Wrapper<MPeriodpicker>;
let fromDateProp: DatePickerSupportedTypes;
let toDateProp: DatePickerSupportedTypes;
let minDateProp: DatePickerSupportedTypes;
let maxDateProp: DatePickerSupportedTypes;

let currentFromScopeProps: MPeriodpickerFromSlotProps;
let currentToScopeProps: MPeriodpickerToSlotProps;

const initializeWrapper: () => Wrapper<MPeriodpicker> = () => {
    wrapper = shallowMount(MPeriodpicker, {
        propsData: {
            value: {
                from: fromDateProp,
                to: toDateProp
            },
            min: minDateProp,
            max: maxDateProp
        },
        scopedSlots: {
            first(props: MPeriodpickerFromSlotProps): void {
                currentFromScopeProps = props;
            },
            second(props: MPeriodpickerToSlotProps): void {
                currentToScopeProps = props;
            }
        }
    });

    return wrapper;
};

const expectSelectionEnd: (expectedValue?: MDateRange) => void = (expectedValue: MDateRange) => {
    expect(wrapper.vm.fromIsFocused).toBe(false);
    expect(wrapper.vm.toIsFocused).toBe(false);

    if (expectedValue) {
        expect(wrapper.emitted('input')[0][0]).toEqual(expectedValue);
    }
};

const expectNoSelectionEnd: () => void = () => {
    expect(wrapper.emitted('input')).toBeUndefined();
};

describe(`m-periodpicker`, () => {
    beforeEach(() => {
        Vue.use(PeriodpickerPlugin);

        wrapper = undefined as any;
        fromDateProp = undefined as any;
        toDateProp = undefined as any;
        minDateProp = undefined as any;
        maxDateProp = undefined as any;

        currentFromScopeProps = undefined as any;
    });

    it(`should show closed / unfocused pickers by default`, () => {
        initializeWrapper();

        expect(currentFromScopeProps.props.focus).toBe(false);
        expect(currentToScopeProps.props.focus).toBe(false);
    });

    it(`should open dateFrom picker only when opening dateFrom picker`, async () => {
        initializeWrapper();

        currentFromScopeProps.handlers.change('2018-04-24');

        await Vue.nextTick();

        expect(currentFromScopeProps.props.focus).toBe(false);
        expect(currentToScopeProps.props.focus).toBe(true);
    });

    it(`should end selection when closing dateFrom picker without changing any value`, () => {
        initializeWrapper();

        expectSelectionEnd();
    });

    it(`should end selection when emptying dateFrom picker value`, () => {
        initializeWrapper();

        currentFromScopeProps.handlers.change(undefined);

        expectSelectionEnd();
    });

    it(`should end selection when emptying dateTo picker value`, () => {
        initializeWrapper();

        currentToScopeProps.handlers.change(undefined);

        expectSelectionEnd();
    });

    describe(`given no props are provided`, () => {
        it(`should pass down empty data to the first date`, () => {
            initializeWrapper();

            expect(currentFromScopeProps.props.value).toBe('');
            expect(currentFromScopeProps.props.min).toBe(undefined);
            expect(currentFromScopeProps.props.max).toBe(undefined);
        });

        it(`should pass down empty data to the second date`, () => {
            initializeWrapper();

            expect(currentToScopeProps.props.value).toBe('');
            expect(currentToScopeProps.props.min).toBe(undefined);
            expect(currentToScopeProps.props.max).toBe(undefined);
        });

        describe(`given dateFrom selector is open`, () => {
            beforeEach(() => {
                initializeWrapper();
            });

            it(`should end selection when emptying the value`, () => {
                currentFromScopeProps.handlers.change(undefined);
                currentFromScopeProps.handlers.blur();

                expectSelectionEnd(new MDateRange(undefined, undefined, true));
            });

            it(`should emit the new value when changing dateToValue`, async () => {
                const newFromDate: Date = new Date();
                const newToDate: Date = new Date();
                currentFromScopeProps.handlers.change(newFromDate);
                currentFromScopeProps.handlers.blur();
                currentToScopeProps.handlers.change(newToDate);
                currentToScopeProps.handlers.blur();
                await Vue.nextTick();
                expectSelectionEnd(new MDateRange(new ModulDate(newFromDate).beginOfDay(), new ModulDate(newToDate).endOfDay(), true));
            });
        });

        describe(`given dateTo selector is open`, () => {
            beforeEach(() => {
                initializeWrapper();
            });

            it(`should end selection when emptying the value`, () => {
                currentToScopeProps.handlers.change(undefined);
                currentToScopeProps.handlers.blur();
                expectSelectionEnd(new MDateRange(undefined, undefined, true));
            });

            it(`should emit the new value when changing dateToValue`, async () => {
                const newToDate: Date = new Date();
                currentToScopeProps.handlers.change(newToDate);
                currentToScopeProps.handlers.blur();
                await Vue.nextTick();
                expectSelectionEnd(new MDateRange(undefined, new ModulDate(newToDate).endOfDay(), true));
            });
        });
    });

    describe(`given all props are provided`, () => {
        beforeEach(() => {
            fromDateProp = new Date();
            toDateProp = new Date(new Date().setDate(fromDateProp.getDate() + 1));
            minDateProp = new Date(new Date().setFullYear(fromDateProp.getFullYear() - 1));
            maxDateProp = new Date(new Date().setFullYear(fromDateProp.getFullYear() + 1));
        });

        it(`should pass down empty data to the first date`, () => {
            initializeWrapper();

            expect(currentFromScopeProps.props.value).toBe(MPeriodpicker.formatIsoDateToLocalString(fromDateProp));
            expect(currentFromScopeProps.props.min).toBe(minDateProp);
            expect(currentFromScopeProps.props.max).toBe(maxDateProp);
        });

        it(`should pass down empty data to the second date`, () => {
            initializeWrapper();

            expect(currentToScopeProps.props.value).toBe(MPeriodpicker.formatIsoDateToLocalString(toDateProp));
            expect(currentToScopeProps.props.min).toBe(MPeriodpicker.formatIsoDateToLocalString(fromDateProp));
            expect(currentToScopeProps.props.max).toBe(maxDateProp);
        });

        describe(`given dateFrom selector is open`, () => {
            beforeEach(() => {
                initializeWrapper();
            });

            it(`should end selection when emptying the value`, () => {
                currentFromScopeProps.handlers.change(undefined);
                currentFromScopeProps.handlers.blur();

                expectSelectionEnd(new MDateRange(undefined, new ModulDate(toDateProp).endOfDay(), true));
            });

            it(`should not end selection and start dateTo pick when changing dateFrom the value`, () => {
                currentFromScopeProps.handlers.change(new Date());

                expectNoSelectionEnd();
                expect(wrapper.vm.fromIsFocused).toBe(false);
                expect(wrapper.vm.toIsFocused).toBe(true);
            });

            it(`should emit the new value when changing dateToValue`, () => {
                const newFromDate: Date = new Date();
                const newToDate: Date = new Date();
                currentFromScopeProps.handlers.change(newFromDate);
                currentFromScopeProps.handlers.blur();
                currentToScopeProps.handlers.change(newToDate);
                currentToScopeProps.handlers.blur();
                expectSelectionEnd(new MDateRange(new ModulDate(newFromDate).beginOfDay(), new ModulDate(newToDate).endOfDay(), true));
            });
        });

        describe(`given dateTo selector is open`, () => {
            beforeEach(() => {
                initializeWrapper();
            });

            it(`should end selection when emptying the value`, () => {
                currentToScopeProps.handlers.change(undefined);
                currentToScopeProps.handlers.blur();

                expectSelectionEnd(new MDateRange(new ModulDate(fromDateProp).beginOfDay(), undefined, true));
            });

            it(`should emit the new value when changing dateToValue`, () => {
                const newToDate: Date = new Date();
                currentToScopeProps.handlers.change(newToDate);
                currentToScopeProps.handlers.blur();
                expectSelectionEnd(new MDateRange(new ModulDate(fromDateProp).beginOfDay(), new ModulDate(newToDate).endOfDay(), true));
            });
        });
    });
});


text:
/* Retrieves the sub ${value_description_long} specified by the path
 * Returns a Python object if successful or NULL on error
 */
PyObject *${python_module_name}_${type_name}_get_sub_${value_name}_by_path(
           ${python_module_name}_${type_name}_t *${python_module_name}_${type_name},
           PyObject *arguments,
           PyObject *keywords )
{
	PyObject *${value_name}_object                     = NULL;
	PyTypeObject *type_object                          = NULL;
	libcerror_error_t *error                           = NULL;
	${library_name}_${value_type}_t *sub_${value_name} = NULL;
	static char *function                              = "${python_module_name}_${type_name}_get_sub_${value_name}_by_path";
	static char *keyword_list[]                        = { "path", NULL };
	char *utf8_path                                    = NULL;
	size_t utf8_path_length                            = 0;
	int result                                         = 0;

	if( ${python_module_name}_${type_name} == NULL )
	{
		PyErr_Format(
		 PyExc_ValueError,
		 "%s: invalid ${type_description}.",
		 function );

		return( NULL );
	}
	if( PyArg_ParseTupleAndKeywords(
	     arguments,
	     keywords,
	     "s",
	     keyword_list,
	     &utf8_path ) == 0 )
	{
		goto on_error;
	}
	utf8_path_length = narrow_string_length(
	                    utf8_path );

	Py_BEGIN_ALLOW_THREADS

	result = ${library_name}_${type_name}_get_sub_${value_name}_by_utf8_path(
	           ${python_module_name}_${type_name}->${type_name},
	           (uint8_t *) utf8_path,
	           utf8_path_length,
	           &sub_${value_name},
	           &error );

	Py_END_ALLOW_THREADS

	if( result == -1 )
	{
		${python_module_name}_error_raise(
		 error,
		 PyExc_IOError,
		 "%s: unable to retrieve sub ${value_description}.",
		 function );

		libcerror_error_free(
		 &error );

		goto on_error;
	}
	else if( result == 0 )
	{
		Py_IncRef(
		 Py_None );

		return( Py_None );
	}
	type_object = ${python_module_name}_${type_name}_get_${value_type}_type_object(
	               sub_${value_name} );

	if( type_object == NULL )
	{
		PyErr_Format(
		 PyExc_IOError,
		 "%s: unable to retrieve ${value_type_description} type object.",
		 function );

		goto on_error;
	}
	${value_name}_object = ${python_module_name}_${value_type}_new(
	                        type_object,
	                        sub_${value_name},
	                        ${python_module_name}_${value_name}->parent_object );

	if( ${value_name}_object == NULL )
	{
		PyErr_Format(
		 PyExc_MemoryError,
		 "%s: unable to create sub ${value_type_description} object.",
		 function );

		goto on_error;
	}
	return( ${value_name}_object );

on_error:
	if( sub_${value_name} != NULL )
	{
		${library_name}_${value_type}_free(
		 &sub_${value_name},
		 NULL );
	}
	return( NULL );
}


text:
using System;
using System.Text;
using System.Threading;
using Bjd;
using Bjd.net;
using Bjd.sock;
using NUnit.Framework;

namespace BjdTest.sock{
    [TestFixture]
    public class SockTcpTest : ILife{
        //テスト用のEchoサーバ
        private class EchoServer : ThreadBase{
            private readonly SockServer _sockServer;
            private readonly String _addr;
            private readonly int _port;
            private readonly Ssl _ssl = null;

            public EchoServer(String addr, int port) : base(null){
                _sockServer = new SockServer(new Kernel(),ProtocolKind.Tcp,_ssl);
                _addr = addr;
                _port = port;
            }

            public override String GetMsg(int no){
                return null;
            }

            protected override bool OnStartThread(){
                return true;
            }

            protected override void OnStopThread(){
                _sockServer.Close();
            }

            protected override void OnRunThread(){
                Ip ip = null;
                try{
                    ip = new Ip(_addr);
                } catch (ValidObjException ex){
                    Assert.Fail(ex.Message);
                }
                if (_sockServer.Bind(ip, _port, 1)){
                    //[C#]
                    ThreadBaseKind = ThreadBaseKind.Running;

                    while (IsLife()){
                        var child = (SockTcp) _sockServer.Select(this);
                        if (child == null){
                            break;
                        }
                        while (IsLife() && child.SockState == SockState.Connect){
                            var len = child.Length();
                            if (len > 0){
                                var buf = child.Recv(len, 100, this);
                                child.Send(buf);
                            }
                        }
                    }
                }
            }
        }
        [Test]
        public void Echoサーバに送信して溜まったデータサイズ_lengthを確認する(){
            //setUp
            const string addr = "127.0.0.1";
            const int port = 9982;
            var sv = new EchoServer(addr, port);
            sv.Start();

            var sut = new SockTcp(new Kernel(), new Ip(addr), port, 100, null);
            const int max = 1000;
            for (int i = 0; i < 3; i++){
                sut.Send(new byte[max]);
            }

            Thread.Sleep(200);

            int expected = max*3;

            //exercise
            var actual = sut.Length();

            //verify
            Assert.That(actual, Is.EqualTo(expected));

            //tearDown
            sut.Close();
            sv.Stop();
        }

        [Test]
        public void Echoサーバにsendで送信てtcpQueueのlength分ずつRecvする(){
            const string addr = "127.0.0.1";
            const int port = 9981;

            var echoServer = new EchoServer(addr, port);
            echoServer.Start();

            const int timeout = 100;
            Ip ip = null;
            try{
                ip = new Ip(addr);
            } catch (ValidObjException ex){
                Assert.Fail(ex.Message);
            }
            var sockTcp = new SockTcp(new Kernel(), ip, port, timeout, null);

            const int max = 1000;
            const int loop = 3;
            var tmp = new byte[max];
            for (var i = 0; i < max; i++){
                tmp[i] = (byte) i;
            }

            int recvCount = 0;
            for (var i = 0; i < loop; i++){
                var len = sockTcp.Send(tmp);
                Assert.That(len, Is.EqualTo(tmp.Length));

                Thread.Sleep(10);

                var b = sockTcp.Recv(len, timeout, this);
                recvCount += b.Length;
                for (int m = 0; m < max; m += 10){
                    Assert.That(b[m], Is.EqualTo(tmp[m])); //送信したデータと受信したデータが同一かどうかのテスト
                }
            }
            Assert.That(loop*max, Is.EqualTo(recvCount)); //送信したデータ数と受信したデータ数が一致するかどうかのテスト

            sockTcp.Close();
            echoServer.Stop();
        }

        [Test]
        public void EchoサーバにstringSendで1行送信してstringRecvで1行受信する(){
            //setUp
            const string addr = "127.0.0.1";
            const int port = 9993;

            var sv = new EchoServer(addr, port);
            sv.Start();
            var sut = new SockTcp(new Kernel(),new Ip(addr), port, 100, null);
            sut.StringSend("本日は晴天なり", "UTF-8");
            Thread.Sleep(10);

            var expected = "本日は晴天なり\r\n";

            //exercise
            var actual = sut.StringRecv("UTF-8", 1, this);

            //verify
            Assert.That(actual, Is.EqualTo(expected));

            //tearDown
            sut.Close();
            sv.Stop();
        }

        [Test]
        public void EchoサーバにlineSendで1行送信してlineRecvで1行受信する(){
            //setUp
            const string addr = "127.0.0.1";
            const int port = 9993;

            var sv = new EchoServer(addr, port);
            sv.Start();
            var sut = new SockTcp(new Kernel(), new Ip(addr), port, 100, null);
            sut.LineSend(Encoding.UTF8.GetBytes("本日は晴天なり"));
            Thread.Sleep(10);

            var expected = "本日は晴天なり\r\n";

            //exercise
            var bytes = sut.LineRecv(1, this);
            var actual = Encoding.UTF8.GetString(bytes);

            //verify
            Assert.That(actual, Is.EqualTo(expected));

            //tearDown
            sut.Close();
            sv.Stop();
        }

        public bool IsLife(){
            return true;
        }
    }
}


text:
package org.codehaus.xfire.jaxws;

import org.codehaus.xfire.aegis.AbstractXFireAegisTest;

public class AbstractJAXWSTest
    extends AbstractXFireAegisTest
{

}


text:
"""
    SALTS XBMC Addon
    Copyright (C) 2014 tknorris

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

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

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""
import log_utils  # @UnusedImport
import proxy

logger = log_utils.Logger.get_logger()

class Proxy(proxy.Proxy):
    try:
        from one23movies_scraper import Scraper as real_scraper
    except Exception as e:
        real_scraper = None
        logger.log('import failed: %s' % (e), log_utils.LOGDEBUG)