text:
.class public Lcom/tencent/qrom/gif/MultiCallback;
.super Ljava/lang/Object;
.source "MultiCallback.java"

# interfaces
.implements Landroid/graphics/drawable/Drawable$Callback;

# annotations
.annotation system Ldalvik/annotation/MemberClasses;
    value = {
        Lcom/tencent/qrom/gif/MultiCallback$ViewWeakReference;
    }
.end annotation

# instance fields
.field private final mViewList:Ljava/util/concurrent/CopyOnWriteArrayList;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Ljava/util/concurrent/CopyOnWriteArrayList",
            "<",
            "Lcom/tencent/qrom/gif/MultiCallback$ViewWeakReference;",
            ">;"
        }
    .end annotation
.end field

# direct methods
.method public constructor <init>()V
    .locals 1

    .prologue
    .line 19
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 21
    new-instance v0, Ljava/util/concurrent/CopyOnWriteArrayList;

    invoke-direct {v0}, Ljava/util/concurrent/CopyOnWriteArrayList;-><init>()V

    iput-object v0, p0, Lcom/tencent/qrom/gif/MultiCallback;->mViewList:Ljava/util/concurrent/CopyOnWriteArrayList;

    .line 99
    return-void
.end method

# virtual methods
.method public addView(Landroid/view/View;)V
    .locals 5
    .param p1, "view"    # Landroid/view/View;

    .prologue
    .line 72
    const/4 v0, 0x0

    .local v0, "i":I
    :goto_0
    iget-object v3, p0, Lcom/tencent/qrom/gif/MultiCallback;->mViewList:Ljava/util/concurrent/CopyOnWriteArrayList;

    invoke-virtual {v3}, Ljava/util/concurrent/CopyOnWriteArrayList;->size()I

    move-result v3

    if-ge v0, v3, :cond_1

    .line 73
    iget-object v3, p0, Lcom/tencent/qrom/gif/MultiCallback;->mViewList:Ljava/util/concurrent/CopyOnWriteArrayList;

    invoke-virtual {v3, v0}, Ljava/util/concurrent/CopyOnWriteArrayList;->get(I)Ljava/lang/Object;

    move-result-object v2

    check-cast v2, Lcom/tencent/qrom/gif/MultiCallback$ViewWeakReference;

    .line 74
    .local v2, "reference":Lcom/tencent/qrom/gif/MultiCallback$ViewWeakReference;
    invoke-virtual {v2}, Lcom/tencent/qrom/gif/MultiCallback$ViewWeakReference;->get()Ljava/lang/Object;

    move-result-object v1

    check-cast v1, Landroid/view/View;

    .line 75
    .local v1, "item":Landroid/view/View;
    if-nez v1, :cond_0

    .line 77
    iget-object v3, p0, Lcom/tencent/qrom/gif/MultiCallback;->mViewList:Ljava/util/concurrent/CopyOnWriteArrayList;

    invoke-virtual {v3, v2}, Ljava/util/concurrent/CopyOnWriteArrayList;->remove(Ljava/lang/Object;)Z

    .line 72
    :cond_0
    add-int/lit8 v0, v0, 0x1

    goto :goto_0

    .line 80
    .end local v1    # "item":Landroid/view/View;
    .end local v2    # "reference":Lcom/tencent/qrom/gif/MultiCallback$ViewWeakReference;
    :cond_1
    iget-object v3, p0, Lcom/tencent/qrom/gif/MultiCallback;->mViewList:Ljava/util/concurrent/CopyOnWriteArrayList;

    new-instance v4, Lcom/tencent/qrom/gif/MultiCallback$ViewWeakReference;

    invoke-direct {v4, p1}, Lcom/tencent/qrom/gif/MultiCallback$ViewWeakReference;-><init>(Landroid/view/View;)V

    invoke-virtual {v3, v4}, Ljava/util/concurrent/CopyOnWriteArrayList;->addIfAbsent(Ljava/lang/Object;)Z

    .line 81
    return-void
.end method

.method public invalidateDrawable(Landroid/graphics/drawable/Drawable;)V
    .locals 4
    .param p1, "who"    # Landroid/graphics/drawable/Drawable;

    .prologue
    .line 25
    const/4 v0, 0x0

    .local v0, "i":I
    :goto_0
    iget-object v3, p0, Lcom/tencent/qrom/gif/MultiCallback;->mViewList:Ljava/util/concurrent/CopyOnWriteArrayList;

    invoke-virtual {v3}, Ljava/util/concurrent/CopyOnWriteArrayList;->size()I

    move-result v3

    if-ge v0, v3, :cond_1

    .line 26
    iget-object v3, p0, Lcom/tencent/qrom/gif/MultiCallback;->mViewList:Ljava/util/concurrent/CopyOnWriteArrayList;

    invoke-virtual {v3, v0}, Ljava/util/concurrent/CopyOnWriteArrayList;->get(I)Ljava/lang/Object;

    move-result-object v1

    check-cast v1, Lcom/tencent/qrom/gif/MultiCallback$ViewWeakReference;

    .line 27
    .local v1, "reference":Lcom/tencent/qrom/gif/MultiCallback$ViewWeakReference;
    invoke-virtual {v1}, Lcom/tencent/qrom/gif/MultiCallback$ViewWeakReference;->get()Ljava/lang/Object;

    move-result-object v2

    check-cast v2, Landroid/view/View;

    .line 28
    .local v2, "view":Landroid/view/View;
    if-eqz v2, :cond_0

    .line 29
    invoke-virtual {v2, p1}, Landroid/view/View;->invalidateDrawable(Landroid/graphics/drawable/Drawable;)V

    .line 25
    :goto_1
    add-int/lit8 v0, v0, 0x1

    goto :goto_0

    .line 32
    :cond_0
    iget-object v3, p0, Lcom/tencent/qrom/gif/MultiCallback;->mViewList:Ljava/util/concurrent/CopyOnWriteArrayList;

    invoke-virtual {v3, v1}, Ljava/util/concurrent/CopyOnWriteArrayList;->remove(Ljava/lang/Object;)Z

    goto :goto_1

    .line 35
    .end local v1    # "reference":Lcom/tencent/qrom/gif/MultiCallback$ViewWeakReference;
    .end local v2    # "view":Landroid/view/View;
    :cond_1
    return-void
.end method

.method public removeView(Landroid/view/View;)V
    .locals 4
    .param p1, "view"    # Landroid/view/View;

    .prologue
    .line 89
    const/4 v0, 0x0

    .local v0, "i":I
    :goto_0
    iget-object v3, p0, Lcom/tencent/qrom/gif/MultiCallback;->mViewList:Ljava/util/concurrent/CopyOnWriteArrayList;

    invoke-virtual {v3}, Ljava/util/concurrent/CopyOnWriteArrayList;->size()I

    move-result v3

    if-ge v0, v3, :cond_2

    .line 90
    iget-object v3, p0, Lcom/tencent/qrom/gif/MultiCallback;->mViewList:Ljava/util/concurrent/CopyOnWriteArrayList;

    invoke-virtual {v3, v0}, Ljava/util/concurrent/CopyOnWriteArrayList;->get(I)Ljava/lang/Object;

    move-result-object v2

    check-cast v2, Lcom/tencent/qrom/gif/MultiCallback$ViewWeakReference;

    .line 91
    .local v2, "reference":Lcom/tencent/qrom/gif/MultiCallback$ViewWeakReference;
    invoke-virtual {v2}, Lcom/tencent/qrom/gif/MultiCallback$ViewWeakReference;->get()Ljava/lang/Object;

    move-result-object v1

    check-cast v1, Landroid/view/View;

    .line 92
    .local v1, "item":Landroid/view/View;
    if-eqz v1, :cond_0

    if-ne v1, p1, :cond_1

    .line 94
    :cond_0
    iget-object v3, p0, Lcom/tencent/qrom/gif/MultiCallback;->mViewList:Ljava/util/concurrent/CopyOnWriteArrayList;

    invoke-virtual {v3, v2}, Ljava/util/concurrent/CopyOnWriteArrayList;->remove(Ljava/lang/Object;)Z

    .line 89
    :cond_1
    add-int/lit8 v0, v0, 0x1

    goto :goto_0

    .line 97
    .end local v1    # "item":Landroid/view/View;
    .end local v2    # "reference":Lcom/tencent/qrom/gif/MultiCallback$ViewWeakReference;
    :cond_2
    return-void
.end method

.method public scheduleDrawable(Landroid/graphics/drawable/Drawable;Ljava/lang/Runnable;J)V
    .locals 4
    .param p1, "who"    # Landroid/graphics/drawable/Drawable;
    .param p2, "what"    # Ljava/lang/Runnable;
    .param p3, "when"    # J

    .prologue
    .line 39
    const/4 v0, 0x0

    .local v0, "i":I
    :goto_0
    iget-object v3, p0, Lcom/tencent/qrom/gif/MultiCallback;->mViewList:Ljava/util/concurrent/CopyOnWriteArrayList;

    invoke-virtual {v3}, Ljava/util/concurrent/CopyOnWriteArrayList;->size()I

    move-result v3

    if-ge v0, v3, :cond_1

    .line 40
    iget-object v3, p0, Lcom/tencent/qrom/gif/MultiCallback;->mViewList:Ljava/util/concurrent/CopyOnWriteArrayList;

    invoke-virtual {v3, v0}, Ljava/util/concurrent/CopyOnWriteArrayList;->get(I)Ljava/lang/Object;

    move-result-object v1

    check-cast v1, Lcom/tencent/qrom/gif/MultiCallback$ViewWeakReference;

    .line 41
    .local v1, "reference":Lcom/tencent/qrom/gif/MultiCallback$ViewWeakReference;
    invoke-virtual {v1}, Lcom/tencent/qrom/gif/MultiCallback$ViewWeakReference;->get()Ljava/lang/Object;

    move-result-object v2

    check-cast v2, Landroid/view/View;

    .line 42
    .local v2, "view":Landroid/view/View;
    if-eqz v2, :cond_0

    .line 43
    invoke-virtual {v2, p1, p2, p3, p4}, Landroid/view/View;->scheduleDrawable(Landroid/graphics/drawable/Drawable;Ljava/lang/Runnable;J)V

    .line 39
    :goto_1
    add-int/lit8 v0, v0, 0x1

    goto :goto_0

    .line 46
    :cond_0
    iget-object v3, p0, Lcom/tencent/qrom/gif/MultiCallback;->mViewList:Ljava/util/concurrent/CopyOnWriteArrayList;

    invoke-virtual {v3, v1}, Ljava/util/concurrent/CopyOnWriteArrayList;->remove(Ljava/lang/Object;)Z

    goto :goto_1

    .line 49
    .end local v1    # "reference":Lcom/tencent/qrom/gif/MultiCallback$ViewWeakReference;
    .end local v2    # "view":Landroid/view/View;
    :cond_1
    return-void
.end method

.method public unscheduleDrawable(Landroid/graphics/drawable/Drawable;Ljava/lang/Runnable;)V
    .locals 4
    .param p1, "who"    # Landroid/graphics/drawable/Drawable;
    .param p2, "what"    # Ljava/lang/Runnable;

    .prologue
    .line 53
    const/4 v0, 0x0

    .local v0, "i":I
    :goto_0
    iget-object v3, p0, Lcom/tencent/qrom/gif/MultiCallback;->mViewList:Ljava/util/concurrent/CopyOnWriteArrayList;

    invoke-virtual {v3}, Ljava/util/concurrent/CopyOnWriteArrayList;->size()I

    move-result v3

    if-ge v0, v3, :cond_1

    .line 54
    iget-object v3, p0, Lcom/tencent/qrom/gif/MultiCallback;->mViewList:Ljava/util/concurrent/CopyOnWriteArrayList;

    invoke-virtual {v3, v0}, Ljava/util/concurrent/CopyOnWriteArrayList;->get(I)Ljava/lang/Object;

    move-result-object v1

    check-cast v1, Lcom/tencent/qrom/gif/MultiCallback$ViewWeakReference;

    .line 55
    .local v1, "reference":Lcom/tencent/qrom/gif/MultiCallback$ViewWeakReference;
    invoke-virtual {v1}, Lcom/tencent/qrom/gif/MultiCallback$ViewWeakReference;->get()Ljava/lang/Object;

    move-result-object v2

    check-cast v2, Landroid/view/View;

    .line 56
    .local v2, "view":Landroid/view/View;
    if-eqz v2, :cond_0

    .line 57
    invoke-virtual {v2, p1}, Landroid/view/View;->unscheduleDrawable(Landroid/graphics/drawable/Drawable;)V

    .line 53
    :goto_1
    add-int/lit8 v0, v0, 0x1

    goto :goto_0

    .line 60
    :cond_0
    iget-object v3, p0, Lcom/tencent/qrom/gif/MultiCallback;->mViewList:Ljava/util/concurrent/CopyOnWriteArrayList;

    invoke-virtual {v3, v1}, Ljava/util/concurrent/CopyOnWriteArrayList;->remove(Ljava/lang/Object;)Z

    goto :goto_1

    .line 63
    .end local v1    # "reference":Lcom/tencent/qrom/gif/MultiCallback$ViewWeakReference;
    .end local v2    # "view":Landroid/view/View;
    :cond_1
    return-void
.end method


text:
import { Component } from "@angular/core";
import {AsyncDescription} from "../../../template/demo-template/demo-template";

@Component({
    selector: 'process-status-vertical',
    templateUrl: './demo.component.html',
})
export class ProcessStatusVerticalFullComponent extends AsyncDescription {
    public demoPath = "demo/process-status/vertical";

