text:
using System;

namespace Metaheuristics
{
	public class DiscreteSSBL2OptBest42SP : DiscreteSS
	{
		public TwoSPInstance Instance { get; protected set; }

		protected int generatedSolutions;

		public DiscreteSSBL2OptBest42SP(TwoSPInstance instance, int poolSize,
		                                int refSetSize, double explorationFactor)
			: base(poolSize, refSetSize, explorationFactor)
		{
			Instance = instance;
			generatedSolutions = 0;
		}

		protected override double Fitness(int[] solution)
		{
			return TwoSPUtils.Fitness(Instance, TwoSPUtils.BLCoordinates(Instance, solution));
		}

		protected override int[] RandomSolution()
		{
			int[] solution;

			if (generatedSolutions == 0) {
				solution = TwoSPUtils.DecreasingArea(Instance);
			}
			else if (generatedSolutions == 1) {
				solution = TwoSPUtils.DecreasingWidth(Instance);
			}
			else if (generatedSolutions == 2) {
				solution = TwoSPUtils.DecreasingHeight(Instance);
			}
			else {
				solution = TwoSPUtils.RandomSolution(Instance);
			}

			generatedSolutions++;
			return solution;
		}

		protected override void Repair(int[] solution)
		{
			TwoSPUtils.Repair(Instance, solution);
		}

		protected override void Improve (int[] solution)
		{
			TwoSPUtils.BLLocalSearch2OptBest(Instance, solution);
		}

		protected override double Distance(int[] a, int[] b)
		{
			return TwoSPUtils.Distance(Instance, a, b);
		}
	}
}


text:
from lxml import etree
import webob

from nova.api.openstack.compute.contrib import flavor_disabled
from nova.compute import flavors
from nova.openstack.common import jsonutils
from nova import test
from nova.tests.api.openstack import fakes

FAKE_FLAVORS = {
    'flavor 1': {
        "flavorid": '1',
        "name": 'flavor 1',
        "memory_mb": '256',
        "root_gb": '10',
        "disabled": False,
    },
    'flavor 2': {
        "flavorid": '2',
        "name": 'flavor 2',
        "memory_mb": '512',
        "root_gb": '20',
        "disabled": True,
    },
}

def fake_flavor_get_by_flavor_id(flavorid, ctxt=None):
    return FAKE_FLAVORS['flavor %s' % flavorid]

def fake_flavor_get_all(*args, **kwargs):
    return FAKE_FLAVORS

class FlavorDisabledTest(test.TestCase):
    content_type = 'application/json'
    prefix = '%s:' % flavor_disabled.Flavor_disabled.alias

    def setUp(self):
        super(FlavorDisabledTest, self).setUp()
        ext = ('nova.api.openstack.compute.contrib'
              '.flavor_disabled.Flavor_disabled')
        self.flags(osapi_compute_extension=[ext])
        fakes.stub_out_nw_api(self.stubs)
        self.stubs.Set(flavors, "get_all_flavors",
                       fake_flavor_get_all)
        self.stubs.Set(flavors,
                       "get_flavor_by_flavor_id",
                       fake_flavor_get_by_flavor_id)

    def _make_request(self, url):
        req = webob.Request.blank(url)
        req.headers['Accept'] = self.content_type
        res = req.get_response(fakes.wsgi_app())
        return res

    def _get_flavor(self, body):
        return jsonutils.loads(body).get('flavor')

    def _get_flavors(self, body):
        return jsonutils.loads(body).get('flavors')

    def assertFlavorDisabled(self, flavor, disabled):
        self.assertEqual(str(flavor.get('%sdisabled' % self.prefix)), disabled)

    def test_show(self):
        url = '/v2/fake/flavors/1'
        res = self._make_request(url)

        self.assertEqual(res.status_int, 200)
        self.assertFlavorDisabled(self._get_flavor(res.body), 'False')

    def test_detail(self):
        url = '/v2/fake/flavors/detail'
        res = self._make_request(url)

        self.assertEqual(res.status_int, 200)
        flavors = self._get_flavors(res.body)
        self.assertFlavorDisabled(flavors[0], 'False')
        self.assertFlavorDisabled(flavors[1], 'True')

class FlavorDisabledXmlTest(FlavorDisabledTest):
    content_type = 'application/xml'
    prefix = '{%s}' % flavor_disabled.Flavor_disabled.namespace

    def _get_flavor(self, body):
        return etree.XML(body)

    def _get_flavors(self, body):
        return etree.XML(body).getchildren()

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/.idea/RegistrationForm.iml" filepath="$PROJECT_DIR$/.idea/RegistrationForm.iml" />
    </modules>
  </component>
</project>


text:
package com.example.ldy.weiyuweather.Utils;

import rx.Observable;
import rx.Scheduler;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by LDY on 2016/10/14.
 */
public class RxUtils {

    //线程切换工具,默认切换方式
    public static <T> Observable.Transformer<T, T> rxSchedulerHelper() {
        return tObservable -> tObservable.subscribeOn(Schedulers.io())
                .unsubscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread());
    }

    //线程切换,自定义线程
    public static <T> Observable.Transformer<T, T> rxSchedulerHelper(Scheduler scheduler) {
        return tObservable -> tObservable.subscribeOn(scheduler)
                .unsubscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread());
    }
}


text:
set( csharp_mono_valid 1 )
if( DEFINED CSHARP_MONO_FOUND )
  # The Mono compiler has already been found
  # It may have been reset by the user, verify it is correct
  if( NOT DEFINED CSHARP_MONO_COMPILER_${CSHARP_MONO_VERSION} )
    set( csharp_mono_version_user ${CSHARP_MONO_VERSION} )
    set( csharp_mono_valid 0 )
    set( CSHARP_MONO_FOUND 0 )
    set( CSHARP_MONO_VERSION "CSHARP_MONO_VERSION-NOTVALID" CACHE STRING "C# Mono compiler version, choices: ${CSHARP_MONO_VERSIONS}" FORCE )
    message( FATAL_ERROR "The C# Mono version '${csharp_mono_version_user}' is not valid. Please enter one of the following: ${CSHARP_MONO_VERSIONS}" )
  endif()
endif()

unset( CSHARP_MONO_VERSIONS CACHE ) # Clear versions
if( WIN32 )
  # Search for Mono on Win32 systems
  # See http://mono-project.com/OldReleases and http://www.go-mono.com/mono-downloads/download.html
  set( csharp_mono_bin_dirs )
  set( csharp_mono_search_hints
    "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Novell\\Mono\\2.11.2;SdkInstallRoot]/bin"
    "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Novell\\Mono\\2.10.9;SdkInstallRoot]/bin"
    "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Novell\\Mono\\2.10.8;SdkInstallRoot]/bin"
    "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Novell\\Mono\\2.10.7;SdkInstallRoot]/bin"
    "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Novell\\Mono\\2.10.6;SdkInstallRoot]/bin"
    "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Novell\\Mono\\2.10.5;SdkInstallRoot]/bin"
    "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Novell\\Mono\\2.10.4;SdkInstallRoot]/bin"
    "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Novell\\Mono\\2.10.3;SdkInstallRoot]/bin"
    "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Novell\\Mono\\2.10.2;SdkInstallRoot]/bin"
    "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Novell\\Mono\\2.10.1;SdkInstallRoot]/bin"
    "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Novell\\Mono\\2.10;SdkInstallRoot]/bin"
    "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Novell\\Mono\\2.8;SdkInstallRoot]/bin"
    "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Novell\\Mono\\2.6.7;SdkInstallRoot]/bin"
    "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Novell\\Mono\\2.6.4;SdkInstallRoot]/bin"
    "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Novell\\Mono\\2.6.3;SdkInstallRoot]/bin"
    "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Novell\\Mono\\2.6.1;SdkInstallRoot]/bin"
    "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Novell\\Mono\\2.6;SdkInstallRoot]/bin"
  )
  foreach( csharp_mono_search_hint ${csharp_mono_search_hints} )
    get_filename_component( csharp_mono_bin_dir "${csharp_mono_search_hint}" ABSOLUTE )
    if ( EXISTS "${csharp_mono_bin_dir}" )
      set( csharp_mono_bin_dirs ${csharp_mono_bin_dirs} ${csharp_mono_bin_dir} )
    endif ()
  endforeach()
  # TODO: Use HKLM_LOCAL_MACHINE\Software\Novell\Mono\DefaultCLR to specify default version
  # get_filename_component( test "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Novell\\Mono;DefaultCLR]" NAME )

  foreach ( csharp_mono_bin_dir ${csharp_mono_bin_dirs} )
    string( REPLACE "\\" "/" csharp_mono_bin_dir ${csharp_mono_bin_dir} )
    if (EXISTS "${csharp_mono_bin_dir}/dmcs.bat")
      set( csharp_mono_executable "${csharp_mono_bin_dir}/dmcs.bat")
    elseif (EXISTS "${csharp_mono_bin_dir}/gmcs.bat")
      set( csharp_mono_executable "${csharp_mono_bin_dir}/gmcs.bat")
    elseif (EXISTS "${csharp_mono_bin_dir}/mcs.bat")
      set( csharp_mono_executable "${csharp_mono_bin_dir}/mcs.bat")
    endif ()

    if( csharp_mono_valid )
      # Extract version number (eg. 2.10.2)
      string(REGEX MATCH "([0-9]*)([.])([0-9]*)([.]*)([0-9]*)" csharp_mono_version_temp ${csharp_mono_bin_dir})
      set( CSHARP_MONO_VERSION ${csharp_mono_version_temp} CACHE STRING "C# Mono compiler version" )
      mark_as_advanced( CSHARP_MONO_VERSION )

      # Add variable holding executable
      set( CSHARP_MONO_COMPILER_${csharp_mono_version_temp} ${csharp_mono_executable} CACHE STRING "C# Mono compiler ${csharp_mono_version_temp}" FORCE )
      mark_as_advanced( CSHARP_MONO_COMPILER_${csharp_mono_version_temp} )

      # Set interpreter
      if (EXISTS "${csharp_mono_bin_dir}/mono.exe")
        set( CSHARP_MONO_INTERPRETER_${csharp_mono_version_temp} "${csharp_mono_bin_dir}/mono.exe" CACHE STRING "C# Mono interpreter ${csharp_mono_version_temp}" FORCE )
        mark_as_advanced( CSHARP_MONO_INTERPRETER_${csharp_mono_version_temp} )
      endif ()
    endif()

    # Create a list of supported compiler versions
    if( NOT DEFINED CSHARP_MONO_VERSIONS )
      set( CSHARP_MONO_VERSIONS "${csharp_mono_version_temp}" CACHE STRING "Available C# Mono compiler versions" FORCE )
    else()
      set( CSHARP_MONO_VERSIONS "${CSHARP_MONO_VERSIONS}, ${csharp_mono_version_temp}"  CACHE STRING "Available C# Mono versions" FORCE )
    endif()
    mark_as_advanced( CSHARP_MONO_VERSIONS )

    # We found at least one Mono compiler version
    set( CSHARP_MONO_FOUND 1 CACHE INTERNAL "Boolean indicating if C# Mono was found" )
  endforeach()

else()
  # Search for Mono on non-Win32 systems
  set( chsarp_mono_names "mcs" "mcs.exe" "dmcs" "dmcs.exe" "smcs" "smcs.exe" "gmcs" "gmcs.exe" )
  set(
    csharp_mono_paths
    "/usr/bin/"
    "/usr/local/bin/"
    "/usr/lib/mono/2.0"
    "/opt/novell/mono/bin"
  )
  find_program(
    csharp_mono_compiler # variable is added to the cache, we removed it below
    NAMES ${chsarp_mono_names}
    PATHS ${csharp_mono_paths}
  )

  if( EXISTS ${csharp_mono_compiler} )
    # Determine version
    find_program(
      csharp_mono_interpreter # variable is added to the cache, we removed it below
      NAMES mono
      PATHS ${csharp_mono_paths}
    )
    if ( EXISTS ${csharp_mono_interpreter} )
      execute_process(
        COMMAND ${csharp_mono_interpreter} -V
        OUTPUT_VARIABLE csharp_mono_version_string
      )
      string( REGEX MATCH "([0-9]*)([.])([0-9]*)([.]*)([0-9]*)" csharp_mono_version_temp ${csharp_mono_version_string} )
      set( CSHARP_MONO_INTERPRETER_${CSHARP_MONO_VERSION} ${csharp_mono_interpreter} CACHE STRING "C# Mono interpreter ${csharp_mono_version_temp}" FORCE )
      mark_as_advanced( CSHARP_MONO_INTERPRETER_${CSHARP_MONO_VERSION} )
    endif ()
    unset( csharp_mono_interpreter CACHE )

    # We found Mono compiler
    set( CSHARP_MONO_VERSION ${csharp_mono_version_temp} CACHE STRING "C# Mono compiler version" )
    mark_as_advanced( CSHARP_MONO_VERSION )
    set( CSHARP_MONO_COMPILER_${CSHARP_MONO_VERSION} ${csharp_mono_compiler} CACHE STRING "C# Mono compiler ${CSHARP_MONO_VERSION}" FORCE )
    mark_as_advanced( CSHARP_MONO_COMPILER_${CSHARP_MONO_VERSION} )
    set( CSHARP_MONO_VERSIONS ${CSHARP_MONO_VERSION} CACHE STRING "Available C# Mono compiler versions" FORCE )
    mark_as_advanced( CSHARP_MONO_VERSIONS )
    set( CSHARP_MONO_FOUND 1 CACHE INTERNAL "Boolean indicating if C# Mono was found" )
  endif()

  # Remove temp variable from cache
  unset( csharp_mono_compiler CACHE )

