text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable disable

using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.VisualStudio.Imaging.Interop;

namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options
{
    /// <summary>
    /// Represents a view model for <see cref="NotificationOption"/>
    /// </summary>
    internal class NotificationOptionViewModel
    {
        public NotificationOptionViewModel(NotificationOption notification, ImageMoniker moniker)
        {
            Notification = notification;
            Name = notification.Name;
            Moniker = moniker;
        }

        public ImageMoniker Moniker { get; }

        public string Name { get; }

        public NotificationOption Notification { get; }
    }
}

redpajama_set_name: RedPajamaGithub


text:
/////////////////////////////////////////////////////////////////////////////
//
// PlainSocket
//
// Original idea:
// David Maw: https://www.codeproject.com/Articles/1000189/A-Working-TCP-Client-and-Server-With-SSL
// License:   https://www.codeproject.com/info/cpol10.aspx
//
#include "stdafx.h"
#include <process.h>
#include <stdlib.h>
#include <WS2tcpip.h>
#include <MSTcpIP.h>
#include "PlainSocket.h"
#include "Logging.h"
#include <mswsock.h>

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

// Constructor for an active connection, socket created later
PlainSocket::PlainSocket(HANDLE p_stopEvent)
            :m_stopEvent(p_stopEvent)
{
  Initialize();
}

// Constructor for an already connected socket
PlainSocket::PlainSocket(SOCKET p_socket,HANDLE p_stopEvent)
            :m_actualSocket(p_socket)
            ,m_stopEvent(p_stopEvent)
{
  Initialize();
}

// Destructor
PlainSocket::~PlainSocket()
{
  Close();

  // Close all pending events
  if(m_read_event)
  {
    WSACloseEvent(m_read_event);
    m_read_event = nullptr;
  }
  if(m_write_event)
  {
    WSACloseEvent(m_write_event);
    m_write_event = nullptr;
  }
  if(m_extraStop)
  {
    CloseHandle(m_extraStop);
    m_extraStop = NULL;
  }
}

//////////////////////////////////////////////////////////////////////////
//
// PUBLIC MEMBERS
//
//////////////////////////////////////////////////////////////////////////

void
PlainSocket::Initialize()
{
  // Re-Set to sane values
	m_lastError     = 0;
	m_recvInitiated = false;

  // Getting the events and check for invalid values
  if(!m_read_event)
  {
    m_read_event = WSACreateEvent();
  }
	WSAResetEvent(m_read_event);
  if(!m_write_event)
  {
    m_write_event = WSACreateEvent();
  }
	WSAResetEvent(m_write_event);

  if(m_read_event == WSA_INVALID_EVENT || m_write_event == WSA_INVALID_EVENT)
  {
    throw "WSACreateEvent failed";
  }

  // Set socket options for TCP/IP
  int rc = true;
	setsockopt(m_actualSocket,IPPROTO_TCP,TCP_NODELAY,(char *)&rc,sizeof(int));

  m_initDone = true;
}

// Find connection type (AF_INET (IPv4) or AF_INET6 (IPv6))
int
PlainSocket::FindConnectType(LPCTSTR p_host,char* p_portname)
{
  ADDRINFO  hints;
  ADDRINFO* result;
  memset(&hints,0,sizeof(ADDRINFO));
  int type = AF_INET;

  // Request streaming type socket in TCP/IP protocol
  hints.ai_family   = AF_UNSPEC;
  hints.ai_socktype = SOCK_STREAM;
  hints.ai_protocol = IPPROTO_TCP;

  DWORD retval = getaddrinfo(p_host,p_portname,&hints,&result);
  if(retval == 0)
  {
    if((result->ai_family == AF_INET6) ||
       (result->ai_family == AF_INET))
    {
      type = result->ai_family;
    }
    freeaddrinfo(result);
  }
  else
  {
    // MESS_INETTYPE
    LogError("Cannot determine if internet is of type IP4 or IP6");
  }
  // Assume it's IP4 as a default
  return type;
}

// Connect as a client to a server actively
bool
PlainSocket::Connect(LPCTSTR p_hostName, USHORT p_portNumber)
{
	SOCKADDR_STORAGE localAddr  = {0};
	SOCKADDR_STORAGE remoteAddr = {0};
	DWORD sizeLocalAddr  = sizeof(localAddr);
	DWORD sizeRemoteAddr = sizeof(remoteAddr);
	char  portName[10]   = {0};
  BOOL    bSuccess     = FALSE;
	timeval timeout      = {0};
  int     result       = 0;

  if(m_initDone == false)
  {
    Initialize();
  }

  // Convert port number and find IPv4 or IPv6
  _itoa_s(p_portNumber, portName, _countof(portName), 10);
  int type = FindConnectType(p_hostName,portName);

  // Create the actual physical socket
	m_actualSocket = socket(type, SOCK_STREAM, 0);
	if (m_actualSocket == INVALID_SOCKET)
  {
		LogError("Socket failed with error: %d\n", WSAGetLastError());
		return false;
	}

  // Find timeout for the connection
  timeout.tv_sec = GetConnTimeoutSeconds();
	CTime Now = CTime::GetCurrentTime();

  USES_CONVERSION;
  std::wstring hostname = A2CW(p_hostName);
  std::wstring portname = A2CW(portName);

	// Note that WSAConnectByName requires Vista or Server 2008
  // Note that WSAConnectByNameA is deprecated, so we convert to the Unicode counterpart.
	bSuccess = WSAConnectByNameW(m_actualSocket
                              ,(LPWSTR) hostname.c_str()
                              ,(LPWSTR) portname.c_str()
                              ,&sizeLocalAddr
                              ,(SOCKADDR*)&localAddr
                              ,&sizeRemoteAddr
                              ,(SOCKADDR*)&remoteAddr
                              ,&timeout
                              ,nullptr);

	CTimeSpan HowLong = CTime::GetCurrentTime() - Now;
	if (!bSuccess)
  {
		m_lastError = WSAGetLastError();
		LogError("**** WSAConnectByName Error %d connecting to \"%s\" (%s)",
				     m_lastError,
				     p_hostName,
				     portName);
		closesocket(m_actualSocket);
		return false;
	}

  DebugMsg("Connection made in %ld second(s)",HowLong.GetTotalSeconds());

  // Activate previously set options
	result = setsockopt(m_actualSocket, SOL_SOCKET,SO_UPDATE_CONNECT_CONTEXT, NULL, 0);
	if (result == SOCKET_ERROR)
  {
		m_lastError = WSAGetLastError();
		LogError("setsockopt for SO_UPDATE_CONNECT_CONTEXT failed with error: %d", m_lastError);
		closesocket(m_actualSocket);
		return false;
	}

  result = true;
	// At this point we have a connection, so set up keep-alive so we can detect if the host disconnects
	// This code is commented out because it does not seen to be helpful
  if(m_useKeepalive)
  {
    result = ActivateKeepalive();
  }

  // We are now a client side socket
  m_active = true;

  // Remember what we connected on
  m_hostName   = p_hostName;
  m_portNumber = p_portNumber;

	return result;
}

bool PlainSocket::ActivateKeepalive()
{
  BOOL so_keepalive = m_useKeepalive;
  int iResult = setsockopt(m_actualSocket, SOL_SOCKET, SO_KEEPALIVE, (const char *)&so_keepalive, sizeof(so_keepalive));
	if (iResult == SOCKET_ERROR)
  {
		m_lastError = WSAGetLastError();
		LogError("Setsockopt for SO_KEEPALIVE failed with error: %d\n",m_lastError);
		closesocket(m_actualSocket);
    m_actualSocket = NULL;
		return false;
	}

  // Now set keep alive timings, if activated
  if(m_useKeepalive)
  {
    DWORD dwBytes = 0;
    tcp_keepalive setting = { 0 };

    setting.onoff             = 1;
    setting.keepalivetime     = m_keepaliveTime     * CLOCKS_PER_SEC;     // Keep Alive in x milli seconds
    setting.keepaliveinterval = m_keepaliveInterval * CLOCKS_PER_SEC;     // Resend if No-Reply
    if (WSAIoctl(m_actualSocket
                ,SIO_KEEPALIVE_VALS
                ,&setting
    	          ,sizeof(setting)
                ,nullptr          // Result buffer sReturned
                ,0                // Size of result buffer
                ,&dwBytes         // Total bytes
                ,nullptr          // Pointer to OVERLAPPED
                ,nullptr) != 0)   // Completion routine
    {
      m_lastError = WSAGetLastError() ;
      LogError("WSAIoctl to set keep-alive failed with error: %d\n", m_lastError);
      closesocket(m_actualSocket);
      m_actualSocket = NULL;
      return false;
    }
  }
  return true;
}

// Set up SSL/TLS state for this connection:
// NEVER USED ON PLAIN SOCKETS! Only on derived classes!!
HRESULT
PlainSocket::InitializeSSL(const void* /*p_buffer*/ /*= nullptr*/,const int /*p_length*/ /*= 0*/)
{
  return SOCKET_ERROR;
}

void PlainSocket::SetConnTimeoutSeconds(int p_newTimeoutSeconds)
{
  if(p_newTimeoutSeconds == INFINITE)
  {
    p_newTimeoutSeconds = MAXINT;
  }
  if(p_newTimeoutSeconds > 0)
  {
    m_connTimeoutSeconds = p_newTimeoutSeconds;
  }
}

void PlainSocket::SetRecvTimeoutSeconds(int NewRecvTimeoutSeconds)
{
  if(NewRecvTimeoutSeconds == INFINITE)
  {
    NewRecvTimeoutSeconds = MAXINT;
  }
	if (NewRecvTimeoutSeconds>0)
	{
		m_recvTimeoutSeconds = NewRecvTimeoutSeconds;
		m_recvEndTime = CTime::GetCurrentTime() + CTimeSpan(0,0,0,m_recvTimeoutSeconds);
	}
}

void
PlainSocket::SetSendTimeoutSeconds(int NewSendTimeoutSeconds)
{
  if(NewSendTimeoutSeconds == INFINITE)
  {
    NewSendTimeoutSeconds = MAXINT;
  }
	if (NewSendTimeoutSeconds>0)
	{
		m_sendTimeoutSeconds = NewSendTimeoutSeconds;
		m_sendEndTime = CTime::GetCurrentTime() + CTimeSpan(0,0,0,m_sendTimeoutSeconds);
	}
}

bool
PlainSocket::SetUseKeepAlive(bool p_keepalive)
{
  m_useKeepalive = p_keepalive;
  if(m_initDone)
  {
    return ActivateKeepalive();
  }
  return true;
}

bool
PlainSocket::SetKeepaliveTime(int p_time)
{
  if(p_time > MINIMUM_KEEPALIVE)
  {
    m_keepaliveTime = p_time;
    if(m_initDone)
    {
      return ActivateKeepalive();
    }
    return true;
  }
  return false;
}

bool
PlainSocket::SetKeepaliveInterval(int p_interval)
{
  if(p_interval > MINIMUM_KEEPALIVE)
  {
    m_keepaliveInterval = p_interval;
    if(m_initDone)
    {
      return ActivateKeepalive();
    }
    return true;
  }
  return false;
}

DWORD PlainSocket::GetLastError()
{
	return m_lastError;
}

// Shutdown one of the sides of the socket, or both
int
PlainSocket::Disconnect(int p_how)
{
  if(m_actualSocket)
  {
    return ::shutdown(m_actualSocket, p_how);
  }
  return NO_ERROR;
}