    public steps = [
        {
            title: 'done',
            subTitle: 'Add a window to configure its compare paramenters',
            status: "done",
        },
        {
            title: 'error',
            subTitle: 'Add a window to configure its compare paramenters',
            status: "error",
        },
        {
            title: 'processing',
            subTitle: 'Add a window to configure its compare paramenters',
            status: "processing",
        },
        {
            title: 'warning',
            subTitle: 'Add a window to configure its compare paramenters',
            status: "warning",
        },
        {
            title: 'skipped',
            subTitle: 'Add a window to configure its compare paramenters',
            status: "skipped",
        },
        {
            title: 'waiting',
            subTitle: 'Add a window to configure its compare paramenters',
            status: "waiting",
        },
    ];
}

redpajama_set_name: RedPajamaGithub


text:
title: About this site
position_number: 2
---

This website serves pi and interactive demos that you can listen to or see pi with.
Scroll down to play with the demos!

To learn more about how this site works, check out the [Serving the Pi](#howserving) section.
We've also published the entire [source code](https://github.com/googlecloudplatform/pi-delivery) of the demos and infrastructure, including Terraform scripts, on GitHub.

This website is not an official Google product. It is managed by volunteers of the [Google Cloud Developer Advocacy team](https://cloud.google.com/developers/advocates) and may become unavailable without notice.


text:
package org.apache.metron.common.configuration.enrichment.handler;

import com.google.common.collect.ImmutableList;
import org.json.simple.JSONObject;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

public interface Config {

  /**
   * Split a message by the fields.  Certain configs will do this differently than others, but
   * these are the messages sent to the enrichment adapter downstream.
   *
   * @param message The Json message to be split
   * @param fields The fields to split by
   * @param fieldToEnrichmentKey A function to get the enrichment key
   * @param config The config to use
   * @return A list of Json objects that have been split from the message.
   */
  List<JSONObject> splitByFields( JSONObject message
                          , Object fields
                          , Function<String, String> fieldToEnrichmentKey
                          , Iterable<Map.Entry<String, Object>> config
                          );

  default List<JSONObject> splitByFields( JSONObject message
                          , Object fields
                          , Function<String, String> fieldToEnrichmentKey
                          , ConfigHandler handler
                          ) {
    return splitByFields(message, fields, fieldToEnrichmentKey, handler.getType().toConfig(handler.getConfig()));
  }

  /**
   * Return the subgroups for a given enrichment.  This will allow the join bolt to know when the join is complete.
   * NOTE: this implies that a given enrichment may have a 1 to many relationship with subgroups.
   * @param config An iterable of config entries
   * @return The list of subgroups
   */
  List<String> getSubgroups(Iterable<Map.Entry<String, Object>> config);

  default List<String> getSubgroups(ConfigHandler handler) {
    return getSubgroups(handler.getType().toConfig(handler.getConfig()));
  }

  /**
   * Convert a config object (currently either a map or list is supported) to a list of configs.
   * @param c Either a map or list representing the enrichment adapter configuration.
   * @return an iterable of config entries
   */
  Iterable<Map.Entry<String, Object>> toConfig(Object c);
}


text:
foo: bar
---

# Test Post with highlighting

```ruby
# Gemfile

group :bunto_plugins do
  gem "bunto-admin"
end
```


text:
@implementation DTPanelWithIndicator

@synthesize title;

- (id) init
{
	if ((self = [self initWithDelegate: nil title: nil]))
    {
	}

	return self;
}

- (id) initWithDelegate: (id<DTProcessIndicator>) aDelegate title: (NSString*) aTitle
{
	if ((self = [super initWithWindowNibName: @"DTPanelWithIndicator"]))
    {
        delegate = aDelegate;
        self.title = aTitle;
	}

	return self;
}

- (void) dealloc
{
    [title release];
    title = nil;

    [super dealloc];
}

- (void) windowDidLoad
{
    [self startProgress];
}

- (void) windowDidUnLoad
{
}

- (void) startProgress
{
    DTAppDelegate* appDelegate = (DTAppDelegate*) [[NSApplication sharedApplication] delegate];
    [self withParentWindow: appDelegate.window];

    [progress startAnimation: nil];
    label.title = title;
}

- (void) stopProgress
{
    [progress stopAnimation: nil];
    [[self window] orderOut: nil];
    [NSApp stopModal];
}

- (void) withParentWindow: (NSWindow*) aParentWindow
{
    //[[self window] setParentWindow: aParentWindow];

    [aParentWindow addChildWindow: [self window] ordered: NSWindowAbove];
}

- (void) showWindow: (id)sender
{

}

- (void) onPressedCancel: (id)sender
{
    [self stopProgress];
    [delegate cancelled];
}

@end


text:
/**
 * A wrapper for assessments that call a component to determine
 * the test outcome.
 */
quail.scriptOnmouseoutHasOnmouseblur = function (quail, test, Case) {
  var options = {
    selector: '[onmouseout]',
    correspondingEvent: 'onblur',
    searchEvent: 'onmouseout'
  };
  quail.components.event(quail, test, Case, options);
};


text:
wordptr.libwpd
==============

libwpd is a branch of the original WORD PTR "exsvcd" example service daemon.
The intent is to make a full-featured daemon library.

News
==============
Initial commit on 2012-11-28: It's not a library, yet, but the code has been
slightly refreshed and includes all bug changes and additions to the original
exsvcd library.


text:
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.

/*=============================================================================
	GenericMacTargetPlatform.h: Declares the TGenericMacTargetPlatform class template.
=============================================================================*/

#pragma once

#if WITH_ENGINE
#include "StaticMeshResources.h"
#endif // WITH_ENGINE

#define LOCTEXT_NAMESPACE "TGenericMacTargetPlatform"

/**
 * Template for Mac target platforms
 */
template<bool HAS_EDITOR_DATA, bool IS_DEDICATED_SERVER, bool IS_CLIENT_ONLY>
class TGenericMacTargetPlatform
	: public TTargetPlatformBase<FMacPlatformProperties<HAS_EDITOR_DATA, IS_DEDICATED_SERVER, IS_CLIENT_ONLY> >
{
public:

	typedef FMacPlatformProperties<HAS_EDITOR_DATA, IS_DEDICATED_SERVER, IS_CLIENT_ONLY> TProperties;
	typedef TTargetPlatformBase<TProperties> TSuper;

	/**
	 * Default constructor.
	 */
	TGenericMacTargetPlatform( )
	{
		LocalDevice = MakeShareable(new FLocalMacTargetDevice(*this));

		#if WITH_ENGINE
			FConfigCacheIni::LoadLocalIniFile(EngineSettings, TEXT("Engine"), true, *this->PlatformName());
			TextureLODSettings = nullptr;
			StaticMeshLODSettings.Initialize(EngineSettings);
		#endif
	}

public:

	// Begin ITargetPlatform interface

	virtual void EnableDeviceCheck(bool OnOff) override {}

	virtual void GetAllDevices( TArray<ITargetDevicePtr>& OutDevices ) const override
	{
		OutDevices.Reset();
		OutDevices.Add(LocalDevice);
	}

	virtual ECompressionFlags GetBaseCompressionMethod( ) const override
	{
		return COMPRESS_ZLIB;
	}

	virtual bool GenerateStreamingInstallManifest(const TMultiMap<FString, int32>& ChunkMap, const TSet<int32>& ChunkIDsInUse) const override
	{
		return true;
	}

	virtual ITargetDevicePtr GetDefaultDevice( ) const override
	{
		return LocalDevice;
	}

	virtual ITargetDevicePtr GetDevice( const FTargetDeviceId& DeviceId )
	{
		if (LocalDevice.IsValid() && (DeviceId == LocalDevice->GetId()))
		{
			return LocalDevice;
		}

		return NULL;
	}

	virtual bool IsRunningPlatform( ) const override
	{
		// Must be Mac platform as editor for this to be considered a running platform
		return PLATFORM_MAC && !UE_SERVER && !UE_GAME && WITH_EDITOR && HAS_EDITOR_DATA;
	}

	virtual bool SupportsFeature( ETargetPlatformFeatures Feature ) const override
	{
		// we currently do not have a build target for MacServer
		if (Feature == ETargetPlatformFeatures::Packaging)
		{
			return (HAS_EDITOR_DATA || !IS_DEDICATED_SERVER);
		}

return TSuper::SupportsFeature(Feature);
	}

#if WITH_ENGINE
	virtual void GetAllPossibleShaderFormats( TArray<FName>& OutFormats ) const override
	{
		// no shaders needed for dedicated server target
		if (!IS_DEDICATED_SERVER)
		{
			static FName NAME_GLSL_150_MAC(TEXT("GLSL_150_MAC"));
			OutFormats.AddUnique(NAME_GLSL_150_MAC);
		}
	}

	virtual void GetAllTargetedShaderFormats(TArray<FName>& OutFormats) const override
	{
		GetAllPossibleShaderFormats( OutFormats );
	}

	virtual const class FStaticMeshLODSettings& GetStaticMeshLODSettings( ) const override
	{
		return StaticMeshLODSettings;
	}

	virtual void GetTextureFormats( const UTexture* Texture, TArray<FName>& OutFormats ) const override
	{
		if (!IS_DEDICATED_SERVER)
		{
			// just use the standard texture format name for this texture (with no DX11 support)
			FName TextureFormatName = this->GetDefaultTextureFormatName(Texture, EngineSettings, false);
			OutFormats.Add(TextureFormatName);
		}
	}

	virtual const UTextureLODSettings& GetTextureLODSettings() const override
	{
		return *TextureLODSettings;
	}

	virtual void RegisterTextureLODSettings(const UTextureLODSettings* InTextureLODSettings) override
	{
		TextureLODSettings = InTextureLODSettings;
	}

	virtual FName GetWaveFormat( const class USoundWave* Wave ) const override
	{
		static FName NAME_OGG(TEXT("OGG"));

		return NAME_OGG;
	}
#endif //WITH_ENGINE

	virtual bool SupportsVariants() const override
	{
		return true;
	}

	virtual FText GetVariantDisplayName() const override
	{
		if (IS_DEDICATED_SERVER)
		{
			return LOCTEXT("MacServerVariantTitle", "Dedicated Server");
		}

		if (HAS_EDITOR_DATA)
		{
			return LOCTEXT("MacClientEditorDataVariantTitle", "Client with Editor Data");
		}

		if (IS_CLIENT_ONLY)
		{
			return LOCTEXT("MacClientOnlyVariantTitle", "Client only");
		}

		return LOCTEXT("MacClientVariantTitle", "Client");
	}

	virtual FText GetVariantTitle() const override
	{
		return LOCTEXT("MacVariantTitle", "Build Type");
	}

	virtual float GetVariantPriority() const override
	{
		return TProperties::GetVariantPriority();
	}

	DECLARE_DERIVED_EVENT(TGenericMacTargetPlatform, ITargetPlatform::FOnTargetDeviceDiscovered, FOnTargetDeviceDiscovered);
	virtual FOnTargetDeviceDiscovered& OnDeviceDiscovered( ) override
	{
		return DeviceDiscoveredEvent;
	}

	DECLARE_DERIVED_EVENT(TGenericMacTargetPlatform, ITargetPlatform::FOnTargetDeviceLost, FOnTargetDeviceLost);
	virtual FOnTargetDeviceLost& OnDeviceLost( ) override
	{
		return DeviceLostEvent;
	}

	// End ITargetPlatform interface

private:

	// Holds the local device.
	ITargetDevicePtr LocalDevice;

#if WITH_ENGINE
	// Holds the Engine INI settings for quick use.
	FConfigFile EngineSettings;

	// Holds the texture LOD settings.
	const UTextureLODSettings* TextureLODSettings;

	// Holds the static mesh LOD settings.
	FStaticMeshLODSettings StaticMeshLODSettings;
#endif // WITH_ENGINE

private:

	// Holds an event delegate that is executed when a new target device has been discovered.
	FOnTargetDeviceDiscovered DeviceDiscoveredEvent;

	// Holds an event delegate that is executed when a target device has been lost, i.e. disconnected or timed out.
	FOnTargetDeviceLost DeviceLostEvent;
};

#undef LOCTEXT_NAMESPACE


text:
#ifndef __DB_DB_GRAPH_EDGE_H__
#define __DB_DB_GRAPH_EDGE_H__

#include "base/util.h"

#include "db/db_entry.h"
#include "db/db_graph_base.h"

class DBGraph;
class DBGraphVertex;

class DBGraphEdge : public DBEntry {
public:
    typedef DBGraphBase::vertex_descriptor Vertex;
    typedef DBGraphBase::edge_descriptor Edge;

    explicit DBGraphEdge(Edge edge_id);

    void SetEdge(Edge edge);

    Edge edge_id() const {
        assert(!IsDeleted());
        // Don't access the edge id after deleting from graph
        return edge_id_;
    }

    DBGraphVertex *source(DBGraph *graph);
    const DBGraphVertex *source(DBGraph *graph) const;

    DBGraphVertex *target(DBGraph *graph);
    const DBGraphVertex *target(DBGraph *graph) const;

private:
    Edge edge_id_;

    DISALLOW_COPY_AND_ASSIGN(DBGraphEdge);
};

#endif


text:
/**
 * @author Justin Carrao
 * @author Zachary Podbela
 * @author Pranava Raparla
 * Date Created: 11/21/14
 * Date Modified: 11/23/14
 */

package com.print_stack_trace.voogasalad.model.engine.physics;

import com.print_stack_trace.voogasalad.model.engine.runtime.RuntimeModel;
import com.print_stack_trace.voogasalad.model.engine.runtime.RuntimeSpriteCharacteristics;

public abstract class CollisionHandler {

	/**
	 * Called when sprites have collided.
	 * Apply the appropriate collision effects based on data from each sprite.
	 * @param s1	the first "sprite" to have collision effects applied
	 * @param s2	the second "sprite" to have collision effects applied
	 */
	public abstract void applyCollisionEffects(RuntimeSpriteCharacteristics s1, RuntimeSpriteCharacteristics s2, RuntimeModel currentRuntime);

	public abstract boolean shouldStick(RuntimeSpriteCharacteristics s1, RuntimeSpriteCharacteristics s2);
}


text:
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
  version="2.0">

  <persistence-unit name="lunch" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <!-- <jta-data-source>java:/DefaultDS</jta-data-source> -->
    <properties>
      <property name="javax.persistence.jdbc.driver" value="org.hsqldb.jdbcDriver" />
      <property name="javax.persistence.jdbc.url" value="jdbc:hsqldb:lunch" />
      <property name="javax.persistence.jdbc.user" value="robina" />
      <property name="javax.persistence.jdbc.password" value="kuh" />
      <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect" />
      <property name="hibernate.hbm2ddl.auto" value="create" />
      <property name="hibernate.show_sql" value="false" />
      <property name="hibernate.format_sql" value="true" />
      <property name="connection.release_mode" value="auto" />
    </properties>
  </persistence-unit>
</persistence>


text:
class CreateWhiteCards < ActiveRecord::Migration[5.1]
  def change
    create_table :white_cards do |t|
      t.text :title

      t.timestamps
    end
  end
end


text:
// Copyright 2018 The Bazel Authors. All rights reserved.
//
// 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.

package com.google.devtools.build.execlog;

import com.google.devtools.common.options.Option;
import com.google.devtools.common.options.OptionDocumentationCategory;
import com.google.devtools.common.options.OptionEffectTag;
import com.google.devtools.common.options.OptionsBase;
import java.util.List;

/** Options for execution log parser. */
public class ParserOptions extends OptionsBase {
  @Option(
      name = "log_path",
      defaultValue = "null",
      category = "logging",
      documentationCategory = OptionDocumentationCategory.UNCATEGORIZED,
      effectTags = {OptionEffectTag.UNKNOWN},
      allowMultiple = true,
      help =
          "Location of the log file to parse. If a second value is specified, both files will be"
              + " converted. The first log will be processed as-is. The actions in the second log"
              + " will be reordered to match the first. An action will be matched if the first"
              + " file contains an action with the same name of the first output. Any actions"
              + " that cannot be matched to the first file will appear at the end of the log. Note"
              + " that this reordering fascilitates easier text-based comparisons, but may break"
              + " any logical order of the actions.")
  public List<String> logPath;

  @Option(
      name = "output_path",
      defaultValue = "null",
      category = "logging",
      documentationCategory = OptionDocumentationCategory.UNCATEGORIZED,
      effectTags = {OptionEffectTag.UNKNOWN},
      allowMultiple = true,
      help =
          "Location where to put the output(s). If left empty, the log will be output to stdout."
              + " If two log paths are specified, needs to be specified and have exactly two"
              + " paths.")
  public List<String> outputPath;

  @Option(
      name = "restrict_to_runner",
      defaultValue = "null",
      category = "logging",
      documentationCategory = OptionDocumentationCategory.UNCATEGORIZED,
      effectTags = {OptionEffectTag.UNKNOWN},
      help = "If set, only output the executions that used the given runner.")
  public String restrictToRunner;
}


text:
package com.maxmind.minfraud.exception;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;

/**
 * This class represents an HTTP transport error. This is not an error returned
 * by the web service itself. As such, it is a IOException instead of a
 * MinFraudException.
 */
public final class HttpException extends IOException {
    private final int httpStatus;
    private final URI uri;

    /**
     * @param message    A message describing the reason why the exception was thrown.
     * @param httpStatus The HTTP status of the response that caused the exception.
     * @param uri        The URI queried.
     */
    public HttpException(String message, int httpStatus, URI uri) {
        super(message);
        this.httpStatus = httpStatus;
        this.uri = uri;
    }

    /**
     * @param message    A message describing the reason why the exception was thrown.
     * @param httpStatus The HTTP status of the response that caused the exception.
     * @param uri        The URI queried.
     * @param cause      The cause of the exception.
     */
    public HttpException(String message, int httpStatus, URI uri,
                         Throwable cause) {
        super(message, cause);
        this.httpStatus = httpStatus;
        this.uri = uri;
    }

    /**
     * @return the HTTP status of the query that caused the exception.
     */
    public int getHttpStatus() {
        return httpStatus;
    }

    /**
     * @return the URI queried.
     */
    public URI getUri() {
        return this.uri;
    }

    /**
     * @return the URL queried.
     * @deprecated Use getUri() instead
     */
    @Deprecated
    public URL getUrl() {
        try {
            return this.uri.toURL();
        } catch (MalformedURLException e) {
            return null;
        }
    }
}


text:
package com.ufavaloro.android.visu.storage.datatypes;

import com.ufavaloro.android.visu.main.StudyType;

public class AcquisitionData {

	// Adc Data
	private AdcData mAdcData;

	// Tipo de estudio
	private char[] mStudyType;
	private int mStudyTypeSize = 50;
	private int mStudyTypeBytes = mStudyTypeSize*((Character.SIZE)/8);

	// Cantidad de muestras almacenadas
	private double mTotalSamples;
	private int mTotalSamplesBytes = (Double.SIZE)/8;

	// Total de bytes para los datos de adquisición.
	private int mAcquisitionDataBytes;

	public AcquisitionData(AdcData mAdcData) {

		this.mAdcData = mAdcData;

		mStudyType = new char[mStudyTypeSize];

		mTotalSamples = 0;

		mAcquisitionDataBytes =  mAdcData.adcBytes + mStudyTypeBytes + mTotalSamplesBytes;

	}

	public AcquisitionData() {
		// TODO Auto-generated constructor stub
	}

	public void setAdcChannel(int mAdcChannel) {
		mAdcData.adcChannel = mAdcChannel;
	}

	public void setBluetoothChannel(int mBluetoothChannel) {
		mAdcData.bluetoothChannel = mBluetoothChannel;
	}

	public int getBits() {
		return mAdcData.bits;
	}

	public double getFs() {
		return mAdcData.fs;
	}

	public int getChannel() {
		return mAdcData.adcChannel;
	}

	public int getBluetoothChannel() {
		return mAdcData.bluetoothChannel;
	}

	public double getVMin() {
		return mAdcData.vMin;
	}

	public double getVMax() {
		return mAdcData.vMax;
	}

	public double getAMin() {
		return mAdcData.aMin;
	}

	public double getAMax() {
		return mAdcData.aMax;
	}

	public void setAMax(double aMax) {
		mAdcData.aMax = aMax;
	}

	public void setAMin(double aMin) {
		mAdcData.aMin = aMin;
	}

	public void setStudyType(int study) {
		mStudyType = new char[mStudyTypeSize];
		mStudyType[0] = (char) study;
	}

	public void setSensor(String sensor_string) {

		char[] sensor = sensor_string.toCharArray();
		int size = sensor_string.length();

		for(int i = 0; i < size; i++) {
			mAdcData.sensor[i] = sensor[i];
		}
	}

	public char[] getSensor() {
		return mAdcData.sensor;
	}

	public char[] getStudyType() {
		return mStudyType;
	}

	public int getAcquisitionDataBytes() {
		return mAcquisitionDataBytes;
	}

	public double getTotalSamples() {
		return mTotalSamples;
	}

	public int getStudyTypeSize() {
		return mStudyTypeSize;
	}

	public int getSensorSize() {
		return mAdcData.sensorSize;
	}

	public int getAdcChannel() {
		return mAdcData.adcChannel;
	}

	public int getSamplesPerPackage() {
		return mAdcData.samplesPerPackage;
	}

	public int getAdcChannelBytes() {
		return mAdcData.adcChannelBytes;
	}

	public void setAdcChannelBytes(int mAdcChannelBytes) {
		mAdcData.adcChannelBytes = mAdcChannelBytes;
	}

	public int getBluetoothChannelBytes() {
		return mAdcData.bluetoothChannelBytes;
	}

	public void setBluetoothChannelBytes(int mBluetoothChannelBytes) {
		mAdcData.bluetoothChannelBytes = mBluetoothChannelBytes;
	}

}// AcquisitionData


text:
package token

import (
	"encoding/json"
	"errors"
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"log"
	"net/http"
	"strings"
	"time"
)

type errOut struct {
	Error string `json:error`
}

const mySigningKey = "Super_Dup3r_S3cret"

func GenerateToken(role string) (string, error) {
	// Create the token
	token := jwt.New(jwt.SigningMethodHS256)
	// Set some claims
	token.Claims = jwt.MapClaims{
		"exp":  time.Now().Add(time.Hour * time.Duration(1)).Unix(),
		"iat":  time.Now().Unix(),
		"role": role,
	}

	// Sign and get the complete encoded token as a string
	tokenString, err := token.SignedString([]byte(mySigningKey))
	fmt.Println(tokenString)
	return tokenString, err
}

func ParseToken(myToken string) (bool, error) {
	token, err := jwt.Parse(myToken, func(token *jwt.Token) (interface{}, error) {
		return []byte(mySigningKey), nil
	})
	//fmt.Println(token.Claims)
	if err == nil && token.Valid {
		return true, nil
	} else {
		return false, err
	}
}

func ExtractToken(r *http.Request) (string, error) {
	auth := r.Header.Get("Authorization")
	split := strings.Split(auth, " ")
	if split[0] != "Bearer" || split[1] == "" {

		return "", errors.New("Malformed Auth Header")
	} else {
		return split[1], nil
	}

}

func TokenHandler(w http.ResponseWriter, r *http.Request) bool {

	authToken, err := ExtractToken(r)
	if err != nil {
		errout := new(errOut)
		errout.Error = err.Error()
		w.WriteHeader(http.StatusBadRequest)
		if err := json.NewEncoder(w).Encode(errout); err != nil {
			log.Panic("Error EncodingJson in TokenHandler", err)
		}
		return false
	} else {
		tokenStatus, err := ParseToken(authToken)
		//fmt.Println("tokenStatus: ", tokenStatus, "err: ", err.Error())
		if err != nil || tokenStatus == false {
			errout := new(errOut)
			errout.Error = err.Error()
			w.WriteHeader(http.StatusForbidden)
			if err := json.NewEncoder(w).Encode(errout); err != nil {
				log.Panic("Error EncodingJson in TokenHandler", err)
			}
			log.Println("token status err: ", err)
			return false

		} else {

			//w.Header().Set("Access-Control-Allow-Origin", "*")
			return true

		}
	}

}


text:
Your issue may already be reported!
Please search on the [issue track](https://github.com/marcosgriselli/SwipeableTabBarController/issues?utf8=✓&q=) before creating one.

## Expected Behavior
<!--- If you're describing a bug, tell us what should happen -->
<!--- If you're suggesting a change/improvement, tell us how it should work -->

## Current Behavior
<!--- If describing a bug, tell us what happens instead of the expected behavior -->
<!--- If suggesting a change/improvement, explain the difference from current behavior -->

## Possible Solution
<!--- Not obligatory, but suggest a fix/reason for the bug, -->
<!--- or ideas how to implement the addition or change -->

## Steps to Reproduce (for bugs)
<!--- Provide a link to a live example or an unambiguous set of steps to -->
<!--- reproduce this bug. Include code to reproduce, if relevant -->
1.
2.
3.
4.

## Environment
<!--- Include as many relevant details about the environment you experienced the bug in -->
* SwipeableTabBarController version:
* Device and OS running tests:
* Demo project link:


text:
package com.thyago.datastorage.entity;

/**
 * Created by thyago on 6/3/16.
 */
public class BaseEntity {
    private long id;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }
}


text:
'use strict';

/* eslint-disable no-loop-func */

/*!
 * Collection
 * https://github.com/kobezzza/Collection
 *
 * Released under the MIT license
 * https://github.com/kobezzza/Collection/blob/master/LICENSE
 */

import $C, { Collection, P } from '../core';

import { isArray, isBoolean, isStructure, getSameAs, canExtendProto, getType } from '../helpers/types';
import { byLink, hasOwnProperty } from '../helpers/link';
import { any } from '../helpers/gcc';

import { EMPTY } from '../consts/primitives';
import { OBJECT_ASSIGN_NATIVE_SUPPORT } from '../consts/env';

const simpleType = {
	'array': true,
	'object': true
};

const {

	create,
	defineProperty,
	getPrototypeOf,
	assign

} = Object;

/**
 * Extends the collection by another objects
 *
 * @param {(boolean|?$$Collection_extend)} deepOrParams - if true, then properties will be copied recursively
 *   OR additional parameters for extending:
 *
 *   * [withUndef = false] - if true, then the original value can be rewritten to undefined
 *   * [withDescriptor = false] - if true, then the descriptor of a property will be copied too
 *   * [withAccessors = false] - if true, then property accessors will be copied too, but not another descriptor properties;
 *   * [withProto = false] - if true, then properties will be copied with prototypes
 *   * [concatArray = false] - if true, then array properties will be concatenated (only if extending by an another array)
 *   * [concatFn = Array.prototype.concat] - function that will be concatenate arrays
 *   * [extendFilter] - function that will be filtering values for deep extending
 *   * [traits = false] - if true, then will be copied only new properties, or if -1, only old
 *   * [deep = false] - if true, then properties will be copied recursively
 *
 * @param {...Object} args - objects for extending
 * @return {(!Object|!Promise)}
 */
Collection.prototype.extend = function (deepOrParams, args) {
	let p = any(deepOrParams);

	if (p instanceof P === false) {
		if (isBoolean(p)) {
			p = {deep: p};

		} else {
			p = p || {};
		}

		this._initParams(p);
		p = any(assign(Object.create(this.p), p));

	} else {
		p = any(Object.create(p));
		this._initParams(p, false);
	}

	const
		withDescriptor = p.withDescriptor && !p.withAccessors;

	if (p.withAccessors) {
		p.withDescriptor = true;
	}

	if (p.withProto) {
		p.notOwn = true;
	}

	let
		{data} = this,
		{type} = p;

	if (!type || data === EMPTY) {
		for (let i = 1; i < arguments.length; i++) {
			type = getType(arguments[i], p.use);

			if (type) {
				break;
			}
		}

		switch (type) {
			case 'object':
				data = {};
				break;

			case 'weakMap':
				data = new WeakMap();
				break;

			case 'weakSet':
				data = new WeakSet();
				break;

			case 'map':
				data = new Map();
				break;

			case 'set':
				data = new Set();
				break;

			default:
				data = [];
		}
	}

	const dataIsSimple = simpleType[type];
	p.result = data;

	if (
		!p.deep &&
		p.withUndef &&
		p.mult &&
		dataIsSimple &&
		OBJECT_ASSIGN_NATIVE_SUPPORT &&
		!p.concatArray &&
		!p.withProto &&
		!p.withDescriptor &&
		!p.withAccessors &&
		!p.traits &&
		!p.extendFilter &&
		!p.filter.length &&
		!p.async &&
		!p.from &&
		!p.count &&
		!p.startIndex &&
		!p.endIndex &&
		!p.notOwn &&
		!p.reverse
	) {
		const
			args = [];

		for (let i = 1; i < arguments.length; i++) {
			args.push(arguments[i]);
		}

		return assign(data, ...args);
	}

	let setVal;
	switch (type) {
		case 'weakMap':
		case 'map':
			setVal = (data, key, val) => {
				if (p.traits && data.has(key) !== (p.traits === -1)) {
					return;
				}

				data.set(key, val);
			};

			break;

		case 'weakSet':
		case 'set':
			setVal = (data, key, val) => {
				if (p.traits && data.has(val) !== (p.traits === -1)) {
					return;
				}

				data.add(val);
			};

			break;

		default:
			setVal = (data, key, val) => {
				if (p.traits && key in data !== (p.traits === -1)) {
					return;
				}

				if (p.withUndef || val !== undefined) {
					data[key] = val;
				}
			};
	}

	let promise = {then(cb) {
		cb();
		return this;
	}};

	if (p.async) {
		promise = Promise.resolve();
	}

	if (p.notOwn && !dataIsSimple) {
		p.notOwn = false;
	}

	for (let i = 1; i < arguments.length; i++) {
		const
			arg = arguments[i];

		if (!arg) {
			continue;
		}

		const
			isSimple = simpleType[getType(arg)];

		promise = promise.then(() => $C(arg).forEach((el, key) => {
			if (dataIsSimple && isSimple && (withDescriptor || p.withAccessors && (el.get || el.set))) {
				if (p.traits && key in data !== (p.traits === -1)) {
					return;
				}

				if (p.withAccessors) {
					defineProperty(data, key, {
						get: el.get,
						set: el.set
					});

				} else if ('value' in el === false || el.value !== undefined || p.withUndef) {
					defineProperty(data, key, el);
				}

				return;
			}

			let
				src = byLink(data, [key]);

			const
				val = isSimple ? arg[key] : el;

			if (data === val || val === arg) {
				return;
			}

			let
				canExtend = Boolean(val);

			if (canExtend && p.extendFilter) {
				canExtend = p.extendFilter(data, val, key);
			}

			let
				valIsArray,
				struct;

			if (canExtend) {
				valIsArray = isArray(val);
				struct = valIsArray ? [] : getSameAs(val);
			}

			if (p.deep && canExtend && (valIsArray || struct)) {
				const
					isExtProto = p.withProto && dataIsSimple && canExtendProto(src);

				let
					srcIsArray = isArray(src);

				if (isExtProto && !(data.hasOwnProperty ? data.hasOwnProperty(key) : hasOwnProperty.call(data, key))) {
					src = srcIsArray ? src.slice() : create(src);
					byLink(data, [key], {value: src});
				}

				let clone;
				if (valIsArray) {
					let
						isProto = false,
						construct;

					if (!srcIsArray && isExtProto && p.concatArray) {
						construct = getPrototypeOf(src);
						srcIsArray = isProto = construct && isArray(construct);
					}

					if (srcIsArray) {
						if (p.concatArray) {
							const o = isProto ? construct : src;
							data[key] = p.concatFn ? p.concatFn(o, val, key) : o.concat(val);
							return;
						}

						clone = src;

					} else {
						clone = [];
					}

				} else {
					clone = isStructure(src) ? src : struct || {};
				}

				const
					childExt = $C(clone).extend(p, val);

				if (p.async) {
					return childExt.then((value) => byLink(data, [key], {value}));
				}

				byLink(data, [key], {value: childExt});

			} else {
				setVal(data, key, val);
			}

		}, p));
	}

	return p.async ? promise.then(() => data) : data;
};

/**
 * Clones an object
 *
 * @param {?} obj - source object
 * @return {?}
 */
$C.clone = function (obj) {
	return JSON.parse(JSON.stringify(obj));
};

/**
 * Extends the specified object by another objects
 *
 * @see Collection.prototype.extend
 * @param {(boolean|?$$Collection_extend)} deepOrParams - additional parameters
 * @param {Object} target - source object
 * @param {...Object} args - objects for extending
 * @return {(!Object|!Promise)}
 */
$C.extend = function (deepOrParams, target, args) {
	args = [deepOrParams];

	for (let i = 2; i < arguments.length; i++) {
		args.push(arguments[i]);
	}

	const obj = $C(target == null ? EMPTY : target);
	return obj.extend.apply(obj, args);
};

Object.assign($C, {extend: $C.extend, clone: $C.clone});


text:
import Tweet from './Tweet'
import mountComponent from '../util/mount-component'
import tweet from '../util/fake-tweet'
import fecha from 'fecha'
import linkifyHtml from 'linkifyjs/html'

/* eslint-disable no-native-reassign */
Date = jest.fn()

jest.mock('linkifyjs/html')

describe('Tweet testing', () => {
  let component

  beforeEach(() => (component = mountComponent(Tweet, { tweet, listName: 'test-list' })))

  it('should init computed props', () => {
    expect(fecha.format.mock.calls.length).toBe(1)
    expect(linkifyHtml.mock.calls.length).toBe(1)
    expect(linkifyHtml.mock.calls[0][0]).toBe('test-content')

    expect(Date.mock.calls.length).toBe(1)
    expect(Date.mock.calls[0][0]).toBe('test-date')

    expect(component.author).toEqual(tweet.user)
  })

  it('should show user image', () => {
    const img = component.$el.querySelector('img')
    expect(img.src).toBe('test-img-url')
  })

  it('should show usuer name', () => {
    const name = component.$el.querySelector('.name')
    expect(name.innerHTML.trim()).toBe('test-author-name')
  })
})


text:
package integration

import (
	"fmt"
	"net"
	"strconv"
	"strings"
	"sync"
	"time"

	_ "github.com/apache/thrift/lib/go/thrift"
	log "github.com/sirupsen/logrus"

	"testing"

	client "github.com/uber/cherami-client-go/client/cherami"
	"github.com/uber/cherami-server/common"
	localMetrics "github.com/uber/cherami-server/common/metrics"
	"github.com/uber/cherami-server/services/controllerhost"
	"github.com/uber/cherami-thrift/.generated/go/cherami"
	"github.com/uber/cherami-thrift/.generated/go/shared"
)

type NodeFailureTestSuite struct {
	testBase
	msgSeq            int32
	ackedIDs          map[string]bool
	receiptIDToMsgSeq map[string]int32
}

func TestNodeFailureTestSuite(t *testing.T) {
	log.Infof("Skipping NodeFailureTestSuite in short mode")
	return
}

func (s *NodeFailureTestSuite) SetupTest() {
	s.msgSeq = 0
	s.ackedIDs = make(map[string]bool)
	s.receiptIDToMsgSeq = make(map[string]int32)
}

func (s *NodeFailureTestSuite) TearDownTest() {
	s.testBase.TearDown()
}

func (s *NodeFailureTestSuite) createDestination(cClient client.Client, path string) (*cherami.DestinationDescription, error) {
	crReq := cherami.NewCreateDestinationRequest()
	crReq.Path = common.StringPtr(path)
	crReq.Type = cherami.DestinationTypePtr(0)
	crReq.ConsumedMessagesRetention = common.Int32Ptr(0)
	crReq.UnconsumedMessagesRetention = common.Int32Ptr(120)
	return cClient.CreateDestination(crReq)
}

func (s *NodeFailureTestSuite) createConsumerGroup(cClient client.Client, destPath string, cgPath string) (*cherami.ConsumerGroupDescription, error) {
	cgReq := cherami.NewCreateConsumerGroupRequest()
	cgReq.ConsumerGroupName = common.StringPtr(cgPath)
	cgReq.DestinationPath = common.StringPtr(destPath)
	cgReq.LockTimeoutInSeconds = common.Int32Ptr(30) // this is the message redelivery timeout
	cgReq.MaxDeliveryCount = common.Int32Ptr(1)
	return cClient.CreateConsumerGroup(cgReq)
}

func (s *NodeFailureTestSuite) publish(cClient client.Client, publisher client.Publisher, maxMessages int, doneCh chan *client.PublisherReceipt, wg *sync.WaitGroup) {
	defer wg.Done()

	for i := 0; i < maxMessages; i++ {
		s.msgSeq++
		data := []byte(fmt.Sprintf("%d", s.msgSeq))
		id, err := publisher.PublishAsync(
			&client.PublisherMessage{
				Data: data,
			},
			doneCh,
		)
		s.NoError(err)
		s.receiptIDToMsgSeq[id] = s.msgSeq
	}
}

func (s *NodeFailureTestSuite) recvReceipts(doneCh chan *client.PublisherReceipt, maxMessages int, idleTimeout time.Duration, wg *sync.WaitGroup) {
	defer wg.Done()

	timeoutCh := time.After(idleTimeout)

	for i := 0; i < maxMessages; i++ {
		select {
		case receipt := <-doneCh:
			if receipt.Error == nil {
				s.ackedIDs[receipt.ID] = true
				log.Infof("Publish receipt success, id=%v, where=%v", receipt.ID, receipt.Receipt)
			} else {
				log.Infof("Publish receipt failure, id=%v, where=%v", receipt.ID, receipt.Receipt)
			}
		case <-timeoutCh:
			log.Infof("Publish receipt timed out")
			return
		}
	}
}

func (s *NodeFailureTestSuite) listOpenExtents(dstUUID string) ([]*shared.ExtentStats, error) {
	mm := controllerhost.NewMetadataMgr(s.mClient, &mockM3Metrics{}, common.GetDefaultLogger())
	return mm.ListExtentsByDstIDStatus(dstUUID, []shared.ExtentStatus{shared.ExtentStatus_OPEN})
}

func (s *NodeFailureTestSuite) TestInputFailure() {
	s.testNodeFailure(common.InputServiceName, 1)
}

func (s *NodeFailureTestSuite) TestOneStoreFailure() {
	s.testNodeFailure(common.StoreServiceName, 1)
}

func (s *NodeFailureTestSuite) TestTwoStoreFailure() {
	s.testNodeFailure(common.StoreServiceName, 2)
}

func (s *NodeFailureTestSuite) testNodeFailure(serviceName string, nKill int) {

	destPath := "/integration.test/nodefailure"
	cgPath := "/integration.test/nodefailure"
	testMsgCount := 2000
	numReplicas := 3

	clusterSzMap := map[string]int{
		common.StoreServiceName:  2 * numReplicas,
		common.InputServiceName:  3,
		common.OutputServiceName: 2,
	}

	s.testBase.SetUp(clusterSzMap, numReplicas)

	// Create the client
	ipaddr, port, _ := net.SplitHostPort(s.GetFrontend().GetTChannel().PeerInfo().HostPort)
	portNum, _ := strconv.Atoi(port)
	cheramiClient, _ := client.NewClient("cherami-test", ipaddr, portNum, nil)

	_, err := s.createDestination(cheramiClient, destPath)
	s.Nil(err)

	mReq := &shared.ReadDestinationRequest{Path: common.StringPtr(destPath)}
	dstDesc, err := s.mClient.ReadDestination(nil, mReq)
	s.Nil(err)

	cPublisherReq := &client.CreatePublisherRequest{
		Path: destPath,
	}

	publisher := cheramiClient.CreatePublisher(cPublisherReq)
	s.NotNil(publisher)

	err = publisher.Open()
	s.NoError(err)
	defer publisher.Close()

	// Publish messages
	doneCh := make(chan *client.PublisherReceipt, testMsgCount)
	var wg sync.WaitGroup

	wg.Add(2)
	go s.recvReceipts(doneCh, testMsgCount, 30*time.Second, &wg)
	go s.publish(cheramiClient, publisher, testMsgCount, doneCh, &wg)

	const warmupMsgCount = 99

	cond := func() bool {
		return len(s.ackedIDs) > warmupMsgCount
	}

	succ := common.SpinWaitOnCondition(cond, time.Minute)
	s.True(succ, "Failed to publish %v async messages within a minute", warmupMsgCount)

	stats, err := s.listOpenExtents(dstDesc.GetDestinationUUID())
	s.Nil(err)
	s.Equal(1, len(stats), "Wrong number of extents for destination")

	var killHosts = make([]string, nKill)

	if strings.Compare(serviceName, common.InputServiceName) == 0 {
		killHosts[0] = stats[0].GetExtent().GetInputHostUUID()
		_, ok := s.InputHosts[killHosts[0]]
		s.True(ok, "Failed to find input host mapped to extent")
		s.InputHosts[killHosts[0]].Stop()
		log.Infof("Killed input host, uuid=%v", killHosts[0])
	} else {
		for i := 0; i < nKill; i++ {
			killHosts[i] = stats[0].GetExtent().GetStoreUUIDs()[i]
			_, ok := s.StoreHosts[killHosts[i]]
			s.True(ok, "Failed to find store host mapped to extent")
			s.StoreHosts[killHosts[i]].Stop() // kill the store host while the msgs are published
			log.Infof("Killed store host, uuid=%v", killHosts[i])
		}
	}

	var ch *controllerhost.Mcp
	for _, ch = range s.Controllers {
		break
	}

	cond = func() bool {
		nInput, _ := clusterSzMap[common.InputServiceName]
		nStores, _ := clusterSzMap[common.StoreServiceName]
		if strings.Compare(serviceName, common.InputServiceName) == 0 {
			var hosts []*common.HostInfo
			hosts, err = ch.GetRingpopMonitor().GetHosts(common.InputServiceName)
			return err == nil && len(hosts) == nInput-1
		}
		var storeHosts []*common.HostInfo
		storeHosts, err = ch.GetRingpopMonitor().GetHosts(common.StoreServiceName)
		return err == nil && len(storeHosts) == nStores-nKill
	}

	success := common.SpinWaitOnCondition(cond, time.Minute)
	s.True(success, "Timed out waiting for Ringpop to detect host failure")

	succ = common.AwaitWaitGroup(&wg, time.Minute*2)
	s.True(succ, "Timed out waiting for publisher to publish all messages")

	wg.Add(2)
	go s.recvReceipts(doneCh, testMsgCount, time.Second*30, &wg)
	go s.publish(cheramiClient, publisher, testMsgCount, doneCh, &wg)
	succ = common.AwaitWaitGroup(&wg, time.Minute*2)
	s.True(succ, "Timed out waiting for publisher to publish all messages")

	log.Infof("Publish complete, starting consumer")

	_, err = s.createConsumerGroup(cheramiClient, destPath, cgPath)
	s.NoError(err)

	cConsumerReq := &client.CreateConsumerRequest{
		Path:              destPath,
		ConsumerGroupName: cgPath,
		ConsumerName:      "TestConsumer",
		PrefetchCount:     1,
		Options:           &client.ClientOptions{Timeout: time.Second * 30}, // this is the thrift context timeout
	}

	consumer := cheramiClient.CreateConsumer(cConsumerReq)
	s.NotNil(consumer)

	// Open the consumer channel
	delivery := make(chan client.Delivery, 100)
	delivery, err = consumer.Open(delivery)
	s.NoError(err)
	defer consumer.Close()

	rcvdMsgs := make(map[int32]bool)

	mm := controllerhost.NewMetadataMgr(s.mClient, &mockM3Metrics{}, common.GetDefaultLogger())

	msgCount := 0
	// Read the messages in a loop. We will exit the loop via a timeout
ReadLoop:
	for {
		timeout := time.NewTimer(time.Second * 30)
		select {
		case msg := <-delivery:
			var data int
			data, err = strconv.Atoi(string(msg.GetMessage().GetPayload().GetData()))
			s.Nil(err)
			rcvdMsgs[int32(data)] = true
			log.Infof("Read message, msg:%v", data)
			msg.Ack()
			msgCount++
		case <-timeout.C:
			log.Infof("Consumer delivery channel timed out after %v messages", msgCount)
			break ReadLoop
		}
	}

	for id := range s.ackedIDs {
		msg := s.receiptIDToMsgSeq[id]
		_, ok := rcvdMsgs[msg]
		s.True(ok, "Failed to receive acked message %v", msg)
	}

	if serviceName == common.InputServiceName {
		stats, err = mm.ListExtentsByInputIDStatus(killHosts[0], common.MetadataExtentStatusPtr(shared.ExtentStatus_SEALED))
		s.Nil(err)
		s.True(len(stats) > 0, "Incorrect number of sealed extents")

		stats, err = mm.ListExtentsByInputIDStatus(killHosts[0], common.MetadataExtentStatusPtr(shared.ExtentStatus_OPEN))
		s.Nil(err)
		s.Equal(0, len(stats), "Incorrect number of open extents")
		return
	}

	for _, h := range killHosts {
		stats, err = mm.ListExtentsByStoreIDStatus(h, common.MetadataExtentStatusPtr(shared.ExtentStatus_SEALED))
		s.Nil(err)
		s.True(len(stats) > 0, "Incorrect number of sealed extents")

		stats, err = mm.ListExtentsByStoreIDStatus(h, common.MetadataExtentStatusPtr(shared.ExtentStatus_OPEN))
		s.Nil(err)
		s.Equal(0, len(stats), "Incorrect number of open extents")
	}
}

type mockM3Metrics struct{}
type mockStopWatch struct{}

func (s *mockStopWatch) Stop() time.Duration                              { return time.Second }
func (m *mockM3Metrics) IncCounter(scope int, counter int)                {}
func (m *mockM3Metrics) AddCounter(scope int, counter int, delta int64)   {}
func (m *mockM3Metrics) UpdateGauge(scope int, counter int, delta int64)  {}
func (m *mockM3Metrics) RecordTimer(op int, idx int, delta time.Duration) {}
func (m *mockM3Metrics) StartTimer(scope int, timer int) localMetrics.Stopwatch {
	return &mockStopWatch{}
}
func (m *mockM3Metrics) GetParentReporter() localMetrics.Reporter { return nil }


text:
<?php

namespace backend\models;

use Yii;

/**
 * This is the model class for table "seller_phone".
 *
 * @property integer $id
 * @property string $purpose
 * @property string $number
 * @property integer $seller_id
 *
 * @property Seller $seller
 */
class SellerPhone extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'seller_phone';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['purpose', 'number', 'seller_id'], 'required'],
            [['seller_id'], 'integer'],
            [['purpose'], 'string', 'max' => 12],
            [['number'], 'string', 'max' => 20],
            [['seller_id'], 'exist', 'skipOnError' => true, 'targetClass' => Seller::className(), 'targetAttribute' => ['seller_id' => 'id']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'purpose' => 'Purpose',
            'number' => 'Number',
            'seller_id' => 'Seller ID',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getSeller()
    {
        return $this->hasOne(Seller::className(), ['id' => 'seller_id']);
    }
}


text:
bool CSegmentManager::Full (void)
{
return Count () >= SEGMENT_LIMIT;
}

// -----------------------------------------------------------------------------

short CSegmentManager::Add (void)
{
#if USE_FREELIST

if (m_free.Empty ())
	return -1;
int nSegment = --m_free;
m_segments [nSegment].Clear ();
return (short) nSegment;

#else //USE_FREELIST

if (Count () >= SEGMENT_LIMIT)
	return -1;
m_segments [Count ()].Reset ();
return Count ()++;

#endif //USE_FREELIST
}

// -----------------------------------------------------------------------------

void CSegmentManager::Remove (short nDelSeg)
{
#if USE_FREELIST
m_free += nDelSeg;
Count ()--;
#else
if (nDelSeg < Count ()) {
	if (nDelSeg < --Count ()) {
		// move the last segment in the segment list to the deleted segment's position
		if (current->SegmentId () == Count ())
			current->SetSegmentId (nDelSeg);
		if (other->m_nSegment == Count ())
			other->SetSegmentId (nDelSeg);
		*Segment (nDelSeg) = *Segment (Count ());
		// update all trigger targets pointing at the moved segment
		triggerManager.UpdateTargets (Count (), nDelSeg);
		objectManager.UpdateSegments (Count (), nDelSeg);
		// update all walls inside the moved segment
		CSide* pSide = Segment (nDelSeg)->Side (0);
		for (int i = 0; i < 6; i++, pSide++) {
			CSegment* pSegment = pSide->Child ();
			if (pSegment != null)
				pSegment->UpdateChildren (Count (), nDelSeg);
			CWall* pWall = pSide->Wall ();
			if (pWall != null)
				pWall->m_nSegment = nDelSeg;
			}
		}
	}
#endif
}

// -----------------------------------------------------------------------------

void CSegmentManager::AddSegments (void)
{
if (theMine->SelectMode () == BLOCK_MODE && segmentManager.TaggedSideCount () > 50) {
	if (Query2Msg ("You are about to insert a large number of cubes.\n"
		"Are you sure you want to do this?", MB_YESNO) != IDYES)
		return;
	}

undoManager.Begin (__FUNCTION__, udSegments);
short nSegment = Create (*current);
if (nSegment < 0) {
	undoManager.End (__FUNCTION__);
	return;
	}
current->SetSegmentId (nSegment);
// In block mode, also insert cubes from all marked sides
if (theMine->SelectMode () == BLOCK_MODE) {
	CSegment* pSegment = Segment (0);
	for (short nSegment = 0, nSegments = Count (); nSegment < nSegments; nSegment++, pSegment++)
		for (short nSide = 0; nSide < 6; nSide++)
			if (pSegment->IsTagged (nSide) && !pSegment->HasChild (nSide))
				if (0 > Create (CSideKey (nSegment, nSide)))
					break;
	}
undoManager.End (__FUNCTION__);
}

// -----------------------------------------------------------------------------

short CSegmentManager::Create (CSideKey key, int addMode)
{
	int i;

if (tunnelMaker.Active ())
	return -1;

if (Full ()) {
	ErrorMsg ("Cannot add a new segment because\nthe maximum number of segments has been reached.");
	return -1;
	}
if (vertexManager.Full ()) {
	ErrorMsg ("Cannot add a new segment because\nthe maximum number of vertices has been reached.");
	return -1;
	}
if ((Count () == MAX_SEGMENTS - 1) && (QueryMsg ("Adding more segments will exceed\nthe maximum segment count for this level type.\nAre you sure you want to continue?") != IDYES)) {
	return -1;
	}

current->Get (key);
CSegment* pSegment = Segment (key.m_nSegment);

short	nCurSide = key.m_nSide;
if (pSegment->ChildId (nCurSide) >= 0) {
	ErrorMsg ("Cannot add a new segment to a side\nwhich already has a segment attached.");
	return -1;
	}

if (Side (key)->VertexCount () < 3) {
	ErrorMsg ("Cannot add a new segment to this side.");
	//undoManager.Unroll (__FUNCTION__);
	return -1;
	}

m_bCreating = true;
undoManager.Begin (__FUNCTION__, udSegments | udVertices);
// get new segment

if (addMode < 0)
	addMode = m_nAddMode;

short nSides [2] = {key.m_nSide, oppSideTable [key.m_nSide]};

if ((addMode == MIRROR) && (pSegment->Side (nSides [0])->Shape () != pSegment->Side (nSides [1])->Shape ())) // mirror not possible!
	addMode = EXTEND;

short nNewSeg = Add ();
CSegment* pNewSeg = Segment (nNewSeg);

ushort newVerts [4];
vertexManager.Add (newVerts, Side (key)->VertexCount ());

short nVertices = ComputeVertices (key, newVerts, addMode);

CSide* pOrgSide = pSegment->Side (nSides [0]);
CSide* pFarSide = pNewSeg->Side (nSides [0]);
CSide* pOppSide = pNewSeg->Side (nSides [1]);
short nOppVertices = pOppSide->VertexCount ();

pNewSeg->Setup ();

if (nVertices == 3) { //create a wedge shaped segment when adding to a triangular segment side
	pNewSeg->SetShape (SEGMENT_SHAPE_WEDGE);
	short nSide = 0;
	for (; nSide < 6; nSide++)
		if ((nSide != nSides [0]) && (nSide != nSides [1]) && pSegment->Side (nSide)->Shape ())
			break;
	CSide* pSide = pNewSeg->Side (nSide);
	short nEdge = 0, i = pSide->m_vertexIdIndex [0], v1, v2 = pNewSeg->m_info.vertexIds [i];
	for (++nEdge; nEdge <= 4; nEdge++) {
		v1 = v2;
		i = pSide->m_vertexIdIndex [nEdge % 4];
		v2 = pNewSeg->m_info.vertexIds [i];
		if (pNewSeg->HasEdge (nSides [0], v1, v2) || pNewSeg->HasEdge (nSides [1], v1, v2))
			break;
		}
	--nEdge;
	segmentManager.CollapseEdge (nNewSeg, nSide, nEdge % pSide->VertexCount (), false);
	if (nEdge < pSide->VertexCount ())
		nEdge++;
	segmentManager.CollapseEdge (nNewSeg, nSide, nEdge % pSide->VertexCount (), false);
	}

#ifdef _DEBUG
for (i = 0; i < 8; i++)
	if (pNewSeg->m_info.vertexIds [i] < MAX_VERTEX)
		pNewSeg->m_info.vertexIds [i] = MAX_VERTEX;
#endif

// Definitions:
//   origin segment: The segment to which a new segment is added
//   origin side: The origin segment's side from which the new segment shall extend
//   opposite side: The side of new segment that forms the back side of the origin side
//   far side: The side of the new segment opposing the base side
//   origin vertices: Vertices of the origin side
// This function assigns the origin vertices to the base side and derives
// the far side's vertices from these (by adding an offset to them)
// The following code assigns vertices to the new segment by looking at the edges of
// the segment connecting opp side and far side

ubyte oppVertexIdIndex [4], * vertexIdIndex = pFarSide->m_vertexIdIndex;
pNewSeg->CreateOppVertexIndex (nSides [0], oppVertexIdIndex);

#if 0

for (short i = 0; i < nVertices; i++) {
	// define vertex numbers for new side
	ubyte h = pFarSide->m_vertexIdIndex [i];
	pNewSeg->m_info.vertexIds [h] = newVerts [i];

	// look for an edge that connects opp and far side and that shares the point we just assigned a vertex to.
	// The other point of that edge is the corresponding point of origin side.
	ubyte v, v1, v2, s1, s2;
	for (short j = 0; j < nEdges; j++) {
		edgeList.Get (j, s1, s2, v1, v2);
		if (v1 == h)
			v = v2;
		else if (v2 == h)
			v = v1;
		else
			continue;
		if ((s1 == nSides [0]) || (s1 == nSides [1]) || (s2 == nSides [0]) || (s2 == nSides [1]))
			continue;
		pNewSeg->m_info.vertexIds [v] = pSegment->m_info.vertexIds [pOrgSide->m_vertexIdIndex [i]];
		break;
		}
	}

#else

for (int i = 0; i < nVertices; i++) {
	// define vertex numbers for new side
	pNewSeg->m_info.vertexIds [vertexIdIndex [i]] = newVerts [i];
	pNewSeg->m_info.vertexIds [oppVertexIdIndex [i]] = pSegment->m_info.vertexIds [pOrgSide->m_vertexIdIndex [i]];
	}

#endif

// define children and special child
pNewSeg->m_info.childFlags = 1 << oppSideTable [nCurSide]; // only opposite side connects to current segment
for (int i = 0; i < MAX_SIDES_PER_SEGMENT; i++) { // no remaining children
	pNewSeg->SetChild (i, (pNewSeg->m_info.childFlags & (1 << i)) ? key.m_nSegment : -1);
	pNewSeg->Side (i)->DetectShape ();
	}

// define textures
for (short nSide = 0; nSide < MAX_SIDES_PER_SEGMENT; nSide++) {
	if (pNewSeg->ChildId (nSide) < 0) {
		// if other segment does not have a child (therefore it has a texture)
		if ((pSegment->ChildId (nSide) < 0) && (pSegment->m_info.function == SEGMENT_FUNC_NONE)) {
			pNewSeg->m_sides [nSide].SetTextures (pSegment->m_sides [nSide].BaseTex (), pSegment->m_sides [nSide].OvlTex ());
			for (i = 0; i < nVertices; i++) {
				if (addMode != ORTHOGONAL)
					memcpy (pNewSeg->m_sides [nSide].m_info.uvls, pSegment->m_sides [nSide].m_info.uvls, sizeof (pNewSeg->m_sides [nSide].m_info.uvls));
				else
					pNewSeg->m_sides [nSide].m_info.uvls [i].l = pSegment->m_sides [nSide].m_info.uvls [i].l;
				}
			}
		}
	else {
		pNewSeg->m_sides [nSide].ResetTextures ();
		}
	}

// define static light
pNewSeg->m_info.staticLight = pSegment->m_info.staticLight;

// delete variable light if it exists
lightManager.DeleteVariableLight (CSideKey (key.m_nSegment, nCurSide));

// update current segment
pSegment->SetChild (nCurSide, nNewSeg);
pOrgSide->SetTextures (0, 0);
memset (pOrgSide->m_info.uvls, 0, sizeof (pOrgSide->m_info.uvls));

// link the new segment with any touching Segment ()
#if 1
CVertex *vNewSeg = vertexManager.Vertex (pNewSeg->m_info.vertexIds [0]);
int nSegments = Count ();
pSegment = Segment (0);
for (int i = 0; i < nSegments; i++, pSegment++) {
	if (i != nNewSeg) {
		// first check to see if Segment () are any where near each other
		// use x, y, and z coordinate of first point of each segment for comparison
		CVertex *vSeg = vertexManager.Vertex (pSegment->m_info.vertexIds [0]);
		if (fabs (vNewSeg->v.x - vSeg->v.x) < 160.0 &&
			 fabs (vNewSeg->v.y - vSeg->v.y) < 160.0 &&
			 fabs (vNewSeg->v.z - vSeg->v.z) < 160.0)
			for (short nNewSide = 0; nNewSide < 6; nNewSide++)
				for (short nSide = 0; nSide < 6; nSide++)
					Link (nNewSeg, nNewSide, i, nSide, 3);
		}
	}
#endif
// auto align textures new segment
for (short nNewSide = 0; nNewSide < 6; nNewSide++)
	AlignSideTextures (key.m_nSegment, nNewSide, nNewSeg, nNewSide, true, true);
// set current segment to new segment
key.m_nSegment = nNewSeg;
Segment (key)->Backup (opAdd);
//		SetLinesToDraw();
DLE.MineView ()->Refresh (false);
DLE.ToolView ()->Refresh ();
undoManager.End (__FUNCTION__);
m_bCreating = false;
return nNewSeg;
}

// -----------------------------------------------------------------------------

short CSegmentManager::Create (short nSegment, bool bCreate, ubyte nFunction, short nTexture, char* szError)
{
if ((szError != null) && DLE.IsD1File ()) {
	if (!DLE.ExpertMode ())
		ErrorMsg (szError);
	return 0;
	}

if (bCreate) {
	if (current->ChildId () >= 0)
		return -1;
	undoManager.Begin (__FUNCTION__, udSegments);
	nSegment = Create (*current, -1);
	if (nSegment < 0) {
		Remove (nSegment);
		undoManager.End (__FUNCTION__);
		return -1;
		}
	}
else
	undoManager.Begin (__FUNCTION__, udSegments);

DLE.MineView ()->DelayRefresh (true);
m_bCreating = true;
if (!Define (nSegment, nFunction, -1)) {
	if (bCreate)
		Remove (nSegment);
	undoManager.End (__FUNCTION__);
	DLE.MineView ()->DelayRefresh (false);
	m_bCreating = false;
	return -1;
	}
Segment (nSegment)->Backup ();
m_bCreating = false;
undoManager.End (__FUNCTION__);
DLE.MineView ()->DelayRefresh (false);
DLE.MineView ()->Refresh ();
return nSegment;
}

// -----------------------------------------------------------------------------

bool CSegmentManager::CreateProducer (short nSegment, bool bCreate, ubyte nType, bool bSetDefTextures,
												  CObjectProducer* producers, CMineItemInfo& info, char* szError)
{
if (info.count >= MAX_MATCENS) {
	ErrorMsg (szError);
	return false;
	}
undoManager.Begin (__FUNCTION__, udSegments);
if (0 > (nSegment = Create (nSegment, bCreate, nType))) {
	undoManager.End (__FUNCTION__);
	return false;
	}
producers [info.count].Setup (nSegment, info.count, 0);
Segment (nSegment)->m_info.value =
Segment (nSegment)->m_info.nProducer = info.count++;
Segment (nSegment)->Backup (); // overwrite backup
undoManager.End (__FUNCTION__);
return true;
}

// -----------------------------------------------------------------------------

bool CSegmentManager::CreateEquipMaker (short nSegment, bool bCreate, bool bSetDefTextures)
{
if (!DLE.IsD2XFile ()) {
	ErrorMsg ("Equipment makers are only available in D2X-XL levels.");
	return false;
	}
return CreateProducer (nSegment, bCreate, SEGMENT_FUNC_EQUIPMAKER, bSetDefTextures, EquipMaker (0), m_producerInfo [1],
							"Maximum number of equipment makers reached");
}

// -----------------------------------------------------------------------------

bool CSegmentManager::CreateRobotMaker (short nSegment, bool bCreate, bool bSetDefTextures)
{
return CreateProducer (nSegment, bCreate, SEGMENT_FUNC_ROBOTMAKER, bSetDefTextures, RobotMaker (0), m_producerInfo [0],
							"Maximum number of robot makers reached");
}

// -----------------------------------------------------------------------------

bool CSegmentManager::CreateReactor (short nSegment, bool bCreate, bool bSetDefTextures)
{
return 0 <= Create (nSegment, bCreate, SEGMENT_FUNC_REACTOR, bSetDefTextures ? DLE.IsD1File () ? 10 : 357 : -1);
}

// -----------------------------------------------------------------------------

bool CSegmentManager::CreateGoal (short nSegment, bool bCreate, bool bSetDefTextures, ubyte nType, short nTexture)
{
return 0 <= Create (nSegment, bCreate, nType, bSetDefTextures ? nTexture : -1, "Flag goals are not available in Descent 1.");
}

// -----------------------------------------------------------------------------

bool CSegmentManager::CreateTeam (short nSegment, bool bCreate, bool bSetDefTextures, ubyte nType, short nTexture)
{
return 0 <= Create (nSegment, bCreate, nType, bSetDefTextures ? nTexture : -1, "Team start positions are not available in Descent 1.");
}

// -----------------------------------------------------------------------------

bool CSegmentManager::CreateSkybox (short nSegment, bool bCreate)
{
return 0 <= Create (nSegment, bCreate, SEGMENT_FUNC_SKYBOX, -1, "Skyboxes are not available in Descent 1.");
}

// -----------------------------------------------------------------------------

bool CSegmentManager::CreateSpeedBoost (short nSegment, bool bCreate)
{
return 0 <= Create (nSegment, bCreate, SEGMENT_FUNC_SPEEDBOOST, -1, "Speed boost segments are not available in Descent 1.");
}

// -----------------------------------------------------------------------------

int CSegmentManager::ProducerCount (void)
{
int nProducers = 0;
for (CSegmentIterator si; si; si++)
	if ((si->m_info.function == SEGMENT_FUNC_PRODUCER) || (si->m_info.function == SEGMENT_FUNC_REPAIRCEN))
		nProducers++;
return nProducers;
}

// -----------------------------------------------------------------------------

short CSegmentManager::CreateProducer (short nSegment, ubyte nType, bool bCreate, bool bSetDefTextures)
{
// count number of fuel centers
int nProducer = ProducerCount ();
if (nProducer >= MAX_NUM_RECHARGERS) {
	ErrorMsg ("Maximum number of fuel centers reached.");
	return 0;
	}

CSegment *pSegment = Segment (0);

undoManager.Begin (__FUNCTION__, udSegments);
if (nType == SEGMENT_FUNC_REPAIRCEN)
	nSegment = Create (nSegment, bCreate, nType, bSetDefTextures ? 433 : -1, "Repair centers are not available in Descent 1.");
else {
	short nLastSeg = current->SegmentId ();
	nSegment = Create (nSegment, bCreate, nType, bSetDefTextures ? DLE.IsD1File () ? 322 : 333 : -1);
	if (nSegment < 0) {
		undoManager.End (__FUNCTION__);
		return -1;
		}
	if (bSetDefTextures) { // add energy spark walls to fuel center sides
		current->SetSegmentId (nLastSeg);
		if (wallManager.Create (*current, WALL_ILLUSION, 0, KEY_NONE, -1, -1) != null) {
			CSideKey back;
			if (BackSide (back))
				wallManager.Create (back, WALL_ILLUSION, 0, KEY_NONE, -1, -1);
			}
		Segment (nSegment)->Backup ();
		current->SetSegmentId (nSegment);
		}
	}
undoManager.End (__FUNCTION__);
return nSegment;
}

// -----------------------------------------------------------------------------

short CSegmentManager::ComputeVerticesOrtho (CSideKey key, ushort newVerts [4])
{
	CSegment*		pSegment = segmentManager.Segment (key);
	CSide*			pSide = pSegment->Side (key.m_nSide);
	short				nVertices = pSide->VertexCount ();

	CDoubleVector	A [4];
	short				i, nPoint = pSide->Point (), points [4];

for (i = 0; i < 4; i++)
	points [i] = (nPoint + i) % 4;
CDoubleVector center = CalcSideCenter (key);
CDoubleVector oppCenter = CalcSideCenter (CSideKey (key.m_nSegment, oppSideTable [key.m_nSide]));
CDoubleVector vNormal = CalcSideNormal (key);
// set the length of the new segment to be one standard segment length
// scale the vector
vNormal *= 20.0; // 20 is edge length of a standard segment
// figure out new center
CDoubleVector newCenter = center + vNormal;
// new method: extend points 0 and 1 with vNormal, then move point 0 toward point 1.
// point 0
ushort i1, i2;
pSegment->GetEdgeVertices (key.m_nSide, nPoint, i1, i2);
CDoubleVector a = vNormal + *vertexManager.Vertex (i1);
// point 1
CDoubleVector b = vNormal + *vertexManager.Vertex (i2);
// center
CDoubleVector c = Average (a, b);
// vector from center to point0 and its length
CDoubleVector d = a - c;
double length = d.Mag ();
// factor to mul
double factor = (length > 0) ? 10.0 / length : 1.0;
// set point 0
d *= factor;
A [points [0]] = c + d;
// set point 1
A [points [1]] = c - d;
// point 2 is orthogonal to the vector 01 and the vNormal vector
c = -CrossProduct (A [points [0]] - A [points [1]], vNormal);
c.Normalize ();
// normalize the vector
A [points [2]] = A [points [1]] + (c * 20);
A [points [3]] = A [points [0]] + (c * 20);
if (nVertices == 3) {
	A [points [2]] += A [points [3]];
	A [points [2]] *= 0.5;
	}
a = A [0];
for (i = 1; i < nVertices; i++)
	a += A [i];
a /= double (nVertices);
// now center the side along about the newCenter
for (i = 0; i < nVertices; i++)
	A [i] += (newCenter - a);
// set the new vertices
for (i = 0; i < nVertices; i++) {
	ushort nVertex = newVerts [i];
	*vertexManager.Vertex (nVertex) = A [i];
	vertexManager.Vertex (nVertex)->Backup (); // update the newly added vertex instead of creating a new backup
	}
return nVertices;
}

// -----------------------------------------------------------------------------

short CSegmentManager::ComputeVerticesExtend (CSideKey key, ushort newVerts [4])
{
	CSegment*		pSegment = segmentManager.Segment (key);
	CSide*			pSide = pSegment->Side (key.m_nSide);
	short				nVertices = pSide->VertexCount ();

CDoubleVector center = CalcSideCenter (key);
CDoubleVector oppCenter = CalcSideCenter (CSideKey (key.m_nSegment, oppSideTable [key.m_nSide]));
CDoubleVector vNormal = CalcSideNormal (key);
// calculate the length of the new segment
vNormal *= Distance (center, oppCenter);
// set the new vertices
for (int i = 0; i < nVertices; i++) {
	ushort nVertex = newVerts [i];
	*vertexManager.Vertex (nVertex) = *pSegment->Vertex (pSide->m_vertexIdIndex [i]) + vNormal;
	vertexManager.Vertex (nVertex)->Backup (); // do not create a new backup right after adding this vertex
	}
return nVertices;
}

// -----------------------------------------------------------------------------

short CSegmentManager::ComputeVerticesMirror (CSideKey key, ushort newVerts [4])
{
	CDoubleVector	A [8], B [8], C [8], D [8], E [8];
	short				i;
	CDoubleVector	center, oppCenter, newCenter, vNormal;

	CSegment*		pSegment = segmentManager.Segment (key);
	CSide*			pSide = pSegment->Side (key.m_nSide);
	CSide*			pOppSide = segmentManager.Side (CSideKey (key.m_nSegment, oppSideTable [key.m_nSide]));
	short				nVertices = pSide->VertexCount ();
	ubyte				oppVertexIdIndex [4];

	pSegment->CreateOppVertexIndex (key.m_nSide, oppVertexIdIndex);

// copy side's four points into A
short nSide = key.m_nSide;
for (i = 0; i < nVertices; i++) {
	A [i] = *pSegment->Vertex (pSide->m_vertexIdIndex [i]);
	A [i + nVertices] = *pSegment->Vertex (oppVertexIdIndex [i]);
	}

// subtract point 0 from all points in A to form B points
for (i = 0; i < 2 * nVertices; i++)
	B [i] = A [i] - A [0];

// calculate angle to put point 1 in x - y plane by spinning on x - axis
// then rotate B points on x - axis to form C points.
// check to see if on x - axis already
double angle1 = atan3 (B [1].v.z, B [1].v.y);
for (i = 0; i < 2 * nVertices; i++)
	C [i].Set (B [i].v.x, B [i].v.y * cos (angle1) + B [i].v.z * sin (angle1), B [i].v.z * cos (angle1) - B [i].v.y * sin (angle1));
// calculate angle to put point 1 on x axis by spinning on z - axis
// then rotate C points on z - axis to form D points
// check to see if on z - axis already
double angle2 = atan3 (C [1].v.y, C [1].v.x);
for (i = 0; i < 2 * nVertices; i++)
	D [i].Set (C [i].v.x * cos (angle2) + C [i].v.y * sin (angle2), C [i].v.y * cos (angle2) - C [i].v.x * sin (angle2), C [i].v.z);

// calculate angle to put point 2 in x - y plane by spinning on x - axis
// the rotate D points on x - axis to form E points
// check to see if on x - axis already
double angle3 = atan3 (D [2].v.z, D [2].v.y);
for (i = 0; i < 2 * nVertices; i++)
	E [i].Set (D [i].v.x, D [i].v.y * cos (angle3) + D [i].v.z * sin (angle3), D [i].v.z * cos (angle3) - D [i].v.y * sin (angle3));

// now points 0, 1, and 2 are in x - y plane and point 3 is close enough.
// mirror new points on z axis
for (i = nVertices; i < 2 * nVertices; i++)
	E [i].v.z = -E [i].v.z;
// now reverse rotations
angle3 = -angle3;
for (i = nVertices; i < 2 * nVertices; i++)
	D [i].Set (E [i].v.x, E [i].v.y * cos (angle3) + E [i].v.z * sin (angle3), E [i].v.z * cos (angle3) - E [i].v.y * sin (angle3));
angle2 = -angle2;
for (i = nVertices; i < 2 * nVertices; i++)
	C [i].Set (D [i].v.x * cos (angle2) + D [i].v.y * sin (angle2), D [i].v.y * cos (angle2) - D [i].v.x * sin (angle2), D [i].v.z);
angle1 = -angle1;
for (i = nVertices; i < 2 * nVertices; i++)
	B [i].Set (C [i].v.x, C [i].v.y * cos (angle1) + C [i].v.z * sin (angle1), C [i].v.z * cos (angle1) - C [i].v.y * sin (angle1));

// and translate back
ushort nVertex = pSegment->m_info.vertexIds [pSide->m_vertexIdIndex [0]];
for (i = nVertices; i < 2 * nVertices; i++)
	A [i] = B [i] + *vertexManager.Vertex (nVertex);

for (i = 0; i < nVertices; i++) {
	nVertex = newVerts [i];
	*vertexManager.Vertex (nVertex) = A [i + nVertices];
	vertexManager.Vertex (nVertex)->Backup ();
	}
return nVertices;
}

// -----------------------------------------------------------------------------
// Calculate vertices when adding a new segment.

short CSegmentManager::ComputeVertices (CSideKey key, ushort newVerts [4], int addMode)
{
	short	nVertices = segmentManager.Side (key)->VertexCount ();

if (nVertices < 3)
	return 0;

if (addMode < 0)
	addMode = m_nAddMode;
if (addMode == ORTHOGONAL)
	nVertices = ComputeVerticesOrtho (key, newVerts);
else if (addMode == EXTEND)
	nVertices = ComputeVerticesExtend (key, newVerts);
else if (addMode == MIRROR)
	nVertices = ComputeVerticesMirror (key, newVerts);
else
	return 0;
for (int i = nVertices; i < 4; i++)
	newVerts [i] = 0xffff;
return nVertices;
}

// -----------------------------------------------------------------------------

bool CSegmentManager::SetDefaultTexture (short nTexture)
{
if (nTexture < 0)
	return true;

short nSegment = current->SegmentId ();
CSegment *pSegment = Segment (nSegment);

if (!m_bCreating)
	pSegment->Backup ();
double scale = textureManager.Scale (DLE.FileType (), nTexture);

undoManager.Begin (__FUNCTION__, udSegments);
pSegment->m_info.childFlags |= (1 << MAX_SIDES_PER_SEGMENT);
// set textures
CSide *pSide = pSegment->m_sides;
for (short nSide = 0; nSide < 6; nSide++, pSide++) {
	if (pSegment->ChildId (nSide) == -1) {
		SetTextures (CSideKey (nSegment, nSide), nTexture, 0);
		for (int i = 0; i < 4; i++) {
			pSide->m_info.uvls [i].u = (short) ((double) defaultUVLs [i].u / scale);
			pSide->m_info.uvls [i].v = (short) ((double) defaultUVLs [i].v / scale);
			pSide->m_info.uvls [i].l = defaultUVLs [i].l;
			}
		Segment (nSegment)->SetUV (nSide, 0, 0);
		}
	}
undoManager.End (__FUNCTION__);
return true;
}

// -----------------------------------------------------------------------------

bool CSegmentManager::Define (short nSegment, ubyte nFunction, short nTexture)
{
undoManager.Begin (__FUNCTION__, udSegments);
CSegment *pSegment = (nSegment < 0) ? current->Segment () : Segment (nSegment);
if (!m_bCreating)
	pSegment->Backup ();
Undefine (Index (pSegment));
pSegment->m_info.function = nFunction;
pSegment->m_info.childFlags |= (1 << MAX_SIDES_PER_SEGMENT);
SetDefaultTexture (nTexture);
undoManager.End (__FUNCTION__);
DLE.MineView ()->Refresh ();
return true;
}

// -----------------------------------------------------------------------------

void CSegmentManager::RemoveProducer (CSegment* pSegment, CObjectProducer* producers, CMineItemInfo& info, int nFunction)
{
if (info.count > 0) {
	// fill in deleted matcen
	int nDelProducer = pSegment->m_info.nProducer;
	if (nDelProducer >= 0) {
		// copy last producer in list to deleted producer's position
		undoManager.Begin (__FUNCTION__, udSegments | udProducers);
		pSegment->m_info.nProducer = -1;
		pSegment->m_info.value = -1;
		if (nDelProducer < --info.count) {
			memcpy (&producers [nDelProducer], &producers [info.count], sizeof (producers [0]));
			producers [nDelProducer].m_info.nProducer = nDelProducer;
			// point owner of relocated producer to that producer's new position
			for (CSegmentIterator si; si; si++) {
				CSegment *pSegment = &(*si);
				if ((pSegment->m_info.function == nFunction) && (pSegment->m_info.nProducer == info.count)) {
					pSegment->Backup ();
					pSegment->m_info.nProducer = nDelProducer;
					break;
					}
				}
			}
		// remove producer from all robot maker triggers targetting it
		CSideKey key = (-Index (pSegment) - 1, 0);
		for (int nClass = 0; nClass < 2; nClass++) {
			CTrigger* pTrigger = triggerManager.Trigger (0, nClass);
			for (CTriggerIterator ti (nClass); ti; ti++) {
				if (ti->Info ().type == TT_MATCEN)
					ti->Delete (key);
				}
			}
		undoManager.End (__FUNCTION__);
		}
	}
pSegment->m_info.nProducer = -1;
}

// -----------------------------------------------------------------------------

void CSegmentManager::Undefine (short nSegment)
{
	CSegment *pSegment = (nSegment < 0) ? current->Segment () : Segment (nSegment);

pSegment->Backup ();
nSegment = Index (pSegment);
if (pSegment->m_info.function == SEGMENT_FUNC_ROBOTMAKER)
	RemoveProducer (pSegment, RobotMaker (0), m_producerInfo [0], SEGMENT_FUNC_ROBOTMAKER);
else if (pSegment->m_info.function == SEGMENT_FUNC_EQUIPMAKER)
	RemoveProducer (pSegment, EquipMaker (0), m_producerInfo [1], SEGMENT_FUNC_EQUIPMAKER);
else if (pSegment->m_info.function == SEGMENT_FUNC_PRODUCER) { //remove all fuel cell walls
	undoManager.Begin (__FUNCTION__, udSegments);
	CSide *pSide = pSegment->m_sides;
	for (short nSide = 0; nSide < 6; nSide++, pSide++) {
		if (pSegment->ChildId (nSide) < 0)	// assume no wall if no child segment at the current side
			continue;
		CSegment* pChildSeg = Segment (pSegment->ChildId (nSide));
		if (pChildSeg->m_info.function == SEGMENT_FUNC_PRODUCER)	// don't delete if child segment is fuel center
			continue;
		// if there is a wall and it's a fuel cell delete it
		CSideKey key (nSegment, nSide);
		CWall *pWall = Wall (key);
		if ((pWall != null) && (pWall->Type () == WALL_ILLUSION) && (pSide->BaseTex () == (DLE.IsD1File () ? 322 : 333)))
			wallManager.Delete (pSide->m_info.nWall);
		// if there is a wall at the opposite side and it's a fuel cell delete it
		CSideKey back;
		if (BackSide (key, back)) {
			pWall = Wall (back);
			if ((pWall != null) && (pWall->Type () == WALL_ILLUSION)) {
				CSide* pOppSide = Side (back);
				if (pOppSide->BaseTex () == (DLE.IsD1File () ? 322 : 333))
					wallManager.Delete (pOppSide->m_info.nWall);
				}
			}
		}
	undoManager.End (__FUNCTION__);
	}
pSegment->m_info.childFlags &= ~(1 << MAX_SIDES_PER_SEGMENT);
pSegment->m_info.function = SEGMENT_FUNC_NONE;
}

// -----------------------------------------------------------------------------

void CSegmentManager::Delete (short nDelSeg, bool bDeleteVerts)
{
if (Count () < 2)
	return;
if (nDelSeg < 0)
	nDelSeg = current->SegmentId ();
if (nDelSeg < 0 || nDelSeg >= Count ())
	return;
if (tunnelMaker.Active ())
	return;

undoManager.Begin (__FUNCTION__, udSegments);
CSegment* pDelSeg = Segment (nDelSeg);
current->Fix (nDelSeg);
other->Fix (nDelSeg);
pDelSeg->Backup (opDelete);
Undefine (nDelSeg);

// delete any variable lights that use this segment
for (int nSide = 0; nSide < 6; nSide++) {
	CSideKey key (nDelSeg, nSide);
	triggerManager.DeleteTargets (key);
	lightManager.DeleteVariableLight (key);
	}

// delete any Walls () within segment (if defined)
DeleteWalls (nDelSeg);

// delete any walls from adjacent segments' sides connecting to this segment
for (short i = 0; i < MAX_SIDES_PER_SEGMENT; i++) {
	if (pDelSeg->ChildId (i) >= 0) {
		CSideKey back, key (nDelSeg, i);
		if (BackSide (key, back))
			wallManager.Delete (Side (back)->m_info.nWall);
		}
	}

	// delete any Objects () within segment
objectManager.DeleteSegmentObjects (nDelSeg);

// delete any control pSegment with this segment
for (short i = triggerManager.ReactorTriggerCount (); i > 0; )
	triggerManager.ReactorTrigger (--i)->Delete (CSideKey (-nDelSeg - 1));

	// update secret segment number if out of range now
	short nSegment = (short) objectManager.SecretSegment ();
	if (nSegment >= Count () || nSegment == nDelSeg)
		objectManager.SecretSegment () = 0;

	// update segment flags
	pDelSeg->UnTag ();

	// unlink any children with this segment number
	int nSegments = segmentManager.Count ();
	for (int si = 0; si < nSegments; si++) {
		CSegment* pSegment = segmentManager.Segment (si);
		for (short nChild = 0; nChild < MAX_SIDES_PER_SEGMENT; nChild++) {
			if (pSegment->ChildId (nChild) == nDelSeg) {
				// remove nChild number and update nChild bitmask
				pSegment->SetChild (nChild, -1);

				// define textures, (u, v) and light
				CSide *pSide = pDelSeg->m_sides + nChild;
				SetTextures (CSideKey (si, nChild), pSide->BaseTex (), pSide->OvlTex ());
				pSegment->SetUV (nChild, 0, 0);
				for (short j = 0; j < 4; j++) {
					pSegment->Uvls (nChild) [j].l = pDelSeg->Uvls (nChild) [j].l;
				}
			}
		}
	}
Remove (nDelSeg);

// delete all unused vertices
vertexManager.DeleteUnused ();

// make sure current segment numbers are valid
DLE.MineView ()->Refresh (false);
DLE.ToolView ()->Refresh ();
undoManager.End (__FUNCTION__);
}

// -----------------------------------------------------------------------------


text:
package io.netty.handler.codec.http2;

import static io.netty.handler.codec.http.HttpMethod.GET;
import static io.netty.handler.codec.http.HttpMethod.POST;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
import static io.netty.handler.codec.http2.Http2CodecUtil.ignoreSettingsHandler;
import static io.netty.util.CharsetUtil.UTF_8;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyShort;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.ChannelPromise;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.DefaultFullHttpRequest;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.util.NetUtil;

import java.net.InetSocketAddress;
import java.util.concurrent.CountDownLatch;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

/**
 * Testing the {@link DelegatingHttp2HttpConnectionHandler} for {@link FullHttpRequest} objects into HTTP/2 frames
 */
public class DelegatingHttp2HttpConnectionHandlerTest {
    @Mock
    private Http2FrameListener clientListener;

    @Mock
    private Http2FrameListener serverListener;

    private ServerBootstrap sb;
    private Bootstrap cb;
    private Channel serverChannel;
    private Channel clientChannel;
    private CountDownLatch requestLatch;
    private static final int CONNECTION_SETUP_READ_COUNT = 2;

    @Before
    public void setup() throws Exception {
        MockitoAnnotations.initMocks(this);

        requestLatch = new CountDownLatch(CONNECTION_SETUP_READ_COUNT + 1);

        sb = new ServerBootstrap();
        cb = new Bootstrap();

        sb.group(new NioEventLoopGroup(), new NioEventLoopGroup());
        sb.channel(NioServerSocketChannel.class);
        sb.childHandler(new ChannelInitializer<Channel>() {
            @Override
            protected void initChannel(Channel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();
                p.addLast(new DelegatingHttp2ConnectionHandler(true, new FrameCountDown()));
                p.addLast(ignoreSettingsHandler());
            }
        });

        cb.group(new NioEventLoopGroup());
        cb.channel(NioSocketChannel.class);
        cb.handler(new ChannelInitializer<Channel>() {
            @Override
            protected void initChannel(Channel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();
                p.addLast(new DelegatingHttp2HttpConnectionHandler(false, clientListener));
                p.addLast(ignoreSettingsHandler());
            }
        });

        serverChannel = sb.bind(new InetSocketAddress(0)).sync().channel();
        int port = ((InetSocketAddress) serverChannel.localAddress()).getPort();

        ChannelFuture ccf = cb.connect(new InetSocketAddress(NetUtil.LOCALHOST, port));
        assertTrue(ccf.awaitUninterruptibly().isSuccess());
        clientChannel = ccf.channel();
    }

    @After
    public void teardown() throws Exception {
        serverChannel.close().sync();
        sb.group().shutdownGracefully();
        sb.childGroup().shutdownGracefully();
        cb.group().shutdownGracefully();
    }

    @Test
    public void testJustHeadersRequest() throws Exception {
        final HttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, GET, "/example");
        final HttpHeaders httpHeaders = request.headers();
        httpHeaders.set(HttpUtil.ExtensionHeaders.Names.STREAM_ID, 5);
        httpHeaders.set(HttpHeaders.Names.HOST, "http://my-user_name@www.example.org:5555/example");
        httpHeaders.set(HttpUtil.ExtensionHeaders.Names.AUTHORITY, "www.example.org:5555");
        httpHeaders.set(HttpUtil.ExtensionHeaders.Names.SCHEME, "http");
        httpHeaders.add("foo", "goo");
        httpHeaders.add("foo", "goo2");
        httpHeaders.add("foo2", "goo2");
        final Http2Headers http2Headers = new DefaultHttp2Headers.Builder()
            .method("GET").path("/example").authority("www.example.org:5555").scheme("http")
            .add("foo", "goo").add("foo", "goo2").add("foo2", "goo2").build();
        ChannelPromise writePromise = newPromise();
        ChannelFuture writeFuture = clientChannel.writeAndFlush(request, writePromise);

        writePromise.awaitUninterruptibly(2, SECONDS);
        assertTrue(writePromise.isSuccess());
        writeFuture.awaitUninterruptibly(2, SECONDS);
        assertTrue(writeFuture.isSuccess());
        awaitRequests();
        verify(serverListener).onHeadersRead(any(ChannelHandlerContext.class), eq(5), eq(http2Headers), eq(0),
            anyShort(), anyBoolean(), eq(0), eq(true));
        verify(serverListener, never()).onDataRead(any(ChannelHandlerContext.class),
            anyInt(), any(ByteBuf.class), anyInt(), anyBoolean());
    }

    @Test
    public void testRequestWithBody() throws Exception {
        requestLatch = new CountDownLatch(CONNECTION_SETUP_READ_COUNT + 2);
        final String text = "foooooogoooo";
        final HttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, POST, "/example",
            Unpooled.copiedBuffer(text, UTF_8));
        final HttpHeaders httpHeaders = request.headers();
        httpHeaders.set(HttpHeaders.Names.HOST, "http://your_user-name123@www.example.org:5555/example");
        httpHeaders.add("foo", "goo");
        httpHeaders.add("foo", "goo2");
        httpHeaders.add("foo2", "goo2");
        final Http2Headers http2Headers = new DefaultHttp2Headers.Builder()
            .method("POST").path("/example").authority("www.example.org:5555").scheme("http")
            .add("foo", "goo").add("foo", "goo2").add("foo2", "goo2").build();
        ChannelPromise writePromise = newPromise();
        ChannelFuture writeFuture = clientChannel.writeAndFlush(request, writePromise);

        writePromise.awaitUninterruptibly(2, SECONDS);
        assertTrue(writePromise.isSuccess());
        writeFuture.awaitUninterruptibly(2, SECONDS);
        assertTrue(writeFuture.isSuccess());
        awaitRequests();
        verify(serverListener).onHeadersRead(any(ChannelHandlerContext.class), eq(3), eq(http2Headers), eq(0),
            anyShort(), anyBoolean(), eq(0), eq(false));
        verify(serverListener).onDataRead(any(ChannelHandlerContext.class),
            eq(3), eq(Unpooled.copiedBuffer(text.getBytes())), eq(0), eq(true));
    }

    private void awaitRequests() throws Exception {
        requestLatch.await(2, SECONDS);
    }

    private ChannelHandlerContext ctx() {
        return clientChannel.pipeline().firstContext();
    }

    private ChannelPromise newPromise() {
        return ctx().newPromise();
    }

     /**
     * A decorator around the serverObserver that counts down the latch so that we can await the
     * completion of the request.
     */
    private final class FrameCountDown implements Http2FrameListener {

        @Override
        public void onDataRead(ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding,
                               boolean endOfStream)
                throws Http2Exception {
            serverListener.onDataRead(ctx, streamId, copy(data), padding, endOfStream);
            requestLatch.countDown();
        }

        @Override
        public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers,
                                  int padding, boolean endStream) throws Http2Exception {
            serverListener.onHeadersRead(ctx, streamId, headers, padding, endStream);
            requestLatch.countDown();
        }

        @Override
        public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers,
                                  int streamDependency, short weight, boolean exclusive, int padding,
                                  boolean endStream) throws Http2Exception {
            serverListener.onHeadersRead(ctx, streamId, headers, streamDependency, weight,
                    exclusive, padding, endStream);
            requestLatch.countDown();
        }

        @Override
        public void onPriorityRead(ChannelHandlerContext ctx, int streamId, int streamDependency,
                                   short weight, boolean exclusive) throws Http2Exception {
            serverListener.onPriorityRead(ctx, streamId, streamDependency, weight, exclusive);
            requestLatch.countDown();
        }

        @Override
        public void onRstStreamRead(ChannelHandlerContext ctx, int streamId, long errorCode)
                throws Http2Exception {
            serverListener.onRstStreamRead(ctx, streamId, errorCode);
            requestLatch.countDown();
        }

        @Override
        public void onSettingsAckRead(ChannelHandlerContext ctx) throws Http2Exception {
            serverListener.onSettingsAckRead(ctx);
            requestLatch.countDown();
        }

        @Override
        public void onSettingsRead(ChannelHandlerContext ctx, Http2Settings settings) throws Http2Exception {
            serverListener.onSettingsRead(ctx, settings);
            requestLatch.countDown();
        }

        @Override
        public void onPingRead(ChannelHandlerContext ctx, ByteBuf data) throws Http2Exception {
            serverListener.onPingRead(ctx, copy(data));
            requestLatch.countDown();
        }

        @Override
        public void onPingAckRead(ChannelHandlerContext ctx, ByteBuf data) throws Http2Exception {
            serverListener.onPingAckRead(ctx, copy(data));
            requestLatch.countDown();
        }

        @Override
        public void onPushPromiseRead(ChannelHandlerContext ctx, int streamId,
                                      int promisedStreamId, Http2Headers headers, int padding) throws Http2Exception {
            serverListener.onPushPromiseRead(ctx, streamId, promisedStreamId, headers, padding);
            requestLatch.countDown();
        }

        @Override
        public void onGoAwayRead(ChannelHandlerContext ctx, int lastStreamId, long errorCode, ByteBuf debugData)
                throws Http2Exception {
            serverListener.onGoAwayRead(ctx, lastStreamId, errorCode, copy(debugData));
            requestLatch.countDown();
        }

        @Override
        public void onWindowUpdateRead(ChannelHandlerContext ctx, int streamId,
                                       int windowSizeIncrement) throws Http2Exception {
            serverListener.onWindowUpdateRead(ctx, streamId, windowSizeIncrement);
            requestLatch.countDown();
        }

        @Override
        public void onUnknownFrame(ChannelHandlerContext ctx, byte frameType, int streamId,
                Http2Flags flags, ByteBuf payload) {
            serverListener.onUnknownFrame(ctx, frameType, streamId, flags, payload);
            requestLatch.countDown();
        }

        ByteBuf copy(ByteBuf buffer) {
            return Unpooled.copiedBuffer(buffer);
        }
    }
}