endif()

if( CSHARP_MONO_FOUND )
  # Report the found versions
  message( STATUS "Found the following C# Mono versions: ${CSHARP_MONO_VERSIONS}" )
endif()

# Set USE_FILE
get_filename_component( current_list_path ${CMAKE_CURRENT_LIST_FILE} PATH )
set( Mono_USE_FILE ${current_list_path}/UseMono.cmake )


text:
package Rex::JobControl::Rexfile;
$Rex::JobControl::Rexfile::VERSION = '0.18.0';
use Mojo::Base 'Mojolicious::Controller';
use Cwd;
use File::Spec;

sub prepare_stash {
  my $self = shift;

  my $project = $self->project( $self->param("project_dir") );
  $self->stash( project => $project );

  my $rexfile = $project->get_rexfile( $self->param("rexfile_dir") );
  $self->stash( rexfile => $rexfile );
}

sub index {
  my $self = shift;
  $self->render;
}

sub rexfile_new {
  my $self = shift;
  $self->render;
}

sub rexfile_new_create {
  my $self = shift;

  $self->app->log->debug( "Got project name: " . $self->param("project_dir") );
  $self->app->log->debug( "Got rexfile name: " . $self->param("rexfile_name") );

  my $pr = $self->project( $self->param("project_dir") );

  my $rexfile_archive = $self->param("rexfile_archive");

  if ( $rexfile_archive && $rexfile_archive->filename ) {
    $self->app->log->debug(
      "This is a fileupload: " . $rexfile_archive->filename );

    if ( $self->req->is_limit_exceeded ) {

      # $ENV{MOJO_MAX_MESSAGE_SIZE} = 1073741824;
      $self->flash(
        {
          title => "File too large.",
          message =>
            "You have reached the upload file limit. You can set this limit higher in the configuration file.",
        }
      );
      return $self->redirect_to( "/project/" . $self->param("project_dir") );
    }

    if ( $rexfile_archive->filename =~ m/\.tar\.gz$/ ) {
      if ( !-d getcwd() . "/upload" ) {
        mkdir getcwd() . "/upload";
      }

      $rexfile_archive->move_to(
        File::Spec->catdir(
          $self->config->{upload_tmp_path},
          $rexfile_archive->filename
        )
      );

      $self->minion->enqueue(
        checkout_rexfile => [
          $pr->directory,
          $self->param("rexfile_name"),
          File::Spec->catdir(
            $self->config->{upload_tmp_path},
            $rexfile_archive->filename
          ),
          $self->param("rexfile_description")
        ]
      );

      $self->flash(
        {
          title => "Rexfile will be extracted in background.",
          message =>
            "Rexfile will be extracted in background. Once it it finished it will appear in the list."
        }
      );
    }
    else {
      $self->flash(
        {
          title   => "Wrong filetype",
          message => "Only .tar.gz files are allowed.",
        }
      );
      return $self->redirect_to( "/project/" . $self->param("project_dir") );
    }
  }
  else {

    $self->minion->enqueue(
      checkout_rexfile => [
        $pr->directory,              $self->param("rexfile_name"),
        $self->param("rexfile_url"), $self->param("rexfile_description")
      ]
    );

    $self->flash(
      {
        title => "Rexfile will be downloaded in background.",
        message =>
          "Rexfile will be downloaded in background. Once it it finished it will appear in the list."
      }
    );

  }

  $self->redirect_to( "/project/" . $self->param("project_dir") );
}

sub view {
  my $self = shift;
  $self->render;
}

sub reload {
  my $self = shift;

  $self->app->log->debug( "Got project name: " . $self->param("project_dir") );
  $self->app->log->debug( "Got rexfile name: " . $self->param("rexfile_name") );

  my $pr      = $self->project( $self->param("project_dir") );
  my $rexfile = $pr->get_rexfile( $self->param("rexfile_dir") );

  $rexfile->reload;

  $self->redirect_to( "/project/" . $pr->directory );
}

sub remove {
  my $self = shift;

  $self->app->log->debug( "Got project name: " . $self->param("project_dir") );
  $self->app->log->debug( "Got rexfile name: " . $self->param("rexfile_name") );

  my $pr      = $self->project( $self->param("project_dir") );
  my $rexfile = $pr->get_rexfile( $self->param("rexfile_dir") );

  $rexfile->remove;

  $self->flash(
    {
      title   => "Rexfile removed",
      message => "Rexfile <b>" . $rexfile->name . "</b> removed."
    }
  );

  $self->redirect_to( "/project/" . $pr->directory );
}

1;


text:
 /*!
 * \file
 * \brief
 */ /*-------------------------------------------------------------------*/

/**
 */ /*!
 * \file  gl4cTextureFilterMinmaxTests.cpp
 * \brief Conformance tests for the ARB_texture_filter_minmax functionality.
 */ /*-------------------------------------------------------------------*/

#include "gl4cTextureFilterMinmaxTests.hpp"
#include "gluContextInfo.hpp"
#include "gluDefs.hpp"
#include "gluDrawUtil.hpp"
#include "gluObjectWrapper.hpp"
#include "gluShaderProgram.hpp"
#include "gluTexture.hpp"
#include "glwEnums.hpp"
#include "glwFunctions.hpp"
#include "tcuImageIO.hpp"
#include "tcuRenderTarget.hpp"
#include "tcuTestLog.hpp"
#include "tcuTextureUtil.hpp"

#include "deUniquePtr.hpp"

#include <map>
#include <vector>

namespace gl4cts
{

static const int   TEXTURE_FILTER_MINMAX_SIZE			  = 32;
static const float TEXTURE_FILTER_MINMAX_DOWNSCALE_FACTOR = 0.57f;
static const float TEXTURE_FILTER_MINMAX_UPSCALE_FACTOR   = 1.63f;

TextureFilterMinmaxUtils::TextureFilterMinmaxUtils()
{
	m_reductionModeParams.push_back(ReductionModeParam(GL_MIN, false));
	m_reductionModeParams.push_back(ReductionModeParam(GL_WEIGHTED_AVERAGE_ARB, false));
	m_reductionModeParams.push_back(ReductionModeParam(GL_MAX, false));

	m_supportedTextureTypes.push_back(new Texture1D());
	m_supportedTextureTypes.push_back(new Texture1DArray());
	m_supportedTextureTypes.push_back(new Texture2D());
	m_supportedTextureTypes.push_back(new Texture2DArray());
	m_supportedTextureTypes.push_back(new Texture3D());
	m_supportedTextureTypes.push_back(new TextureCube());

	m_supportedTextureDataTypes.push_back(SupportedTextureDataType(GL_RED, GL_FLOAT, MINMAX));
	m_supportedTextureDataTypes.push_back(SupportedTextureDataType(GL_RED, GL_UNSIGNED_BYTE, MINMAX));
	m_supportedTextureDataTypes.push_back(
		SupportedTextureDataType(GL_DEPTH_COMPONENT, GL_FLOAT, MINMAX | EXCLUDE_3D | EXCLUDE_CUBE));
	m_supportedTextureDataTypes.push_back(
		SupportedTextureDataType(GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, MINMAX | EXCLUDE_3D | EXCLUDE_CUBE));
}

TextureFilterMinmaxUtils::~TextureFilterMinmaxUtils()
{
	for (SupportedTextureTypeIter iter = m_supportedTextureTypes.begin(); iter != m_supportedTextureTypes.end(); ++iter)
	{
		SupportedTextureType* textureType = *iter;
		delete textureType;
	}
}

// SupportedTextureType

void TextureFilterMinmaxUtils::SupportedTextureType::replaceAll(std::string& str, const std::string& from,
																const std::string& to)
{
	size_t start = 0;
	while ((start = str.find(from, start)) != std::string::npos)
	{
		str.replace(start, from.length(), to);
		start += to.length();
	}
}

TextureFilterMinmaxUtils::SupportedTextureType::SupportedTextureType(glw::GLenum		type,
																	 const std::string& shaderTexcoordType,
																	 const std::string& shaderSamplerType)
	: m_type(type)
{
	m_vertexShader = "#version 450 core\n"
					 "in highp vec2 position;\n"
					 "in <texcoord_type> inTexcoord;\n"
					 "out <texcoord_type> texcoord;\n"
					 "void main()\n"
					 "{\n"
					 "	texcoord = inTexcoord;\n"
					 "	gl_Position = vec4(position, 0.0, 1.0);\n"
					 "}\n";

	m_fragmentShader = "#version 450 core\n"
					   "uniform <sampler_type> sampler;\n"
					   "in <texcoord_type> texcoord;\n"
					   "out vec4 color;\n"
					   "void main()\n"
					   "{\n"
					   "	color = texture(sampler, texcoord);\n"
					   "}\n";

	replaceAll(m_vertexShader, "<texcoord_type>", shaderTexcoordType);
	replaceAll(m_fragmentShader, "<texcoord_type>", shaderTexcoordType);
	replaceAll(m_fragmentShader, "<sampler_type>", shaderSamplerType);
}

void TextureFilterMinmaxUtils::SupportedTextureType::renderToFBO(const glu::RenderContext& context,
																 glw::GLuint resultTextureId, tcu::IVec2 size,
																 glw::GLint reductionMode)
{
	const glw::Functions& gl = context.getFunctions();

	gl.bindTexture(GL_TEXTURE_2D, resultTextureId);
	GLU_EXPECT_NO_ERROR(gl.getError(), "glBindTexture() call failed.");

	gl.texStorage2D(GL_TEXTURE_2D, 1, GL_RGBA8, size.x(), size.y());
	GLU_EXPECT_NO_ERROR(gl.getError(), "glTexStorage2D() call failed.");

	glw::GLuint fbo = 0;
	gl.genFramebuffers(1, &fbo);
	GLU_EXPECT_NO_ERROR(gl.getError(), "genFramebuffers error occurred");

	gl.bindFramebuffer(GL_FRAMEBUFFER, fbo);
	GLU_EXPECT_NO_ERROR(gl.getError(), "bindFramebuffer error occurred");

	gl.framebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, resultTextureId, 0);
	GLU_EXPECT_NO_ERROR(gl.getError(), "framebufferTexture2D error occurred");