bool
PlainSocket::Close(void)
{
  // Possibly notify a waiting application for HttpWaitForDisconnect
  if(m_extraStop)
  {
    SetEvent(m_extraStop);
  }

  // If initialized: close the underlying system socket
  if(m_initDone)
  {
    // Shutdown both sides of the socket
    if(Disconnect(SD_SEND) != 0)
    {
		  m_lastError = ::WSAGetLastError();
		  return false;
	  }

    if(closesocket(m_actualSocket))
    {
      // Log the error
      m_lastError = WSAGetLastError();
      return false;
    }
    m_actualSocket = NULL;
    m_initDone = false;
  }
  return true;
}

// Waiting for this socket to disconnect
ULONG
PlainSocket::RegisterForDisconnect()
{
  if(m_extraStop)
  {
    return ERROR_ALREADY_EXISTS;
  }
  m_extraStop = ::CreateEvent(nullptr,FALSE,FALSE,nullptr);
  DWORD result = WaitForSingleObject(m_extraStop,INFINITE);

  // Ready with stop event
  CloseHandle(m_extraStop);
  m_extraStop = NULL;

  // Result
  return result == WAIT_OBJECT_0 ? NO_ERROR : ERROR_CONNECTION_ABORTED;
}

//////////////////////////////////////////////////////////////////////////
//
// RECEIVING AND SENDING DATA
//
//////////////////////////////////////////////////////////////////////////

// Receives up to Len bytes of data and returns the amount received - or SOCKET_ERROR if it times out
int
PlainSocket::RecvPartial(LPVOID p_buffer, const ULONG p_length)
{
	WSABUF    buffer;
	WSAEVENT  hEvents[2] = { m_stopEvent,m_read_event };
  DWORD			bytes_read = 0;
  DWORD     msg_flags  = 0;
	int       received   = 0;

	if (m_recvInitiated)
	{
		// Special case, the previous read timed out, so we are trying again, maybe it completed in the meantime
		received      = SOCKET_ERROR;
		m_lastError   = WSA_IO_PENDING;
		m_recvEndTime = 0;
	}
	else
	{
		// Normal case, the last read completed normally, now we're reading again

		// Setup the buffers array
		buffer.buf = static_cast<char*>(p_buffer);
		buffer.len = p_length;

		// Create the overlapped I/O event and structures
		memset(&m_os, 0, sizeof(OVERLAPPED));
		m_os.hEvent = hEvents[1];
		WSAResetEvent(m_os.hEvent);
		m_recvInitiated = true;
		received = WSARecv(m_actualSocket, &buffer, 1, &bytes_read, &msg_flags, &m_os, NULL); // Start an asynchronous read
		m_lastError = WSAGetLastError();
	}

	// If the timer has been invalidated, restart it
  if(m_recvEndTime == 0)
  {
    m_recvEndTime = CTime::GetCurrentTime() + CTimeSpan(0,0,0,m_recvTimeoutSeconds);
  }
	// Now wait for the I/O to complete if necessary, and see what happened
	bool IOCompleted = false;

	if ((received == SOCKET_ERROR) && (m_lastError == WSA_IO_PENDING))  // Read in progress, normal case
	{
		CTimeSpan TimeLeft = m_recvEndTime - CTime::GetCurrentTime();
		DWORD dwWait, milliSecondsLeft = (DWORD)TimeLeft.GetTotalSeconds()*1000;
    if(milliSecondsLeft <= 5)
    {
      dwWait = WAIT_TIMEOUT;
    }
		else
		{
			dwWait = WaitForMultipleObjects(2, hEvents, false, milliSecondsLeft);
      if(dwWait == WAIT_OBJECT_0 + 1) // The read event
      {
        IOCompleted = true;
      }
		}
	}
  else if(!received) // if received is zero, the read was completed immediately
  {
    IOCompleted = true;
  }
	if(IOCompleted)
	{
		m_recvInitiated = false;
		if(WSAGetOverlappedResult(m_actualSocket,&m_os,&bytes_read,true,&msg_flags) && (bytes_read > 0))
		{
      if(!InSecureMode())
      {
        DebugMsg(" ");
        DebugMsg("Received message has %d bytes",bytes_read);
        PrintHexDump(bytes_read,p_buffer);
      }

			m_lastError = 0;
      if(bytes_read == p_length) // We got what was requested
      {
        m_recvEndTime = 0; // Restart the timer on the next read
      }
			return bytes_read; // Normal case, we read some bytes, it's all good
		}
		else
		{
      // A bad thing happened
			int error = WSAGetLastError();
      if(error == 0) // The socket was closed
      {
        return 0;
      }
      else if(m_lastError == 0)
      {
        m_lastError = error;
      }
		}
	}
	return SOCKET_ERROR;
}

// Receives exactly Len bytes of data and returns the amount received - or SOCKET_ERROR if it times out
int PlainSocket::RecvMsg(LPVOID p_buffer, const ULONG p_length)
{
  ULONG bytes_received       = 0;
	ULONG total_bytes_received = 0;

	m_recvEndTime = 0; // Tell RecvPartial to restart the timer

	while (total_bytes_received < p_length)
	{
		bytes_received = PlainSocket::RecvPartial((char*)p_buffer+total_bytes_received, p_length-total_bytes_received);
    if(bytes_received == SOCKET_ERROR)
    {
      return SOCKET_ERROR;
    }
    else if(bytes_received == 0)
    {
      break; // socket is closed, no data left to receive
    }
    else
    {
      total_bytes_received += bytes_received;
    }
	}; // loop
	return (total_bytes_received);
}

// sends a message, or part of one
int PlainSocket::SendPartial(LPCVOID p_buffer, const ULONG p_length)
{
	WSAOVERLAPPED os;
	WSABUF buffer;
	DWORD bytes_sent = 0;

	// Setup the buffer array
	buffer.buf = (char *)p_buffer;
	buffer.len = p_length;

  if(!InSecureMode())
  {
    DebugMsg(" ");
    DebugMsg("Send message has %d bytes",p_length);
    PrintHexDump(p_length,p_buffer);
  }

	// Reset the timer if it has been invalidated
  if(m_sendEndTime == 0)
  {
    m_sendEndTime = CTime::GetCurrentTime() + CTimeSpan(0,0,0,m_sendTimeoutSeconds);
  }
	m_lastError = 0;

	// Create the overlapped I/O event and structures
	memset(&os, 0, sizeof(OVERLAPPED));
	os.hEvent = m_write_event;
	WSAResetEvent(m_read_event);
	int received = WSASend(m_actualSocket, &buffer, 1, &bytes_sent, 0, &os, NULL);
	m_lastError  = WSAGetLastError();

	// Now wait for the I/O to complete if necessary, and see what happened
	bool IOCompleted = false;

	if ((received == SOCKET_ERROR) && (m_lastError == WSA_IO_PENDING))  // Write in progress
	{
		WSAEVENT hEvents[2] = { m_stopEvent,m_write_event };
	  DWORD dwWait;
		CTimeSpan TimeLeft = m_sendEndTime - CTime::GetCurrentTime();
		dwWait = WaitForMultipleObjects(2, hEvents, false, (DWORD)TimeLeft.GetTotalSeconds()*1000);
    if(dwWait == WAIT_OBJECT_0 + 1) // The write event
    {
      IOCompleted = true;
    }
	}
  else if(!received) // if rc is zero, the write was completed immediately, which is common
  {
    IOCompleted = true;
  }

	if (IOCompleted)
	{
		DWORD msg_flags = 0;
		if (WSAGetOverlappedResult(m_actualSocket, &os, &bytes_sent, true, &msg_flags))
		{
      if(bytes_sent == p_length) // Everything that was requested was sent
      {
        m_sendEndTime = 0;  // Invalidate the timer so it is set next time through
      }
			return bytes_sent;
		}
	}
	return SOCKET_ERROR;
}

// sends all the data or returns a timeout
//
int
PlainSocket::SendMsg(LPCVOID p_buffer, const ULONG p_length)
{
	ULONG	bytes_sent       = 0;
	ULONG total_bytes_sent = 0;

  // Do we have something to do?
  if(p_length == 0)
  {
    return 0;
  }

	m_sendEndTime = 0; // Invalidate the timer so SendPartial can reset it.

	while (total_bytes_sent < p_length)
	{
		bytes_sent = PlainSocket::SendPartial((char*)p_buffer + total_bytes_sent, p_length - total_bytes_sent);
    if((bytes_sent == SOCKET_ERROR))
    {
      return SOCKET_ERROR;
    }
    else if(bytes_sent == 0)
    {
      if(total_bytes_sent == 0)
      {
        return SOCKET_ERROR;
      }
      else
      {
        break; // socket is closed, no chance of sending more
      }
    }
    else
    {
      total_bytes_sent += bytes_sent;
    }
	}; // loop
	return (total_bytes_sent);
}

// Test if the socket is (still) readable
bool
PlainSocket::IsReadible(bool& p_readible)
{
  timeval timeout = {0, 0};
  fd_set  fds;
  FD_ZERO(&fds);
  FD_SET(m_actualSocket,&fds);
  int status = select(0,&fds,nullptr,nullptr,&timeout);
  if(status == SOCKET_ERROR)
  {
    return false;
  }
  else
  {
    p_readible = !(status == 0);
    return true;
  }
}


text:
<?php

declare(strict_types=1);

namespace OAuth2Framework\Tests\Component\AuthorizationEndpoint\Tests\AuthorizationRequest;

use OAuth2Framework\Component\AuthorizationEndpoint\AuthorizationRequest\AuthorizationRequest;
use OAuth2Framework\Component\Core\Client\Client;
use OAuth2Framework\Component\Core\DataBag\DataBag;
use OAuth2Framework\Component\Core\ResourceServer\ResourceServer;
use OAuth2Framework\Component\Core\UserAccount\UserAccount;
use PHPUnit\Framework\TestCase;
use Prophecy\PhpUnit\ProphecyTrait;

/**
 * @group AuthorizationEndpoint
 * @group AuthorizationRequest
 *
 * @internal
 */
final class AuthorizationRequestTest extends TestCase
{
    use ProphecyTrait;

    /**
     * @test
     */
    public function basicCalls()
    {
        $client = $this->prophesize(Client::class);
        $userAccount = $this->prophesize(UserAccount::class);
        $resourceServer = $this->prophesize(ResourceServer::class);
        $params = [
            'prompt' => 'consent login select_account',
            'ui_locales' => 'fr en',
            'scope' => 'scope1 scope2',
            'redirect_uri' => 'https://localhost',
        ];
        $authorizationRequest = new AuthorizationRequest($client->reveal(), $params);

        $authorizationRequest->setUserAccount($userAccount->reveal());
        $authorizationRequest->setResponseParameter('foo', 'bar');
        $authorizationRequest->setResponseHeader('X-FOO', 'bar');
        $authorizationRequest->setResourceServer($resourceServer->reveal());

        static::assertEquals($params, $authorizationRequest->getQueryParams());
        static::assertFalse($authorizationRequest->hasQueryParam('client_id'));
        static::assertTrue($authorizationRequest->hasQueryParam('prompt'));
        static::assertEquals('consent login select_account', $authorizationRequest->getQueryParam('prompt'));
        static::assertInstanceOf(Client::class, $authorizationRequest->getClient());
        static::assertEquals('https://localhost', $authorizationRequest->getRedirectUri());
        static::assertInstanceOf(UserAccount::class, $authorizationRequest->getUserAccount());
        static::assertEquals(['foo' => 'bar'], $authorizationRequest->getResponseParameters());
        static::assertFalse($authorizationRequest->hasResponseParameter('bar'));
        static::assertTrue($authorizationRequest->hasResponseParameter('foo'));
        static::assertEquals('bar', $authorizationRequest->getResponseParameter('foo'));
        static::assertEquals(['X-FOO' => 'bar'], $authorizationRequest->getResponseHeaders());
        static::assertFalse($authorizationRequest->hasPrompt('none'));
        static::assertTrue($authorizationRequest->hasPrompt('login'));
        static::assertEquals(['consent', 'login', 'select_account'], $authorizationRequest->getPrompt());
        static::assertTrue($authorizationRequest->hasUiLocales());
        static::assertEquals(['fr', 'en'], $authorizationRequest->getUiLocales());
        $authorizationRequest->allow();
        static::assertTrue($authorizationRequest->isAuthorized());
        $authorizationRequest->deny();
        static::assertFalse($authorizationRequest->isAuthorized());
        static::assertInstanceOf(ResourceServer::class, $authorizationRequest->getResourceServer());
        static::assertTrue($authorizationRequest->hasScope());
        static::assertEquals('scope1 scope2', $authorizationRequest->getScope());
        static::assertInstanceOf(DataBag::class, $authorizationRequest->getMetadata());
    }
}


