text:
using namespace Palleon;

#define CLSNAME							_T("Win32EmbedControl")
#define WNDSTYLE						(WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_TABSTOP)
#define WNDSTYLEEX						(0)

#define TIMER_DELAY						16
#define TIMER_ID						1

CWin32EmbedControl::CWin32EmbedControl(HWND parentWnd, const RECT& windowRect,
	const std::tstring& executablePath, const std::tstring& workingDir)
: m_embedClient(executablePath, workingDir)
{
	if(!DoesWindowClassExist(CLSNAME))
	{
		WNDCLASSEX w;
		memset(&w, 0, sizeof(WNDCLASSEX));
		w.cbSize		= sizeof(WNDCLASSEX);
		w.lpfnWndProc	= CWindow::WndProc;
		w.lpszClassName	= CLSNAME;
		w.hbrBackground = NULL;
		w.hInstance		= GetModuleHandle(NULL);
		w.hCursor		= LoadCursor(NULL, IDC_ARROW);
		RegisterClassEx(&w);
	}

	Create(WNDSTYLEEX, CLSNAME, _T(""), WNDSTYLE, windowRect, parentWnd, this);
	SetClassPtr();

	CreateDevice();
	CreateSharedTexture();

	SetRunning(true);
}

CWin32EmbedControl::~CWin32EmbedControl()
{

}

void CWin32EmbedControl::SetRunning(bool running)
{
	if(!m_running && running)
	{
		SetTimer(m_hWnd, TIMER_ID, TIMER_DELAY, 0);
		m_running = true;
		return;
	}
	if(m_running && !running)
	{
		KillTimer(m_hWnd, TIMER_ID);
		m_running = false;
		return;
	}
}

bool CWin32EmbedControl::IsClientActive() const
{
	return m_embedClientActive;
}

std::string CWin32EmbedControl::ExecuteCommand(const std::string& command)
{
	std::string commandResult;
	if(m_embedClientActive)
	{
		//Disable timer to that we don't get in a situation where
		//the control is locked because lots of WM_TIMER messages are sent
		bool runningBefore = m_running;
		SetRunning(false);

		BSTR rpcCommandResult = nullptr;
		BSTR rpcCommand = SysAllocString(string_cast<std::wstring>(command).c_str());

		auto application = m_embedClient.GetApplication();
		HRESULT result = application->NotifyExternalCommand(rpcCommand, &rpcCommandResult);

		SysFreeString(rpcCommand);
		if(rpcCommandResult != nullptr)
		{
			commandResult = string_cast<std::string>(rpcCommandResult);
			SysFreeString(rpcCommandResult);
		}

		//Enable timer here because "ErrorRaised" might change
		//the running state for some reason
		SetRunning(runningBefore);

		if(FAILED(result))
		{
			m_embedClientActive = false;
			ErrorRaised(this);
		}
	}
	return commandResult;
}

void CWin32EmbedControl::CreateDevice()
{
	DXGI_SWAP_CHAIN_DESC swapChainDesc = {};

	HRESULT result = S_OK;

	auto clientRect = GetSurfaceSize();

	swapChainDesc.BufferCount							= 1;
	swapChainDesc.BufferDesc.Width						= clientRect.Width();
	swapChainDesc.BufferDesc.Height						= clientRect.Height();
	swapChainDesc.BufferDesc.Format						= DXGI_FORMAT_R8G8B8A8_UNORM;
	swapChainDesc.BufferDesc.RefreshRate.Numerator		= 0;
	swapChainDesc.BufferDesc.RefreshRate.Denominator	= 1;
	swapChainDesc.BufferDesc.ScanlineOrdering			= DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
	swapChainDesc.BufferDesc.Scaling					= DXGI_MODE_SCALING_UNSPECIFIED;
	swapChainDesc.BufferUsage							= DXGI_USAGE_RENDER_TARGET_OUTPUT;
	swapChainDesc.OutputWindow							= m_hWnd;
	swapChainDesc.SampleDesc.Count						= 1;
	swapChainDesc.SampleDesc.Quality					= 0;
	swapChainDesc.Windowed								= true;
	swapChainDesc.SwapEffect							= DXGI_SWAP_EFFECT_DISCARD;
	swapChainDesc.Flags									= 0;

	D3D_FEATURE_LEVEL featureLevel = D3D_FEATURE_LEVEL_11_0;

	UINT deviceCreationFlags = 0;
#ifdef _DEBUG
	deviceCreationFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif

	result = D3D11CreateDeviceAndSwapChain(nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr, deviceCreationFlags, &featureLevel, 1, D3D11_SDK_VERSION,
		&swapChainDesc, &m_swapChain, &m_device, NULL, &m_deviceContext);
	assert(SUCCEEDED(result));

	CreateOutputTexture();
}

void CWin32EmbedControl::CreateOutputTexture()
{
	HRESULT result = S_OK;

	{
		result = m_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), reinterpret_cast<void**>(&m_outputTexture));
		assert(SUCCEEDED(result));

		result = m_device->CreateRenderTargetView(m_outputTexture, nullptr, &m_outputTextureView);
		assert(SUCCEEDED(result));
	}
}

void CWin32EmbedControl::CreateSharedTexture()
{
	if(!m_embedClientActive)
	{
		return;
	}

	HRESULT result = S_OK;
	auto surfaceSize = GetSurfaceSize();

	auto application = m_embedClient.GetApplication();

	result = application->SetSurfaceSize(surfaceSize.Width(), surfaceSize.Height());
	assert(SUCCEEDED(result));
	if(FAILED(result))
	{
		m_embedClientActive = false;
		ErrorRaised(this);
		return;
	}

	HANDLE surfaceHandle = INVALID_HANDLE_VALUE;
	result = application->GetSurfaceHandle(reinterpret_cast<DWORD_PTR*>(&surfaceHandle));
	assert(SUCCEEDED(result));
	if(FAILED(result))
	{
		m_embedClientActive = false;
		ErrorRaised(this);
		return;
	}

	result = m_device->OpenSharedResource(surfaceHandle, __uuidof(ID3D11Texture2D), reinterpret_cast<void**>(&m_sharedTexture));
	assert(SUCCEEDED(result));

	result = m_sharedTexture->QueryInterface<IDXGIKeyedMutex>(reinterpret_cast<IDXGIKeyedMutex**>(&m_sharedTextureMutex));
	assert(SUCCEEDED(result));
}

Framework::Win32::CRect CWin32EmbedControl::GetSurfaceSize()
{
	auto clientRect = GetClientRect();
	int widthAdjust = 0, heightAdjust = 0;
	if(clientRect.Width() < 8)
	{
		widthAdjust = 8 - clientRect.Width();
	}
	if(clientRect.Height() < 8)
	{
		heightAdjust = 8 - clientRect.Height();
	}
	clientRect.Inflate(widthAdjust, heightAdjust);
	return clientRect;
}

KEY_CODE CWin32EmbedControl::TranslateKeyCode(unsigned int keyCode)
{
	switch(keyCode)
	{
	case 'W':		return KEY_CODE_W;
	case 'A':		return KEY_CODE_A;
	case 'S':		return KEY_CODE_S;
	case 'D':		return KEY_CODE_D;
	case VK_DOWN:	return KEY_CODE_ARROW_DOWN;
	case VK_UP:		return KEY_CODE_ARROW_UP;
	case VK_LEFT:	return KEY_CODE_ARROW_LEFT;
	case VK_RIGHT:	return KEY_CODE_ARROW_RIGHT;
	default:		return KEY_CODE_NONE;
	}
}

long CWin32EmbedControl::OnMouseMove(WPARAM, int posX, int posY)
{
	if(m_embedClientActive)
	{
		auto application = m_embedClient.GetApplication();
		HRESULT result = application->NotifyMouseMove(posX, posY);
		assert(SUCCEEDED(result));
		if(FAILED(result))
		{
			m_embedClientActive = false;
			ErrorRaised(this);
		}
	}
	return FALSE;
}

long CWin32EmbedControl::OnMouseWheel(int, int, short z)
{
	if(m_embedClientActive)
	{
		auto application = m_embedClient.GetApplication();
		HRESULT result = application->NotifyMouseWheel(z);
		assert(SUCCEEDED(result));
		if(FAILED(result))
		{
			m_embedClientActive = false;
			ErrorRaised(this);
		}
	}
	return FALSE;
}

long CWin32EmbedControl::OnLeftButtonDown(int, int)
{
	SetFocus();
	SetCapture(m_hWnd);
	if(m_embedClientActive)
	{
		auto application = m_embedClient.GetApplication();
		HRESULT result = application->NotifyMouseDown();
		assert(SUCCEEDED(result));
		if(FAILED(result))
		{
			m_embedClientActive = false;
			ErrorRaised(this);
		}
	}
	return FALSE;
}

long CWin32EmbedControl::OnLeftButtonUp(int, int)
{
	ReleaseCapture();
	if(m_embedClientActive)
	{
		auto application = m_embedClient.GetApplication();
		HRESULT result = application->NotifyMouseUp();
		assert(SUCCEEDED(result));
		if(FAILED(result))
		{
			m_embedClientActive = false;
			ErrorRaised(this);
		}
	}
	return FALSE;
}

long CWin32EmbedControl::OnKeyDown(WPARAM keyCode, LPARAM flags)
{
	//Check repeat flag
	if((flags & 0x40000000) == 0)
	{
		auto translatedKeyCode = TranslateKeyCode(keyCode);
		if(translatedKeyCode != KEY_CODE_NONE)
		{
			auto application = m_embedClient.GetApplication();
			application->NotifyKeyDown(translatedKeyCode);
		}
	}
	return TRUE;
}

long CWin32EmbedControl::OnKeyUp(WPARAM keyCode, LPARAM flags)
{
	auto translatedKeyCode = TranslateKeyCode(keyCode);
	if(translatedKeyCode != KEY_CODE_NONE)
	{
		auto application = m_embedClient.GetApplication();
		application->NotifyKeyUp(translatedKeyCode);
	}
	return TRUE;
}

long CWin32EmbedControl::OnTimer(WPARAM)
{
	if(!m_running) return FALSE;

	KillTimer(m_hWnd, TIMER_ID);

	HRESULT result = S_OK;

	if(m_embedClientActive)
	{
		auto application = m_embedClient.GetApplication();
		result = application->Update(1.f / 60.f);
		assert(SUCCEEDED(result));
		if(FAILED(result))
		{
			m_embedClientActive = false;
			ErrorRaised(this);
		}
	}

	static const float clearColor[4] = { 0, 0, 0, 0 };
	m_deviceContext->ClearRenderTargetView(m_outputTextureView, clearColor);

	if(m_embedClientActive)
	{
		result = m_sharedTextureMutex->AcquireSync(1, INFINITE);
		if(result != WAIT_OBJECT_0) return FALSE;

		m_deviceContext->CopyResource(m_outputTexture, m_sharedTexture);

		result = m_sharedTextureMutex->ReleaseSync(0);
		assert(SUCCEEDED(result));
	}

	m_swapChain->Present(0, 0);

	SetTimer(m_hWnd, TIMER_ID, TIMER_DELAY, 0);

	return FALSE;
}

long CWin32EmbedControl::OnSize(unsigned int, unsigned int width, unsigned int height)
{
	HRESULT result = S_OK;

	if(!m_swapChain.IsEmpty())
	{
		auto surfaceSize = GetSurfaceSize();

		m_outputTexture.Reset();
		m_outputTextureView.Reset();
		m_sharedTexture.Reset();
		m_sharedTextureMutex.Reset();

		result = m_swapChain->ResizeBuffers(1, surfaceSize.Width(), surfaceSize.Height(), DXGI_FORMAT_R8G8B8A8_UNORM, 0);
		assert(SUCCEEDED(result));

		CreateOutputTexture();
		CreateSharedTexture();
	}

	return FALSE;
}

long CWin32EmbedControl::OnGetDlgCode(WPARAM, LPARAM)
{
	return DLGC_WANTALLKEYS;
}


text:
/* Auto-generated header */
#include "SickConfig.hh"

/* Implementation dependencies */
#include <iomanip>
#include <iostream>
#include <arpa/inet.h>

#include "SickLMS1xxMessage.hh"
#include "SickLMS1xxUtility.hh" // for byye-order conversions where necessary

/* Associate the namespace */
namespace SickToolbox {

  /**
   * \brief A default constructor
   */
  SickLMS1xxMessage::SickLMS1xxMessage( ) :
    SickMessage< SICK_LMS_1XX_MSG_HEADER_LEN, SICK_LMS_1XX_MSG_PAYLOAD_MAX_LEN, SICK_LMS_1XX_MSG_TRAILER_LEN >(),
    _command_type(""),
    _command("")
  {

    /* Initialize the object */
    Clear();

  }