	if (gl.checkFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
	{
		throw 0;
	}

	gl.viewport(0, 0, size.x(), size.y());
	renderQuad(context, reductionMode);

	gl.deleteFramebuffers(1, &fbo);
}

void TextureFilterMinmaxUtils::SupportedTextureType::renderQuad(const glu::RenderContext& context,
																glw::GLint				  reductionMode)
{
	const glw::Functions& gl = context.getFunctions();

	deUint16 const quadIndices[] = { 0, 1, 2, 2, 1, 3 };

	float const position[] = { -1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f };

	std::vector<float> texCoords = getTexCoords();

	glu::VertexArrayBinding vertexArrays[] = { glu::va::Float("position", 2, 4, 0, position),
											   glu::va::Float("inTexcoord", 1, 4, 0, texCoords.data()) };

	gl.bindTexture(m_type, this->getTextureGL());
	GLU_EXPECT_NO_ERROR(gl.getError(), "glBindTexture() call failed.");

	gl.texParameteri(m_type, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	gl.texParameteri(m_type, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	gl.texParameteri(m_type, GL_TEXTURE_REDUCTION_MODE_ARB, reductionMode);

	glu::ShaderProgram program(context, glu::makeVtxFragSources(m_vertexShader, m_fragmentShader));
	if (!program.isOk())
	{
		TCU_FAIL("Shader compilation failed");
	}

	gl.useProgram(program.getProgram());
	GLU_EXPECT_NO_ERROR(gl.getError(), "glUseProgram failed");

	gl.uniform1i(gl.getUniformLocation(program.getProgram(), "sampler"), 0);
	GLU_EXPECT_NO_ERROR(gl.getError(), "glUniform1i failed");

	gl.clear(GL_COLOR_BUFFER_BIT);

	glu::draw(context, program.getProgram(), DE_LENGTH_OF_ARRAY(vertexArrays), vertexArrays,
			  glu::pr::TriangleStrip(DE_LENGTH_OF_ARRAY(quadIndices), quadIndices));
}

// Texture1D

TextureFilterMinmaxUtils::Texture1D::Texture1D() : SupportedTextureType(GL_TEXTURE_1D, "float", "sampler1D")
{
}

glw::GLuint TextureFilterMinmaxUtils::Texture1D::getTextureGL()
{
	return m_texture->getGLTexture();
}

std::vector<float> TextureFilterMinmaxUtils::Texture1D::getTexCoords()
{
	float const texCoord[] = { 0.0f, 0.0f, 1.0f, 1.0f };
	return std::vector<float>(texCoord, texCoord + sizeof(texCoord) / sizeof(float));
}

void TextureFilterMinmaxUtils::Texture1D::generate(const glu::RenderContext& context, tcu::IVec3 size,
												   glw::GLenum format, glw::GLenum type, bool generateMipmaps)
{
	const glw::Functions& gl = context.getFunctions();

	m_texture = de::MovePtr<glu::Texture1D>(new glu::Texture1D(context, format, type, size.x()));

	m_texture->getRefTexture().allocLevel(0);
	if (generateMipmaps)
	{
		m_texture->getRefTexture().allocLevel(1);
	}
	GLU_EXPECT_NO_ERROR(gl.getError(), "glu::Texture1D error occurred");

	tcu::fillWithGrid(m_texture->getRefTexture().getLevel(0), 4, tcu::Vec4(1.0f, 1.0f, 1.0f, 1.0f),
					  tcu::Vec4(0.0f, 0.0f, 0.0f, 1.0f));
	GLU_EXPECT_NO_ERROR(gl.getError(), "glu::Texture1D error occurred");

	m_texture->upload();
	GLU_EXPECT_NO_ERROR(gl.getError(), "glu::Texture1D error occurred");

	if (generateMipmaps)
	{
		gl.generateTextureMipmap(m_texture->getGLTexture());
	}

	gl.activeTexture(GL_TEXTURE0);
}

// Texture1DArray

TextureFilterMinmaxUtils::Texture1DArray::Texture1DArray()
	: SupportedTextureType(GL_TEXTURE_1D_ARRAY, "vec2", "sampler1DArray")
{
}

glw::GLuint TextureFilterMinmaxUtils::Texture1DArray::getTextureGL()
{
	return m_texture->getGLTexture();
}

std::vector<float> TextureFilterMinmaxUtils::Texture1DArray::getTexCoords()
{
	float const texCoord[] = { 0.0f, 0.5f, 0.0f, 0.5f, 1.0f, 0.5f, 1.0f, 0.5f };
	return std::vector<float>(texCoord, texCoord + sizeof(texCoord) / sizeof(float));
}

void TextureFilterMinmaxUtils::Texture1DArray::generate(const glu::RenderContext& context, tcu::IVec3 size,
														glw::GLenum format, glw::GLenum type, bool generateMipmaps)
{
	DE_UNREF(generateMipmaps);

	const glw::Functions& gl = context.getFunctions();

	m_texture = de::MovePtr<glu::Texture1DArray>(new glu::Texture1DArray(context, format, type, size.x(), 2));

	m_texture->getRefTexture().allocLevel(0);
	m_texture->getRefTexture().allocLevel(1);
	GLU_EXPECT_NO_ERROR(gl.getError(), "glu::Texture1DArray error occurred");

	tcu::fillWithGrid(m_texture->getRefTexture().getLevel(0), 4, tcu::Vec4(1.0f, 1.0f, 1.0f, 1.0f),
					  tcu::Vec4(0.0f, 0.0f, 0.0f, 1.0f));
	GLU_EXPECT_NO_ERROR(gl.getError(), "glu::Texture1DArray error occurred");

	tcu::fillWithGrid(m_texture->getRefTexture().getLevel(1), 4, tcu::Vec4(0.0f, 1.0f, 1.0f, 1.0f),
					  tcu::Vec4(1.0f, 0.0f, 0.0f, 1.0f));
	GLU_EXPECT_NO_ERROR(gl.getError(), "glu::Texture1DArray error occurred");

	m_texture->upload();
	GLU_EXPECT_NO_ERROR(gl.getError(), "glu::Texture1DArray error occurred");

	gl.activeTexture(GL_TEXTURE0);
}

// Texture2D

TextureFilterMinmaxUtils::Texture2D::Texture2D() : SupportedTextureType(GL_TEXTURE_2D, "vec2", "sampler2D")
{
}

glw::GLuint TextureFilterMinmaxUtils::Texture2D::getTextureGL()
{
	return m_texture->getGLTexture();
}

std::vector<float> TextureFilterMinmaxUtils::Texture2D::getTexCoords()
{
	float const texCoord[] = { 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f };
	return std::vector<float>(texCoord, texCoord + sizeof(texCoord) / sizeof(float));
}

void TextureFilterMinmaxUtils::Texture2D::generate(const glu::RenderContext& context, tcu::IVec3 size,
												   glw::GLenum format, glw::GLenum type, bool generateMipmaps)
{
	const glw::Functions& gl = context.getFunctions();

	m_texture = de::MovePtr<glu::Texture2D>(new glu::Texture2D(context, format, type, size.x(), size.y()));

	m_texture->getRefTexture().allocLevel(0);
	if (generateMipmaps)
	{
		m_texture->getRefTexture().allocLevel(1);
	}
	GLU_EXPECT_NO_ERROR(gl.getError(), "glu::Texture2D error occurred");

	tcu::fillWithGrid(m_texture->getRefTexture().getLevel(0), 4, tcu::Vec4(1.0f, 1.0f, 1.0f, 1.0f),
					  tcu::Vec4(0.0f, 0.0f, 0.0f, 1.0f));
	GLU_EXPECT_NO_ERROR(gl.getError(), "glu::Texture2D error occurred");

	m_texture->upload();
	GLU_EXPECT_NO_ERROR(gl.getError(), "glu::Texture2D error occurred");

	if (generateMipmaps)
	{
		gl.generateTextureMipmap(m_texture->getGLTexture());
	}

	gl.activeTexture(GL_TEXTURE0);
}

// Texture2DArray

TextureFilterMinmaxUtils::Texture2DArray::Texture2DArray()
	: SupportedTextureType(GL_TEXTURE_2D_ARRAY, "vec3", "sampler2DArray")
{
}

glw::GLuint TextureFilterMinmaxUtils::Texture2DArray::getTextureGL()
{
	return m_texture->getGLTexture();
}

std::vector<float> TextureFilterMinmaxUtils::Texture2DArray::getTexCoords()
{
	float const texCoord[] = { 0.0f, 0.0f, 0.5f, 0.0f, 1.0f, 0.5f, 1.0f, 0.0f, 0.5f, 1.0f, 1.0f, 0.5f };
	return std::vector<float>(texCoord, texCoord + sizeof(texCoord) / sizeof(float));
}

void TextureFilterMinmaxUtils::Texture2DArray::generate(const glu::RenderContext& context, tcu::IVec3 size,
														glw::GLenum format, glw::GLenum type, bool generateMipmaps)
{
	DE_UNREF(generateMipmaps);

	const glw::Functions& gl = context.getFunctions();

	m_texture = de::MovePtr<glu::Texture2DArray>(new glu::Texture2DArray(context, format, type, size.x(), size.y(), 2));

	m_texture->getRefTexture().allocLevel(0);
	m_texture->getRefTexture().allocLevel(1);
	GLU_EXPECT_NO_ERROR(gl.getError(), "glu::Texture2DArray error occurred");

	tcu::fillWithGrid(m_texture->getRefTexture().getLevel(0), 4, tcu::Vec4(1.0f, 1.0f, 1.0f, 1.0f),
					  tcu::Vec4(0.0f, 0.0f, 0.0f, 1.0f));
	GLU_EXPECT_NO_ERROR(gl.getError(), "glu::Texture2DArray error occurred");

	tcu::fillWithGrid(m_texture->getRefTexture().getLevel(1), 4, tcu::Vec4(0.0f, 1.0f, 1.0f, 1.0f),
					  tcu::Vec4(1.0f, 0.0f, 0.0f, 1.0f));
	GLU_EXPECT_NO_ERROR(gl.getError(), "glu::Texture2DArray error occurred");

	m_texture->upload();
	GLU_EXPECT_NO_ERROR(gl.getError(), "glu::Texture2DArray error occurred");

	gl.activeTexture(GL_TEXTURE0);
}

// Texture3D

TextureFilterMinmaxUtils::Texture3D::Texture3D() : SupportedTextureType(GL_TEXTURE_3D, "vec3", "sampler3D")
{
}

glw::GLuint TextureFilterMinmaxUtils::Texture3D::getTextureGL()
{
	return m_texture->getGLTexture();
}

std::vector<float> TextureFilterMinmaxUtils::Texture3D::getTexCoords()
{
	float const texCoord[] = { 0.0f, 0.0f, 0.5f, 0.0f, 1.0f, 0.5f, 1.0f, 0.0f, 0.5f, 1.0f, 1.0f, 0.5f };
	return std::vector<float>(texCoord, texCoord + sizeof(texCoord) / sizeof(float));
}

void TextureFilterMinmaxUtils::Texture3D::generate(const glu::RenderContext& context, tcu::IVec3 size,
												   glw::GLenum format, glw::GLenum type, bool generateMipmaps)
{
	DE_UNREF(generateMipmaps);

	const glw::Functions& gl = context.getFunctions();

	m_texture = de::MovePtr<glu::Texture3D>(new glu::Texture3D(context, format, type, size.x(), size.y(), size.z()));

	m_texture->getRefTexture().allocLevel(0);
	GLU_EXPECT_NO_ERROR(gl.getError(), "glu::Texture3D error occurred");

	tcu::fillWithGrid(m_texture->getRefTexture().getLevel(0), 4, tcu::Vec4(1.0f, 1.0f, 1.0f, 1.0f),
					  tcu::Vec4(0.0f, 0.0f, 0.0f, 1.0f));
	GLU_EXPECT_NO_ERROR(gl.getError(), "glu::Texture3D error occurred");

	m_texture->upload();
	GLU_EXPECT_NO_ERROR(gl.getError(), "glu::Texture3D error occurred");

	gl.activeTexture(GL_TEXTURE0);
}

// TextureCube

TextureFilterMinmaxUtils::TextureCube::TextureCube() : SupportedTextureType(GL_TEXTURE_CUBE_MAP, "vec3", "samplerCube")
{
}

glw::GLuint TextureFilterMinmaxUtils::TextureCube::getTextureGL()
{
	return m_texture->getGLTexture();
}

std::vector<float> TextureFilterMinmaxUtils::TextureCube::getTexCoords()
{
	float const texCoord[] = { 1.0f, 1.0f, 0.0f, -1.0f, 1.0f, 0.0f, -1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f };
	return std::vector<float>(texCoord, texCoord + sizeof(texCoord) / sizeof(float));
}

void TextureFilterMinmaxUtils::TextureCube::generate(const glu::RenderContext& context, tcu::IVec3 size,
													 glw::GLenum format, glw::GLenum type, bool generateMipmaps)
{
	DE_UNREF(generateMipmaps);

	const glw::Functions& gl = context.getFunctions();

	m_texture = de::MovePtr<glu::TextureCube>(new glu::TextureCube(context, format, type, size.x()));

	for (int faceIndex = 0; faceIndex < tcu::CUBEFACE_LAST; ++faceIndex)
	{
		m_texture->getRefTexture().allocLevel((tcu::CubeFace)faceIndex, 0);
		GLU_EXPECT_NO_ERROR(gl.getError(), "glu::TextureCube error occurred");

		tcu::fillWithGrid(m_texture->getRefTexture().getLevelFace(0, (tcu::CubeFace)faceIndex), 4,
						  tcu::Vec4(1.0f, 1.0f, 1.0f, 1.0f), tcu::Vec4(0.0f, 0.0f, 0.0f, 1.0f));
		GLU_EXPECT_NO_ERROR(gl.getError(), "glu::TextureCube error occurred");
	}

	m_texture->upload();
	GLU_EXPECT_NO_ERROR(gl.getError(), "glu::TextureCube error occurred");

	gl.activeTexture(GL_TEXTURE0);
}

// TextureFilterMinmaxUtils methods

std::vector<glw::GLuint> TextureFilterMinmaxUtils::getDataFromTexture(const glu::RenderContext& context,
																	  glw::GLuint textureId, tcu::IVec2 textureSize,
																	  glw::GLenum format, glw::GLenum type)
{
	const glw::Functions& gl = context.getFunctions();

	glw::GLsizei imageLength = textureSize.x() * textureSize.y();

	std::vector<glw::GLuint> data;
	data.resize(imageLength);

	gl.bindTexture(GL_TEXTURE_2D, textureId);
	GLU_EXPECT_NO_ERROR(gl.getError(), "bindTexture error occurred");

	gl.getTexImage(GL_TEXTURE_2D, 0, format, type, &data[0]);
	GLU_EXPECT_NO_ERROR(gl.getError(), "getTexImage error occurred");

	return data;
}

glw::GLuint TextureFilterMinmaxUtils::calcPixelSumValue(const glu::RenderContext& context, glw::GLuint textureId,
														tcu::IVec2 textureSize, glw::GLenum format, glw::GLenum type)
{
	std::vector<glw::GLuint> textureData = getDataFromTexture(context, textureId, textureSize, format, type);

	glw::GLuint sum = 0;

	for (size_t texel = 0; texel < textureData.size(); ++texel)
	{
		tcu::RGBA rgba(textureData[texel]);
		sum += rgba.getRed();
		sum += rgba.getGreen();
		sum += rgba.getBlue();
		sum += rgba.getAlpha();
	}

	return sum;
}

/** Constructor.
*
*  @param context Rendering context
*/
TextureFilterMinmaxParameterQueriesTestCase::TextureFilterMinmaxParameterQueriesTestCase(deqp::Context& context)
	: TestCase(context, "TextureFilterMinmaxParameterQueries",
			   "Implements all parameter queries tests described in CTS_ARB_texture_filter_minmax")
{
	/* Left blank intentionally */
}

/** Executes test iteration.
 *
 *  @return Returns STOP when test has finished executing, CONTINUE if more iterations are needed.
 */
tcu::TestNode::IterateResult TextureFilterMinmaxParameterQueriesTestCase::iterate()
{
	if (!m_context.getContextInfo().isExtensionSupported("GL_ARB_texture_filter_minmax"))
	{
		m_testCtx.setTestResult(QP_TEST_RESULT_NOT_SUPPORTED, "Not Supported");
		return STOP;
	}

	const glw::Functions& gl = m_context.getRenderContext().getFunctions();

	testReductionModeQueriesDefaultValues(gl);

	for (TextureFilterMinmaxUtils::ReductionModeParamIter iter = m_utils.getReductionModeParams().begin();
		 iter != m_utils.getReductionModeParams().end(); ++iter)
	{
		testReductionModeQueries(gl, iter->m_reductionMode);
	}

	m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "Pass");

	return STOP;
}

void TextureFilterMinmaxParameterQueriesTestCase::testReductionModeQueriesDefaultValues(const glw::Functions& gl)
{
	const glu::RenderContext& renderContext = m_context.getRenderContext();
	de::MovePtr<glu::Sampler> sampler		= de::MovePtr<glu::Sampler>(new glu::Sampler(renderContext));
	GLU_EXPECT_NO_ERROR(gl.getError(), "glu::Sampler error occurred");

	glw::GLint params;

	gl.getSamplerParameteriv(**sampler, GL_TEXTURE_REDUCTION_MODE_ARB, &params);
	GLU_EXPECT_NO_ERROR(gl.getError(), "getSamplerParameteriv error occurred");
	TCU_CHECK_MSG(params == GL_WEIGHTED_AVERAGE_ARB, "getSamplerParameteriv value mismatch with expected default");

	for (TextureFilterMinmaxUtils::SupportedTextureTypeIter iter = m_utils.getSupportedTextureTypes().begin();
		 iter != m_utils.getSupportedTextureTypes().end(); ++iter)
	{
		TextureFilterMinmaxUtils::SupportedTextureType* textureType = *iter;

		gl.getTexParameteriv(textureType->getType(), GL_TEXTURE_REDUCTION_MODE_ARB, &params);
		GLU_EXPECT_NO_ERROR(gl.getError(), "getTexParameteriv error occurred");
		TCU_CHECK_MSG(params == GL_WEIGHTED_AVERAGE_ARB, "getTexParameteriv value mismatch with expected default");

		gl.getTexParameterIiv(textureType->getType(), GL_TEXTURE_REDUCTION_MODE_ARB, &params);
		GLU_EXPECT_NO_ERROR(gl.getError(), "getTexParameterIiv error occurred");
		TCU_CHECK_MSG(params == GL_WEIGHTED_AVERAGE_ARB, "getTexParameterIiv value mismatch with expected default");
	}

	for (TextureFilterMinmaxUtils::SupportedTextureDataTypeIter iter = m_utils.getSupportedTextureDataTypes().begin();
		 iter != m_utils.getSupportedTextureDataTypes().end(); ++iter)
	{
		de::MovePtr<glu::Texture2D> texture = de::MovePtr<glu::Texture2D>(new glu::Texture2D(
			renderContext, iter->m_format, iter->m_type, TEXTURE_FILTER_MINMAX_SIZE, TEXTURE_FILTER_MINMAX_SIZE));
		texture->upload();
		GLU_EXPECT_NO_ERROR(gl.getError(), "glu::Texture2D error occurred");

		gl.getTextureParameteriv(texture->getGLTexture(), GL_TEXTURE_REDUCTION_MODE_ARB, &params);
		GLU_EXPECT_NO_ERROR(gl.getError(), "getTextureParameteriv error occurred");
		TCU_CHECK_MSG(params == GL_WEIGHTED_AVERAGE_ARB, "getTextureParameteriv value mismatch with expected default");

		gl.getTextureParameterIiv(texture->getGLTexture(), GL_TEXTURE_REDUCTION_MODE_ARB, &params);
		GLU_EXPECT_NO_ERROR(gl.getError(), "getTextureParameterIiv error occurred");
		TCU_CHECK_MSG(params == GL_WEIGHTED_AVERAGE_ARB, "getTextureParameterIiv value mismatch with expected default");
	}
}

void TextureFilterMinmaxParameterQueriesTestCase::testReductionModeQueries(const glw::Functions& gl, glw::GLint pname)
{
	const glu::RenderContext& renderContext = m_context.getRenderContext();
	de::MovePtr<glu::Sampler> sampler		= de::MovePtr<glu::Sampler>(new glu::Sampler(renderContext));
	GLU_EXPECT_NO_ERROR(gl.getError(), "glu::Sampler error occurred");

	gl.samplerParameteri(**sampler, GL_TEXTURE_REDUCTION_MODE_ARB, pname);
	GLU_EXPECT_NO_ERROR(gl.getError(), "samplerParameteri error occurred");

	for (TextureFilterMinmaxUtils::SupportedTextureTypeIter iter = m_utils.getSupportedTextureTypes().begin();
		 iter != m_utils.getSupportedTextureTypes().end(); ++iter)
	{
		TextureFilterMinmaxUtils::SupportedTextureType* textureType = *iter;

		gl.texParameteriv(textureType->getType(), GL_TEXTURE_REDUCTION_MODE_ARB, &pname);
		GLU_EXPECT_NO_ERROR(gl.getError(), "texParameteriv error occurred");

		gl.texParameterIiv(textureType->getType(), GL_TEXTURE_REDUCTION_MODE_ARB, &pname);
		GLU_EXPECT_NO_ERROR(gl.getError(), "texParameterIiv error occurred");
	}

	for (TextureFilterMinmaxUtils::SupportedTextureDataTypeIter iter = m_utils.getSupportedTextureDataTypes().begin();
		 iter != m_utils.getSupportedTextureDataTypes().end(); ++iter)
	{
		de::MovePtr<glu::Texture2D> texture = de::MovePtr<glu::Texture2D>(new glu::Texture2D(
			renderContext, iter->m_format, iter->m_type, TEXTURE_FILTER_MINMAX_SIZE, TEXTURE_FILTER_MINMAX_SIZE));
		texture->upload();
		GLU_EXPECT_NO_ERROR(gl.getError(), "glu::Texture2D error occurred");

		gl.textureParameteriv(texture->getGLTexture(), GL_TEXTURE_REDUCTION_MODE_ARB, &pname);
		GLU_EXPECT_NO_ERROR(gl.getError(), "textureParameteriv error occurred");

		gl.textureParameterIiv(texture->getGLTexture(), GL_TEXTURE_REDUCTION_MODE_ARB, &pname);
		GLU_EXPECT_NO_ERROR(gl.getError(), "textureParameterIiv error occurred");
	}
}

/** Base class for minmax render tests. Constructor.
*
*  @param context Rendering context
*  @param name TestCase name
*  @param description TestCase description
*  @param renderScale Scale of rendered texture
*  @param mipmapping Is mipmapping enabled
*/
TextureFilterMinmaxFilteringTestCaseBase::TextureFilterMinmaxFilteringTestCaseBase(deqp::Context& context,
																				   const char*	name,
																				   const char*	description,
																				   float renderScale, bool mipmapping)
	: deqp::TestCase(context, name, description), m_renderScale(renderScale), m_mipmapping(mipmapping)
{
}

/** Executes test iteration.
*
*  @return Returns STOP when test has finished executing, CONTINUE if more iterations are needed.
*/
tcu::TestNode::IterateResult TextureFilterMinmaxFilteringTestCaseBase::iterate()
{
	if (!m_context.getContextInfo().isExtensionSupported("GL_ARB_texture_filter_minmax"))
	{
		m_testCtx.setTestResult(QP_TEST_RESULT_NOT_SUPPORTED, "Not Supported");
		return STOP;
	}

	const glu::RenderContext& renderContext = m_context.getRenderContext();
	const glw::Functions&	 gl			= renderContext.getFunctions();

	for (TextureFilterMinmaxUtils::SupportedTextureTypeIter textureTypeIter =
			 m_utils.getSupportedTextureTypes().begin();
		 textureTypeIter != m_utils.getSupportedTextureTypes().end(); ++textureTypeIter)
	{
		TextureFilterMinmaxUtils::SupportedTextureType* textureType = *textureTypeIter;

		for (TextureFilterMinmaxUtils::SupportedTextureDataTypeIter dataTypeIter =
				 m_utils.getSupportedTextureDataTypes().begin();
			 dataTypeIter != m_utils.getSupportedTextureDataTypes().end(); ++dataTypeIter)
		{
			if (!dataTypeIter->hasFlag(TextureFilterMinmaxUtils::MINMAX))
				continue;

			if (dataTypeIter->hasFlag(TextureFilterMinmaxUtils::EXCLUDE_3D) && textureType->getType() == GL_TEXTURE_3D)
				continue;

			if (dataTypeIter->hasFlag(TextureFilterMinmaxUtils::EXCLUDE_CUBE) &&
				textureType->getType() == GL_TEXTURE_CUBE_MAP)
				continue;

			std::map<glw::GLint, glw::GLuint> reductionModeTexelSumMap;

			for (TextureFilterMinmaxUtils::ReductionModeParamIter paramIter = m_utils.getReductionModeParams().begin();
				 paramIter != m_utils.getReductionModeParams().end(); ++paramIter)
			{
				if (paramIter->m_queryTestOnly)
					continue;

				tcu::IVec2 scaledTextureSize(int(float(TEXTURE_FILTER_MINMAX_SIZE) * m_renderScale));

				textureType->generate(renderContext, tcu::IVec3(TEXTURE_FILTER_MINMAX_SIZE), dataTypeIter->m_format,
									  dataTypeIter->m_type, m_mipmapping);

				glw::GLuint resultTextureId = 0;
				gl.genTextures(1, &resultTextureId);
				GLU_EXPECT_NO_ERROR(gl.getError(), "glGenTextures() call failed.");

				textureType->renderToFBO(renderContext, resultTextureId, scaledTextureSize, paramIter->m_reductionMode);

				reductionModeTexelSumMap[paramIter->m_reductionMode] = m_utils.calcPixelSumValue(
					renderContext, resultTextureId, scaledTextureSize, GL_RED, GL_UNSIGNED_BYTE);

				gl.deleteTextures(1, &resultTextureId);
			}

			TCU_CHECK_MSG(reductionModeTexelSumMap[GL_MIN] < reductionModeTexelSumMap[GL_WEIGHTED_AVERAGE_ARB],
						  "Sum of texels for GL_MIN should be smaller than for GL_WEIGHTED_AVERAGE_ARB");

			TCU_CHECK_MSG(reductionModeTexelSumMap[GL_MAX] > reductionModeTexelSumMap[GL_WEIGHTED_AVERAGE_ARB],
						  "Sum of texels for GL_MAX should be greater than for GL_WEIGHTED_AVERAGE_ARB");
		}
	}

	m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "Pass");

	return STOP;
}

/** Constructor.
*
*  @param context Rendering context
*/
TextureFilterMinmaxMinificationFilteringTestCase::TextureFilterMinmaxMinificationFilteringTestCase(
	deqp::Context& context)
	: TextureFilterMinmaxFilteringTestCaseBase(
		  context, "TextureFilterMinmaxMinificationFiltering",
		  "Implements minification filtering tests described in CTS_ARB_texture_filter_minmax",
		  TEXTURE_FILTER_MINMAX_DOWNSCALE_FACTOR, false)
{
	/* Left blank intentionally */
}

/** Constructor.
*
*  @param context Rendering context
*/
TextureFilterMinmaxMagnificationFilteringTestCase::TextureFilterMinmaxMagnificationFilteringTestCase(
	deqp::Context& context)
	: TextureFilterMinmaxFilteringTestCaseBase(
		  context, "TextureFilterMinmaxMagnificationFiltering",
		  "Implements magnification filtering tests described in CTS_ARB_texture_filter_minmax",
		  TEXTURE_FILTER_MINMAX_UPSCALE_FACTOR, false)
{
	/* Left blank intentionally */
}

/** Constructor.
*
*  @param context Rendering context
*/
TextureFilterMinmaxMipmapMinificationFilteringTestCase::TextureFilterMinmaxMipmapMinificationFilteringTestCase(
	deqp::Context& context)
	: TextureFilterMinmaxFilteringTestCaseBase(
		  context, "TextureFilterMinmaxMipmapMinificationFiltering",
		  "Implements mipmap minification filtering tests described in CTS_ARB_texture_filter_minmax",
		  TEXTURE_FILTER_MINMAX_DOWNSCALE_FACTOR, true)
{
	/* Left blank intentionally */
}

/** Constructor.
*
*  @param context Rendering context
*/
TextureFilterMinmaxSupportTestCase::TextureFilterMinmaxSupportTestCase(deqp::Context& context)
	: TestCase(context, "TextureFilterMinmaxSupport", "Implements calling GetInternalFormat* and validates with "
													  "expected result described in CTS_ARB_texture_filter_minmax")
{
}

/** Executes test iteration.
*
*  @return Returns STOP when test has finished executing, CONTINUE if more iterations are needed.
*/
tcu::TestNode::IterateResult TextureFilterMinmaxSupportTestCase::iterate()
{
	if (!m_context.getContextInfo().isExtensionSupported("GL_ARB_texture_filter_minmax"))
	{
		m_testCtx.setTestResult(QP_TEST_RESULT_NOT_SUPPORTED, "Not Supported");
		return STOP;
	}

	const glu::RenderContext& renderContext = m_context.getRenderContext();
	const glw::Functions&	 gl			= renderContext.getFunctions();

	for (TextureFilterMinmaxUtils::SupportedTextureTypeIter textureTypeIter =
			 m_utils.getSupportedTextureTypes().begin();
		 textureTypeIter != m_utils.getSupportedTextureTypes().end(); ++textureTypeIter)
	{
		TextureFilterMinmaxUtils::SupportedTextureType* textureType = *textureTypeIter;

		for (TextureFilterMinmaxUtils::SupportedTextureDataTypeIter dataTypeIter =
				 m_utils.getSupportedTextureDataTypes().begin();
			 dataTypeIter != m_utils.getSupportedTextureDataTypes().end(); ++dataTypeIter)
		{
			if (!dataTypeIter->hasFlag(TextureFilterMinmaxUtils::MINMAX))
				continue;

			if (dataTypeIter->hasFlag(TextureFilterMinmaxUtils::EXCLUDE_3D) && textureType->getType() == GL_TEXTURE_3D)
				continue;

			if (dataTypeIter->hasFlag(TextureFilterMinmaxUtils::EXCLUDE_CUBE) &&
				textureType->getType() == GL_TEXTURE_CUBE_MAP)
				continue;

			glw::GLint params = 0;
			gl.getInternalformativ(textureType->getType(), dataTypeIter->m_format, GL_TEXTURE_REDUCTION_MODE_ARB,
								   sizeof(glw::GLint), &params);
			GLU_EXPECT_NO_ERROR(gl.getError(), "getInternalformativ() call failed.");
			TCU_CHECK_MSG(params, "GetInternalformativ incorrect value");
		}
	}

	m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "Pass");