text:
package org.gameontext.map;

import javax.enterprise.context.ApplicationScoped;
import javax.ws.rs.Consumes;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.ext.Provider;

import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;

@Provider
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@ApplicationScoped
public class JaxbJsonProvider extends JacksonJaxbJsonProvider {

}


text:
'use strict';

/**
 * @ngdoc service
 * @name wwwApp.config
 * @description
 * # config
 * Service in the wwwApp.
 */
angular.module('wwwApp')
  .service('config', function () {
    this.api = {
      baseURL: '/api',
      version: '1.0'
    };
  });


text:
<?php

namespace Afk11\Pkcs5\Tests\Digest\Pbkdf2;

use Afk11\Pkcs5\Digest\Pbkdf2\Pbkdf2Factory;
use Afk11\Pkcs5\Digest\Pbkdf2\Pbkdf2Params;
use Afk11\Pkcs5\Tests\AbstractTestCase;

class Pbkdf2ParamsTest extends AbstractTestCase
{
    public function testInstance()
    {
        $method = Pbkdf2Factory::PBKDF2_WITH_SHA256;
        $salt = 'abcd01234';
        $iterCount = 1000;
        $keyLength = 32;
        $params = new Pbkdf2Params($method, $salt, $iterCount, $keyLength);

        $this->assertEquals($method, $params->getMethod());
        $this->assertEquals($salt, $params->getSalt());
        $this->assertEquals($iterCount, $params->getIterationCount());
        $this->assertEquals($keyLength, $params->getKeyLength());
    }

    /**
     * @expectedException \RuntimeException
     * @expectedExceptionMessage Iteration count must be numeric
     */
    public function testInvalidAlgo()
    {
        $method = Pbkdf2Factory::PBKDF2_WITH_SHA256;
        $salt = 'abcd01234';
        $iterCount = 'blah';
        $keyLength = 32;
        new Pbkdf2Params($method, $salt, $iterCount, $keyLength);
    }

    /**
     * @expectedException \RuntimeException
     */
    public function testInvalidKeyLength()
    {
        $method = 'invalid';
        $salt = 'abcd01234';
        $iterCount = 1000;
        $keyLength = 'asdf';
        new Pbkdf2Params($method, $salt, $iterCount, $keyLength);
    }

    /**
     * @expectedException \RuntimeException
     * @expectedExceptionMessage Salt must be a string
     */
    public function testInvalidSalt()
    {
        $method = Pbkdf2Factory::PBKDF2_WITH_SHA224;
        $salt = false;
        $iterCount = 1000;
        $keyLength = 32;
        new Pbkdf2Params($method, $salt, $iterCount, $keyLength);
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<phpunit colors="true" bootstrap="tests/TestAutoLoad.php">
    <testsuites>
        <testsuite name="Culqi PHP Tests">
            <directory suffix="Test.php">tests</directory>
            <file>Test.php</file>
        </testsuite>
    </testsuites>
    <php>
         <ini name="display_errors" value="true"/>
    </php>
</phpunit>


text:
package org.elasticsearch.index;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardTokenizer;
import org.apache.lucene.index.AssertingDirectoryReader;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.FieldInvertState;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.CollectionStatistics;
import org.apache.lucene.search.QueryCachingPolicy;
import org.apache.lucene.search.TermStatistics;
import org.apache.lucene.search.Weight;
import org.apache.lucene.search.similarities.BM25Similarity;
import org.apache.lucene.search.similarities.Similarity;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.SetOnce.AlreadySetException;
import org.elasticsearch.Version;
import org.elasticsearch.cluster.metadata.IndexMetadata;
import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.routing.RecoverySource;
import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.cluster.routing.UnassignedInfo;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.CheckedFunction;
import org.elasticsearch.common.breaker.CircuitBreaker;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Setting.Property;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.util.BigArrays;
import org.elasticsearch.common.util.PageCacheRecycler;
import org.elasticsearch.common.util.concurrent.EsRejectedExecutionException;
import org.elasticsearch.core.internal.io.IOUtils;
import org.elasticsearch.env.Environment;
import org.elasticsearch.env.NodeEnvironment;
import org.elasticsearch.env.ShardLock;
import org.elasticsearch.env.TestEnvironment;
import org.elasticsearch.index.analysis.AnalysisRegistry;
import org.elasticsearch.index.analysis.AnalyzerProvider;
import org.elasticsearch.index.analysis.AnalyzerScope;
import org.elasticsearch.index.cache.query.DisabledQueryCache;
import org.elasticsearch.index.cache.query.IndexQueryCache;
import org.elasticsearch.index.cache.query.QueryCache;
import org.elasticsearch.index.engine.Engine;
import org.elasticsearch.index.engine.InternalEngineFactory;
import org.elasticsearch.index.engine.InternalEngineTests;
import org.elasticsearch.index.fielddata.IndexFieldDataCache;
import org.elasticsearch.index.mapper.ParsedDocument;
import org.elasticsearch.index.mapper.Uid;
import org.elasticsearch.index.shard.IndexEventListener;
import org.elasticsearch.index.shard.IndexingOperationListener;
import org.elasticsearch.index.shard.SearchOperationListener;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.index.shard.ShardPath;
import org.elasticsearch.index.similarity.NonNegativeScoresSimilarity;
import org.elasticsearch.index.similarity.SimilarityService;
import org.elasticsearch.index.store.FsDirectoryFactory;
import org.elasticsearch.indices.IndicesModule;
import org.elasticsearch.indices.IndicesQueryCache;
import org.elasticsearch.indices.analysis.AnalysisModule;
import org.elasticsearch.indices.breaker.CircuitBreakerService;
import org.elasticsearch.indices.breaker.NoneCircuitBreakerService;
import org.elasticsearch.indices.cluster.IndicesClusterStateService.AllocatedIndices.IndexRemovalReason;
import org.elasticsearch.indices.fielddata.cache.IndicesFieldDataCache;
import org.elasticsearch.indices.mapper.MapperRegistry;
import org.elasticsearch.indices.recovery.RecoveryState;
import org.elasticsearch.plugins.IndexStorePlugin;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.search.internal.ReaderContext;
import org.elasticsearch.test.ClusterServiceUtils;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.test.IndexSettingsModule;
import org.elasticsearch.test.engine.MockEngineFactory;
import org.elasticsearch.threadpool.TestThreadPool;
import org.elasticsearch.threadpool.ThreadPool;
import org.hamcrest.Matchers;

import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

import static java.util.Collections.emptyMap;
import static java.util.Collections.singletonMap;
import static org.elasticsearch.index.IndexService.IndexCreationContext.CREATE_INDEX;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.hasToString;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.mockito.Mockito.mock;

public class IndexModuleTests extends ESTestCase {
    private Index index;
    private Settings settings;
    private IndexSettings indexSettings;
    private Environment environment;
    private AnalysisRegistry emptyAnalysisRegistry;
    private NodeEnvironment nodeEnvironment;
    private IndicesQueryCache indicesQueryCache;

    private IndexService.ShardStoreDeleter deleter = new IndexService.ShardStoreDeleter() {
        @Override
        public void deleteShardStore(String reason, ShardLock lock, IndexSettings indexSettings) throws IOException {
        }
        @Override
        public void addPendingDelete(ShardId shardId, IndexSettings indexSettings) {
        }
    };

    private final IndexFieldDataCache.Listener listener = new IndexFieldDataCache.Listener() {};
    private MapperRegistry mapperRegistry;
    private ThreadPool threadPool;
    private CircuitBreakerService circuitBreakerService;
    private BigArrays bigArrays;
    private ScriptService scriptService;
    private ClusterService clusterService;

    @Override
    public void setUp() throws Exception {
        super.setUp();
        settings = Settings.builder().put(IndexMetadata.SETTING_VERSION_CREATED, Version.CURRENT)
                .put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toString()).build();
        indicesQueryCache = new IndicesQueryCache(settings);
        indexSettings = IndexSettingsModule.newIndexSettings("foo", settings);
        index = indexSettings.getIndex();
        environment = TestEnvironment.newEnvironment(settings);
        emptyAnalysisRegistry = new AnalysisRegistry(environment, emptyMap(), emptyMap(), emptyMap(), emptyMap(), emptyMap(),
                emptyMap(), emptyMap(), emptyMap(), emptyMap());
        threadPool = new TestThreadPool("test");
        circuitBreakerService = new NoneCircuitBreakerService();
        PageCacheRecycler pageCacheRecycler = new PageCacheRecycler(settings);
        bigArrays = new BigArrays(pageCacheRecycler, circuitBreakerService, CircuitBreaker.REQUEST);
        scriptService = new ScriptService(settings, Collections.emptyMap(), Collections.emptyMap());
        clusterService = ClusterServiceUtils.createClusterService(threadPool);
        nodeEnvironment = new NodeEnvironment(settings, environment);
        mapperRegistry = new IndicesModule(Collections.emptyList()).getMapperRegistry();
    }

    @Override
    public void tearDown() throws Exception {
        super.tearDown();
        IOUtils.close(nodeEnvironment, indicesQueryCache, clusterService);
        ThreadPool.terminate(threadPool, 10, TimeUnit.SECONDS);
    }

    private IndexService newIndexService(IndexModule module) throws IOException {
        return module.newIndexService(CREATE_INDEX, nodeEnvironment, xContentRegistry(), deleter, circuitBreakerService, bigArrays,
                threadPool, scriptService, clusterService, null, indicesQueryCache, mapperRegistry,
                new IndicesFieldDataCache(settings, listener), writableRegistry(), () -> false, null);
    }

    public void testWrapperIsBound() throws IOException {
        final MockEngineFactory engineFactory = new MockEngineFactory(AssertingDirectoryReader.class);
        IndexModule module = new IndexModule(
                indexSettings,
                emptyAnalysisRegistry,
                engineFactory,
                Collections.emptyMap(),
                () -> true,
                new IndexNameExpressionResolver(),
                Collections.emptyMap());
        module.setReaderWrapper(s -> new Wrapper());

        IndexService indexService = newIndexService(module);
        assertTrue(indexService.getReaderWrapper() instanceof Wrapper);
        assertSame(indexService.getEngineFactory(), module.getEngineFactory());
        indexService.close("simon says", false);
    }

    public void testRegisterIndexStore() throws IOException {
        final Settings settings = Settings
            .builder()
            .put(IndexMetadata.SETTING_VERSION_CREATED, Version.CURRENT)
            .put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toString())
            .put(IndexModule.INDEX_STORE_TYPE_SETTING.getKey(), "foo_store")
            .build();
        final IndexSettings indexSettings = IndexSettingsModule.newIndexSettings(index, settings);
        final Map<String, IndexStorePlugin.DirectoryFactory> indexStoreFactories = singletonMap(
            "foo_store", new FooFunction());
        final IndexModule module = new IndexModule(indexSettings, emptyAnalysisRegistry, new InternalEngineFactory(), indexStoreFactories,
            () -> true, new IndexNameExpressionResolver(), Collections.emptyMap());

        final IndexService indexService = newIndexService(module);
        assertThat(indexService.getDirectoryFactory(), instanceOf(FooFunction.class));

        indexService.close("simon says", false);
    }