  /**
   * \brief Another constructor.
   * \param *payload_buffer The payload for the packet as an array of bytes (including the header)
   * \param payload_length The length of the payload array in bytes
   */
  SickLMS1xxMessage::SickLMS1xxMessage( const uint8_t * const payload_buffer, const unsigned int payload_length ) :
    SickMessage< SICK_LMS_1XX_MSG_HEADER_LEN, SICK_LMS_1XX_MSG_PAYLOAD_MAX_LEN, SICK_LMS_1XX_MSG_TRAILER_LEN >(),
    _command_type("Unknown"),
    _command("Unknown")
  {

    /* Build the message object (implicit initialization) */
    BuildMessage(payload_buffer,payload_length);

  }

  /**
   * \brief Another constructor.
   * \param *message_buffer A well-formed message to be parsed into the class' fields
   */
  SickLMS1xxMessage::SickLMS1xxMessage( const uint8_t * const message_buffer ) :
    SickMessage< SICK_LMS_1XX_MSG_HEADER_LEN, SICK_LMS_1XX_MSG_PAYLOAD_MAX_LEN, SICK_LMS_1XX_MSG_TRAILER_LEN >(),
    _command_type("Unknown"),
    _command("Unknown")
  {

    /* Parse the message into the container (implicit initialization) */
    ParseMessage(message_buffer);

  }

  /**
   * \brief Constructs a well-formed Sick LMS 1xx message
   * \param *payload_buffer An address of the first byte to be copied into the message's payload
   * \param payload_length The number of bytes to be copied into the message buffer
   */
  void SickLMS1xxMessage::BuildMessage( const uint8_t * const payload_buffer, const unsigned int payload_length ) {

    /* Call the parent method
     * NOTE: The parent method resets the object and assigns _message_length, _payload_length,
     *       _populated and copies the payload into the message buffer at the correct position
     */
    SickMessage< SICK_LMS_1XX_MSG_HEADER_LEN, SICK_LMS_1XX_MSG_PAYLOAD_MAX_LEN, SICK_LMS_1XX_MSG_TRAILER_LEN >
      ::BuildMessage(payload_buffer,payload_length);

    /*
     * Set the message header!
     */
    _message_buffer[0] = 0x02;                 // STX

    /*
     * Set the message trailer!
     */
    _message_buffer[_message_length-1] = 0x03; // ETX

    /* Grab the (3-byte) command type */
    char command_type[4] = {0};
    for (int i = 0; i < 3; i++) {
      command_type[i] = _message_buffer[i+1];
    }
    command_type[4] = '\0';
    _command_type = command_type;

    /* Grab the command (max length is 14 bytes) */
    char command[15] = {0};
    int i = 0;
    for (; (i < 14) && (_message_buffer[5+i] != 0x20); i++) {
      command[i] = _message_buffer[5+i];
    }
    command[i] = '\0';
    _command = command;

  }

  /**
   * \brief Parses a sequence of bytes into a SickLMS1xxMessage object
   * \param *message_buffer A well-formed message to be parsed into the class' fields
   */
  void SickLMS1xxMessage::ParseMessage( const uint8_t * const message_buffer ) throw (SickIOException) {

    /* Call the parent method
     * NOTE: This method resets the object and assigns _populated as true
     */
    SickMessage< SICK_LMS_1XX_MSG_HEADER_LEN, SICK_LMS_1XX_MSG_PAYLOAD_MAX_LEN, SICK_LMS_1XX_MSG_TRAILER_LEN >
      ::ParseMessage(message_buffer);

    /* Compute the message length */
    int i = 1;
    const char * token = NULL;
    while (message_buffer[i-1] != 0x03) {

      if (i == 1) {

	/* Grab the command type */
	if ((token = strtok((char *)&_message_buffer[1]," ")) == NULL) {
	  throw SickIOException("SickLMS1xxMessage::ParseMessage: strtok() failed!");
	}

	_command_type = token;

	/* Grab the Command Code */
	if ((token = strtok(NULL," ")) == NULL) {
	  throw SickIOException("SickLMS1xxMessage::ParseMessage: strtok() failed!");
	}

	_command = token;

      }

      i++; // Update message length

      /* A sanity check */
      if (i > SickLMS1xxMessage::MESSAGE_MAX_LENGTH) {
	throw SickIOException("SickLMS1xxMessage::ParseMessage: Message Exceeds Max Message Length!");
      }

    }

    /* Compute the total message length */
    _payload_length = _message_length - MESSAGE_HEADER_LENGTH - MESSAGE_TRAILER_LENGTH;

    /* Copy the given packet into the buffer */
    memcpy(_message_buffer,message_buffer,_message_length);

  }

  /**
   * \brief Reset all internal fields and buffers associated with the object.
   */
  void SickLMS1xxMessage::Clear( ) {

    /* Call the parent method and clear out class' protected members */
    SickMessage< SICK_LMS_1XX_MSG_HEADER_LEN, SICK_LMS_1XX_MSG_PAYLOAD_MAX_LEN, SICK_LMS_1XX_MSG_TRAILER_LEN >::Clear();

    /* Reset the class' additional fields */
    _command_type = "Unknown";
    _command = "Unknown";

  }

  /**
   * \brief Print the message contents.
   */
  void SickLMS1xxMessage::Print( ) const {

    //std::cout.setf(std::ios::hex,std::ios::basefield);
    std::cout << "Command Type: " << GetCommandType() << std::endl;
    std::cout << "Command Code: " << GetCommand() << std::endl;
    std::cout << std::flush;

    /* Call parent's print function */
    SickMessage< SICK_LMS_1XX_MSG_HEADER_LEN, SICK_LMS_1XX_MSG_PAYLOAD_MAX_LEN, SICK_LMS_1XX_MSG_TRAILER_LEN >::Print();

  }

  SickLMS1xxMessage::~SickLMS1xxMessage( ) { }

} /* namespace SickToolbox */

redpajama_set_name: RedPajamaGithub


text:
package org.killbill.billing.util.entity.dao;

import java.util.Iterator;
import java.util.List;

import org.killbill.billing.callcontext.InternalCallContext;
import org.killbill.billing.callcontext.InternalTenantContext;
import org.killbill.billing.entity.EntityPersistenceException;
import org.killbill.billing.util.audit.ChangeType;
import org.killbill.billing.util.cache.Cachable;
import org.killbill.billing.util.cache.Cachable.CacheType;
import org.killbill.billing.util.cache.CachableKey;
import org.killbill.billing.util.dao.AuditSqlDao;
import org.killbill.billing.util.dao.HistorySqlDao;
import org.killbill.billing.util.entity.Entity;
import org.killbill.commons.jdbi.statement.SmartFetchSize;
import org.skife.jdbi.v2.sqlobject.Bind;
import org.skife.jdbi.v2.sqlobject.BindBean;
import org.skife.jdbi.v2.sqlobject.SqlQuery;
import org.skife.jdbi.v2.sqlobject.SqlUpdate;
import org.skife.jdbi.v2.sqlobject.customizers.Define;
import org.skife.jdbi.v2.sqlobject.mixins.CloseMe;
import org.skife.jdbi.v2.sqlobject.mixins.Transactional;

@EntitySqlDaoStringTemplate
public interface EntitySqlDao<M extends EntityModelDao<E>, E extends Entity> extends AuditSqlDao, HistorySqlDao<M, E>, Transactional<EntitySqlDao<M, E>>, CloseMe {

    @SqlUpdate
    @Audited(ChangeType.INSERT)
    public void create(@BindBean final M entity,
                       @BindBean final InternalCallContext context) throws EntityPersistenceException;

    @SqlQuery
    public M getById(@Bind("id") final String id,
                     @BindBean final InternalTenantContext context);

    @SqlQuery
    public M getByRecordId(@Bind("recordId") final Long recordId,
                           @BindBean final InternalTenantContext context);

    @SqlQuery
    public List<M> getByAccountRecordId(@BindBean final InternalTenantContext context);

    @SqlQuery
    public List<M> getByAccountRecordIdIncludedDeleted(@BindBean final InternalTenantContext context);

    @SqlQuery
    @Cachable(CacheType.RECORD_ID)
    public Long getRecordId(@CachableKey(1) @Bind("id") final String id,
                            @BindBean final InternalTenantContext context);

    @SqlQuery
    @SmartFetchSize(shouldStream = true)
    public Iterator<M> search(@Bind("searchKey") final String searchKey,
                              @Bind("likeSearchKey") final String likeSearchKey,
                              @Bind("offset") final Long offset,
                              @Bind("rowCount") final Long rowCount,
                              @BindBean final InternalTenantContext context);

    @SqlQuery
    public Long getSearchCount(@Bind("searchKey") final String searchKey,
                               @Bind("likeSearchKey") final String likeSearchKey,
                               @BindBean final InternalTenantContext context);

    @SqlQuery
    @SmartFetchSize(shouldStream = true)
    public Iterator<M> getAll(@BindBean final InternalTenantContext context);

    @SqlQuery
    @SmartFetchSize(shouldStream = true)
    public Iterator<M> get(@Bind("offset") final Long offset,
                           @Bind("rowCount") final Long rowCount,
                           @Define("orderBy") final String orderBy,
                           @BindBean final InternalTenantContext context);

    @SqlQuery
    public Long getCount(@BindBean final InternalTenantContext context);

    @SqlUpdate
    public void test(@BindBean final InternalTenantContext context);
}


text:
@interface PostManageViewController : UIViewController

@end


text:
namespace ts {
    describe("convertToBase64", () => {
        function runTest(input: string): void {
            const actual = convertToBase64(input);
            const expected = sys.base64encode!(input);
            assert.equal(actual, expected, "Encoded string using convertToBase64 does not match buffer.toString('base64')");
        }

        if (Buffer) {
            it("Converts ASCII charaters correctly", () => {
                runTest(" !\"#$ %&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~");
            });

            it("Converts escape sequences correctly", () => {
                runTest("\t\n\r\\\"\'\u0062");
            });

            it("Converts simple unicode characters correctly", () => {
                runTest("ΠΣ ٵپ औठ ⺐⺠");
            });

            it("Converts simple code snippet correctly", () => {
                runTest(`/// <reference path="file.ts" />
var x: string = "string";
console.log(x);`);
            });

            it("Converts simple code snippet with unicode characters correctly", () => {
                runTest(`var Π = 3.1415; console.log(Π);`);
            });
        }
    });
}


text:
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1998

\section[PatSyn]{@PatSyn@: Pattern synonyms}
-}