	return STOP;
}

/** Constructor.
 *
 *  @param context Rendering context.
 */
TextureFilterMinmax::TextureFilterMinmax(deqp::Context& context)
	: TestCaseGroup(context, "texture_filter_minmax_tests",
					"Verify conformance of CTS_ARB_texture_filter_minmax implementation")
{
}

/** Initializes the test group contents. */
void TextureFilterMinmax::init()
{
	addChild(new TextureFilterMinmaxParameterQueriesTestCase(m_context));
	addChild(new TextureFilterMinmaxMinificationFilteringTestCase(m_context));
	addChild(new TextureFilterMinmaxMagnificationFilteringTestCase(m_context));
	addChild(new TextureFilterMinmaxMipmapMinificationFilteringTestCase(m_context));
	addChild(new TextureFilterMinmaxSupportTestCase(m_context));
}
} /* gl4cts namespace */


text:
package de.mobilej;

import org.gradle.api.DefaultTask;
import org.gradle.api.GradleException;
import org.gradle.api.file.FileCollection;
import org.gradle.api.tasks.CacheableTask;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.InputFiles;
import org.gradle.api.tasks.OutputDirectory;
import org.gradle.api.tasks.OutputFile;
import org.gradle.api.tasks.PathSensitive;
import org.gradle.api.tasks.PathSensitivity;
import org.gradle.api.tasks.TaskAction;