    public void testOtherServiceBound() throws IOException {
        final AtomicBoolean atomicBoolean = new AtomicBoolean(false);
        final IndexEventListener eventListener = new IndexEventListener() {
            @Override
            public void beforeIndexRemoved(IndexService indexService, IndexRemovalReason reason) {
                atomicBoolean.set(true);
            }
        };
        IndexSettings indexSettings = IndexSettingsModule.newIndexSettings(index, settings);
        IndexModule module = createIndexModule(indexSettings, emptyAnalysisRegistry);
        module.addIndexEventListener(eventListener);
        IndexService indexService = newIndexService(module);
        IndexSettings x = indexService.getIndexSettings();
        assertEquals(x.getSettings(), indexSettings.getSettings());
        assertEquals(x.getIndex(), index);
        indexService.getIndexEventListener().beforeIndexRemoved(null, null);
        assertTrue(atomicBoolean.get());
        indexService.close("simon says", false);
    }

    public void testListener() throws IOException {
        Setting<Boolean> booleanSetting = Setting.boolSetting("index.foo.bar", false, Property.Dynamic, Property.IndexScope);
        final IndexSettings indexSettings = IndexSettingsModule.newIndexSettings(index, settings, booleanSetting);
        IndexModule module = createIndexModule(indexSettings, emptyAnalysisRegistry);
        Setting<Boolean> booleanSetting2 = Setting.boolSetting("index.foo.bar.baz", false, Property.Dynamic, Property.IndexScope);
        AtomicBoolean atomicBoolean = new AtomicBoolean(false);
        module.addSettingsUpdateConsumer(booleanSetting, atomicBoolean::set);

        try {
            module.addSettingsUpdateConsumer(booleanSetting2, atomicBoolean::set);
            fail("not registered");
        } catch (IllegalArgumentException ex) {

        }

        IndexService indexService = newIndexService(module);
        assertSame(booleanSetting, indexService.getIndexSettings().getScopedSettings().get(booleanSetting.getKey()));

        indexService.close("simon says", false);
    }

    public void testAddIndexOperationListener() throws IOException {
        final IndexSettings indexSettings = IndexSettingsModule.newIndexSettings(index, settings);
        IndexModule module = createIndexModule(indexSettings, emptyAnalysisRegistry);
        AtomicBoolean executed = new AtomicBoolean(false);
        IndexingOperationListener listener = new IndexingOperationListener() {
            @Override
            public Engine.Index preIndex(ShardId shardId, Engine.Index operation) {
                executed.set(true);
                return operation;
            }
        };
        module.addIndexOperationListener(listener);

        expectThrows(IllegalArgumentException.class, () -> module.addIndexOperationListener(listener));
        expectThrows(IllegalArgumentException.class, () -> module.addIndexOperationListener(null));

        IndexService indexService = newIndexService(module);
        assertEquals(2, indexService.getIndexOperationListeners().size());
        assertEquals(IndexingSlowLog.class, indexService.getIndexOperationListeners().get(0).getClass());
        assertSame(listener, indexService.getIndexOperationListeners().get(1));

        ParsedDocument doc = InternalEngineTests.createParsedDoc("1", null);
        Engine.Index index = new Engine.Index(new Term("_id",  Uid.encodeId(doc.id())), randomNonNegativeLong(), doc);
        ShardId shardId = new ShardId(new Index("foo", "bar"), 0);
        for (IndexingOperationListener l : indexService.getIndexOperationListeners()) {
            l.preIndex(shardId, index);
        }
        assertTrue(executed.get());
        indexService.close("simon says", false);
    }

    public void testAddSearchOperationListener() throws IOException {
        final IndexSettings indexSettings = IndexSettingsModule.newIndexSettings(index, settings);
        IndexModule module = createIndexModule(indexSettings, emptyAnalysisRegistry);
        AtomicBoolean executed = new AtomicBoolean(false);
        SearchOperationListener listener = new SearchOperationListener() {
            @Override
            public void onNewReaderContext(ReaderContext readerContext) {
                executed.set(true);
            }
        };
        module.addSearchOperationListener(listener);

        expectThrows(IllegalArgumentException.class, () -> module.addSearchOperationListener(listener));
        expectThrows(IllegalArgumentException.class, () -> module.addSearchOperationListener(null));

        IndexService indexService = newIndexService(module);
        assertEquals(2, indexService.getSearchOperationListener().size());
        assertEquals(SearchSlowLog.class, indexService.getSearchOperationListener().get(0).getClass());
        assertSame(listener, indexService.getSearchOperationListener().get(1));
        for (SearchOperationListener l : indexService.getSearchOperationListener()) {
            l.onNewReaderContext(mock(ReaderContext.class));
        }
        assertTrue(executed.get());
        indexService.close("simon says", false);
    }

    public void testAddSimilarity() throws IOException {
        Settings settings = Settings.builder()
                .put(IndexMetadata.SETTING_VERSION_CREATED, Version.CURRENT)
                .put("index.similarity.my_similarity.type", "test_similarity")
                .put("index.similarity.my_similarity.key", "there is a key")
                .put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toString())
                .build();
        final IndexSettings indexSettings = IndexSettingsModule.newIndexSettings("foo", settings);
        IndexModule module =
                createIndexModule(indexSettings, emptyAnalysisRegistry);
        module.addSimilarity("test_similarity",
                (providerSettings, indexCreatedVersion, scriptService) -> new TestSimilarity(providerSettings.get("key")));