{-# LANGUAGE CPP #-}

module PatSyn (
        -- * Main data types
        PatSyn, mkPatSyn,

        -- ** Type deconstruction
        patSynName, patSynArity, patSynIsInfix,
        patSynArgs,
        patSynMatcher, patSynBuilder,
        patSynUnivTyVarBinders, patSynExTyVars, patSynExTyVarBinders, patSynSig,
        patSynInstArgTys, patSynInstResTy, patSynFieldLabels,
        patSynFieldType,

        tidyPatSynIds, pprPatSynType
    ) where

#include "HsVersions.h"

import GhcPrelude

import Type
import Name
import Outputable
import Unique
import Util
import BasicTypes
import Var
import FieldLabel

import qualified Data.Data as Data
import Data.Function
import Data.List

{-
************************************************************************
*                                                                      *
\subsection{Pattern synonyms}
*                                                                      *
************************************************************************
-}

-- | Pattern Synonym
--
-- See Note [Pattern synonym representation]
-- See Note [Pattern synonym signature contexts]
data PatSyn
  = MkPatSyn {
        psName        :: Name,
        psUnique      :: Unique,       -- Cached from Name

        psArgs        :: [Type],
        psArity       :: Arity,        -- == length psArgs
        psInfix       :: Bool,         -- True <=> declared infix
        psFieldLabels :: [FieldLabel], -- List of fields for a
                                       -- record pattern synonym
                                       -- INVARIANT: either empty if no
                                       -- record pat syn or same length as
                                       -- psArgs

        -- Universally-quantified type variables
        psUnivTyVars  :: [TyVarBinder],

        -- Required dictionaries (may mention psUnivTyVars)
        psReqTheta    :: ThetaType,

        -- Existentially-quantified type vars
        psExTyVars    :: [TyVarBinder],

        -- Provided dictionaries (may mention psUnivTyVars or psExTyVars)
        psProvTheta   :: ThetaType,

        -- Result type
        psResultTy   :: Type,  -- Mentions only psUnivTyVars
                                -- See Note [Pattern synonym result type]

        -- See Note [Matchers and builders for pattern synonyms]
        psMatcher     :: (Id, Bool),
             -- Matcher function.
             -- If Bool is True then prov_theta and arg_tys are empty
             -- and type is
             --   forall (p :: RuntimeRep) (r :: TYPE p) univ_tvs.
             --                          req_theta
             --                       => res_ty
             --                       -> (forall ex_tvs. Void# -> r)
             --                       -> (Void# -> r)
             --                       -> r
             --
             -- Otherwise type is
             --   forall (p :: RuntimeRep) (r :: TYPE r) univ_tvs.
             --                          req_theta
             --                       => res_ty
             --                       -> (forall ex_tvs. prov_theta => arg_tys -> r)
             --                       -> (Void# -> r)
             --                       -> r

        psBuilder     :: Maybe (Id, Bool)
             -- Nothing  => uni-directional pattern synonym
             -- Just (builder, is_unlifted) => bi-directional
             -- Builder function, of type
             --  forall univ_tvs, ex_tvs. (req_theta, prov_theta)
             --                       =>  arg_tys -> res_ty
             -- See Note [Builder for pattern synonyms with unboxed type]
  }

{- Note [Pattern synonym signature contexts]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In a pattern synonym signature we write
   pattern P :: req => prov => t1 -> ... tn -> res_ty

Note that the "required" context comes first, then the "provided"
context.  Moreover, the "required" context must not mention
existentially-bound type variables; that is, ones not mentioned in
res_ty.  See lots of discussion in Trac #10928.

If there is no "provided" context, you can omit it; but you
can't omit the "required" part (unless you omit both).

Example 1:
      pattern P1 :: (Num a, Eq a) => b -> Maybe (a,b)
      pattern P1 x = Just (3,x)

  We require (Num a, Eq a) to match the 3; there is no provided
  context.

Example 2:
      data T2 where
        MkT2 :: (Num a, Eq a) => a -> a -> T2

      pattern P2 :: () => (Num a, Eq a) => a -> T2
      pattern P2 x = MkT2 3 x

  When we match against P2 we get a Num dictionary provided.
  We can use that to check the match against 3.

Example 3:
      pattern P3 :: Eq a => a -> b -> T3 b

   This signature is illegal because the (Eq a) is a required
   constraint, but it mentions the existentially-bound variable 'a'.
   You can see it's existential because it doesn't appear in the
   result type (T3 b).

Note [Pattern synonym result type]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
   data T a b = MkT b a

   pattern P :: a -> T [a] Bool
   pattern P x = MkT True [x]

P's psResultTy is (T a Bool), and it really only matches values of
type (T [a] Bool).  For example, this is ill-typed

   f :: T p q -> String
   f (P x) = "urk"

This is differnet to the situation with GADTs:

   data S a where
     MkS :: Int -> S Bool

Now MkS (and pattern synonyms coming from MkS) can match a
value of type (S a), not just (S Bool); we get type refinement.

That in turn means that if you have a pattern

   P x :: T [ty] Bool

it's not entirely straightforward to work out the instantiation of
P's universal tyvars. You have to /match/
  the type of the pattern, (T [ty] Bool)
against
  the psResultTy for the pattern synonym, T [a] Bool
to get the instantiation a := ty.

This is very unlike DataCons, where univ tyvars match 1-1 the
arguments of the TyCon.

Note [Pattern synonym representation]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider the following pattern synonym declaration

        pattern P x = MkT [x] (Just 42)

where
        data T a where
              MkT :: (Show a, Ord b) => [b] -> a -> T a

so pattern P has type

        b -> T (Maybe t)

with the following typeclass constraints:

        requires: (Eq t, Num t)
        provides: (Show (Maybe t), Ord b)

In this case, the fields of MkPatSyn will be set as follows:

  psArgs       = [b]
  psArity      = 1
  psInfix      = False

  psUnivTyVars = [t]
  psExTyVars   = [b]
  psProvTheta  = (Show (Maybe t), Ord b)
  psReqTheta   = (Eq t, Num t)
  psResultTy  = T (Maybe t)

Note [Matchers and builders for pattern synonyms]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For each pattern synonym P, we generate

  * a "matcher" function, used to desugar uses of P in patterns,
    which implements pattern matching

  * A "builder" function (for bidirectional pattern synonyms only),
    used to desugar uses of P in expressions, which constructs P-values.

For the above example, the matcher function has type:

        $mP :: forall (r :: ?) t. (Eq t, Num t)
            => T (Maybe t)
            -> (forall b. (Show (Maybe t), Ord b) => b -> r)
            -> (Void# -> r)
            -> r

with the following implementation:

        $mP @r @t $dEq $dNum scrut cont fail
          = case scrut of
              MkT @b $dShow $dOrd [x] (Just 42) -> cont @b $dShow $dOrd x
              _                                 -> fail Void#

Notice that the return type 'r' has an open kind, so that it can
be instantiated by an unboxed type; for example where we see
     f (P x) = 3#

The extra Void# argument for the failure continuation is needed so that
it is lazy even when the result type is unboxed.

For the same reason, if the pattern has no arguments, an extra Void#
argument is added to the success continuation as well.

For *bidirectional* pattern synonyms, we also generate a "builder"
function which implements the pattern synonym in an expression
context. For our running example, it will be:

        $bP :: forall t b. (Eq t, Num t, Show (Maybe t), Ord b)
            => b -> T (Maybe t)
        $bP x = MkT [x] (Just 42)

NB: the existential/universal and required/provided split does not
apply to the builder since you are only putting stuff in, not getting
stuff out.

Injectivity of bidirectional pattern synonyms is checked in
tcPatToExpr which walks the pattern and returns its corresponding
expression when available.

Note [Builder for pattern synonyms with unboxed type]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For bidirectional pattern synonyms that have no arguments and have an
unboxed type, we add an extra Void# argument to the builder, else it
would be a top-level declaration with an unboxed type.

        pattern P = 0#

        $bP :: Void# -> Int#
        $bP _ = 0#

This means that when typechecking an occurrence of P in an expression,
we must remember that the builder has this void argument. This is
done by TcPatSyn.patSynBuilderOcc.

Note [Pattern synonyms and the data type Type]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The type of a pattern synonym is of the form (See Note
[Pattern synonym signatures] in TcSigs):

    forall univ_tvs. req => forall ex_tvs. prov => ...

We cannot in general represent this by a value of type Type:

 - if ex_tvs is empty, then req and prov cannot be distinguished from
   each other
 - if req is empty, then univ_tvs and ex_tvs cannot be distinguished
   from each other, and moreover, prov is seen as the "required" context
   (as it is the only context)

************************************************************************
*                                                                      *
\subsection{Instances}
*                                                                      *
************************************************************************
-}

instance Eq PatSyn where
    (==) = (==) `on` getUnique
    (/=) = (/=) `on` getUnique

instance Uniquable PatSyn where
    getUnique = psUnique

instance NamedThing PatSyn where
    getName = patSynName

instance Outputable PatSyn where
    ppr = ppr . getName

instance OutputableBndr PatSyn where
    pprInfixOcc = pprInfixName . getName
    pprPrefixOcc = pprPrefixName . getName

instance Data.Data PatSyn where
    -- don't traverse?
    toConstr _   = abstractConstr "PatSyn"
    gunfold _ _  = error "gunfold"
    dataTypeOf _ = mkNoRepType "PatSyn"

{-
************************************************************************
*                                                                      *
\subsection{Construction}
*                                                                      *
************************************************************************
-}

-- | Build a new pattern synonym
mkPatSyn :: Name
         -> Bool                 -- ^ Is the pattern synonym declared infix?
         -> ([TyVarBinder], ThetaType) -- ^ Universially-quantified type variables
                                 --   and required dicts
         -> ([TyVarBinder], ThetaType) -- ^ Existentially-quantified type variables
                                 --   and provided dicts
         -> [Type]               -- ^ Original arguments
         -> Type                 -- ^ Original result type
         -> (Id, Bool)           -- ^ Name of matcher
         -> Maybe (Id, Bool)     -- ^ Name of builder
         -> [FieldLabel]         -- ^ Names of fields for
                                 --   a record pattern synonym
         -> PatSyn
 -- NB: The univ and ex vars are both in TyBinder form and TyVar form for
 -- convenience. All the TyBinders should be Named!
mkPatSyn name declared_infix
         (univ_tvs, req_theta)
         (ex_tvs, prov_theta)
         orig_args
         orig_res_ty
         matcher builder field_labels
    = MkPatSyn {psName = name, psUnique = getUnique name,
                psUnivTyVars = univ_tvs,
                psExTyVars = ex_tvs,
                psProvTheta = prov_theta, psReqTheta = req_theta,
                psInfix = declared_infix,
                psArgs = orig_args,
                psArity = length orig_args,
                psResultTy = orig_res_ty,
                psMatcher = matcher,
                psBuilder = builder,
                psFieldLabels = field_labels
                }

-- | The 'Name' of the 'PatSyn', giving it a unique, rooted identification
patSynName :: PatSyn -> Name
patSynName = psName

-- | Should the 'PatSyn' be presented infix?
patSynIsInfix :: PatSyn -> Bool
patSynIsInfix = psInfix

-- | Arity of the pattern synonym
patSynArity :: PatSyn -> Arity
patSynArity = psArity

patSynArgs :: PatSyn -> [Type]
patSynArgs = psArgs

patSynFieldLabels :: PatSyn -> [FieldLabel]
patSynFieldLabels = psFieldLabels

-- | Extract the type for any given labelled field of the 'DataCon'
patSynFieldType :: PatSyn -> FieldLabelString -> Type
patSynFieldType ps label
  = case find ((== label) . flLabel . fst) (psFieldLabels ps `zip` psArgs ps) of
      Just (_, ty) -> ty
      Nothing -> pprPanic "dataConFieldType" (ppr ps <+> ppr label)

patSynUnivTyVarBinders :: PatSyn -> [TyVarBinder]
patSynUnivTyVarBinders = psUnivTyVars

patSynExTyVars :: PatSyn -> [TyVar]
patSynExTyVars ps = binderVars (psExTyVars ps)

patSynExTyVarBinders :: PatSyn -> [TyVarBinder]
patSynExTyVarBinders = psExTyVars

patSynSig :: PatSyn -> ([TyVar], ThetaType, [TyVar], ThetaType, [Type], Type)
patSynSig (MkPatSyn { psUnivTyVars = univ_tvs, psExTyVars = ex_tvs
                    , psProvTheta = prov, psReqTheta = req
                    , psArgs = arg_tys, psResultTy = res_ty })
  = (binderVars univ_tvs, req, binderVars ex_tvs, prov, arg_tys, res_ty)

patSynMatcher :: PatSyn -> (Id,Bool)
patSynMatcher = psMatcher

patSynBuilder :: PatSyn -> Maybe (Id, Bool)
patSynBuilder = psBuilder

tidyPatSynIds :: (Id -> Id) -> PatSyn -> PatSyn
tidyPatSynIds tidy_fn ps@(MkPatSyn { psMatcher = matcher, psBuilder = builder })
  = ps { psMatcher = tidy_pr matcher, psBuilder = fmap tidy_pr builder }
  where
    tidy_pr (id, dummy) = (tidy_fn id, dummy)

patSynInstArgTys :: PatSyn -> [Type] -> [Type]
-- Return the types of the argument patterns
-- e.g.  data D a = forall b. MkD a b (b->a)
--       pattern P f x y = MkD (x,True) y f
--          D :: forall a. forall b. a -> b -> (b->a) -> D a
--          P :: forall c. forall b. (b->(c,Bool)) -> c -> b -> P c
--   patSynInstArgTys P [Int,bb] = [bb->(Int,Bool), Int, bb]
-- NB: the inst_tys should be both universal and existential
patSynInstArgTys (MkPatSyn { psName = name, psUnivTyVars = univ_tvs
                           , psExTyVars = ex_tvs, psArgs = arg_tys })
                 inst_tys
  = ASSERT2( tyvars `equalLength` inst_tys
          , text "patSynInstArgTys" <+> ppr name $$ ppr tyvars $$ ppr inst_tys )
    map (substTyWith tyvars inst_tys) arg_tys
  where
    tyvars = binderVars (univ_tvs ++ ex_tvs)

patSynInstResTy :: PatSyn -> [Type] -> Type
-- Return the type of whole pattern
-- E.g.  pattern P x y = Just (x,x,y)
--         P :: a -> b -> Just (a,a,b)
--         (patSynInstResTy P [Int,Bool] = Maybe (Int,Int,Bool)
-- NB: unlike patSynInstArgTys, the inst_tys should be just the *universal* tyvars
patSynInstResTy (MkPatSyn { psName = name, psUnivTyVars = univ_tvs
                          , psResultTy = res_ty })
                inst_tys
  = ASSERT2( univ_tvs `equalLength` inst_tys
           , text "patSynInstResTy" <+> ppr name $$ ppr univ_tvs $$ ppr inst_tys )
    substTyWith (binderVars univ_tvs) inst_tys res_ty

-- | Print the type of a pattern synonym. The foralls are printed explicitly
pprPatSynType :: PatSyn -> SDoc
pprPatSynType (MkPatSyn { psUnivTyVars = univ_tvs,  psReqTheta  = req_theta
                        , psExTyVars   = ex_tvs,    psProvTheta = prov_theta
                        , psArgs       = orig_args, psResultTy = orig_res_ty })
  = sep [ pprForAll univ_tvs
        , pprThetaArrowTy req_theta
        , ppWhen insert_empty_ctxt $ parens empty <+> darrow
        , pprType sigma_ty ]
  where
    sigma_ty = mkForAllTys ex_tvs  $
               mkFunTys prov_theta $
               mkFunTys orig_args orig_res_ty
    insert_empty_ctxt = null req_theta && not (null prov_theta && null ex_tvs)


text:
namespace Algolia.Search.Models.Enums
{
    /// <summary>
    /// Compression type for outgoing HTTP requests
    /// </summary>
    public enum CompressionType
    {
        /// <summary>
        /// No compression
        /// </summary>
        NONE = 1,

        /// <summary>
        /// GZip Compression. Only supported by Search API.
        /// </summary>
        GZIP = 2
    }
}


text:
package com.intellij.openapi.diff.impl.patch.formove;

import com.intellij.openapi.vfs.VirtualFile;

import java.util.Comparator;

public final class FilePathComparator implements Comparator<VirtualFile> {
  private static final FilePathComparator ourInstance = new FilePathComparator();

  public static FilePathComparator getInstance() {
    return ourInstance;
  }

  public int compare(final VirtualFile o1, final VirtualFile o2) {
    return o1.getPath().compareTo(o2.getPath());
  }
}


text:
orthopoly-quadrature
====================

Orthopoly Quadrature is a collection of Cython scripts for computing
various types of orthogonal polynomials and quadrature rules. Most of
the codes are based on Walter Gautschi's OPQ Matlab suite for generating
orthogonal polynomials and quadrature rules

https://www.cs.purdue.edu/archives/2002/wxg/codes/OPQ.html


text:
/* @flow
*
*/

//import {RunTimeCheckE} from '../definition/def.js';

// union should be wrote by user , this implement is inefficient
export function union<A, B>(validA:(fv:mixed)=>A, validB:(fv:mixed)=>B)
  :(rv:mixed)=> A|B {
  return function(v:mixed):A|B {
    try {
      return validA(v);
    } catch (e) {
      return validB(v);
    }
  };
}


text:
package lombok;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Generates an all-args constructor.
 * An all-args constructor requires one argument for every field in the class.
 *

 * Complete documentation is found at the project lombok features page for @Constructor.
 *

 * Even though it is not listed, this annotation also has the {@code onConstructor} parameter. See the full documentation for more details.
 *
 * @see NoArgsConstructor
 * @see RequiredArgsConstructor
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.SOURCE)
public @interface AllArgsConstructor {
	/**
	 * If set, the generated constructor will be private, and an additional static 'constructor'
	 * is generated with the same argument list that wraps the real constructor.
	 *
	 * Such a static 'constructor' is primarily useful as it infers type arguments.
	 */
	String staticName() default "";

	/**
	 * Any annotations listed here are put on the generated constructor. The syntax for this feature is: {@code @AllArgsConstructor(onConstructor=@__({@AnnotationsGoHere}))}
	 */
	AnyAnnotation[] onConstructor() default {};

	/**
	 * Sets the access level of the constructor. By default, generated constructors are {@code public}.
	 */
	AccessLevel access() default lombok.AccessLevel.PUBLIC;

	/**
	 * Constructors are generated with the {@link java.beans.ConstructorProperties} annotation.
	 * However, this annotation is new in 1.6 which means those compiling for 1.5 will need
	 * to set this value to true.
	 *
	 * @deprecated THIS FEATURE WILL BE REMOVED after March 31st 2015. Use configuration key {@link ConfigurationKeys#ANY_CONSTRUCTOR_SUPPRESS_CONSTRUCTOR_PROPERTIES} instead.
	 */
	@Deprecated
	boolean suppressConstructorProperties() default false;

	/**
	  * Placeholder annotation to enable the placement of annotations on the generated code.
	  * @deprecated Don't use this annotation, ever - Read the documentation.
	  */
	@Deprecated
	@Retention(RetentionPolicy.SOURCE)
	@Target({})
	@interface AnyAnnotation {}
}


text:
class SubjectWorkflowStatusCreateWorker
  include Sidekiq::Worker

  def perform(subject_id, workflow_id)
    return unless Panoptes.flipper[:subject_workflow_status_create_worker].enabled?

    if SetMemberSubject.by_subject_workflow(subject_id, workflow_id).exists?
      SubjectWorkflowStatus.create!(
        subject_id: subject_id,
        workflow_id: workflow_id
      )
    end
  rescue ActiveRecord::RecordInvalid
  end
end


text:
package com.comcast.video.dawg.common.security.service;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.apache.directory.api.ldap.model.cursor.CursorException;
import org.apache.directory.api.ldap.model.cursor.EntryCursor;
import org.apache.directory.api.ldap.model.entry.Attribute;
import org.apache.directory.api.ldap.model.entry.DefaultAttribute;
import org.apache.directory.api.ldap.model.entry.DefaultEntry;
import org.apache.directory.api.ldap.model.entry.DefaultModification;
import org.apache.directory.api.ldap.model.entry.Entry;
import org.apache.directory.api.ldap.model.entry.Modification;
import org.apache.directory.api.ldap.model.entry.ModificationOperation;
import org.apache.directory.api.ldap.model.exception.LdapException;
import org.apache.directory.api.ldap.model.exception.LdapNoSuchObjectException;
import org.apache.directory.api.ldap.model.message.SearchScope;
import org.apache.directory.ldap.client.api.LdapConnection;
import org.apache.directory.ldap.client.api.LdapNetworkConnection;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import com.comcast.video.dawg.common.exceptions.UserException;
import com.comcast.video.dawg.common.security.LdapAuthServerConfig;
import com.comcast.video.dawg.common.security.model.DawgUser;
import com.comcast.video.dawg.common.security.model.DawgUserAndRoles;

public class LdapUserService implements UserService {

    private LdapAuthServerConfig config;

    private LdapConnection connection;
    private PasswordEncoder passwordEncoder;

    public LdapUserService(LdapAuthServerConfig config) {
        this(config, new BCryptPasswordEncoder());
    }

    public LdapUserService(LdapAuthServerConfig config, PasswordEncoder passwordEncoder) {
        this.config = config;
        this.passwordEncoder = passwordEncoder;
    }

    void checkConnection() throws LdapException {
        if ((this.connection == null) || !connection.isConnected()) {
            connection = new LdapNetworkConnection(config.getLdapHost(), config.getLdapPort(), config.isLdapSsl());
            this.connection.bind(config.getBindDn(), config.getBindPassword());
        }
    }

    private Map<String, String> toInetOrgPerson(DawgUser user) {
        Map<String, String> person = new HashMap<String, String>();
        putIfNotNull(person, "cn", cn(user));
        putIfNotNull(person, "sn", user.getLastName());
        putIfNotNull(person, "givenName", user.getFirstName());
        String encoded = passwordEncoder.encode(user.getPassword());
        putIfNotNull(person, "userPassword", encoded);
        putIfNotNull(person, "mail", user.getMail());
        return person;
    }

    private static String cn(DawgUser user) {
        if((user.getFirstName() != null) && (user.getLastName() != null)) {
            return user.getFirstName() + " " + user.getLastName();
        }
        return user.getUid();
    }

    private static void putIfNotNull(Map<String, String> map, String key, String val) {
        if (val != null) map.put(key, val);
    }

    private Object[] toLdapElements(DawgUser user) {
        Map<String, String> person = toInetOrgPerson(user);

        person.put("objectClass", "inetOrgPerson");
        person.put("ou", config.getUsersOrganizationalUnit());
        Object[] eles = new Object[person.keySet().size()];
        int i = 0;
        for (String key : person.keySet()) {
            eles[i++] = key + ": " + person.get(key);
        }
        return eles;
    }

    private String userDn(String uid) {
        return config.getUserDnPatterns().replace("{0}", uid);
    }

    @Override
    public void addUser(DawgUser user, Set<String> roles) throws UserException {
        if (roles == null) throw new UserException("Missing roles field");
        if (user.getUid() == null) throw new UserException("Missing uid field");
        if (user.getPassword() == null) throw new UserException("Missing password field");
        try {
            checkConnection();
            String userdn = userDn(user.getUid());
            connection.add(new DefaultEntry(userdn, toLdapElements(user)));
            changeRoles(user.getUid(), roles, (Set<String>) null);
        } catch (LdapException e) {
            throw new UserException(e);
        }
    }

    public DawgUserAndRoles getUser(String userId) throws UserException {
        try {
            checkConnection();
            Entry entry = connection.lookup(userDn(userId));
            if (entry == null) return null;

            Set<String> roles = getUserRoles(userId);
            return new DawgUserAndRoles(userId,
                    entry.get("givenName").getString(),
                    entry.get("sn").getString(),
                    entry.get("mail").getString(),
                    null, roles);
        } catch (LdapException e) {
            throw new UserException(e);
        }
    }

    @Override
    public void modifyUser(DawgUser modifications) throws UserException {
        boolean fn = modifications.getFirstName() != null;
        boolean ln = modifications.getLastName() != null;
        /** cn is both fn and ln, so if we only allow changing one part of the name
            then we have to do a get on the db to get the other part, lets just
            not allow it */
        if (fn ^ ln) throw new UserException("Can only change full name");
        try {

            checkConnection();

            String userdn = userDn(modifications.getUid());
            Map<String, String> personMods = toInetOrgPerson(modifications);
            if (!fn && !ln) {
                /** Don't change cn if we didn't change first name and last name */
                personMods.remove("cn");
            }
            Set<Modification> mods = new HashSet<Modification>();
            for (String m : personMods.keySet()) {
                Attribute attr = new DefaultAttribute(m, personMods.get(m));
                mods.add(new DefaultModification(ModificationOperation.REPLACE_ATTRIBUTE, attr));
            }
            connection.modify(userdn, mods.toArray(new Modification[mods.size()]));
        } catch (LdapException e) {
            throw new UserException(e);
        }
    }

    @Override
    public void deleteUser(String userId) throws UserException {
        try {
            checkConnection();
            connection.delete(userDn(userId));
            changeRoles(userId, null, getUserRoles(userId));

        } catch (LdapNoSuchObjectException e) {
            /** Ignore, if not there then no need to delete */
        } catch (LdapException e) {
            throw new UserException(e);
        }
    }

    @Override
    public void changeRoles(String userId, Set<String> addRoles, Set<String> removeRoles) throws UserException {
        changeRoles(userId, addRoles, ModificationOperation.ADD_ATTRIBUTE);
        changeRoles(userId, removeRoles, ModificationOperation.REMOVE_ATTRIBUTE);
    }

    private void changeRoles(String userId, Set<String> roles, ModificationOperation op) throws UserException {
        try {
            checkConnection();
            if ((roles != null) && !roles.isEmpty()) {
                String userdn = userDn(userId);
                for (String role : roles) {
                    String dn = "cn=" + role + "," + config.getGroupSearchBase();
                    try {
                        connection.modify(dn, new DefaultModification(op, new DefaultAttribute("member", userdn)));
                    }  catch (LdapNoSuchObjectException e) {
                        throw new UserException("Role '" + role + "' does not exist.", e);
                    }
                }
            }
        } catch (LdapException e) {
            throw new UserException(e);
        }
    }

    @Override
    public Set<String> getUserRoles(String userId) throws UserException {
        Set<String> roles = new HashSet<String>();
        try {
            String filter = "(" + config.getGroupFilter().replace("{0}", userDn(userId)) + ")";
            EntryCursor cursor = connection.search(config.getGroupSearchBase(), filter,
                    SearchScope.SUBTREE);

            while(cursor.next()) {
                Entry entry = cursor.get();
                roles.add(entry.get("cn").getString());
            }
        } catch (LdapException | CursorException e) {
            throw new UserException(e);
        }
        return roles;
    }

}


text:
alter table predictor alter column shortname set not null;
alter table predictor drop constraint if exists predictor_unique_shortname;
alter table predictor add constraint predictor_unique_shortname unique (shortname);


text:
package org.apache.camel.spring.interceptor;

import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.spring.SpringRouteBuilder;

/**
 * Using transaction error handler in the routes
 */
public class TransactionalClientDataSourceTransactionErrorHandlerTest extends TransactionalClientDataSourceTest {

    protected RouteBuilder createRouteBuilder() throws Exception {
        return new SpringRouteBuilder() {
            public void configure() throws Exception {
                // START SNIPPET: e1
                // use a global transaction error handler so all routes is transacted
                errorHandler(transactionErrorHandler());

                from("direct:okay")
                    .transacted()
                    .setBody(constant("Tiger in Action")).bean("bookService")
                    .setBody(constant("Elephant in Action")).bean("bookService");

                // marks this route as transacted that will use the single policy defined in the registry
                from("direct:fail")
                    .transacted()
                    .setBody(constant("Tiger in Action")).bean("bookService")
                    .setBody(constant("Donkey in Action")).bean("bookService");
                // END SNIPPET: e1
            }
        };
    }

}


text:
author: admin
comments: true
date: 2011-09-15 14:31:10+00:00
layout: post
slug: phd-diary-an-introduction-and-a-little-light-reading
title: 'PhD Diary: An Introduction and A Little Light Reading'
categories:
- Uni
tags:
- phd
- qub
---

[caption id="" align="alignright" width="600" caption="Sometimes I worry about the accuracy of webcomics..."][![PhD Ponzi Scheme](http://www.phdcomics.com/comics/archive/phd030909s.gif)](http://www.phdcomics.com/comics.php?f=1144)[/caption]

So today is the start of the rest of your life. Seems kind of appropriate today. Had a meeting with my PhD Supervisor to start to develop my project. Of course at this point it would help to explain what the project is, but I can't right now, so shush.

What was innocuous about the meeting was the relatively small pile of papers that I was handed; that was until I flicked through and saw that the actual material he wanted researched had been highlighted in the bibloigraphies. In fact, it would have been more efficient to highlight the ones NOT to read.

Ahh well, I bought a Kindle for a reason.

My supervisor passed on an interesting commentary on what a PhD actually is; he said that it comes in three stages (not years, stages). (I may have taken some artistic liberties with the language, but you'll get the point)

  1. Bright Eyed Apprentice and Zen Master; the student has all the energy and relies on the supervisor for guidance and verification

  2. The Petulant Brat and the Withering Lord; the student now has about as much knowledge in the subject as the supervisor, leading to inevitable 'conflicts of opinion' and a need for the student to back up his arguments constantly.

  3. The Master and the Emeritus; the student is now a domain expert and can more or less 'school' the now obsolete (in this field) supervisor.

Considering the personalities of myself and  my supervisor, that second bit could be interesting.

Thankfully, I have several friends who has not only done/are doing PhD's, but some have worked under the same supervisor, so advice is readily available.

On some of that advice, I've started to have a look at [Mendeley](http://www.mendeley.com/), a fantastic looking combination between Linkedin, CiteULike, and Dropbox for managing academic references and citations. Of course, if anyone has any other tips in general (I'm particularly clueless as to how to manage a lit-review and the best way of note-taking on papers) leave a comment.


text:
class CreatePatients < ActiveRecord::Migration[6.0]
  def change
    create_table :patients do |t|
      t.string :name, null: false
      t.string :primary_phone, null: false
      t.string :other_contact
      t.string :other_phone
      t.string :other_contact_relationship
      t.string :identifier

      t.string :voicemail_preference, default: 'not_specified'
      t.string :line, null: false

      t.string :language
      t.string :pronouns
      t.date :initial_call_date, null: false
      t.boolean :urgent_flag
      t.integer :last_menstrual_period_weeks
      t.integer :last_menstrual_period_days

      t.integer :age
      t.string :city
      t.string :state
      t.string :county
      t.string :zipcode
      t.string :race_ethnicity
      t.string :employment_status
      t.integer :household_size_children
      t.integer :household_size_adults
      t.string :insurance
      t.string :income
      t.string :special_circumstances, array: true, default: []
      t.string :referred_by
      t.boolean :referred_to_clinic
      t.boolean :completed_ultrasound

      t.date :appointment_date
      t.integer :procedure_cost
      t.integer :patient_contribution
      t.integer :naf_pledge
      t.integer :fund_pledge
      t.datetime :fund_pledged_at
      t.boolean :pledge_sent
      t.boolean :resolved_without_fund
      t.datetime :pledge_generated_at
      t.datetime :pledge_sent_at
      t.boolean :textable

      t.references :clinic, foreign_key: true
      t.references :pledge_generated_by, foreign_key: { to_table: :users }
      t.references :pledge_sent_by, foreign_key: { to_table: :users }
      t.references :last_edited_by, foreign_key: { to_table: :users }

      # Scratch field - temporary BSON ID from Mongo so we can link things back
      t.string :mongo_id

      t.timestamps
    end

    add_index :patients, :primary_phone, unique: true
    add_index :patients, :other_phone
    add_index :patients, :other_contact
    add_index :patients, :name
    add_index :patients, :line
    add_index :patients, :urgent_flag
    add_index :patients, :identifier
    add_index :patients, :pledge_sent
  end
end


text:
package org.springframework.cloud.gcp.autoconfigure.logging.extractors;

/**
 * An extractor that can provide a trace ID from an HTTP request.
 *
 * @author Chengyuan Zhao
 *
 * @deprecated use
 * {@link org.springframework.cloud.gcp.logging.extractors.TraceIdExtractor}
 */
@Deprecated
public interface TraceIdExtractor extends org.springframework.cloud.gcp.logging.extractors.TraceIdExtractor {

}


text:
// Code generated by client-gen. DO NOT EDIT.

// This package has the automatically generated fake clientset.
package fake


text:
package demo;

/**
 * Interface for data access code to be implemented manually.
 *
 * @author Oliver Gierke
 * @author Thomas Darimont
 */
interface ProductRepositoryCustom {

	/**
	 * Raises {@link Product}s prices by the given factor.
	 *
	 * @param price
	 */
	void raisePricesForWinterSaleBy(double factor);
}


text:
ALTER TABLE QUESTION RENAME COLUMN ANSWER_DATA_TYPE TO QUESTION_TYPE_ID;
ALTER TABLE QUESTION MODIFY QUESTION_TYPE_ID NUMBER(12,0);

CREATE OR REPLACE VIEW OSP$QUESTION AS SELECT
    A.QUESTION_ID,
    A.QUESTION,
    A.MAX_ANSWERS,
    A.VALID_ANSWER,
    A.LOOKUP_NAME,
    B.QUESTION_TYPE_NAME AS ANSWER_DATA_TYPE,
    A.ANSWER_MAX_LENGTH,
    A.LOOKUP_GUI,
    A.UPDATE_TIMESTAMP,
    A.UPDATE_USER,
    A.GROUP_TYPE_CODE
FROM QUESTION A,
     QUESTION_TYPES B
WHERE A.QUESTION_TYPE_ID = B.QUESTION_TYPE_ID;


text:
package com.yassergonzalez.pagerank;

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.ShortWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

public class PageRankMatrixMapper extends
		Mapper<LongWritable, Text, ShortArrayWritable, ShortArrayWritable> {

	@Override
	public void map(LongWritable inKey, Text inValue, Context context)
			throws IOException, InterruptedException {

		// This task gets a line from links-simple-sorted.txt that contains the
		// out links of a page v. It produces results with keys (i, j)
		// corresponding to the indexes of the block M_{i,j} in which each
		// link v -> w should be stored. The value is (v, w, degree(v)).

		Configuration conf = context.getConfiguration();
		short blockSize = Short.parseShort(conf.get("pagerank.block_size"));

		String[] lineParts = inValue.toString().split(":\\s+");
		String[] vOutlinks = lineParts[1].split("\\s+");

		ShortWritable[] blockIndexes = new ShortWritable[2];
		blockIndexes[0] = new ShortWritable();
		blockIndexes[1] = new ShortWritable();

		ShortWritable[] blockEntry = new ShortWritable[3];
		blockEntry[0] = new ShortWritable();
		blockEntry[1] = new ShortWritable();
		blockEntry[2] = new ShortWritable();

		int v, w;
		short i, j;

		v = Integer.parseInt(lineParts[0]);
		j = (short) ((v - 1) / blockSize + 1);

		for (int k = 0; k < vOutlinks.length; k++) {
			w = Integer.parseInt(vOutlinks[k]);
			i = (short) ((w - 1) / blockSize + 1);

			// Indexes of the block M_{i,j}.
			blockIndexes[0].set(i);
			blockIndexes[1].set(j);
			// One entry of the block M_{i,j} corresponding to the v -> w link.
			// The sparse block representation also needs information about
			// the degree of the vector v.
			blockEntry[0].set((short) ((v - 1) % blockSize));
			blockEntry[1].set((short) ((w - 1) % blockSize));
			blockEntry[2].set((short) vOutlinks.length);

			context.write(new ShortArrayWritable(blockIndexes),
					new ShortArrayWritable(blockEntry));
		}
	}
}


text:
#ifndef SLIC_H
#define SLIC_H

/* slic.h.
 *
 * Written by: Pascal Mettes.
 *
 * This file contains the class elements of the class Slic. This class is an
 * implementation of the SLIC Superpixel algorithm by Achanta et al. [PAMI'12,
 * vol. 34, num. 11, pp. 2274-2282].
 *
 * This implementation is created for the specific purpose of creating
 * over-segmentations in an OpenCV-based environment.
 */

#include <opencv/cv.h>
#include <opencv/highgui.h>
#include <stdio.h>
#include <math.h>
#include <vector>
#include <float.h>

/*
 * class Slic.
 *
 * In this class, an over-segmentation is created of an image, provided by the
 * step-size (distance between initial cluster locations) and the colour
 * distance parameter.
 */
class Slic {
	public:
		/* The number of iterations run by the clustering algorithm. */
		static const unsigned int NR_ITERATIONS = 25;

		const cv::Mat1i& get_clusters() const { return clusters; }
		const cv::Rect& get_roi() const { return roi; }

    private:
        /* The cluster assignments and distance values for each pixel. */
        cv::Mat1i clusters;
        cv::Mat1d distances;

		cv::Rect roi;

        /* The LAB and xy values of the centers. */
		struct center_t {
			size_t id;
			double color;
			cv::Point2i coord;
		};
		std::vector<center_t> centers;
        /* The number of occurrences of each center. */
        std::vector<int> center_counts;

        /* The step size per cluster, and the color (nc) and distance (ns) parameters. */
        int step, ns;
		double nc;

        /* Compute the distance between a center and an individual pixel. */
		inline double compute_dist(const center_t c, cv::Point pixel, const double& colour);
        /* Find the pixel with the lowest gradient in a 3x3 surrounding. */
		cv::Point find_local_minimum(cv::Mat1d& image, const cv::Point2i center, const int r = 5);

		// Clear the data as saved by the algorithm.
        void clear_data()
		{
			clusters.release();
			distances.release();
			centers.clear();
			center_counts.clear();
		}

		/*
		* Initialize the cluster centers and initial values of the pixel-wise cluster
		* assignment and distance values.
		*
		* Input : The image (IplImage*).
		* Output: -
		*/
        void init_data(cv::Mat1d& image);

    public:
        // Class constructors and destructors.
		Slic(){}
		~Slic(){}

        // Generate an over-segmentation for an image.
		void generate_superpixels(cv::Mat1d& image, const int superpixel_num, const double nc, cv::Rect roi = cv::Rect());
        // Enforce connectivity for an image.
		void create_connectivity(cv::Mat1d& image);

        // Draw functions.
		void display_center_grid(cv::Mat3d& image, const cv::Scalar& colour);
		void display_contours(cv::Mat3d& image, const cv::Scalar& colour, const double scale = 1.0);
        void colour_with_cluster_means(cv::Mat3d& image);
};

#endif


text:
#include "UnrealEnginePythonPrivatePCH.h"

// destructor
static void ue_pycallable_dealloc(ue_PyCallable *self) {
#if defined(UEPY_MEMORY_DEBUG)
	UE_LOG(LogPython, Warning, TEXT("Destroying ue_PyCallable %p mapped to UFunction %p"), self, self->u_function);
#endif
	Py_TYPE(self)->tp_free((PyObject *)self);
}

static PyObject* ue_pycallable_call(ue_PyCallable *self, PyObject *args, PyObject *kw) {
	if (!self->u_function ||
		!self->u_target ||
		!self->u_function->IsValidLowLevel() ||
		!self->u_target->IsValidLowLevel() ||
		self->u_function->IsPendingKillOrUnreachable() ||
		self->u_target->IsPendingKillOrUnreachable()) {
		return PyErr_Format(PyExc_Exception, "UFunction/UObject is in invalid state for python callable");
	}

	return py_ue_ufunction_call(self->u_function, self->u_target, args, 0, kw);
}

static PyTypeObject ue_PyCallableType = {
	PyVarObject_HEAD_INIT(NULL, 0)
	"unreal_engine.Callable", /* tp_name */
	sizeof(ue_PyCallable), /* tp_basicsize */
	0,                         /* tp_itemsize */
	(destructor)ue_pycallable_dealloc,       /* tp_dealloc */
	0,                         /* tp_print */
	0,                         /* tp_getattr */
	0,                         /* tp_setattr */
	0,                         /* tp_reserved */
	0,                         /* tp_repr */
	0,                         /* tp_as_number */
	0,                         /* tp_as_sequence */
	0,                         /* tp_as_mapping */
	0,                         /* tp_hash  */
	(ternaryfunc)ue_pycallable_call,                         /* tp_call */
	0,                         /* tp_str */
	0,                         /* tp_getattro */
	0,                         /* tp_setattro */
	0,                         /* tp_as_buffer */
	Py_TPFLAGS_DEFAULT,        /* tp_flags */
	"Unreal Engine Python Callable",           /* tp_doc */
	0,                         /* tp_traverse */
	0,                         /* tp_clear */
	0,                         /* tp_richcompare */
	0,                         /* tp_weaklistoffset */
	0,                         /* tp_iter */
	0,                         /* tp_iternext */
	0,             /* tp_methods */
	0,
	0,
};

void ue_python_init_callable(PyObject *ue_module) {
	ue_PyCallableType.tp_new = PyType_GenericNew;

	if (PyType_Ready(&ue_PyCallableType) < 0)
		return;

	Py_INCREF(&ue_PyCallableType);
	PyModule_AddObject(ue_module, "Callable", (PyObject *)&ue_PyCallableType);
}

PyObject *py_ue_new_callable(UFunction *u_function, UObject *u_target) {
	ue_PyCallable *ret = (ue_PyCallable *)PyObject_New(ue_PyCallable, &ue_PyCallableType);
	ret->u_function = u_function;
	ret->u_target = u_target;
	return (PyObject *)ret;
}

ue_PyCallable *py_ue_is_callable(PyObject *obj) {
	if (!PyObject_IsInstance(obj, (PyObject *)&ue_PyCallableType))
		return nullptr;
	return (ue_PyCallable *)obj;
}


text:
import argparse
import json
import os
import os.path
import platform
import re
import sys

ROOT_DIR = os.path.dirname(os.path.realpath(__file__))
SRC_DIR = os.path.join(ROOT_DIR, 'src')
BUILD_DIR = os.path.join(ROOT_DIR, 'build')

SUPPORTED_ARCHS = [ 'x86_64', 'aarch64' ];
DEFAULT_ARCH = 'x86_64'

SUPPORTED_LEVELS = [ 0, 1, 2, 3 ]
DEFAULT_LEVEL = 3

DEFAULT_INFIX = '-elf-'

parser = argparse.ArgumentParser(description='Arwen OS build configurer.')
parser.add_argument('--arch', dest='arch', action='store',
                    choices=SUPPORTED_ARCHS, default=DEFAULT_ARCH,
                    help='target CPU architecture (default: %s)'%DEFAULT_ARCH)
parser.add_argument('--level', dest='level', action='store',
                    type=int, choices=SUPPORTED_LEVELS, default=DEFAULT_LEVEL,
                    help='optimization level (default: %d)'%DEFAULT_LEVEL)
parser.add_argument('--prefix', dest='prefix', action='store',
                    help='binutils prefix (default: <arch>%s)'% \
                        DEFAULT_INFIX)
args = parser.parse_args()

if not args.prefix:
    args.prefix = args.arch + DEFAULT_INFIX

def which(program):
    def is_exe(fpath):
        return os.path.isfile(fpath) and os.access(fpath, os.X_OK)

    fpath, fname = os.path.split(program)
    if fpath:
        if is_exe(program):
            return program
    else:
        for path in os.environ['PATH'].split(os.pathsep):
            path = path.strip('"')
            exe_file = os.path.join(path, program)
            if is_exe(exe_file):
                return exe_file

    return None

def find_program(program):
    filename = which(program)
    if not filename:
        sys.stderr.write("error: didn't find '%s' program\n"%program)
        sys.exit(1)
    return filename

rustc = find_program('rustc')
objcopy = find_program(args.prefix+'objcopy')
ar = find_program(args.prefix+'ar')
gas = find_program(args.prefix+'as')
ld = find_program(args.prefix+'ld')
qemu = find_program('qemu-system-'+args.arch)

def read_build_json(filename):
    try:
        with open(filename, 'r') as f:
            return json.loads(f.read())
    except IOError:
        return {}

def build_dir(path):
    relpath = os.path.relpath(path, ROOT_DIR)
    return os.path.join(BUILD_DIR, relpath)

def prettify_target(filename):
    return os.path.relpath(filename, BUILD_DIR)

def rlib_target(name):
    return os.path.join(build_dir(SRC_DIR), name, 'lib%s.rlib'%name)

def robj_target(name):
    return os.path.join(build_dir(SRC_DIR), name, '%s.rust.o'%name)

def sobj_target(name):
    return os.path.join(build_dir(SRC_DIR), name, '%s.asm.o'%name)

def mod_target(name):
    return os.path.join(build_dir(SRC_DIR), name, '%s.mod'%name)

def render(makefile, str):
    makefile.write(str.replace(ROOT_DIR, '$(ROOT)'))

class Module:
    def __init__(self, name):
        self.name = name
        self.asm_files = []
        self.rust_files =[]
        self.dependencies = []
        self.build_dirs = []
        self.rust_args = []
        self.scan_dirs(self.path())
        self.dependencies = list(set(self.dependencies))

    def path(self):
        return os.path.join(SRC_DIR, self.name)

    def scan_dirs(self, path):
        data = read_build_json(os.path.join(path, 'build.json'))
        if 'asmFiles' in data:
            self.asm_files += map(
                lambda f: os.path.join(path, f), data['asmFiles'])
        if 'rustFiles' in data:
            self.rust_files += map(
                lambda f: os.path.join(path, f), data['rustFiles'])
        if 'dependencies' in data:
            self.dependencies += map(
                lambda m: rlib_target(m), data['dependencies'])
        if 'rustArgs' in data:
            self.rust_args += data['rustArgs']
        if 'subdirs' in data:
            for d in data['subdirs']:
                if d == 'arch': d += '-' + args.arch
                self.scan_dirs(os.path.join(path, d))
        else:
            self.build_dirs.append(build_dir(path))

    def build_dirs_target(self):
        return os.path.join(build_dir(self.path()), '.build_dirs')

    def render(self, makefile):
        render(makefile, '# Module: %s\n'%self.name)
        self.render_build_dirs(makefile)
        self.render_rlib(makefile)
        self.render_robj(makefile)
        self.render_sobj(makefile)
        self.render_mod(makefile)

    def render_build_dirs(self, makefile):
        target = self.build_dirs_target()
        render(makefile, '\n%s:\n'%target)
        render(makefile, '\t@echo Creating build dirs for \'%s\'\n'%self.name)
        render(makefile, '\t@mkdir -p %s\n'%(' '.join(self.build_dirs)))
        render(makefile, '\t@touch %s\n'%target)

    def render_rlib(self, makefile):
        target = rlib_target(self.name)
        rlibs = ' ' + ' '.join(self.dependencies) if self.dependencies else ''
        rfiles = ' ' + ' '.join(self.rust_files) if self.rust_files else ''

        render(makefile, '\n%s: %s%s%s\n'% \
            (target, self.build_dirs_target(), rlibs, rfiles))
        render(makefile, '\t@echo Creating \'%s\'\n'%prettify_target(target))

        flags = ('--crate-type rlib --target %s-unknown-linux-gnu ' + \
            '-C opt-level=%d -C no-stack-check -Z no-landing-pads ' + \
            '--cfg arch_%s --sysroot /dev/null') % \
            (args.arch, args.level, args.arch)

        # TODO: remove this in future (see issue #1)
        if args.arch == 'x86_64':
            flags += ' -C relocation-model=static'

        lib_path = ' -L ' + ' -L '.join(
            map(lambda d: os.path.dirname(d), self.dependencies)) \
            if self.dependencies else ''

        extra_args = ' ' + ' '.join(self.rust_args) if self.rust_args else ''

        librs = os.path.join(self.path(), 'lib.rs')
        render(makefile, '\t@%s %s%s%s %s -o %s\n'% \
            (rustc, flags, lib_path, extra_args, librs, target))

    def render_robj(self, makefile):
        source = rlib_target(self.name)
        target = robj_target(self.name)
        tmplib = os.path.join(build_dir(SRC_DIR),
            self.name, 'lib%s.a'%self.name)
        tmpobj = os.path.join(build_dir(SRC_DIR),
            self.name, 'lib%s.0.o'%self.name)

        render(makefile, '\n%s: %s\n'%(target, source))
        render(makefile, '\t@echo Creating \'%s\'\n'%prettify_target(target))
        render(makefile, '\t@%s %s %s 2> /dev/null\n'% \
            (objcopy, source, tmplib))
        render(makefile, '\t@cd %s && %s -x %s lib%s.0.o\n'% \
            (build_dir(self.path()), ar, tmplib, self.name))
        render(makefile, '\t@mv %s %s\n'%(tmpobj, target))
        render(makefile, '\t@rm %s\n'%tmplib)

    def render_sobj(self, makefile):
        if not self.asm_files: return
        source = ' '.join(self.asm_files)
        target = sobj_target(self.name)
        render(makefile, '\n%s: %s %s\n'% \
            (target, self.build_dirs_target(), source))
        render(makefile, '\t@echo Creating \'%s\'\n'%prettify_target(target))
        render(makefile, '\t@%s %s -o %s\n'%(gas, source, target))

    def render_mod(self, makefile):
        source = '%s %s'% (sobj_target(self.name), robj_target(self.name)) \
            if self.asm_files else robj_target(self.name)
        target = mod_target(self.name)
        lds = os.path.join(SRC_DIR, 'kernel', 'module.lds')
        render(makefile, '\n%s: %s\n'%(target, source))
        render(makefile, '\t@echo Creating \'%s\'\n'%prettify_target(target))
        render(makefile, '\t@%s -r -T %s %s -o %s\n'%(ld, lds, source, target))
        render(makefile, '\n.PHONY: %s.mod\n%s.mod: %s\n'% \
            (self.name, self.name, target))

data = read_build_json(os.path.join(SRC_DIR, 'build.json'))
kmodules = map(lambda n: Module(n), data['kernelModules'])
kernel_target = os.path.join(build_dir(SRC_DIR), 'kernel', 'arwen.ker')

def render_prolog(makefile):
    render(makefile, '# Generated by configure.py, do not modify\n')
    render(makefile, '\nROOT := $(shell dirname $(realpath' +
                   ' $(lastword $(MAKEFILE_LIST))))\n')
    render(makefile, '\n.PHONY: all\nall: arwen.ker\n')
    render(makefile, '\n.PHONY: clean\nclean:\n')
    render(makefile, '\t@echo Removing build dirs\n')
    render(makefile, '\t@rm -rf %s\n'%BUILD_DIR)

def render_kernel(makefile):
    source = ' '.join(map(lambda m: mod_target(m.name), kmodules))
    lds = os.path.join(SRC_DIR, 'kernel', 'arch-'+args.arch, 'kernel.lds')

    render(makefile, '\n# Kernel\n')
    render(makefile, '\n%s: %s\n'%(kernel_target, source))
    render(makefile, '\t@echo Creating \'%s\'\n'% \
        prettify_target(kernel_target))
    render(makefile, '\t@%s -nostdlib -z max-page-size=4096 -T %s %s -o %s\n' \
        %(ld, lds, source, kernel_target))
    render(makefile, '\n.PHONY: arwen.ker\narwen.ker: %s\n'%kernel_target)

def render_run(makefile):
    flags = ' -nographic'
    if args.arch == 'aarch64':
        flags += ' -machine type=virt -cpu cortex-a57'
    render(makefile, '\n# Run\n')
    render(makefile, '\n.PHONY: run\nrun: %s\n'%kernel_target)
    render(makefile, '\t@echo "Running QEMU (to exit press Ctrl-a x)"\n')
    render(makefile, '\t@%s%s -kernel %s\n'%(qemu, flags, kernel_target))

with open(os.path.join(ROOT_DIR, 'Makefile'), 'w') as f:
    render_prolog(f)

    for m in kmodules:
        f.write('\n')
        m.render(f)

    render_kernel(f)
    render_run(f)


text:
using System;
using System.Runtime.InteropServices;

namespace SharpVk
{
    /// <summary>
    ///
    /// </summary>
    [StructLayout(LayoutKind.Sequential)]
    public partial struct DescriptorUpdateTemplateEntry
    {
        /// <summary>
        ///
        /// </summary>
        public DescriptorUpdateTemplateEntry(uint destinationBinding, uint destinationArrayElement, uint descriptorCount, SharpVk.DescriptorType descriptorType, HostSize offset, HostSize stride)
        {
            this.DestinationBinding = destinationBinding;
            this.DestinationArrayElement = destinationArrayElement;
            this.DescriptorCount = descriptorCount;
            this.DescriptorType = descriptorType;
            this.Offset = offset;
            this.Stride = stride;
        }

        /// <summary>
        ///
        /// </summary>
        public uint DestinationBinding;

        /// <summary>
        ///
        /// </summary>
        public uint DestinationArrayElement;

        /// <summary>
        ///
        /// </summary>
        public uint DescriptorCount;

        /// <summary>
        ///
        /// </summary>
        public SharpVk.DescriptorType DescriptorType;

        /// <summary>
        ///
        /// </summary>
        public HostSize Offset;

        /// <summary>
        ///
        /// </summary>
        public HostSize Stride;
    }
}


text:
package com.paul.robert.model.users;

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

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import org.springframework.security.core.CredentialsContainer;
import org.springframework.security.core.userdetails.UserDetails;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@Builder
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode
@Entity
@Table(name="users")
@JsonIgnoreProperties(ignoreUnknown=true)
public class User implements UserDetails, CredentialsContainer {

	private static final long serialVersionUID = 1069958132736171825L;

	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	@Getter @Setter
	private Long id;
	@Getter @Setter
	@Column(name="user_name")
	private String username;
	@Getter @Setter
	private String subject;
	@Getter @Setter
	private String sid;

	@Getter @Setter
	private String password;
	@Getter @Setter
	@Column(name="is_enabled")
	private boolean enabled = true;
	@Getter @Setter
	@Column(name="is_account_non_expired")
	private boolean accountNonExpired = false;
	@Getter @Setter
	@Column(name="is_account_non_locked")
	private boolean accountNonLocked = true;
	@Getter @Setter
	@Column(name="is_credential_non_expired")
	private boolean credentialsNonExpired = false;

	@OneToMany(fetch=FetchType.EAGER)
	@JoinTable(name="user_roles",
			   joinColumns={@JoinColumn(name="user_id", referencedColumnName="id")},
			   inverseJoinColumns={@JoinColumn(name="role_id", referencedColumnName="id")})
	@Getter @Setter
	private Collection<Role> authorities = new ArrayList<>();

	@Override
	public void eraseCredentials() {
		//In Spring the default User class simply sets the password to null
		this.password = null;
	}

	//TODO: Org Team Assignments

}


text:
using System;
using System.IO;

namespace Protobuild
{
    internal class PackageGitRepoCommand : ICommand
    {
        private readonly IFeatureManager _featureManager;

        public PackageGitRepoCommand(IFeatureManager featureManager)
        {
            _featureManager = featureManager;
        }

        public void Encounter(Execution pendingExecution, string[] args)
        {
            if (args.Length < 1 || args[0] == null)
            {
                throw new InvalidOperationException("You must provide the repository URL to -package-git-repo.");
            }

            pendingExecution.PackageGitRepositoryUrl = args[0];
        }

        public int Execute(Execution execution)
        {
            throw new NotSupportedException();
        }

        public string GetShortCategory()
        {
            return "Package management";
        }

        public string GetShortDescription()
        {
            return "sets the Git repository URL associated with the package";
        }

        public string GetDescription()
        {
            return @"
Sets the Git repository URL associated with the package.  If this option
is not used, the repository URL information will be omitted.  This option has no effect
for packages not stored in the nuget/zip format.
";
        }

        public int GetArgCount()
        {
            return 1;
        }

        public string[] GetShortArgNames()
        {
            return new[] { "https_git_url" };
        }

        public string[] GetArgNames()
        {
            return new[] { "package-git-repo" };
        }

        public bool IsInternal()
        {
            return false;
        }

        public bool IsRecognised()
        {
            return _featureManager.IsFeatureEnabled(Feature.PackageManagement);
        }

        public bool IsIgnored()
        {
            return false;
        }
    }
}


text:
package com.gemstone.gemfire.cache.query.internal.index;

import com.gemstone.gemfire.*;
//import com.gemstone.gemfire.cache.query.*;
import com.gemstone.gemfire.internal.StatisticsTypeFactoryImpl;
import com.gemstone.gemfire.internal.cache.CachePerfStats;

/**
 * IndexStats tracks statistics about query index use.
 */
public class IndexStats {

  //////////////////  Static fields ///////////////////////////

  private static final StatisticsType type;

  private static final int numKeysId;
  private static final int numValuesId;
  private static final int numUpdatesId;
  private static final int numUsesId;
  private static final int updateTimeId;
  private static final int useTimeId;
  private static final int updatesInProgressId;
  private static final int usesInProgressId;
  private static final int readLockCountId;
  private static final int numMapIndexKeysId;
  private static final int numBucketIndexesId;

  /** The Statistics object that we delegate most behavior to */
  private final Statistics stats;

  ////////////////////////  Static methods  ////////////////////////

  static {
    StatisticsTypeFactory f = StatisticsTypeFactoryImpl.singleton();

    final String numKeysDesc = "Number of keys in this index";
    final String numValuesDesc = "Number of values in this index";
    final String numUpdatesDesc = "Number of updates that have completed on this index";
    final String numUsesDesc = "Number of times this index has been used while executing a query";
    final String updateTimeDesc = "Total time spent updating this index";

    type = f.createType(
      "IndexStats",
      "Statistics about a query index",
      new StatisticDescriptor[] {
        f.createLongGauge("numKeys", numKeysDesc, "keys"),
        f.createLongGauge("numValues", numValuesDesc, "values"),
        f.createLongCounter("numUpdates", numUpdatesDesc, "operations"),
        f.createLongCounter("numUses", numUsesDesc, "operations"),
        f.createLongCounter("updateTime", updateTimeDesc, "nanoseconds"),
        f.createLongCounter("useTime", "Total time spent using this index", "nanoseconds"),
        f.createIntGauge("updatesInProgress", "Current number of updates in progress.", "updates"),
        f.createIntGauge("usesInProgress", "Current number of uses in progress.", "uses"),
        f.createIntGauge("readLockCount", "Current number of read locks taken.", "uses"),
        f.createLongGauge("numMapIndexKeys", "Number of keys in this Map index", "keys"),
        f.createIntGauge("numBucketIndexes", "Number of bucket indexes in the partitioned region", "indexes"),
      }
    );

    // Initialize id fields
    numKeysId = type.nameToId("numKeys");
    numValuesId = type.nameToId("numValues");
    numUpdatesId = type.nameToId("numUpdates");
    numUsesId = type.nameToId("numUses");
    updateTimeId = type.nameToId("updateTime");
    updatesInProgressId = type.nameToId("updatesInProgress");
    usesInProgressId = type.nameToId("usesInProgress");
    useTimeId = type.nameToId("useTime");
    readLockCountId = type.nameToId("readLockCount");
    numMapIndexKeysId = type.nameToId("numMapIndexKeys");
    numBucketIndexesId = type.nameToId("numBucketIndexes");
  }

  ////////////////////////  Constructors  ////////////////////////

  /**
   * Creates a new CachePerfStats and registers itself
   * with the given statistics factory.
   */
  public IndexStats(StatisticsFactory factory, String indexName) {
    stats = factory.createAtomicStatistics(type, indexName);
  }

  //////////////////////  Accessing Stats  //////////////////////

   public long getNumberOfKeys() {
     return stats.getLong(numKeysId);
   }

   public long getNumberOfValues() {
     return stats.getLong(numValuesId);
   }

   public long getNumUpdates() {
     return stats.getLong(numUpdatesId);
   }

   public long getTotalUses() {
     return stats.getLong(numUsesId);
   }

   public long getTotalUpdateTime() {
     return CachePerfStats.enableClockStats? stats.getLong(updateTimeId) : 0;
   }

   public long getUseTime() {
     return CachePerfStats.enableClockStats? stats.getLong(useTimeId) : 0;
   }

   public int getReadLockCount() {
     return stats.getInt(readLockCountId);
   }

   public long getNumberOfMapIndexKeys() {
     return stats.getLong(numMapIndexKeysId);
   }

   public int getNumberOfBucketIndexes() {
     return stats.getInt(numBucketIndexesId);
   }

  //////////////////////  Updating Stats  //////////////////////

   public void incNumUpdates() {
     this.stats.incLong(numUpdatesId, 1);
   }
   public void incNumUpdates(int delta) {
     this.stats.incLong(numUpdatesId, delta);
   }
   public void incNumValues(int delta) {
     this.stats.incLong(numValuesId, delta);
   }

   public void updateNumKeys(long numKeys) {
     this.stats.setLong(numKeysId, numKeys);
   }

   public void incNumKeys(long numKeys) {
     this.stats.incLong(numKeysId, numKeys);
   }

   public void incUpdateTime(long delta) {
     if (CachePerfStats.enableClockStats) {
       this.stats.incLong(updateTimeId, delta);
     }
   }

   public void incNumUses() {
     this.stats.incLong(numUsesId, 1);
   }
   public void incUpdatesInProgress(int delta) {
     this.stats.incInt(updatesInProgressId, delta);
   }
   public void incUsesInProgress(int delta) {
     this.stats.incInt(usesInProgressId, delta);
   }
   public void incUseTime(long delta) {
     if (CachePerfStats.enableClockStats) {
       this.stats.incLong(useTimeId, delta);
     }
   }
   public void incReadLockCount(int delta) {
     this.stats.incInt(readLockCountId, delta);
   }

   public void incNumMapIndexKeys(long delta) {
     this.stats.incLong(numMapIndexKeysId, delta);
   }

   public void incNumBucketIndexes(int delta) {
     this.stats.incInt(numBucketIndexesId, delta);
   }
  ////// Special Instance Methods /////

  /**
   * Closes these stats so that they can not longer be used.  The
   * stats are closed when the {@linkplain
   * com.gemstone.gemfire.internal.cache.GemFireCacheImpl#close cache}
   * is closed.
   *
   * @since 3.5
   */
  void close() {
    this.stats.close();
  }

  /**
   * Returns whether or not these stats have been closed
   *
   * @since 3.5
   */
  public boolean isClosed() {
    return this.stats.isClosed();
  }

  /**
   * Returns the Statistics instance that stores the cache perf stats.
   * @since 3.5
   */
  public Statistics getStats() {
    return this.stats;
  }
}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="CurrentRoomEmptyRoomTtlProperty.cs" company="Exit Games GmbH">
//   Part of: Pun Cockpit
// </copyright>
// <author>developer@exitgames.com</author>
// --------------------------------------------------------------------------------------------------------------------

using UnityEngine.UI;

namespace Photon.Pun.Demo.Cockpit
{
    /// <summary>
    /// PhotonNetwork.CurrentRoom.EmptyRoomTtl UI property.
    /// </summary>
    public class CurrentRoomEmptyRoomTtlProperty : PropertyListenerBase
    {
        public Text Text;

        int _cache = -1;

        void Update()
        {
            if (PhotonNetwork.CurrentRoom != null)
            {
                if (PhotonNetwork.CurrentRoom.EmptyRoomTtl != _cache)
                {
                    _cache = PhotonNetwork.CurrentRoom.EmptyRoomTtl;
                    Text.text = _cache.ToString();
                    this.OnValueChanged();
                }
            }
            else
            {
                if (_cache != -1)
                {
                    _cache = -1;
                    Text.text = "n/a";
                }
            }

        }
    }
}


text:
/* jshint expr:true */
import { expect } from 'chai';
import {
  describeModule,
  it
} from 'ember-mocha';

describeModule(
  'controller:s/vendors/vendor/opportunities/opportunity',
  'SVendorsVendorOpportunitiesOpportunityController',
  {
    // Specify the other units that are required for this test.
    // needs: ['controller:foo']
  },
  function() {
    // Replace this with your real tests.
    it('exists', function() {
      var controller = this.subject();
      expect(controller).to.be.ok;
    });
  }
);


text:
package org.kuali.kra.iacuc.committee.bo;

import org.kuali.coeus.common.committee.impl.bo.CommitteeScheduleBase;
import org.kuali.kra.iacuc.actions.submit.IacucProtocolSubmission;
import org.kuali.kra.iacuc.committee.meeting.IacucCommitteeScheduleMinute;

public class IacucCommitteeSchedule extends CommitteeScheduleBase<IacucCommitteeSchedule, IacucCommittee, IacucProtocolSubmission, IacucCommitteeScheduleMinute> {

    private static final long serialVersionUID = -579662475857490755L;

    private IacucCommittee committee;

    public IacucCommittee getParentCommittee() {
        return this.getCommittee();
    }

    public IacucCommittee getCommittee() {
        if (committee == null && getCommitteeIdFk() == null) {
            committee = new IacucCommittee();
        }
        return committee;
    }

    public void setCommittee(IacucCommittee committee) {
        this.committee = committee;
    }

}


text:
cat <<EOF
#%Module1.0
proc ModulesHelp { } {
  global dotversion
  puts stderr "SuiteSparse $VER ($TOOLCHAIN build)"
}

module-whatis "SuiteSparse $VER ($TOOLCHAIN build)"
set basedir /share/apps/SuiteSparse-$VER-$TOOLCHAIN

prepend-path CPATH \$basedir/include
prepend-path LIBRARY_PATH \$basedir/lib
prepend-path LD_RUN_PATH \$basedir/lib
EOF


text:
package org.cdlib.xtf.textEngine.facet;

/** Gather documents for all incoming groups. Always ends a selector chain */
public class DocsSelector extends GroupSelector
{
  int start;
  int max;

  public DocsSelector(int start, int max) {
    this.start = start;
    this.max = max;
  }

  public void process(int group) {
    counts.selectGroup(group);
    counts.gatherDocs(group, start, max);
  }

  public String toString() {
    return "docs(" + start + "," + max + ")";
  }
}


text:
var searchData=
[
  ['missingcostfunctionerror',['MissingCostFunctionError',['../class_missing_cost_function_error.html',1,'']]],
  ['missingschedulererror',['MissingSchedulerError',['../class_missing_scheduler_error.html',1,'']]]
];


text:
@interface PlayerController : NSObject<TIPInputManagerDelegate> {
	IBOutlet NSTableView *_table;
	NSMutableArray *_players;
	id _delegate;

	TriviaPlayerGetInputController *_getInputController;
}

- (id)delegate;
- (void)setDelegate:(id)newDelegate;

- (IBAction)setButton:(id)sender;
- (void)reloadData;

- (NSArray*)players;

- (void)setAllPlayersEnabled:(BOOL)willEnable;
- (BOOL)allPlayersDisabled;
@end

@interface NSObject (PlayerDelegate)
- (void)playerBuzzed:(TriviaPlayer *)thePlayer;
@end


text:
p.test a { background-color : red }
p.test *:visited { background-color : lime }


text:
# gpMgmt/bin/Makefile

default: install

top_builddir=../..
ifneq "$(wildcard $(top_builddir)/src/Makefile.global)" ""
include $(top_builddir)/src/Makefile.global
endif

SUBDIRS = stream gpcheckcat_modules gpconfig_modules gpssh_modules gppylib lib
SUBDIRS += ifaddrs

$(recurse)

PROGRAMS= analyzedb gpactivatestandby gpaddmirrors gpcheckcat gpcheckperf \
	gpcheckresgroupimpl gpconfig gpdeletesystem gpexpand gpinitstandby \
	gpinitsystem gpload gpload.py gplogfilter gpmovemirrors \
	gppkg gprecoverseg gpreload gpscp gpsd gpssh gpssh-exkeys gpstart \
	gpstate gpstop minirepro gpmemwatcher gpmemreport

installdirs:
	$(MKDIR_P) '$(DESTDIR)$(bindir)/lib'

installprograms: installdirs
	for file in $(PROGRAMS); do \
		$(INSTALL_SCRIPT) $$file '$(DESTDIR)$(bindir)/'$$file ; \
		$(PERL) $(top_builddir)/putversion '$(DESTDIR)$(bindir)/'$$file ; \
	done
	# Symlink gpcheckcat from bin to bin/lib to maintain backward compatibility
	if [ ! -L $(DESTDIR)$(bindir)/lib/gpcheckcat  ]; then \
		cd $(DESTDIR)$(bindir)/lib/ && $(LN_S) ../gpcheckcat gpcheckcat; \
	fi
	$(INSTALL_DATA) gpload.bat '$(DESTDIR)$(bindir)/gpload.bat'

uninstall:
	for file in $(PROGRAMS); do \
		rm -f '$(DESTDIR)$(bindir)/'$$file ; \
	done
	rm -f '$(DESTDIR)$(bindir)/gpload.bat'

#
# SOURCE DIRECTORIES
#
SRC=$(CURDIR)
PYLIB_SRC=$(SRC)/pythonSrc
PYLIB_SRC_EXT=$(PYLIB_SRC)/ext
SBIN_DIR=$(SRC)/../sbin
SERVER_SRC=$(SRC)
SERVER_SBIN=$(SERVER_SRC)/../sbin

#
# INSTALL DIRECTORY
#
LIB_DIR=$(SRC)/lib
PYLIB_DIR=$(SRC)/ext

core:
	python3 gpconfig_modules/parse_guc_metadata.py $(DESTDIR)$(prefix)

ifeq ($(with_pythonsrc_ext), yes)
install: installdirs installprograms core psutil pygresql pyyaml
else
install: installdirs installprograms core
endif

#
# Python Libraries
#

#
# PyGreSQL
#
PYGRESQL_VERSION=5.2
PYGRESQL_DIR=PyGreSQL-$(PYGRESQL_VERSION)
pygresql:
	@echo "--- PyGreSQL"
	cd $(PYLIB_SRC_EXT)/ && $(TAR) xzf $(PYGRESQL_DIR).tar.gz
	cd $(PYLIB_SRC_EXT)/$(PYGRESQL_DIR)/ && PATH=$(DESTDIR)$(bindir):$$PATH LDFLAGS='$(LDFLAGS) $(PYGRESQL_LDFLAGS)' python3 setup.py build
	cp -r $(PYLIB_SRC_EXT)/$(PYGRESQL_DIR)/build/lib*-3*/* $(PYLIB_DIR)/

#
# PSUTIL
#
PSUTIL_VERSION=5.7.0
PSUTIL_DIR=psutil-$(PSUTIL_VERSION)

psutil:
	@echo "--- psutil"
ifeq "$(findstring $(BLD_ARCH),aix7_ppc_64 )" ""
	cd $(PYLIB_SRC_EXT)/ && $(TAR) xzf $(PSUTIL_DIR).tar.gz
	cd $(PYLIB_SRC_EXT)/$(PSUTIL_DIR)/ && env -u CC python3 setup.py build
	cp -r $(PYLIB_SRC_EXT)/$(PSUTIL_DIR)/build/lib.*/psutil $(PYLIB_DIR)
endif

#
# PYYAML
#
PYYAML_VERSION=5.3.1
PYYAML_DIR=PyYAML-$(PYYAML_VERSION)

pyyaml:
	@echo "--- pyyaml"
	cd $(PYLIB_SRC_EXT)/ && $(TAR) xzf $(PYYAML_DIR).tar.gz
	cd $(PYLIB_SRC_EXT)/$(PYYAML_DIR)/ && env -u CC python3 setup.py build
	cp -r $(PYLIB_SRC_EXT)/$(PYYAML_DIR)/build/lib*-3.*/* $(PYLIB_DIR)

#
# PYLINT
#

PYLINT_VERSION=0.21.0
PYLINT_DIR=pylint-$(PYLINT_VERSION)
PYLINT_PYTHONPATH=$(PYLIB_DIR):$(PYLIB_SRC_EXT)/$(PYLINT_DIR)/build/lib/
MOCK_VERSION=1.0.1
MOCK_DIR=mock-$(MOCK_VERSION)
SETUP_TOOLS_VERSION=36.6.0
PARSE_VERSION=1.8.2
SETUP_TOOLS_DIR=setuptools-$(SETUP_TOOLS_VERSION)
PARSE_DIR=parse-$(PARSE_VERSION)
PYTHONSRC_INSTALL=$(PYLIB_SRC_EXT)/install
PYTHON_VERSION=$(shell python3 -c "import sys; print ('%s.%s' % (sys.version_info[0:2]))")
PYTHONSRC_INSTALL_SITE=$(PYLIB_SRC_EXT)/install/lib/python$(PYTHON_VERSION)/site-packages
PYTHONSRC_INSTALL_PYTHON_PATH=$(PYTHONPATH):$(PYTHONSRC_INSTALL_SITE)
# TODO: mock-1.0.1-py2.6.egg package should be updated.
MOCK_BIN=$(PYTHONSRC_INSTALL)/lib/python$(PYTHON_VERSION)/site-packages/mock-1.0.1-py2.6.egg
UBUNTU_PLATFORM=$(shell if lsb_release -a 2>/dev/null | grep -q 'Ubuntu' ; then echo "Ubuntu"; fi)

pylint:
	@echo "--- pylint"
	@cd $(PYLIB_SRC_EXT)/ && $(TAR) xzf $(PYLINT_DIR).tar.gz
	@cd $(PYLIB_SRC_EXT)/$(PYLINT_DIR)/ && python3 setup.py build 1> /dev/null
	@touch $(PYLIB_SRC_EXT)/$(PYLINT_DIR)/build/lib/__init__.py

$(MOCK_BIN):
	@echo "--- mock for platform $(UBUNTU_PLATFORM)"
	@if [ "$(UBUNTU_PLATFORM)" = "Ubuntu" ]; then\
       pip3 install mock;\
     else\
       mkdir -p $(PYTHONSRC_INSTALL_SITE) && \
	   cd $(PYLIB_SRC_EXT)/ && $(TAR) xzf $(MOCK_DIR).tar.gz && \
	   cd $(PYLIB_SRC_EXT)/$(MOCK_DIR)/ && \
	   PYTHONPATH=$(PYTHONSRC_INSTALL_PYTHON_PATH) python3 setup.py install --prefix $(PYTHONSRC_INSTALL) ; \
	 fi;

PYTHON_FILES=`grep -l --exclude=Makefile --exclude=gplogfilter "/bin/env python3" *`\
			 `grep -l "/bin/env python3" $(SRC)/../sbin/*`\
			 `find ./gppylib -name "*.py"`\
			 `find $(SRC)/../sbin -name "*.py"`

checkcode: pylint
	@echo "Running pylint on management scripts..."
	@PYTHONPATH=$(PYTHONPATH):$(PYLINT_PYTHONPATH) $(PYLIB_SRC_EXT)/$(PYLINT_DIR)/bin/pylint -i y $(PYTHON_FILES) --rcfile=.rcfile > $(SRC)/../pylint.txt || true
	@echo -n "pylint_score=" > $(SRC)/../pylint_score.properties
	@grep "Your code has been rated at" $(SRC)/../pylint.txt | sed -e "s|Your .* \(.*\)/.*|\1|" >> $(SRC)/../pylint_score.properties

check: $(MOCK_BIN)
	@echo "Running pure unit and also "unit" tests that require cluster to be up..."
	@TMPDIR=/tmp PYTHONPATH=$(SERVER_SRC):$(SERVER_SBIN):$(PYTHONPATH):$(PYTHONSRC_INSTALL_PYTHON_PATH):$(SRC)/ext:$(SBIN_DIR):$(LIB_DIR):$(PYLIB_DIR)/mock-1.0.1 \
	gppylib/gpunit discover --verbose -s $(SRC)/gppylib -p "test_unit*.py" 2> $(SRC)/../gpMgmt_testunit_results.log 1> $(SRC)/../gpMgmt_testunit_output.log
	@TMPDIR=/tmp PYTHONPATH=$(SERVER_SRC):$(SERVER_SBIN):$(PYTHONPATH):$(PYTHONSRC_INSTALL_PYTHON_PATH):$(SRC)/ext:$(SBIN_DIR):$(LIB_DIR):$(PYLIB_DIR)/mock-1.0.1 \
	gppylib/gpunit discover --verbose -s $(SRC)/gppylib -p "test_cluster*.py" 2>> $(SRC)/../gpMgmt_testunit_results.log 1>> $(SRC)/../gpMgmt_testunit_output.log

unitdevel:
	@echo "Running pure unit tests..."
	PYTHONPATH=$(SERVER_SRC):$(SERVER_SBIN):$(PYTHONPATH):$(PYTHONSRC_INSTALL_PYTHON_PATH):$(SRC)/ext:$(SBIN_DIR):$(LIB_DIR):$(PYLIB_DIR)/mock-1.0.1 \
	    python3 -m unittest discover --verbose -s $(SRC)/gppylib -p "test_unit*.py"

.PHONY: installcheck-bash
installcheck-bash:
	./test/suite.bash

.PHONY: installcheck
installcheck: installcheck-bash
	$(MAKE) -C gpload_test $@

clean distclean:
	rm -rf $(PYLIB_SRC_EXT)/$(PYLINT_DIR)
	rm -rf $(PYLIB_SRC_EXT)/$(PYGRESQL_DIR)/build
	rm -rf $(PYLIB_SRC)/$(PYGRESQL_DIR)/build
	rm -rf *.pyc
	rm -f analyzedbc gpactivatestandbyc gpaddmirrorsc gpcheckcatc \
		  gpcheckperfc gpcheckresgroupimplc gpchecksubnetcfgc gpconfigc \
		  gpdeletesystemc gpexpandc gpinitstandbyc gplogfilterc gpmovemirrorsc \
		  gppkgc gprecoversegc gpreloadc gpscpc gpsdc gpssh-exkeysc gpsshc \
		  gpstartc gpstatec gpstopc minireproc
	rm -f gpconfig_modules/gucs_disallowed_in_file.txt