import java.io.File;
import java.util.List;

import static java.util.Objects.requireNonNull;

/**
 * Gradle task to handle unmocking.
 *
 * Actual work is delegated to {@link ProcessRealAndroidJar} but this task handles defining all inputs
 * and outputs so Gradle can do proper up-to-date checking and only run the task when necessary.
 *
 * Note that all File properties specify {@link PathSensitivity} NONE. This is because the task does not care
 * about the names or paths of any of these files. All that matters to this task is that the contents of the
 * input jar can be read and that data can be written to the output directory and output jar file.
 */
@CacheableTask
public class UnMockTask extends DefaultTask {

    private FileCollection allAndroid;
    private File outputDir;
    private File unmockedOutputJar;
    private List<String> keepClasses;
    private List<String> renameClasses;
    private List<String> delegateClasses;

    @InputFiles
    @PathSensitive(PathSensitivity.NONE)
    public FileCollection getAllAndroid() {
        return allAndroid;
    }

    public void setAllAndroid(FileCollection allAndroid) {
        this.allAndroid = allAndroid;
    }

    @OutputDirectory
    public File getOutputDir() {
        return outputDir;
    }

    public void setOutputDir(File outputDir) {
        this.outputDir = outputDir;
    }

    @OutputFile
    public File getUnmockedOutputJar() {
        return unmockedOutputJar;
    }

    public void setUnmockedOutputJar(File unmockedOutputJar) {
        this.unmockedOutputJar = unmockedOutputJar;
    }

    @Input
    public List<String> getKeepClasses() {
        return keepClasses;
    }

    public void setKeepClasses(List<String> keepClasses) {
        this.keepClasses = keepClasses;
    }

    @Input
    public List<String> getRenameClasses() {
        return renameClasses;
    }

    public void setRenameClasses(List<String> renameClasses) {
        this.renameClasses = renameClasses;
    }

    @Input
    public List<String> getDelegateClasses() {
        return delegateClasses;
    }

    public void setDelegateClasses(List<String> delegateClasses) {
        this.delegateClasses = delegateClasses;
    }

    @TaskAction
    public void unmock() {
        requireNonNull(outputDir, "No output directory provided for UnMockTask");
        requireNonNull(unmockedOutputJar, "No output file name provided for UnMockTask");
        requireNonNull(keepClasses, "UnMock keep class list cannot be null");
        requireNonNull(renameClasses, "UnMock rename class list cannot be null");
        requireNonNull(delegateClasses, "UnMock delegate class list cannot be null");

        File allAndroidFile = allAndroid.getSingleFile();

        try {
            ProcessRealAndroidJar.process(
                    allAndroidFile,
                    outputDir,
                    unmockedOutputJar,
                    keepClasses.toArray(new String[0]),
                    renameClasses.toArray(new String[0]),
                    delegateClasses.toArray(new String[0]),
                    getLogger()
            );
        } catch (Exception e) {
            throw new GradleException("Exception while unmocking", e);
        }
    }
}


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('conversion', '0011_remove_falsely_zeroed_unzipped_result_size_values_20160718_1445'),
    ]

    operations = [
        migrations.AlterField(
            model_name='parametrization',
            name='out_format',
            field=models.CharField(choices=[('fgdb', 'Esri File Geodatabase'), ('shapefile', 'Esri Shapefile'), ('gpkg', 'GeoPackage'), ('spatialite', 'SpatiaLite'), ('garmin', 'Garmin navigation & map data'), ('pbf', 'OSM Protocolbuffer Binary Format')], max_length=100, verbose_name='out format'),
        ),
    ]


text:
import pygame

class Ship():

    def __init__(self, ai_settings, screen):
        """Initialize the ship and set its starting position."""
        self.screen = screen
        self.ai_settings = ai_settings

        # Load the ship image and get its rect.
        self.image = pygame.image.load('images/ship.bmp')
        self.rect = self.image.get_rect()
        self.screen_rect = screen.get_rect()

        # Start each new ship at the bottom center of the screen.
        self.rect.centerx = self.screen_rect.centerx
        self.rect.bottom = self.screen_rect.bottom

        # Store a decimal value for the ship's center.
        self.center = float(self.rect.centerx)

        # Movement flags
        self.moving_right = False
        self.moving_left = False

    def update(self):
        """Update the ship's position based on the movement flags."""
        # Update the ship's center value, not the rect.
        if self.moving_right and self.rect.right < self.screen_rect.right:
            self.center += self.ai_settings.ship_speed_factor
        if self.moving_left and self.rect.left > 0:
            self.center -= self.ai_settings.ship_speed_factor

        # Update rect object from self.center.
        self.rect.centerx = self.center

    def blitme(self):
        """Draw the ship at its current location."""
        self.screen.blit(self.image, self.rect)

    def center_ship(self):
        """Center the ship on the screen."""
        self.center = self.screen_rect.centerx


text:
**Includes a SPICE model suitable for use with LTspice**

By Martin Falatic (www.Falatic.com)

Except where otherwise noted, my contributions are licensed under the MIT license (see the LICENSE file for details).

Originally released via web 2013-01-10:

http://www.falatic.com/index.php/69/memristor-simulation-with-ltspice-a-practical-example

** These examples are provided for informational purposes ONLY. **
** No warranty is expressed or implied. **