        IndexService indexService = newIndexService(module);
        SimilarityService similarityService = indexService.similarityService();
        Similarity similarity = similarityService.getSimilarity("my_similarity").get();
        assertNotNull(similarity);
        assertThat(similarity, Matchers.instanceOf(NonNegativeScoresSimilarity.class));
        similarity = ((NonNegativeScoresSimilarity) similarity).getDelegate();
        assertThat(similarity, Matchers.instanceOf(TestSimilarity.class));
        assertEquals("my_similarity", similarityService.getSimilarity("my_similarity").name());
        assertEquals("there is a key", ((TestSimilarity) similarity).key);
        indexService.close("simon says", false);
    }

    public void testFrozen() {
        final IndexSettings indexSettings = IndexSettingsModule.newIndexSettings(index, settings);
        IndexModule module = createIndexModule(indexSettings, emptyAnalysisRegistry);
        module.freeze();
        String msg = "Can't modify IndexModule once the index service has been created";
        assertEquals(msg, expectThrows(IllegalStateException.class, () -> module.addSearchOperationListener(null)).getMessage());
        assertEquals(msg, expectThrows(IllegalStateException.class, () -> module.addIndexEventListener(null)).getMessage());
        assertEquals(msg, expectThrows(IllegalStateException.class, () -> module.addIndexOperationListener(null)).getMessage());
        assertEquals(msg, expectThrows(IllegalStateException.class, () -> module.addSimilarity(null, null)).getMessage());
        assertEquals(msg, expectThrows(IllegalStateException.class, () -> module.setReaderWrapper(null)).getMessage());
        assertEquals(msg, expectThrows(IllegalStateException.class, () -> module.forceQueryCacheProvider(null)).getMessage());
    }

    public void testSetupUnknownSimilarity() {
        Settings settings = Settings.builder()
                .put("index.similarity.my_similarity.type", "test_similarity")
                .put(IndexMetadata.SETTING_VERSION_CREATED, Version.CURRENT)
                .put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toString())
                .build();
        final IndexSettings indexSettings = IndexSettingsModule.newIndexSettings("foo", settings);
        IndexModule module =
                createIndexModule(indexSettings, emptyAnalysisRegistry);
        Exception ex = expectThrows(IllegalArgumentException.class, () -> newIndexService(module));
        assertEquals("Unknown Similarity type [test_similarity] for [my_similarity]", ex.getMessage());
    }

    public void testSetupWithoutType() {
        Settings settings = Settings.builder()
                .put("index.similarity.my_similarity.foo", "bar")
                .put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toString())
                .put(IndexMetadata.SETTING_VERSION_CREATED, Version.CURRENT)
                .build();
        final IndexSettings indexSettings = IndexSettingsModule.newIndexSettings("foo", settings);
        IndexModule module = createIndexModule(indexSettings, emptyAnalysisRegistry);
        Exception ex = expectThrows(IllegalArgumentException.class, () -> newIndexService(module));
        assertEquals("Similarity [my_similarity] must have an associated type", ex.getMessage());
    }

    public void testForceCustomQueryCache() throws IOException {
        Settings settings = Settings.builder()
                .put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toString())
                .put(IndexMetadata.SETTING_VERSION_CREATED, Version.CURRENT).build();
        final IndexSettings indexSettings = IndexSettingsModule.newIndexSettings("foo", settings);
        IndexModule module = createIndexModule(indexSettings, emptyAnalysisRegistry);
        final Set<CustomQueryCache> liveQueryCaches = new HashSet<>();
        module.forceQueryCacheProvider((a, b) -> {
            final CustomQueryCache customQueryCache = new CustomQueryCache(liveQueryCaches);
            liveQueryCaches.add(customQueryCache);
            return customQueryCache;
        });
        expectThrows(AlreadySetException.class, () -> module.forceQueryCacheProvider((a, b) -> {
            throw new AssertionError("never called");
        }));
        IndexService indexService = newIndexService(module);
        assertTrue(indexService.cache().query() instanceof CustomQueryCache);
        indexService.close("simon says", false);
        assertThat(liveQueryCaches, empty());
    }

    public void testDefaultQueryCacheImplIsSelected() throws IOException {
        Settings settings = Settings.builder()
                .put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toString())
                .put(IndexMetadata.SETTING_VERSION_CREATED, Version.CURRENT).build();
        final IndexSettings indexSettings = IndexSettingsModule.newIndexSettings("foo", settings);
        IndexModule module = createIndexModule(indexSettings, emptyAnalysisRegistry);
        IndexService indexService = newIndexService(module);
        assertTrue(indexService.cache().query() instanceof IndexQueryCache);
        indexService.close("simon says", false);
    }

    public void testDisableQueryCacheHasPrecedenceOverForceQueryCache() throws IOException {
        Settings settings = Settings.builder()
            .put(IndexModule.INDEX_QUERY_CACHE_ENABLED_SETTING.getKey(), false)
            .put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toString())
            .put(IndexMetadata.SETTING_VERSION_CREATED, Version.CURRENT).build();
        final IndexSettings indexSettings = IndexSettingsModule.newIndexSettings("foo", settings);
        IndexModule module = createIndexModule(indexSettings, emptyAnalysisRegistry);
        module.forceQueryCacheProvider((a, b) -> new CustomQueryCache(null));
        IndexService indexService = newIndexService(module);
        assertTrue(indexService.cache().query() instanceof DisabledQueryCache);
        indexService.close("simon says", false);
    }

    public void testCustomQueryCacheCleanedUpIfIndexServiceCreationFails() {
        Settings settings = Settings.builder()
            .put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toString())
            .put(IndexMetadata.SETTING_VERSION_CREATED, Version.CURRENT).build();
        final IndexSettings indexSettings = IndexSettingsModule.newIndexSettings("foo", settings);
        IndexModule module = createIndexModule(indexSettings, emptyAnalysisRegistry);
        final Set<CustomQueryCache> liveQueryCaches = new HashSet<>();
        module.forceQueryCacheProvider((a, b) -> {
            final CustomQueryCache customQueryCache = new CustomQueryCache(liveQueryCaches);
            liveQueryCaches.add(customQueryCache);
            return customQueryCache;
        });
        threadPool.shutdown(); // causes index service creation to fail
        expectThrows(EsRejectedExecutionException.class, () -> newIndexService(module));
        assertThat(liveQueryCaches, empty());
    }

    public void testIndexAnalyzersCleanedUpIfIndexServiceCreationFails() {
        Settings settings = Settings.builder()
            .put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toString())
            .put(IndexMetadata.SETTING_VERSION_CREATED, Version.CURRENT).build();
        final IndexSettings indexSettings = IndexSettingsModule.newIndexSettings("foo", settings);

        final HashSet<Analyzer> openAnalyzers = new HashSet<>();
        final AnalysisModule.AnalysisProvider<AnalyzerProvider<?>> analysisProvider = (i,e,n,s) -> new AnalyzerProvider<>() {
            @Override
            public String name() {
                return "test";
            }

            @Override
            public AnalyzerScope scope() {
                return AnalyzerScope.INDEX;
            }

            @Override
            public Analyzer get() {
                final Analyzer analyzer = new Analyzer() {
                    @Override
                    protected TokenStreamComponents createComponents(String fieldName) {
                        return new TokenStreamComponents(new StandardTokenizer());
                    }

                    @Override
                    public void close() {
                        super.close();
                        openAnalyzers.remove(this);
                    }
                };
                openAnalyzers.add(analyzer);
                return analyzer;
            }
        };
        final AnalysisRegistry analysisRegistry = new AnalysisRegistry(environment, emptyMap(), emptyMap(), emptyMap(),
            singletonMap("test", analysisProvider), emptyMap(), emptyMap(), emptyMap(), emptyMap(), emptyMap());
        IndexModule module = createIndexModule(indexSettings, analysisRegistry);
        threadPool.shutdown(); // causes index service creation to fail
        expectThrows(EsRejectedExecutionException.class, () -> newIndexService(module));
        assertThat(openAnalyzers, empty());
    }

    public void testMmapNotAllowed() {
        String storeType = randomFrom(IndexModule.Type.HYBRIDFS.getSettingsKey(), IndexModule.Type.MMAPFS.getSettingsKey());
        final Settings settings = Settings.builder()
                .put(Environment.PATH_HOME_SETTING.getKey(), createTempDir())
                .put("index.store.type", storeType)
                .build();
        final Settings nodeSettings = Settings.builder()
                .put(IndexModule.NODE_STORE_ALLOW_MMAP.getKey(), false)
                .build();
        final IndexSettings indexSettings = IndexSettingsModule.newIndexSettings(new Index("foo", "_na_"), settings, nodeSettings);
        final IndexModule module =
                createIndexModule(indexSettings, emptyAnalysisRegistry);
        final IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> newIndexService(module));
        assertThat(e, hasToString(containsString("store type [" + storeType + "] is not allowed")));
    }

    public void testRegisterCustomRecoveryStateFactory() throws IOException {
        final Settings settings = Settings
            .builder()
            .put(IndexMetadata.SETTING_VERSION_CREATED, Version.CURRENT)
            .put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toString())
            .put(IndexModule.INDEX_RECOVERY_TYPE_SETTING.getKey(), "test_recovery")
            .build();

        final IndexSettings indexSettings = IndexSettingsModule.newIndexSettings(index, settings);

        RecoveryState recoveryState = mock(RecoveryState.class);
        final Map<String, IndexStorePlugin.RecoveryStateFactory> recoveryStateFactories = singletonMap(
            "test_recovery", (shardRouting, targetNode, sourceNode) -> recoveryState);

        final IndexModule module = new IndexModule(indexSettings,
            emptyAnalysisRegistry,
            new InternalEngineFactory(),
            Collections.emptyMap(),
            () -> true,
            new IndexNameExpressionResolver(),
            recoveryStateFactories);

        final IndexService indexService = newIndexService(module);

        ShardRouting shard = createInitializedShardRouting();

        assertThat(indexService.createRecoveryState(shard, mock(DiscoveryNode.class), mock(DiscoveryNode.class)), is(recoveryState));

        indexService.close("closing", false);
    }

    private ShardRouting createInitializedShardRouting() {
        ShardRouting shard = ShardRouting.newUnassigned(new ShardId("test","_na_", 0), true,
            RecoverySource.ExistingStoreRecoverySource.INSTANCE, new UnassignedInfo(UnassignedInfo.Reason.INDEX_CREATED, null));
        shard = shard.initialize("node1", null, -1);
        return shard;
    }

    private static IndexModule createIndexModule(IndexSettings indexSettings, AnalysisRegistry emptyAnalysisRegistry) {
        return new IndexModule(indexSettings, emptyAnalysisRegistry, new InternalEngineFactory(), Collections.emptyMap(), () -> true,
            new IndexNameExpressionResolver(), Collections.emptyMap());
    }

    class CustomQueryCache implements QueryCache {

        private final Set<CustomQueryCache> liveQueryCaches;

        CustomQueryCache(Set<CustomQueryCache> liveQueryCaches) {
            this.liveQueryCaches = liveQueryCaches;
        }

        @Override
        public void clear(String reason) {
        }

        @Override
        public void close() {
            assertTrue(liveQueryCaches == null || liveQueryCaches.remove(this));
        }

        @Override
        public Index index() {
            return new Index("test", "_na_");
        }

        @Override
        public Weight doCache(Weight weight, QueryCachingPolicy policy) {
            return weight;
        }
    }

    private static class TestSimilarity extends Similarity {
        private final Similarity delegate = new BM25Similarity();
        private final String key;

        TestSimilarity(String key) {
            if (key == null) {
                throw new AssertionError("key is null");
            }
            this.key = key;
        }

        @Override
        public long computeNorm(FieldInvertState state) {
            return delegate.computeNorm(state);
        }

        @Override
        public SimScorer scorer(float boost, CollectionStatistics collectionStats, TermStatistics... termStats) {
            return delegate.scorer(boost, collectionStats, termStats);
        }
    }

    public static final class FooFunction implements IndexStorePlugin.DirectoryFactory {

        @Override
        public Directory newDirectory(IndexSettings indexSettings, ShardPath shardPath) throws IOException {
            return new FsDirectoryFactory().newDirectory(indexSettings, shardPath);
        }
    }

    public static final class Wrapper implements CheckedFunction<DirectoryReader, DirectoryReader, IOException> {
        @Override
        public DirectoryReader apply(DirectoryReader reader) {
            return null;
        }
    }
}


text:
import operator
import heapq
from .distances import log_distance

def create_dijkstra_map(graph, start, target=None, cost_func=None, include_diagonals=None):
    """Creates a dijkstra map

    Args:
        graph (list): a set of nodes
        start (node): the starting position
        target (node): the ending position; None means all nodes
        cost_func (callback):  the cost function or distance formula
        include_diagonals (bool):  Only use cardinal directions if False, else include all 8 possibilities

    Returns:
        dict: mapping of node: cost
    """
    mapping = {
        node: cost
        for cost, node in dijkstra(graph, start, target=target, cost_func=cost_func, include_diagonals=include_diagonals)
    }
    return mapping

def dijkstra(graph, start, target=None, cost_func=None, include_diagonals=None):
    """Implementation of dijkstra's algorithm as a generator.

    This one uses a priority queue for a stack.

    See: https://en.wikipedia.org/wiki/Dijkstra's_algorithm

    Args:
        graph (list): a set of nodes
        start (node): the starting position
        target (node): the ending position; None means all nodes
        cost_func (callback):  the cost function or distance formula
        include_diagonals (bool):  Only use cardinal directions if False, else include all 8 possibilities

    Yields:
        cost, node
    """
    cost_func = cost_func or log_distance
    queue = []
    heapq.heapify(queue)
    costs = {start: 0}
    heapq.heappush(queue, (costs[start], start))
    yield (costs[start], start)
    while queue:
        node_cost, node = heapq.heappop(queue)
        node_cost = costs[node]
        neighbors = get_neighbors(node, include_diagonals=include_diagonals)
        neighbors = [
            neighbor for neighbor in neighbors
            if neighbor in graph  # short circuit on nodes not available
            if neighbor not in costs  # short circuit on nodes already calculated
        ]
        for neighbor in neighbors:
            neighbor_cost = cost_func(start, neighbor) + node_cost
            yield (neighbor_cost, neighbor)
            costs[neighbor] = neighbor_cost
            heapq.heappush(queue, (neighbor_cost, neighbor))
            if neighbor == target:
                break

def get_neighbors(node=None, include_diagonals=None):
    """Creates a list of neighbors.

    Yields:
        point:  a neighbor node
    """
    if node is None:
        node = (0, 0)
    cardinals = [(0, 1), (0, -1), (1, 0), (-1, 0)]
    diagonals = [(1, 1), (1, -1), (-1, -1), (-1, 1)]
    directions = cardinals + diagonals if include_diagonals else cardinals
    for offset in directions:
        yield tuple(map(operator.add, node, offset))