text:
package org.apache.wicket;

import org.apache.wicket.markup.html.WebPage;

/**
 * @author jcompagner
 */
public class LoginPage extends WebPage
{
	private static final long serialVersionUID = 1L;

	/**
	 * Construct.
	 */
	public LoginPage()
	{
	}

}


text:
package com.ajjpj.macro.jdk18.tree.support;

import com.ajjpj.macro.tree.support.MType;
import com.ajjpj.macro.util.MTypes;
import com.sun.tools.javac.code.Symtab;
import com.sun.tools.javac.jvm.ClassReader;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.Names;

/**
 * @author arno
 */
public class MJavacTypes implements MTypes {
    private final Symtab syms;
    private final ClassReader classes;
    private final Names names;

    public MJavacTypes (Context context) {
        this.syms = Symtab.instance (context);
        this.classes = ClassReader.instance (context);
        this.names = Names.instance (context);
    }

    @Override public MType intType () {
        return new MJavacType (syms.intType);
    }

    @Override public MJavacType stringType () {
        return new MJavacType (syms.stringType);
    }

    @Override public MType fromFqn (String fqn) {
        return new MJavacType (classes.enterClass (names.fromString (fqn)).type);
    }
}


text:
import React from 'react';
import HeightsSection from './HeightsSection';
import { mount } from 'enzyme';

describe('(Component) Sigmet/HeightsSection', () => {
  it('renders a HeightsSection', () => {
    const _component = mount(<HeightsSection><div /></HeightsSection>);
    expect(_component.type()).to.eql(HeightsSection);
  });
});