I've been curious about memristors for a while, and decided to see if I could
model one in LTspice (since I didn't find one there). This is the result.
This is not by any means definitive, just an example of the memristor as
described in one of the more well-known papers on the subject.

This was most recently tested successfully with LTspice IV 4.23i and LTspice XVII 2016-08-24 (see install notes).

http://www.linear.com/designtools/software/#LTspice

Install the contents of the LTspice_model folder into the corresponding LTspice folders of your installation:
* For LTspice IV: "C:\Program Files\LTS\LTspiceIV" or wherever you installed it at.
* For LTspice XVII: Careful! Even though the install dirs are similar to those in IV, there is a fully copy of `examples` and `lib` in "C:\Users\%username%\Documents\LTspiceXVII", which is currently the only tree XVII reads its libs and examples from! Therefore you should put the memristor lib files with the other libs in that tree if the default doesn't work for you (not sure if this is a transient or permanent quirk).

Simulation:
* Open `memristor_sim.asc`
* Select "Simulate" -> "Run"
* Click on the graph tab
* Select "Plot Settings" -> "Open Plot Settings File"
* Select `memristor_sim.plt`
* This output should match what you see in the `memristor_sim_example.png` file

Resources used:
* SPICE Model of Memristor with Nonlinear Dopant Drift (2009, Biolek, et. al.) (can be found at http://www.radioeng.cz/fulltexts/2009/09_02_210_214.pdf)
* Discussions on EDAboard (particularly http://www.edaboard.com/thread202648.html)


text:
data_dir = './data'

# FloydHub - Use with data ID "R5KrjnANiKVhLWAkpXhNBe"
data_dir = '/input'

"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
import helper

helper.download_extract('mnist', data_dir)
helper.download_extract('celeba', data_dir)

# ## Explore the Data
# ### MNIST
# As you're aware, the [MNIST](http://yann.lecun.com/exdb/mnist/) dataset contains images of handwritten digits. You can view the first number of examples by changing `show_n_images`.

show_n_images = 25

"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
get_ipython().magic('matplotlib inline')
import os
from glob import glob
from matplotlib import pyplot

mnist_images = helper.get_batch(glob(os.path.join(data_dir, 'mnist/*.jpg'))[:show_n_images], 28, 28, 'L')
pyplot.imshow(helper.images_square_grid(mnist_images, 'L'), cmap='gray')

# ### CelebA
# The [CelebFaces Attributes Dataset (CelebA)](http://mmlab.ie.cuhk.edu.hk/projects/CelebA.html) dataset contains over 200,000 celebrity images with annotations.  Since you're going to be generating faces, you won't need the annotations.  You can view the first number of examples by changing `show_n_images`.

show_n_images = 25

"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
mnist_images = helper.get_batch(glob(os.path.join(data_dir, 'img_align_celeba/*.jpg'))[:show_n_images], 28, 28, 'RGB')
pyplot.imshow(helper.images_square_grid(mnist_images, 'RGB'))

# ## Preprocess the Data
# Since the project's main focus is on building the GANs, we'll preprocess the data for you.  The values of the MNIST and CelebA dataset will be in the range of -0.5 to 0.5 of 28x28 dimensional images.  The CelebA images will be cropped to remove parts of the image that don't include a face, then resized down to 28x28.
#
# The MNIST images are black and white images with a single [color channel](https://en.wikipedia.org/wiki/Channel_(digital_image%29) while the CelebA images have [3 color channels (RGB color channel)](https://en.wikipedia.org/wiki/Channel_(digital_image%29#RGB_Images).
# ## Build the Neural Network
# You'll build the components necessary to build a GANs by implementing the following functions below:
# - `model_inputs`
# - `discriminator`
# - `generator`
# - `model_loss`
# - `model_opt`
# - `train`
#
# ### Check the Version of TensorFlow and Access to GPU
# This will check to make sure you have the correct version of TensorFlow and access to a GPU

"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
from distutils.version import LooseVersion
import warnings
import tensorflow as tf

# Check TensorFlow Version
assert LooseVersion(tf.__version__) >= LooseVersion('1.0'), 'Please use TensorFlow version 1.0 or newer.  You are using {}'.format(tf.__version__)
print('TensorFlow Version: {}'.format(tf.__version__))

# Check for a GPU
if not tf.test.gpu_device_name():
    warnings.warn('No GPU found. Please use a GPU to train your neural network.')
else:
    print('Default GPU Device: {}'.format(tf.test.gpu_device_name()))

# ### Input
# Implement the `model_inputs` function to create TF Placeholders for the Neural Network. It should create the following placeholders:
# - Real input images placeholder with rank 4 using `image_width`, `image_height`, and `image_channels`.
# - Z input placeholder with rank 2 using `z_dim`.
# - Learning rate placeholder with rank 0.
#
# Return the placeholders in the following the tuple (tensor of real input images, tensor of z data)

import problem_unittests as tests

def model_inputs(image_width, image_height, image_channels, z_dim):
    """
    Create the model inputs
    :param image_width: The input image width
    :param image_height: The input image height
    :param image_channels: The number of image channels
    :param z_dim: The dimension of Z
    :return: Tuple of (tensor of real input images, tensor of z data, learning rate)
    """
    # TODO: Implement Function
    inputs_real = tf.placeholder(tf.float32, shape=(None, image_width, image_height, image_channels), name='input_real')
    inputs_z = tf.placeholder(tf.float32, (None, z_dim), name='input_z')
    learning_rate = tf.placeholder(tf.float32, name='learning_rate')

    return inputs_real, inputs_z, learning_rate

"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_model_inputs(model_inputs)

# ### Discriminator
# Implement `discriminator` to create a discriminator neural network that discriminates on `images`.  This function should be able to reuse the variabes in the neural network.  Use [`tf.variable_scope`](https://www.tensorflow.org/api_docs/python/tf/variable_scope) with a scope name of "discriminator" to allow the variables to be reused.  The function should return a tuple of (tensor output of the discriminator, tensor logits of the discriminator).

def discriminator(images, reuse=False):
    """
    Create the discriminator network
    :param image: Tensor of input image(s)
    :param reuse: Boolean if the weights should be reused
    :return: Tuple of (tensor output of the discriminator, tensor logits of the discriminator)
    """
    alpha = 0.2
    keep_prob=0.8

    with tf.variable_scope('discriminator', reuse=reuse):
        # using 4 layer network as in DCGAN Paper

        # Conv 1
        conv1 = tf.layers.conv2d(images, 64, 5, 2, 'SAME', kernel_initializer=tf.contrib.layers.xavier_initializer())
        lrelu1 = tf.maximum(alpha * conv1, conv1)

        # Conv 2
        conv2 = tf.layers.conv2d(lrelu1, 128, 5, 2, 'SAME', kernel_initializer=tf.contrib.layers.xavier_initializer())
        batch_norm2 = tf.layers.batch_normalization(conv2, training=True)
        lrelu2 = tf.maximum(alpha * batch_norm2, batch_norm2)
        drop2 = tf.nn.dropout(lrelu2, keep_prob=keep_prob)

        # Conv 3
        conv3 = tf.layers.conv2d(drop2, 256, 5, 1, 'SAME', kernel_initializer=tf.contrib.layers.xavier_initializer())
        batch_norm3 = tf.layers.batch_normalization(conv3, training=True)
        lrelu3 = tf.maximum(alpha * batch_norm3, batch_norm3)
        drop3 = tf.nn.dropout(lrelu3, keep_prob=keep_prob)

        # Conv 4
        conv4 = tf.layers.conv2d(drop3, 512, 5, 1, 'SAME', kernel_initializer=tf.contrib.layers.xavier_initializer())
        batch_norm4 = tf.layers.batch_normalization(conv4, training=True)
        lrelu4 = tf.maximum(alpha * batch_norm4, batch_norm4)
        drop4 = tf.nn.dropout(lrelu4, keep_prob=keep_prob)

        # Flatten
        flat = tf.reshape(drop4, (-1, 7*7*512))

        # Logits
        logits = tf.layers.dense(flat, 1)

        # Output
        out = tf.sigmoid(logits)

        return out, logits

"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_discriminator(discriminator, tf)

# ### Generator
# Implement `generator` to generate an image using `z`. This function should be able to reuse the variabes in the neural network.  Use [`tf.variable_scope`](https://www.tensorflow.org/api_docs/python/tf/variable_scope) with a scope name of "generator" to allow the variables to be reused. The function should return the generated 28 x 28 x `out_channel_dim` images.

def generator(z, out_channel_dim, is_train=True):
    """
    Create the generator network
    :param z: Input z
    :param out_channel_dim: The number of channels in the output image
    :param is_train: Boolean if generator is being used for training
    :return: The tensor output of the generator
    """
    alpha = 0.2
    keep_prob=0.8

    with tf.variable_scope('generator', reuse=False if is_train==True else True):
        # Fully connected
        fc1 = tf.layers.dense(z, 7*7*512)
        fc1 = tf.reshape(fc1, (-1, 7, 7, 512))
        fc1 = tf.maximum(alpha*fc1, fc1)

        # Starting Conv Transpose Stack
        deconv2 = tf.layers.conv2d_transpose(fc1, 256, 3, 1, 'SAME', kernel_initializer=tf.contrib.layers.xavier_initializer())
        batch_norm2 = tf.layers.batch_normalization(deconv2, training=is_train)
        lrelu2 = tf.maximum(alpha * batch_norm2, batch_norm2)
        drop2 = tf.nn.dropout(lrelu2, keep_prob=keep_prob)

        deconv3 = tf.layers.conv2d_transpose(drop2, 128, 3, 1, 'SAME', kernel_initializer=tf.contrib.layers.xavier_initializer())
        batch_norm3 = tf.layers.batch_normalization(deconv3, training=is_train)
        lrelu3 = tf.maximum(alpha * batch_norm3, batch_norm3)
        drop3 = tf.nn.dropout(lrelu3, keep_prob=keep_prob)

        deconv4 = tf.layers.conv2d_transpose(drop3, 64, 3, 2, 'SAME', kernel_initializer=tf.contrib.layers.xavier_initializer())
        batch_norm4 = tf.layers.batch_normalization(deconv4, training=is_train)
        lrelu4 = tf.maximum(alpha * batch_norm4, batch_norm4)
        drop4 = tf.nn.dropout(lrelu4, keep_prob=keep_prob)

        # Logits
        logits = tf.layers.conv2d_transpose(drop4, out_channel_dim, 3, 2, 'SAME', kernel_initializer=tf.contrib.layers.xavier_initializer())

        # Output
        out = tf.tanh(logits)

        return out

"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_generator(generator, tf)

# ### Loss
# Implement `model_loss` to build the GANs for training and calculate the loss.  The function should return a tuple of (discriminator loss, generator loss).  Use the following functions you implemented:
# - `discriminator(images, reuse=False)`
# - `generator(z, out_channel_dim, is_train=True)`

def model_loss(input_real, input_z, out_channel_dim):
    """
    Get the loss for the discriminator and generator
    :param input_real: Images from the real dataset
    :param input_z: Z input
    :param out_channel_dim: The number of channels in the output image
    :return: A tuple of (discriminator loss, generator loss)
    """
    g_model = generator(input_z, out_channel_dim)
    d_model_real, d_logits_real = discriminator(input_real)
    d_model_fake, d_logits_fake = discriminator(g_model, reuse=True)

    d_loss_real = tf.reduce_mean(
        tf.nn.sigmoid_cross_entropy_with_logits(logits=d_logits_real, labels=tf.ones_like(d_model_real) * 0.9)
    )
    d_loss_fake = tf.reduce_mean(
        tf.nn.sigmoid_cross_entropy_with_logits(logits=d_logits_fake, labels=tf.zeros_like(d_model_fake))
    )
    d_loss = d_loss_real + d_loss_fake

    g_loss = tf.reduce_mean(
        tf.nn.sigmoid_cross_entropy_with_logits(logits=d_logits_fake, labels=tf.ones_like(d_model_fake))
    )

    return d_loss, g_loss

"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_model_loss(model_loss)

# ### Optimization
# Implement `model_opt` to create the optimization operations for the GANs. Use [`tf.trainable_variables`](https://www.tensorflow.org/api_docs/python/tf/trainable_variables) to get all the trainable variables.  Filter the variables with names that are in the discriminator and generator scope names.  The function should return a tuple of (discriminator training operation, generator training operation).

def model_opt(d_loss, g_loss, learning_rate, beta1):
    """
    Get optimization operations
    :param d_loss: Discriminator loss Tensor
    :param g_loss: Generator loss Tensor
    :param learning_rate: Learning Rate Placeholder
    :param beta1: The exponential decay rate for the 1st moment in the optimizer
    :return: A tuple of (discriminator training operation, generator training operation)
    """
    t_vars = tf.trainable_variables()
    d_vars = [var for var in t_vars if var.name.startswith('discriminator')]
    g_vars = [var for var in t_vars if var.name.startswith('generator')]

    # Optimize
    d_train_opt = tf.train.AdamOptimizer(learning_rate, beta1=beta1).minimize(d_loss, var_list=d_vars)

    with tf.control_dependencies(tf.get_collection(tf.GraphKeys.UPDATE_OPS, scope='generator')):
        g_train_opt = tf.train.AdamOptimizer(learning_rate = learning_rate,beta1 = beta1).minimize(g_loss, var_list = g_vars)

    return d_train_opt, g_train_opt

"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_model_opt(model_opt, tf)

# ## Neural Network Training
# ### Show Output
# Use this function to show the current output of the generator during training. It will help you determine how well the GANs is training.

"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
import numpy as np

def show_generator_output(sess, n_images, input_z, out_channel_dim, image_mode):
    """
    Show example output for the generator
    :param sess: TensorFlow session
    :param n_images: Number of Images to display
    :param input_z: Input Z Tensor
    :param out_channel_dim: The number of channels in the output image
    :param image_mode: The mode to use for images ("RGB" or "L")
    """
    cmap = None if image_mode == 'RGB' else 'gray'
    z_dim = input_z.get_shape().as_list()[-1]
    example_z = np.random.uniform(-1, 1, size=[n_images, z_dim])

    samples = sess.run(
        generator(input_z, out_channel_dim, False),
        feed_dict={input_z: example_z})

    images_grid = helper.images_square_grid(samples, image_mode)
    pyplot.imshow(images_grid, cmap=cmap)
    pyplot.show()

# ### Train
# Implement `train` to build and train the GANs.  Use the following functions you implemented:
# - `model_inputs(image_width, image_height, image_channels, z_dim)`
# - `model_loss(input_real, input_z, out_channel_dim)`
# - `model_opt(d_loss, g_loss, learning_rate, beta1)`
#
# Use the `show_generator_output` to show `generator` output while you train. Running `show_generator_output` for every batch will drastically increase training time and increase the size of the notebook.  It's recommended to print the `generator` output every 100 batches.

def train(epoch_count, batch_size, z_dim, learning_rate, beta1, get_batches, data_shape, data_image_mode):
    """
    Train the GAN
    :param epoch_count: Number of epochs
    :param batch_size: Batch Size
    :param z_dim: Z dimension
    :param learning_rate: Learning Rate
    :param beta1: The exponential decay rate for the 1st moment in the optimizer
    :param get_batches: Function to get batches
    :param data_shape: Shape of the data
    :param data_image_mode: The image mode to use for images ("RGB" or "L")
    """
    tf.reset_default_graph()
    input_real, input_z, _ = model_inputs(data_shape[1], data_shape[2], data_shape[3], z_dim)
    d_loss, g_loss = model_loss(input_real, input_z, data_shape[3])
    d_opt, g_opt = model_opt(d_loss, g_loss, learning_rate, beta1)

    steps = 0

    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        for epoch_i in range(epoch_count):
            for batch_images in get_batches(batch_size):
                batch_images = batch_images * 2
                steps += 1

                batch_z = np.random.uniform(-1, 1, size=(batch_size, z_dim))

                _ = sess.run(d_opt, feed_dict={input_real: batch_images, input_z: batch_z})
                _ = sess.run(g_opt, feed_dict={input_z: batch_z})

                if steps % 100 == 0:
                    train_loss_d = d_loss.eval({input_z: batch_z, input_real: batch_images})
                    train_loss_g = g_loss.eval({input_z: batch_z})

                    print("Epoch {}/{}...".format(epoch_i+1, epochs),
                          "Discriminator Loss: {:.4f}...".format(train_loss_d),
                          "Generator Loss: {:.4f}".format(train_loss_g))

                    _ = show_generator_output(sess, 1, input_z, data_shape[3], data_image_mode)

# ### MNIST
# Test your GANs architecture on MNIST.  After 2 epochs, the GANs should be able to generate images that look like handwritten digits.  Make sure the loss of the generator is lower than the loss of the discriminator or close to 0.

batch_size = 32
z_dim = 100
learning_rate = 0.0002
beta1 = 0.5

"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
epochs = 2

mnist_dataset = helper.Dataset('mnist', glob(os.path.join(data_dir, 'mnist/*.jpg')))
with tf.Graph().as_default():
    train(epochs, batch_size, z_dim, learning_rate, beta1, mnist_dataset.get_batches,
          mnist_dataset.shape, mnist_dataset.image_mode)

# ### CelebA
# Run your GANs on CelebA.  It will take around 20 minutes on the average GPU to run one epoch.  You can run the whole epoch or stop when it starts to generate realistic faces.

batch_size = 64
z_dim = 100
learning_rate = 0.0002
beta1 = 0.5

"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
epochs = 1

celeba_dataset = helper.Dataset('celeba', glob(os.path.join(data_dir, 'img_align_celeba/*.jpg')))
with tf.Graph().as_default():
    train(epochs, batch_size, z_dim, learning_rate, beta1, celeba_dataset.get_batches,
          celeba_dataset.shape, celeba_dataset.image_mode)

# ### Submitting This Project
# When submitting this project, make sure to run all the cells before saving the notebook. Save the notebook file as "dlnd_face_generation.ipynb" and save it as a HTML file under "File" -> "Download as". Include the "helper.py" and "problem_unittests.py" files in your submission.

print("Done")


text:
@interface ACAccountStoreMock : ACAccountStore
@property (nonatomic) NSString* method;
@property (nonatomic) id handler;
- (void)requestAccessToAccountsWithType:(ACAccountType *)accountType withCompletionHandler:(ACAccountStoreRequestAccessCompletionHandler)handler;
- (void)requestAccessToAccountsWithType:(ACAccountType *)accountType options:(NSDictionary *)options completion:(ACAccountStoreRequestAccessCompletionHandler)completion;
- (void)renewCredentialsForAccount:(ACAccount *)account completion:(ACAccountStoreCredentialRenewalHandler)completionHandler;
- (void)removeAccount:(ACAccount *)account withCompletionHandler:(ACAccountStoreRemoveCompletionHandler)completionHandler;
@end

@implementation ACAccountStoreMock
- (void)requestAccessToAccountsWithType:(ACAccountType *)accountType withCompletionHandler:(ACAccountStoreRequestAccessCompletionHandler)handler
{
    self.handler = handler;
    self.method  = @"requestAccessToAccountsWithType:withCompletionHandler:";
}
- (void)requestAccessToAccountsWithType:(ACAccountType *)accountType options:(NSDictionary *)options completion:(ACAccountStoreRequestAccessCompletionHandler)completion
{
    self.handler = completion;
    self.method  = @"requestAccessToAccountsWithType:options:completion:";
}
- (void)renewCredentialsForAccount:(ACAccount *)account completion:(ACAccountStoreCredentialRenewalHandler)completionHandler
{
    self.handler = completionHandler;
    self.method  = @"renewCredentialsForAccount:completion:";
}
- (void)removeAccount:(ACAccount *)account withCompletionHandler:(ACAccountStoreRemoveCompletionHandler)completionHandler
{
    self.handler = completionHandler;
    self.method  = @"removeAccount:withCompletionHandler:";
}
@end

SPEC_BEGIN(ACAccountStoreSpec)

describe(@"AsyncResult generated by", ^{
    registerMatchers(@"AR");

    __block id<AsyncResult>     result  = nil;
    __block HandlerMock*        handler = nil;
    __block ACAccountStoreMock* mock    = nil;
    __block ACAccountType*      accType = nil;
    __block ACAccount*          account = nil;

    beforeEach(^{
        handler = [[HandlerMock alloc] init];
        mock    = [[ACAccountStoreMock alloc] init];
        accType = [mock accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
        account = [[ACAccount alloc] initWithAccountType:accType];
    });

    afterEach(^{
        result  = nil;
        handler = [handler clear];
        mock    = nil;
        accType = nil;
        account = nil;
    });

    context(@"requestAccessToAccountsWithType:", ^{

        it(@"should success when twitter account access is granted", ^{
            result = [mock requestAccessToAccountsWithType:accType];
            asyncWait(result, handler.block);

            void(^callback)(BOOL, NSError*) = mock.handler;
            callback(YES, nil);

            [[handler should] beCalledWithValue:mock result:result onMainThread:YES];
            [[handler.lastCall.metadata should] equal:@{ @"accountStore":mock }];
            [[mock.method should] equal:@"requestAccessToAccountsWithType:withCompletionHandler:"];
        });

        it(@"should error when twitter account access is rejected", ^{
            result = [mock requestAccessToAccountsWithType:accType];
            asyncWait(result, handler.block);

            void(^callback)(BOOL, NSError*) = mock.handler;
            NSError* error = [[NSError alloc] initWithDomain:ACErrorDomain code:ACErrorPermissionDenied userInfo:nil];
            callback(NO, error);

            [[handler should] beCalledWithError:error result:result onMainThread:YES];
            [[handler.lastCall.metadata should] equal:@{ @"accountStore":mock }];
            [[mock.method should] equal:@"requestAccessToAccountsWithType:withCompletionHandler:"];
        });

        it(@"should error when twitter account access is rejected even without error information", ^{
            result = [mock requestAccessToAccountsWithType:accType];
            asyncWait(result, handler.block);

            void(^callback)(BOOL, NSError*) = mock.handler;
            callback(NO, nil);

            [[handler should] beCalledWithError:nil result:result onMainThread:YES];
            [[handler.lastCall.metadata should] equal:@{ @"accountStore":mock }];
            [[mock.method should] equal:@"requestAccessToAccountsWithType:withCompletionHandler:"];
        });

    });

    context(@"requestAccessToAccountsWithType:options:", ^{

        it(@"should success when twitter account access is granted", ^{
            result = [mock requestAccessToAccountsWithType:accType options:nil];
            asyncWait(result, handler.block);

            void(^callback)(BOOL, NSError*) = mock.handler;
            callback(YES, nil);

            [[handler should] beCalledWithValue:mock result:result onMainThread:YES];
            [[handler.lastCall.metadata should] equal:@{ @"accountStore":mock }];
            [[mock.method should] equal:@"requestAccessToAccountsWithType:options:completion:"];
        });

        it(@"should error when twitter account access is rejected", ^{
            result = [mock requestAccessToAccountsWithType:accType options:nil];
            asyncWait(result, handler.block);

            void(^callback)(BOOL, NSError*) = mock.handler;
            NSError* error = [[NSError alloc] initWithDomain:ACErrorDomain code:ACErrorPermissionDenied userInfo:nil];
            callback(NO, error);

            [[handler should] beCalledWithError:error result:result onMainThread:YES];
            [[handler.lastCall.metadata should] equal:@{ @"accountStore":mock }];
            [[mock.method should] equal:@"requestAccessToAccountsWithType:options:completion:"];
        });

        it(@"should error when twitter account access is rejected even without error information", ^{
            result = [mock requestAccessToAccountsWithType:accType options:nil];
            asyncWait(result, handler.block);

            void(^callback)(BOOL, NSError*) = mock.handler;
            callback(NO, nil);

            [[handler should] beCalledWithError:nil result:result onMainThread:YES];
            [[handler.lastCall.metadata should] equal:@{ @"accountStore":mock }];
            [[mock.method should] equal:@"requestAccessToAccountsWithType:options:completion:"];
        });

    });

    context(@"renewCredentialsForAccount:", ^{

        it(@"should success when the account is renewed", ^{
            result = [mock renewCredentialsForAccount:account];
            asyncWait(result, handler.block);

            void(^callback)(ACAccountCredentialRenewResult, NSError*) = mock.handler;
            callback(ACAccountCredentialRenewResultRenewed, nil);

            NSDictionary* metadata = @{ @"accountStore":mock, @"account":account, @"renewResult":[[NSNumber alloc] initWithInteger:ACAccountCredentialRenewResultRenewed] };
            [[handler should] beCalledWithValue:account result:result onMainThread:YES];
            [[handler.lastCall.metadata should] equal:metadata];
            [[mock.method should] equal:@"renewCredentialsForAccount:completion:"];
        });

        it(@"should error when renewing the account is rejected", ^{
            result = [mock renewCredentialsForAccount:account];
            asyncWait(result, handler.block);

            void(^callback)(ACAccountCredentialRenewResult, NSError*) = mock.handler;
            NSError* error = [[NSError alloc] initWithDomain:ACErrorDomain code:ACErrorPermissionDenied userInfo:nil];
            callback(ACAccountCredentialRenewResultRejected, error);

            NSDictionary* metadata = @{ @"accountStore":mock, @"account":account, @"renewResult":[[NSNumber alloc] initWithInteger:ACAccountCredentialRenewResultRejected] };
            [[handler should] beCalledWithError:error result:result onMainThread:YES];
            [[handler.lastCall.metadata should] equal:metadata];
            [[mock.method should] equal:@"renewCredentialsForAccount:completion:"];
        });

        it(@"should error when renewing the account is rejected even without error information", ^{
            result = [mock renewCredentialsForAccount:account];
            asyncWait(result, handler.block);

            void(^callback)(ACAccountCredentialRenewResult, NSError*) = mock.handler;
            callback(ACAccountCredentialRenewResultFailed, nil);

            NSDictionary* metadata = @{ @"accountStore":mock, @"account":account, @"renewResult":[[NSNumber alloc] initWithInteger:ACAccountCredentialRenewResultFailed] };
            [[handler should] beCalledWithError:nil result:result onMainThread:YES];
            [[handler.lastCall.metadata should] equal:metadata];
            [[mock.method should] equal:@"renewCredentialsForAccount:completion:"];
        });

    });

    context(@"removeAccount:", ^{

        it(@"should success when the account is deleted", ^{
            result = [mock removeAccount:account];
            asyncWait(result, handler.block);

            void(^callback)(BOOL, NSError*) = mock.handler;
            callback(YES, nil);

            [[handler should] beCalledWithValue:account result:result onMainThread:YES];
            [[handler.lastCall.metadata should] equal:@{ @"accountStore":mock, @"account":account }];
            [[mock.method should] equal:@"removeAccount:withCompletionHandler:"];
        });

        it(@"should error when renewing the account is rejected", ^{
            result = [mock removeAccount:account];
            asyncWait(result, handler.block);

            void(^callback)(BOOL, NSError*) = mock.handler;
            NSError* error = [[NSError alloc] initWithDomain:ACErrorDomain code:ACErrorAccountNotFound userInfo:nil];
            callback(NO, error);

            [[handler should] beCalledWithError:error result:result onMainThread:YES];
            [[handler.lastCall.metadata should] equal:@{ @"accountStore":mock, @"account":account }];
            [[mock.method should] equal:@"removeAccount:withCompletionHandler:"];
        });

        it(@"should error when renewing the account is rejected even without error information", ^{
            result = [mock removeAccount:account];
            asyncWait(result, handler.block);

            void(^callback)(BOOL, NSError*) = mock.handler;
            callback(NO, nil);

            [[handler should] beCalledWithError:nil result:result onMainThread:YES];
            [[handler.lastCall.metadata should] equal:@{ @"accountStore":mock, @"account":account }];
            [[mock.method should] equal:@"removeAccount:withCompletionHandler:"];
        });

    });

});

SPEC_END


text:
const path = require('path');
const webpack = require('webpack');
const { execSync } = require('child_process');

// prettier-ignore
webpack(
  {
    entry: './index.js',
    output: {
      path: path.resolve(__dirname, 'dist'),
      filename: 'bundle.js',
    },
    target: 'node',
    mode: 'development',
  },
  function(err, stats) {
    if (err) {
      console.error(err.stack || err);
      if (err.details) {
        console.error(err.details);
      }
      return;
    }

    const info = stats.toJson();

    if (stats.hasErrors()) {
      console.error(info.errors);
      process.exit(1);
    }

    if (stats.hasWarnings()) {
      console.warn(info.warnings);
      process.exit(1);
    }
    runTests();
  }
);

function runTests() {
  try {
    execSync('node ' + path.resolve(__dirname, 'dist', 'bundle.js'));
  } catch (_) {
    process.exit(1);
  }
}


text:
using ServiceStack.ServiceHost;
using Nonagon.Modular.DynamicForm.Operations;

namespace Nonagon.Modular.DynamicForm.Service
{
	[Route("/formInstance/{FormInstanceId}")]
	public class GetFormInstanceDetails : GetFormInstanceDetailsOperation.Param {}

	[Route("/formInstanceByRef/{Reference}")]
	public class GetFormInstanceDetailsByRef : GetFormInstanceDetailsOperation.Param {}
}


text:
A little while back, there was an article in the
Verge
discussing Microsoft's long-term thinking around the mobile internet experience.
The particular point in the article that caught my eye was that Satya (CEO) and
Qi (VP of ASG) believe the future of mobile internet lies in what they call a
"conversation canvas." The premise is that today's model for interacting with
the Internet on mobile devices is fundamentally flawed, leaving users generally
unhappy and doing the majority of their Internet browsing on conventional
desktops.

The idea is that the "conversation canvas" will allow a more natural way to
interface with your mobile device and increase engagement on mobile platforms.
Much of this idea is based around improvements in AI and natural language
processing, allowing users to interact with their devices in a more natural way.
While I don't know how I feel yet about talking to Siri or Cortana or Alexa
(what does Google call theirs?), I recognize the value in the idea and am quite
pleased that smart people in my own company are as convinced as I am that user
interfaces could be so much better.

Now I said I'm not sold on the "natural" interface by itself -- but the article
got me thinking about what I dislike about user interfaces. Windows, macOS, and
*nix share the same general model for desktop user interfaces. Android, iOS, and
Windows Phone share the same general model for mobile user interfaces. These
models work, but they're not great. Depending on how you feel, they're anywhere
from bad to slightly above mediocre.

So if the answer isn't today's model and if I'm not convinced it's necessarily
the "natural" interface, then what is it?

Text.

Seriously?

Yes. Text.

Think about how you interact with your computer today. It's primarily text
manipulation. You write emails, papers, text messages (SMS, Facebook, WhatsApp,
etc), search terms, notes, and so on. If you're not writing, you're reading
because that is the human mechanism that is most common for conveying
information. For simplicity's sake, let's not think too hard about graphic
artists or gamers (I consider these closely tied in interface models, especially
with the advent of VR). They are an interaction model that has more in common
with the "conversation canvas" mentioned above and I don't know enough about the
space to babble meaningfully about it.

History Detour: Once upon a time, there was a computer known as the
Canon Cat. This machine
was designed by Jef Raskin, the famed designer of the original Macintosh
computer. It had a novel text-only user interface combined with a special
keyboard. The keyboard combined the standard QWERTY layout with a pair of meta
keys1 that allowed you to invoke meaningful
commands that interact with the text user interface. The beauty of this system
was the speed with which one could navigate it and query information - for
example looking up the definition of a word on screen or bringing up a list of
adjectives for a highlighted word. Extrapolate that to programming which isn't
all that different from writing and you've got a very productive environment.

The problem with our user interfaces today are that they're not high fidelity
enough with the mediums we interact with. The "conversation canvas", NUI, and VR
are one approach to improving fidelity with visual and physical mediums. The
approach Jef Raskin developed with the Canon Cat is a way to improve fidelity
with certain text mediums. In fact, the Internet, as Tim Berners-Lee imagined it
was meant to improve the fidelity of our experience with text.

So what do we do? Well - it's clear that we're in the age of VR/AR now. Facebook
has Oculus, Steam has their on VR system, and Microsoft is developing HoloLens.
In developer tools, we've seen things like Chris Granger's
LightTable project as well as things like
Haskell for Mac. I've not seen an
improved text interface for word processing yet. It seems like this space may be
ripe for innovation - an immersive experience that better ties together the
practice of writing, researching, and reading.

1.
Here's a video that
will better explain the interface.


text:
'use strict';
/**
 * Module dependencies.
 */
const path = require('path'),
  authpolicy = require('../auth/apiv2.server.auth.js'),
  devicesController = require('../controllers/devices.server.controller');

module.exports = function (app) {
  app.route('/apiv3/devices/update/:deviceId')
    .all(authpolicy.isAllowed)
    .put(devicesController.updateMediaPlayer);
};


text:
package std.util;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import net.sf.json.JSONObject;

/**
 * Helper
 *
 * <pre>
 * 注意:已应用单例模式、序列化
 * 参考:java.lang.System
 */
public class Helper implements Serializable {

	private static final long serialVersionUID = 1L;
	private static volatile Helper instance = null;
	private static Map<Integer, Long> timeConsumingMap = new HashMap<Integer, Long>();
	private static final int TIME_CONSUMING_MAX_SIZE = Integer.MAX_VALUE;
	private static Map<Integer, JSONObject> repositoryDataMap = new HashMap<Integer, JSONObject>();
	private static final int REPOSITORY_DATA_MAX_SIZE = Integer.MAX_VALUE;

	private Helper() {
	}

	private static synchronized void initHelper() {
		if (null == instance)
			instance = new Helper();
	}

	public static Helper getInstance() {
		if (null == instance)
			initHelper();
		return instance;
	}

	public synchronized Integer installTimeConsuming() {
		Integer timeConsumingKey = null;
		if (timeConsumingMap.size() < TIME_CONSUMING_MAX_SIZE) {
			Random random = new Random();
			random.setSeed(System.currentTimeMillis());
			while (timeConsumingMap.containsKey(timeConsumingKey = random.nextInt(TIME_CONSUMING_MAX_SIZE)))
				;
			timeConsumingMap.put(timeConsumingKey, System.currentTimeMillis());
		}
		return timeConsumingKey;
	}

	public Long uninstallTimeConsuming(Integer timeConsumingKey) {
		return uninstallTimeConsuming(timeConsumingKey, System.currentTimeMillis());
	}

	private synchronized Long uninstallTimeConsuming(Integer timeConsumingKey, long getOutMilliseconds) {
		Long getInMilliseconds = timeConsumingMap.get(timeConsumingKey);
		timeConsumingMap.remove(timeConsumingKey);
		if (getInMilliseconds != null)
			return getOutMilliseconds - getInMilliseconds;
		return null;
	}

	public synchronized Integer createRepositoryData(long validityDuration, JSONObject repositoryDataValue) {
		Integer repositoryDataKey = null;
		if (repositoryDataMap.size() < REPOSITORY_DATA_MAX_SIZE) {
			Random random = new Random();
			random.setSeed(System.currentTimeMillis());
			while (repositoryDataMap.containsKey(repositoryDataKey = random.nextInt(REPOSITORY_DATA_MAX_SIZE)))
				;
			repositoryDataMap.put(repositoryDataKey, repositoryDataValue);
			new Thread(new RepositoryDataDestroyThread(repositoryDataKey, validityDuration, repositoryDataMap)).start();
		}
		return repositoryDataKey;
	}

	public JSONObject grabRepositoryData(Integer repositoryDataKey) {
		return repositoryDataMap.get(repositoryDataKey);
	}

}

class RepositoryDataDestroyThread implements Serializable, Runnable {

	private static final long serialVersionUID = 1L;
	private int repositoryDataKey;
	private long validityDuration;
	private Map<Integer, JSONObject> repositoryDataMap;

	public RepositoryDataDestroyThread(int repositoryDataKey, long validityDuration, Map<Integer, JSONObject> repositoryDataMap) {
		super();
		this.repositoryDataKey = repositoryDataKey;
		this.validityDuration = validityDuration;
		this.repositoryDataMap = repositoryDataMap;
	}

	public void run() {
		try {
			Thread.sleep(validityDuration);
			repositoryDataMap.remove(repositoryDataKey);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

}


text:
/*
 * Do not modify this file. This file is generated from the ec2-2015-10-01.normal.json service model.
 */
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;

using Amazon.Runtime;
using Amazon.Runtime.Internal;

namespace Amazon.EC2.Model
{
    ///
    /// Container for the parameters to the CreateFlowLogs operation.
    /// Creates one or more flow logs to capture IP traffic for a specific network interface,
    /// subnet, or VPC. Flow logs are delivered to a specified log group in Amazon CloudWatch
    /// Logs. If you specify a VPC or subnet in the request, a log stream is created in CloudWatch
    /// Logs for each network interface in the subnet or VPC. Log streams can include information
    /// about accepted and rejected traffic to a network interface. You can view the data
    /// in your log streams using Amazon CloudWatch Logs.
    ///
    ///
    /// <para>
    /// In your request, you must also specify an IAM role that has permission to publish
    /// logs to CloudWatch Logs.
    /// </para>
    ///
    public partial class CreateFlowLogsRequest : AmazonEC2Request
    {
        private string _clientToken;
        private string _deliverLogsPermissionArn;
        private string _logGroupName;
        private List<string> _resourceIds = new List<string>();
        private FlowLogsResourceType _resourceType;
        private TrafficType _trafficType;

        ///
        /// Gets and sets the property ClientToken.
        /// <para>
        /// Unique, case-sensitive identifier you provide to ensure the idempotency of the request.
        /// For more information, see How
        /// to Ensure Idempotency.
        /// </para>
        ///
        public string ClientToken
        {
            get { return this._clientToken; }
            set { this._clientToken = value; }
        }

        // Check to see if ClientToken property is set
        internal bool IsSetClientToken()
        {
            return this._clientToken != null;
        }

        ///
        /// Gets and sets the property DeliverLogsPermissionArn.
        /// <para>
        /// The ARN for the IAM role that's used to post flow logs to a CloudWatch Logs log group.
        /// </para>
        ///
        public string DeliverLogsPermissionArn
        {
            get { return this._deliverLogsPermissionArn; }
            set { this._deliverLogsPermissionArn = value; }
        }

        // Check to see if DeliverLogsPermissionArn property is set
        internal bool IsSetDeliverLogsPermissionArn()
        {
            return this._deliverLogsPermissionArn != null;
        }

        ///
        /// Gets and sets the property LogGroupName.
        /// <para>
        /// The name of the CloudWatch log group.
        /// </para>
        ///
        public string LogGroupName
        {
            get { return this._logGroupName; }
            set { this._logGroupName = value; }
        }

        // Check to see if LogGroupName property is set
        internal bool IsSetLogGroupName()
        {
            return this._logGroupName != null;
        }

        ///
        /// Gets and sets the property ResourceIds.
        /// <para>
        /// One or more subnet, network interface, or VPC IDs.
        /// </para>
        ///
        public List<string> ResourceIds
        {
            get { return this._resourceIds; }
            set { this._resourceIds = value; }
        }

        // Check to see if ResourceIds property is set
        internal bool IsSetResourceIds()
        {
            return this._resourceIds != null && this._resourceIds.Count > 0;
        }

        ///
        /// Gets and sets the property ResourceType.
        /// <para>
        /// The type of resource on which to create the flow log.
        /// </para>
        ///
        public FlowLogsResourceType ResourceType
        {
            get { return this._resourceType; }
            set { this._resourceType = value; }
        }

        // Check to see if ResourceType property is set
        internal bool IsSetResourceType()
        {
            return this._resourceType != null;
        }

        ///
        /// Gets and sets the property TrafficType.
        /// <para>
        /// The type of traffic to log.
        /// </para>
        ///
        public TrafficType TrafficType
        {
            get { return this._trafficType; }
            set { this._trafficType = value; }
        }

        // Check to see if TrafficType property is set
        internal bool IsSetTrafficType()
        {
            return this._trafficType != null;
        }

    }
}