text:
%This function initializes all parameters used by the simulation code
%This version uses the orphan drug parameters discussed in
%"Financing drug discovery for orphan diseases" Fagnan et al. 2013.
%@params is of type struct and has 4 fields simu (simulation parameters),
%   assets (asset parameters), bonds (bond parameters), and ce (guarantee parameters)
function params = init_params_fn()

    % ASSET PARAMETERS
    assets = struct;
	assets.mode = 'Markov';
	%Correlation value for asset valuation.
    assets.rho = 0.2;

	%Present value upon succesful FDA approval.
	approvalValue = 817.643;

	%Costs for clinical trials by phase.
	costs = [5,5,8,43,0];

	%Discount rates for estimating valuation at phases prior to approval.
	disc = [0.3, 0.3, 0.3, 0.25, 0.15];

	%Duration of each phase in years.
	dur = [1, 1.6561, 2.0942, 2.1497, 0.8];

	%Probabilities of technical and regulatory success by phase.
	%%Note that the original paper by Fernandez et al. uses a more
	%%advanced generating matrix approach using data unavailable for
	%%the Orphan drug paper published in Drug Discovery Today.
	steady = [.69, .84, .53, .74, .96];

	%Target phase (eg. 4 = P3, 3 = P2), used for calculating budgeting rules.
   	target = 4;

	%Orphan drug utility functions build the capped log-normal distributions
	%Uses values for the standard deviations derived from previous work by Fernandez et al. 2012.
    assets.pricing_params = createTransMat(approvalValue,costs,disc,dur,steady,target);
	assets.trans_prob=createProbMat(steady,dur);

   %%Set the named variables to the corresponding column numbers.
   %DSC refers to a state of withdrawal or discontinued.
    assets.trans_prob_row.DSC = 1;
    assets.trans_prob_row.PRE = 2;
    assets.trans_prob_row.P1  = 3;
    assets.trans_prob_row.P2  = 4;
    assets.trans_prob_row.P3  = 5;
    assets.trans_prob_row.NDA = 6;
    assets.trans_prob_row.APP = 7;
    assets.trans_prob_col     = assets.trans_prob_row;

    assets.pricing_params_row     = assets.trans_prob_row;
    assets.pricing_params_col.vmu            = 1;
    assets.pricing_params_col.vsigma         = 2;
    assets.pricing_params_col.vmx            = 3;
    assets.pricing_params_col.UpFront        = 4;
    assets.pricing_params_col.Milestone      = 5;
    assets.pricing_params_col.mu             = 6;
    assets.pricing_params_col.sigma          = 7;
    assets.pricing_params_col.max            = 8;
    assets.pricing_params_col.FutureCostEst  = 9;

	%Sell compounds upon reaching this phase.
	%Note that it is possible for a compound to transition
	%past the target phase due to parallel trials (code
	%only checks for transition every six months).
    assets.sell_in_phase = {'P3'};
    assets.sale_time = ones(7,1).*1.5;
    assets.sale_time_col = assets.trans_prob_col;

	%Percent that assets are worth if they remain in the same stage
	%for the entirety of the simulation.
	assets.ratio_unchanged = 1.00;

	%Share of valuation payouts that go to the megafund.
	%eg. 0.85 means 85% of the sale value goes to the megafund
	% with 15% paid out as royalties, lost to the megafund.
    assets.equity_stake    = 0.85;

    %BOND PARAMETERS
    bonds = struct;
	%Capital structure percentages e.g. senior, junior, equity
    bonds.capital_structure = [0.15 0.2 0.65]; %A1, A2, EQ

    bonds.capital_structure_col.A1  = 1;
    bonds.capital_structure_col.A2  = 2;
    bonds.capital_structure_col.EQ  = 3;

	%Number of periods for which to cover expected interest
	% and coupon payments with cash. (interest coverage)
    bonds.IC_pers = 2;

	% Interest coverage ratios
	% e.g. hold cash equal to 1.75x future senior tranche interest & coupon
	% and 3.5x the future junior tranche interest & coupon
    bonds.interest_coverage = [1.75, 3.5,  0];  %A1, A2, EQ
    bonds.interest_coverage_col = bonds.capital_structure_col;

	%Bond amortization schedule.
	%e.g. Senior tranche is paid out from Period 5 through 8
	% 	  Junior tranche is paid out from Period 9 through 12
	%Note that Coupon payments are paid semi-annually until completion of the schedule.
    bonds.amort_timing  = [...
    ... %start, stop
         5,      8; ... %A1
         9,     12; ... %A2
    ];
    bonds.amort_timing_row.A1 = 1;
    bonds.amort_timing_row.A2 = 2;
    bonds.amort_timing_col.start = 1;
    bonds.amort_timing_col.stop  = 2;

	%Annual coupon rates scaled for semi-annual payments.
    bonds.coupon = [0.05/2, 0.08/2, 0];   %A1, A2, EQ
    bonds.coupon_col = bonds.capital_structure_col;

	%Servicing rate or management fee for the fund.
    bonds.servicing_rate = 0.0025;

	%Accrual rate on missed service payments.
    bonds.svc_accrual_int_rate = 0.07/2;

	%Interest rate on unused cash on hand.
    bonds.cash_accrual_int_rate = 0.01/2;

    %CE PARAMETERS - Guarantees
    ce.ce_amt = 0;
    ce.ce_repay = false;
    ce.ce_premium = 0;

    % SIMU PARAMETERS
    simu = struct;
	%Number of simulations recommend 100K for quick estimates,
	% or 2 million for a complete profile.
    simu.NSIMUS = 1000;
    simu.TIMESTEPS =  max(reshape(bonds.amort_timing,1,[]))+1;
	%Total capital to be spread across tranches.
    simu.initial_cash  = 575;

    simu.initial_compounds = [0, 8, 8, 0, 0, 0, 0];
    simu.initial_compounds_col = assets.trans_prob_col;

    %Set the nominal amounts corresponding to the CS and total capital.
    bonds.nominal = simu.initial_cash*bonds.capital_structure;
    bonds.nominal_col = bonds.capital_structure_col;

    %create global parameter list
    params = struct;
    params.simu   = simu;
    params.assets = assets;
    params.bonds  = bonds;
    params.ce     = ce;
end
%COPYRIGHT 2013
% This program is free software: you can redistribute it and/or modify
%    it under the terms of the GNU General Public License as published by
%    the Free Software Foundation, either version 3 of the License, or
%    (at your option) any later version.
%
%    This program is distributed in the hope that it will be useful,
%    but WITHOUT ANY WARRANTY; without even the implied warranty of
%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%    GNU General Public License for more details.
%
%    You should have received a copy of the GNU General Public License
%    along with this program.  If not, see <http://www.gnu.org/licenses/>.
%
%


text:
package org.apache.tools.ant.filters;

import java.io.Reader;
import org.apache.tools.ant.types.Parameter;
import org.apache.tools.ant.types.Parameterizable;

/**
 * Parameterized base class for core filter readers.
 *
 */
public abstract class BaseParamFilterReader
    extends BaseFilterReader
    implements Parameterizable {
    /** The passed in parameter array. */
    private Parameter[] parameters;

    /**
     * Constructor for "dummy" instances.
     *
     * @see BaseFilterReader#BaseFilterReader()
     */
    public BaseParamFilterReader() {
        super();
    }

    /**
     * Creates a new filtered reader.
     *
     * @param in A Reader object providing the underlying stream.
     *           Must not be null.
     */
    public BaseParamFilterReader(final Reader in) {
        super(in);
    }

    /**
     * Sets the parameters used by this filter, and sets
     * the filter to an uninitialized status.
     *
     * @param parameters The parameters to be used by this filter.
     *                   Should not be null.
     */
    public final void setParameters(final Parameter[] parameters) {
        this.parameters = parameters;
        setInitialized(false);
    }

    /**
     * Returns the parameters to be used by this filter.
     *
     * @return the parameters to be used by this filter
     */
    protected final Parameter[] getParameters() {
        return parameters;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using GoogleApi.Entities.Common;
using GoogleApi.Entities.Common.Enums;
using GoogleApi.Entities.Common.Extensions;

namespace GoogleApi.Entities.Maps.Geocoding.Address.Request
{
    /// <summary>
    /// Geocoding Request.
    /// </summary>
    public class AddressGeocodeRequest : BaseGeocodeRequest
    {
        /// <summary>
        /// Address (required).
        /// The address that you want to geocode.
        /// </summary>
        public virtual string Address { get; set; }

        /// <summary>
        /// Region (optional) — The region code, specified as a ccTLD ("top-level domain") two-character value. (For more information see Region Biasing below.)
        /// The bounds and region parameters will only influence, not fully restrict, results from the geocoder.
        /// </summary>
        public virtual string Region { get; set; }

        /// <summary>
        /// Bounds (optional) — The bounding box of the viewport within which to bias geocode results more prominently. (For more information see Viewport Biasing below.)
        /// The bounds and region parameters will only influence, not fully restrict, results from the geocoder.
        /// For more information see: https://developers.google.com/maps/documentation/geocoding/intro#Viewports
        /// </summary>
        public virtual ViewPort Bounds { get; set; }

        /// <summary>
        /// Components. The component filters, separated by a pipe (|).
        /// Each component filter consists of a component:value pair and will fully restrict the results from the geocoder.
        /// For more information see Component Filtering: https://developers.google.com/maps/documentation/geocoding/intro#ComponentFiltering
        /// </summary>
        public virtual IEnumerable<KeyValuePair<Component, string>> Components { get; set; }

        /// <summary>
        /// See <see cref="BaseGeocodeRequest.GetQueryStringParameters()"/>.
        /// </summary>
        /// <returns>The <see cref="IList{KeyValuePair}"/> collection.</returns>
        public override IList<KeyValuePair<string, string>> GetQueryStringParameters()
        {
            if (string.IsNullOrWhiteSpace(this.Address) && (this.Components == null || !this.Components.Any()))
                throw new ArgumentException("Address or Components is required");

            var parameters = base.GetQueryStringParameters();

            if (!string.IsNullOrEmpty(this.Address))
                parameters.Add("address", this.Address);

            if (!string.IsNullOrEmpty(this.Region))
                parameters.Add("region", this.Region);

            if (this.Bounds != null)
                parameters.Add("bounds", $"{this.Bounds.SouthWest}|{this.Bounds.NorthEast}");

            if (this.Components != null && this.Components.Any())
                parameters.Add("components", string.Join("|", this.Components.Select(x => $"{x.Key.ToString().ToLower()}:{x.Value}")));

            return parameters;
        }
    }
}


text:
<?

defined( 'ABSPATH' ) or die( '' );

function woocommerce_rrp_register_setting() {
	register_setting( 'woocommerce_rrp_options', 'my_option_name' );
}

add_action( 'admin_init', 'woocommerce_rrp_register_setting' );


text:
using System.Collections.Generic;
using System.ComponentModel;
using System.Security.Cryptography;

namespace SKM.V3.Models
{
    public class CreateAuthRequestResult
    {
        //(byte[] authorizationToken, RSAParameters parameters)
        public byte[] AuthorizationToken { get; set; }
        public RSAParameters Parameters { get; set; }

    }

    public class GetLicenseKeysResult
    {
        public List<LicenseKey> Licenses { get; set; }
        public string Error { get; set; }
        public string LicenseKeyToken { get; set; }
    }

    internal class GetLicenseKeysModel : RequestModel
    {
        public bool Sign { get; set; }

        [DefaultValue("")]
        public string MachineCode { get; set; }

        public SignMethod SignMethod { get; set; }
    }

    internal class GetLicenseKeysResultStringSign : BasicResult
    {
        public string Results { get; set; }
        public string ActivatedMachineCodes { get; set; }
        public string Signature { get; set; }

    }

    internal class GetLicenseKeysResultLinqSign : BasicResult
    {
        public string Results { get; set; }
        public string ActivatedMachineCodes { get; set; }
        public string Signature { get; set; }
        public long SignDate { get; set; }

    }

    /// <summary>
    /// Sets what should be signed and returned when returning a license key object
    /// that is intended to be stored on the end user machine.
    /// </summary>
    public enum SignMethod
    {
        /// <summary>
        /// This one is the default for the .NET library, but is not very flexible.
        /// It should not be used in newer models and methods.
        /// </summary>
        LinqSign = 0, // default

        /// <summary>
        /// This one is the preferred way of signing any type of information since it
        /// does not care about the conversion, only about the actual string being signed.
        /// </summary>
        StringSign = 1 // treat the license key as separate json string wrapped inside basic result
    }

    internal class GetTokenModel : GetChallengeModel
    {
        public string SignedChallenge { get; set; }
        public long Date { get; set; }
    }

    internal class GetTokenResult : BasicResult
    {
        public string Token { get; set; }
    }

    public class GetChallengeModel: RequestModel
    {
        public string AuthorizationToken { get; set; }
    }

    internal class GetChallengeResult : BasicResult
    {
        public string Challenge { get; set; }
    }

    internal class AuthorizeAppModel
    {
        public string AuthorizationToken { get; set; }
        public string PublicKey { get; set; }
        public string Scope { get; set; }
        public string VendorAppName { get; set; }
        public int Expires { get; set; }
        public int TokenId { get; set; }
        public string MachineCode { get; set; }
        public string DeviceName { get; set; }

        public SignatureAlgorithm Algorithm { get; set; }
    }

    internal enum SignatureAlgorithm
    {
        RSA_2048 = 0
    }

    public class Scope
    {
        [DefaultValue(false)]
        public bool Deactivate { get; set; }

        [DefaultValue(false)]
        public bool CreateKey { get; set; }

        [DefaultValue(false)]
        public bool GetKeys { get; set; }

        [DefaultValue(false)]
        public bool Activate { get; set; }

        [DefaultValue(false)]
        public bool ExtendLicense { get; set; }

        [DefaultValue(false)]
        public bool AddFeature { get; set; }

        [DefaultValue(false)]
        public bool RemoveFeature { get; set; }

        [DefaultValue(false)]
        public bool AddDataObject { get; set; }

        [DefaultValue(false)]
        public bool ListDataObjects { get; set; }

        [DefaultValue(false)]
        public bool SetStringValue { get; set; }

        [DefaultValue(false)]
        public bool SetIntValue { get; set; }

        [DefaultValue(false)]
        public bool IncrementIntValue { get; set; }

        [DefaultValue(false)]
        public bool DecrementIntValue { get; set; }

        [DefaultValue(false)]
        public bool RemoveDataObject { get; set; }

        [DefaultValue(false)]
        public bool BlockKey { get; set; }

        [DefaultValue(false)]
        public bool UnblockKey { get; set; }

        [DefaultValue(false)]
        public bool KeyInfo { get; set; }

        [DefaultValue(false)]
        public bool GetFeatureDefinitions { get; set; }

        [DefaultValue(false)]
        public bool ChangeNotes { get; set; }

        [DefaultValue(false)]
        public bool GetCustomers { get; set; }

        [DefaultValue(false)]
        public bool ChangeCustomer { get; set; }

        [DefaultValue(false)]
        public bool AddCustomer { get; set; }
        [DefaultValue(false)]
        public bool RemoveCustomer { get; set; }
        [DefaultValue(false)]
        public bool GetCustomerLicenses { get; set; }

        [DefaultValue(false)]
        public bool TrialActivation { get; set; }

        [DefaultValue(false)]
        public bool MachineLockLimit { get; set; }

        [DefaultValue(false)]
        public bool GetLicenseKeys { get; set; }

        [DefaultValue(false)]
        public bool PaymentForms { get; set; }

        [DefaultValue(0)]
        public int LockToProduct { get; set; }

        [DefaultValue(0)]
        public int LockToKey { get; set; }

        [DefaultValue(0)]
        public int LockToFeature { get; set; }
    }
}


text:
package errorlint

import (
	"fmt"
	"go/ast"
	"go/constant"
	"go/token"
	"go/types"
	"regexp"
)

type Lint struct {
	Message string
	Pos     token.Pos
}

type ByPosition []Lint

func (l ByPosition) Len() int      { return len(l) }
func (l ByPosition) Swap(i, j int) { l[i], l[j] = l[j], l[i] }

func (l ByPosition) Less(i, j int) bool {
	return l[i].Pos < l[j].Pos
}

func LintFmtErrorfCalls(fset *token.FileSet, info types.Info) []Lint {
	lints := []Lint{}
	for expr, t := range info.Types {
		// Search for error expressions that are the result of fmt.Errorf
		// invocations.
		if t.Type.String() != "error" {
			continue
		}
		call, ok := isFmtErrorfCallExpr(info, expr)
		if !ok {
			continue
		}

		// Find all % fields in the format string.
		formatVerbs, ok := printfFormatStringVerbs(info, call)
		if !ok {
			continue
		}

		// For any arguments that are errors, check whether the wrapping verb
		// is used. Only one %w verb may be used in a single format string at a
		// time, so we stop after finding a correct %w.
		var lintArg ast.Expr
		args := call.Args[1:]
		for i := 0; i < len(args) && i < len(formatVerbs); i++ {
			if !implementsError(info.Types[args[i]].Type) && !isErrorStringCall(info, args[i]) {
				continue
			}

			if formatVerbs[i] == "%w" {
				lintArg = nil
				break
			}

			if lintArg == nil {
				lintArg = args[i]
			}
		}
		if lintArg != nil {
			lints = append(lints, Lint{
				Message: "non-wrapping format verb for fmt.Errorf. Use `%w` to format errors",
				Pos:     lintArg.Pos(),
			})
		}
	}
	return lints
}

// isErrorStringCall tests whether the expression is a string expression that
// is the result of an `(error).Error()` method call.
func isErrorStringCall(info types.Info, expr ast.Expr) bool {
	if info.Types[expr].Type.String() == "string" {
		if call, ok := expr.(*ast.CallExpr); ok {
			if callSel, ok := call.Fun.(*ast.SelectorExpr); ok {
				fun := info.Uses[callSel.Sel].(*types.Func)
				return fun.Type().String() == "func() string" && fun.Name() == "Error"
			}
		}
	}
	return false
}

func printfFormatStringVerbs(info types.Info, call *ast.CallExpr) ([]string, bool) {
	if len(call.Args) <= 1 {
		return nil, false
	}
	strLit, ok := call.Args[0].(*ast.BasicLit)
	if !ok {
		// Ignore format strings that are not literals.
		return nil, false
	}
	formatString := constant.StringVal(info.Types[strLit].Value)

	// Naive format string argument verb. This does not take modifiers such as
	// padding into account...
	re := regexp.MustCompile(`%[^%]`)
	return re.FindAllString(formatString, -1), true
}

func isFmtErrorfCallExpr(info types.Info, expr ast.Expr) (*ast.CallExpr, bool) {
	call, ok := expr.(*ast.CallExpr)
	if !ok {
		return nil, false
	}
	fn, ok := call.Fun.(*ast.SelectorExpr)
	if !ok {
		// TODO: Support fmt.Errorf variable aliases?
		return nil, false
	}
	obj := info.Uses[fn.Sel]

	pkg := obj.Pkg()
	if pkg != nil && pkg.Name() == "fmt" && obj.Name() == "Errorf" {
		return call, true
	}
	return nil, false
}

func LintErrorComparisons(fset *token.FileSet, info *TypesInfoExt) []Lint {
	lints := []Lint{}

	for expr := range info.Types {
		// Find == and != operations.
		binExpr, ok := expr.(*ast.BinaryExpr)
		if !ok {
			continue
		}
		if binExpr.Op != token.EQL && binExpr.Op != token.NEQ {
			continue
		}
		// Comparing errors with nil is okay.
		if isNilComparison(binExpr) {
			continue
		}
		// Find comparisons of which one side is a of type error.
		if !isErrorComparison(info.Info, binExpr) {
			continue
		}

		if isAllowedErrorComparison(info, binExpr) {
			continue
		}

		lints = append(lints, Lint{
			Message: fmt.Sprintf("comparing with %s will fail on wrapped errors. Use errors.Is to check for a specific error", binExpr.Op),
			Pos:     binExpr.Pos(),
		})
	}

	for scope := range info.Scopes {
		// Find value switch blocks.
		switchStmt, ok := scope.(*ast.SwitchStmt)
		if !ok {
			continue
		}
		// Check whether the switch operates on an error type.
		if switchStmt.Tag == nil {
			continue
		}
		tagType := info.Types[switchStmt.Tag]
		if tagType.Type.String() != "error" {
			continue
		}

		lints = append(lints, Lint{
			Message: "switch on an error will fail on wrapped errors. Use errors.Is to check for specific errors",
			Pos:     switchStmt.Pos(),
		})
	}

	return lints
}

func isNilComparison(binExpr *ast.BinaryExpr) bool {
	if ident, ok := binExpr.X.(*ast.Ident); ok && ident.Name == "nil" {
		return true
	}
	if ident, ok := binExpr.Y.(*ast.Ident); ok && ident.Name == "nil" {
		return true
	}
	return false
}

func isErrorComparison(info types.Info, binExpr *ast.BinaryExpr) bool {
	tx := info.Types[binExpr.X]
	ty := info.Types[binExpr.Y]
	return tx.Type.String() == "error" || ty.Type.String() == "error"
}

func LintErrorTypeAssertions(fset *token.FileSet, info types.Info) []Lint {
	lints := []Lint{}

	for expr := range info.Types {
		// Find type assertions.
		typeAssert, ok := expr.(*ast.TypeAssertExpr)
		if !ok {
			continue
		}

		// Find type assertions that operate on values of type error.
		if !isErrorTypeAssertion(info, typeAssert) {
			continue
		}

		lints = append(lints, Lint{
			Message: "type assertion on error will fail on wrapped errors. Use errors.As to check for specific errors",
			Pos:     typeAssert.Pos(),
		})
	}

	for scope := range info.Scopes {
		// Find type switches.
		typeSwitch, ok := scope.(*ast.TypeSwitchStmt)
		if !ok {
			continue
		}

		// Find the type assertion in the type switch.
		var typeAssert *ast.TypeAssertExpr
		switch t := typeSwitch.Assign.(type) {
		case *ast.ExprStmt:
			typeAssert = t.X.(*ast.TypeAssertExpr)
		case *ast.AssignStmt:
			typeAssert = t.Rhs[0].(*ast.TypeAssertExpr)
		}

		// Check whether the type switch is on a value of type error.
		if !isErrorTypeAssertion(info, typeAssert) {
			continue
		}

		lints = append(lints, Lint{
			Message: "type switch on error will fail on wrapped errors. Use errors.As to check for specific errors",
			Pos:     typeAssert.Pos(),
		})
	}

	return lints
}

func isErrorTypeAssertion(info types.Info, typeAssert *ast.TypeAssertExpr) bool {
	t := info.Types[typeAssert.X]
	return t.Type.String() == "error"
}

func implementsError(t types.Type) bool {
	mset := types.NewMethodSet(t)

	for i := 0; i < mset.Len(); i++ {
		if mset.At(i).Kind() != types.MethodVal {
			continue
		}

		obj := mset.At(i).Obj()
		if obj.Name() == "Error" && obj.Type().String() == "func() string" {
			return true
		}
	}

	return false
}


text:
'use strict';

/*!
 * Module dependencies.
 */

const MongooseArray = require('./array');
const ObjectId = require('./objectid');
const ObjectIdSchema = require('../schema/objectid');
const internalToObjectOptions = require('../options').internalToObjectOptions;
const utils = require('../utils');
const Document = require('../document');
const getDiscriminatorByValue = require('../queryhelpers').getDiscriminatorByValue;

/**
 * DocumentArray constructor
 *
 * @param {Array} values
 * @param {String} path the path to this array
 * @param {Document} doc parent document
 * @api private
 * @return {MongooseDocumentArray}
 * @inherits MongooseArray
 * @see http://bit.ly/f6CnZU
 */

function MongooseDocumentArray(values, path, doc) {
  var arr = [].concat(values);
  arr._path = path;

  var props = {
    isMongooseArray: true,
    isMongooseDocumentArray: true,
    validators: [],
    _atomics: {},
    _schema: void 0,
    _handlers: void 0
  };

  // Values always have to be passed to the constructor to initialize, since
  // otherwise MongooseArray#push will mark the array as modified to the parent.
  var keysMA = Object.keys(MongooseArray.mixin);
  var numKeys = keysMA.length;
  for (var j = 0; j < numKeys; ++j) {
    arr[keysMA[j]] = MongooseArray.mixin[keysMA[j]];
  }

  var keysMDA = Object.keys(MongooseDocumentArray.mixin);
  numKeys = keysMDA.length;
  for (var i = 0; i < numKeys; ++i) {
    arr[keysMDA[i]] = MongooseDocumentArray.mixin[keysMDA[i]];
  }

  var keysP = Object.keys(props);
  numKeys = keysP.length;
  for (var k = 0; k < numKeys; ++k) {
    arr[keysP[k]] = props[keysP[k]];
  }

  // Because doc comes from the context of another function, doc === global
  // can happen if there was a null somewhere up the chain (see #3020 && #3034)
  // RB Jun 17, 2015 updated to check for presence of expected paths instead
  // to make more proof against unusual node environments
  if (doc && doc instanceof Document) {
    arr._parent = doc;
    arr._schema = doc.schema.path(path);
    arr._handlers = {
      isNew: arr.notify('isNew'),
      save: arr.notify('save')
    };

    doc.on('save', arr._handlers.save);
    doc.on('isNew', arr._handlers.isNew);
  }

  return arr;
}

/*!
 * Inherits from MongooseArray
 */
// MongooseDocumentArray.mixin = Object.create( MongooseArray.mixin );
MongooseDocumentArray.mixin = {
  /*!
   * ignore
   */
  toBSON: function() {
    return this.toObject(internalToObjectOptions);
  },

  /**
   * Overrides MongooseArray#cast
   *
   * @method _cast
   * @api private
   * @receiver MongooseDocumentArray
   */

  _cast: function(value, index) {
    var Constructor = this._schema.casterConstructor;
    if (value instanceof Constructor ||
        // Hack re: #5001, see #5005
        (value && value.constructor && value.constructor.baseCasterConstructor === Constructor)) {
      if (!(value.__parent && value.__parentArray)) {
        // value may have been created using array.create()
        value.__parent = this._parent;
        value.__parentArray = this;
      }
      value.__index = index;
      return value;
    }

    if (value === undefined || value === null) {
      return null;
    }

    // handle cast('string') or cast(ObjectId) etc.
    // only objects are permitted so we can safely assume that
    // non-objects are to be interpreted as _id
    if (Buffer.isBuffer(value) ||
        value instanceof ObjectId || !utils.isObject(value)) {
      value = {_id: value};
    }

    if (value &&
        Constructor.discriminators &&
        Constructor.schema &&
        Constructor.schema.options &&
        Constructor.schema.options.discriminatorKey) {
      if (typeof value[Constructor.schema.options.discriminatorKey] === 'string' &&
          Constructor.discriminators[value[Constructor.schema.options.discriminatorKey]]) {
        Constructor = Constructor.discriminators[value[Constructor.schema.options.discriminatorKey]];
      } else {
        var constructorByValue = getDiscriminatorByValue(Constructor, value[Constructor.schema.options.discriminatorKey]);
        if (constructorByValue) {
          Constructor = constructorByValue;
        }
      }
    }

    return new Constructor(value, this, undefined, undefined, index);
  },

  /**
   * Searches array items for the first document with a matching _id.
   *
   * ####Example:
   *
   *     var embeddedDoc = m.array.id(some_id);
   *
   * @return {EmbeddedDocument|null} the subdocument or null if not found.
   * @param {ObjectId|String|Number|Buffer} id
   * @TODO cast to the _id based on schema for proper comparison
   * @method id
   * @api public
   * @receiver MongooseDocumentArray
   */

  id: function(id) {
    var casted,
        sid,
        _id;

    try {
      var casted_ = ObjectIdSchema.prototype.cast.call({}, id);
      if (casted_) {
        casted = String(casted_);
      }
    } catch (e) {
      casted = null;
    }

    for (var i = 0, l = this.length; i < l; i++) {
      if (!this[i]) {
        continue;
      }
      _id = this[i].get('_id');

      if (_id === null || typeof _id === 'undefined') {
        continue;
      } else if (_id instanceof Document) {
        sid || (sid = String(id));
        if (sid == _id._id) {
          return this[i];
        }
      } else if (!(id instanceof ObjectId) && !(_id instanceof ObjectId)) {
        if (utils.deepEqual(id, _id)) {
          return this[i];
        }
      } else if (casted == _id) {
        return this[i];
      }
    }

    return null;
  },

  /**
   * Returns a native js Array of plain js objects
   *
   * ####NOTE:
   *
   * _Each sub-document is converted to a plain object by calling its `#toObject` method._
   *
   * @param {Object} [options] optional options to pass to each documents `toObject` method call during conversion
   * @return {Array}
   * @method toObject
   * @api public
   * @receiver MongooseDocumentArray
   */

  toObject: function(options) {
    return this.map(function(doc) {
      return doc && doc.toObject(options) || null;
    });
  },

  /**
   * Helper for console.log
   *
   * @method inspect
   * @api public
   * @receiver MongooseDocumentArray
   */

  inspect: function() {
    return Array.prototype.slice.call(this);
  },

  /**
   * Creates a subdocument casted to this schema.
   *
   * This is the same subdocument constructor used for casting.
   *
   * @param {Object} obj the value to cast to this arrays SubDocument schema
   * @method create
   * @api public
   * @receiver MongooseDocumentArray
   */

  create: function(obj) {
    var Constructor = this._schema.casterConstructor;
    if (obj &&
        Constructor.discriminators &&
        Constructor.schema &&
        Constructor.schema.options &&
        Constructor.schema.options.discriminatorKey) {
      if (typeof obj[Constructor.schema.options.discriminatorKey] === 'string' &&
          Constructor.discriminators[obj[Constructor.schema.options.discriminatorKey]]) {
        Constructor = Constructor.discriminators[obj[Constructor.schema.options.discriminatorKey]];
      } else {
        var constructorByValue = getDiscriminatorByValue(Constructor, obj[Constructor.schema.options.discriminatorKey]);
        if (constructorByValue) {
          Constructor = constructorByValue;
        }
      }
    }

    return new Constructor(obj);
  },

  /**
   * Creates a fn that notifies all child docs of `event`.
   *
   * @param {String} event
   * @return {Function}
   * @method notify
   * @api private
   * @receiver MongooseDocumentArray
   */

  notify: function notify(event) {
    var _this = this;
    return function notify(val) {
      var i = _this.length;
      while (i--) {
        if (!_this[i]) {
          continue;
        }
        switch (event) {
          // only swap for save event for now, we may change this to all event types later
          case 'save':
            val = _this[i];
            break;
          default:
            // NO-OP
            break;
        }
        _this[i].emit(event, val);
      }
    };
  }

};

/*!
 * Module exports.
 */

module.exports = MongooseDocumentArray;


text:
package actors;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.apache.avro.generic.GenericData;
import org.apache.kafka.common.serialization.Deserializer;
import kafka.consumer.ConsumerIterator;
import kafka.consumer.KafkaStream;
import kafka.message.MessageAndMetadata;

import akka.actor.UntypedActor;
import msgs.KafkaResponseMsg;
import play.Logger;
import wherehows.common.kafka.schemaregistry.client.SchemaRegistryClient;
import wherehows.common.kafka.serializers.KafkaAvroDeserializer;
import wherehows.common.schemas.AbstractRecord;

/**
 * Akka actor for listening to a Kafka topic and waiting for messages.
 */
public class KafkaConsumerWorker extends UntypedActor {
  private final String _topic;
  private final int _threadId;
  private final KafkaStream<byte[], byte[]> _kafkaStream;
  private final SchemaRegistryClient _schemaRegistryRestfulClient;
  private final Object _processorClass;
  private final Method _processorMethod;

  public KafkaConsumerWorker(String topic, int threadNumber,
      KafkaStream<byte[], byte[]> stream, SchemaRegistryClient schemaRegistryRestfulClient,
      Object processorClass, Method processorMethod) {
    this._topic = topic;
    this._threadId = threadNumber;
    this._kafkaStream = stream;
    this._schemaRegistryRestfulClient = schemaRegistryRestfulClient;
    this._processorClass = processorClass;
    this._processorMethod = processorMethod;
  }

  @Override
  public void onReceive(Object message) throws Exception {
    if (message.equals("Start")) {
      Logger.info("Starting Thread: " + _threadId + " for topic: " + _topic);
      final ConsumerIterator<byte[], byte[]> it = _kafkaStream.iterator();
      final Deserializer<Object> avroDeserializer = new KafkaAvroDeserializer(_schemaRegistryRestfulClient);

      while (it.hasNext()) { // block for next input
        try {
          MessageAndMetadata<byte[], byte[]> msg = it.next();
          GenericData.Record kafkaMsgRecord = (GenericData.Record) avroDeserializer.deserialize(_topic, msg.message());
          // Logger.debug("Kafka worker ThreadId " + _threadId + " Topic " + _topic + " record: " + rec);

          final AbstractRecord record = (AbstractRecord) _processorMethod.invoke(
              _processorClass, kafkaMsgRecord, _topic);
          // send processed record to master
          if (record != null) {
            getSender().tell(new KafkaResponseMsg(record, _topic), getSelf());
          }
        } catch (InvocationTargetException ite) {
          Logger.error("Processing topic " + _topic + " record error: " + ite.getCause()
              + " - " + ite.getTargetException());
        } catch (Throwable ex) {
          Logger.error("Error in notify order. ", ex);
        }
      }
      Logger.info("Shutting down Thread: " + _threadId + " for topic: " + _topic);
    } else {
      unhandled(message);
    }
  }
}


text:
package thebob.assetloader.map;

import java.io.File;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import thebob.assetloader.map.core.MapData;
import thebob.assetloader.xml.XmlLoader;

public class MapLoader {
    protected XmlLoader xml;

    public MapLoader(XmlLoader xml) {
        this.xml = xml;
    }

    public MapData loadMapFile(String fileName) {
        try (final RandomAccessFile file = new RandomAccessFile(fileName, "r")) {
            FileChannel fc = file.getChannel();
            MappedByteBuffer fileBuffer = fc.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
            fileBuffer.order(ByteOrder.LITTLE_ENDIAN);

            return loadMap(fileBuffer);
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return null;
    }

    public MapData loadMap(ByteBuffer data) {
        MapData map = new MapData();

        map.setXmlDataSource(xml);
        map.loadMap(data);

        return map;
    }

    // ===================================================
    public static final boolean logFileIO = false;
    public static final boolean logEverything = false;
    public static final boolean printJunk = false;

}


text:
<?php namespace Konduto\Core;

use Konduto\Exceptions as Exceptions;

class HttpResponse {

    const HTTP_STATUS_OK = 200;
    const HTTP_STATUS_BAD_REQUEST = 400;
    const HTTP_STATUS_UNAUTHORIZED = 401;
    const HTTP_STATUS_FORBIDDEN = 403;
    const HTTP_STATUS_NOT_FOUND = 404;
    const HTTP_TOO_MANY_REQUESTS = 429;
    const HTTP_STATUS_INTERNAL_ERROR = 500;

    protected $body;
    protected $jsonBody = null;
    protected $httpStatus;
    protected $curlCode;

    public function __construct(CurlSession $openCurlSession) {
        $this->httpStatus = $openCurlSession->getInfo(CURLINFO_HTTP_CODE);
        $this->curlCode = $openCurlSession->getErrorNo();
        $this->body = $openCurlSession->getResponseBody();
    }

    public function checkCurlResponse() {
        // Treat curl errors
        switch ($this->curlCode) {
            case CURLE_OK:  // No errors.
                break;
            case CURLE_OPERATION_TIMEOUTED:
                throw new Exceptions\TimeoutException();
                break;
            case CURLE_COULDNT_CONNECT:
            default:
                throw new Exceptions\CommunicationErrorException($this->curlCode);
        }
    }

    public function getBody() {
        return $this->body;
    }

    public function getBodyAsJson() {
        if (is_null($this->jsonBody))
            $this->jsonBody = json_decode($this->getBody(), true);
        return $this->jsonBody;
    }

    public function getCurlCode() {
        return $this->curlCode;
    }

    public function getHttpStatus() {
        return $this->httpStatus;
    }

    public function isOk() {
        return $this->httpStatus == self::HTTP_STATUS_OK;
    }
}


text:
// Copyright (c) Dyoub Applications. All rights reserved.
// Licensed under MIT (https://github.com/dyoub/app/blob/master/LICENSE).

using Dyoub.App.Filters;
using System;

namespace Dyoub.App.Models.ViewModel.Commercial.RentContracts
{
    public class ListRentContractsViewModel
    {
        public int? StoreId { get; set; }

        public DateTime? FromDate { get; set; }

        public DateTime? ToDate { get; set; }

        [ValidIf]
        public bool StartLowerThanEnd
        {
            get
            {
                if (FromDate == null || ToDate == null)
                {
                    return true;
                }

                return FromDate.Value < ToDate.Value;
            }
        }

        public int Index { get; set; }
    }
}


text:
var uuidPackage = require('node-uuid');

module.exports = function uuid(prefix) {
	return (prefix ? (prefix + '-') : '') + uuidPackage.v4();
};