text:
#include "includes.h"

#ifdef WITH_SSL
#include <ssl.h>
#undef Realloc  /* SSLeay defines this and samba has a function of this name */
extern SSL  *ssl;
extern int  sslFd;
#endif  /* WITH_SSL */

extern int DEBUGLEVEL;

BOOL passive = False;

/* the client file descriptor */
int Client = -1;

/* the last IP received from */
struct in_addr lastip;

/* the last port received from */
int lastport=0;

int smb_read_error = 0;

/****************************************************************************
 Determine if a file descriptor is in fact a socket.
****************************************************************************/

BOOL is_a_socket(int fd)
{
  int v,l;
  l = sizeof(int);
  return(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&v, &l) == 0);
}

enum SOCK_OPT_TYPES {OPT_BOOL,OPT_INT,OPT_ON};

struct
{
  char *name;
  int level;
  int option;
  int value;
  int opttype;
} socket_options[] = {
  {"SO_KEEPALIVE",      SOL_SOCKET,    SO_KEEPALIVE,    0,                 OPT_BOOL},
  {"SO_REUSEADDR",      SOL_SOCKET,    SO_REUSEADDR,    0,                 OPT_BOOL},
  {"SO_BROADCAST",      SOL_SOCKET,    SO_BROADCAST,    0,                 OPT_BOOL},
#ifdef TCP_NODELAY
  {"TCP_NODELAY",       IPPROTO_TCP,   TCP_NODELAY,     0,                 OPT_BOOL},
#endif
#ifdef IPTOS_LOWDELAY
  {"IPTOS_LOWDELAY",    IPPROTO_IP,    IP_TOS,          IPTOS_LOWDELAY,    OPT_ON},
#endif
#ifdef IPTOS_THROUGHPUT
  {"IPTOS_THROUGHPUT",  IPPROTO_IP,    IP_TOS,          IPTOS_THROUGHPUT,  OPT_ON},
#endif
#ifdef SO_REUSEPORT
  {"SO_REUSEPORT",      SOL_SOCKET,    SO_REUSEPORT,    0,                 OPT_BOOL},
#endif
#ifdef SO_SNDBUF
  {"SO_SNDBUF",         SOL_SOCKET,    SO_SNDBUF,       0,                 OPT_INT},
#endif
#ifdef SO_RCVBUF
  {"SO_RCVBUF",         SOL_SOCKET,    SO_RCVBUF,       0,                 OPT_INT},
#endif
#ifdef SO_SNDLOWAT
  {"SO_SNDLOWAT",       SOL_SOCKET,    SO_SNDLOWAT,     0,                 OPT_INT},
#endif
#ifdef SO_RCVLOWAT
  {"SO_RCVLOWAT",       SOL_SOCKET,    SO_RCVLOWAT,     0,                 OPT_INT},
#endif
#ifdef SO_SNDTIMEO
  {"SO_SNDTIMEO",       SOL_SOCKET,    SO_SNDTIMEO,     0,                 OPT_INT},
#endif
#ifdef SO_RCVTIMEO
  {"SO_RCVTIMEO",       SOL_SOCKET,    SO_RCVTIMEO,     0,                 OPT_INT},
#endif
  {NULL,0,0,0,0}};

/****************************************************************************
 Set user socket options.
****************************************************************************/

void set_socket_options(int fd, char *options)
{
	fstring tok;

	while (next_token(&options,tok," \t,", sizeof(tok))) {
		int ret=0,i;
		int value = 1;
		char *p;
		BOOL got_value = False;

		if ((p = strchr(tok,'='))) {
			*p = 0;
			value = atoi(p+1);
			got_value = True;
		}

		for (i=0;socket_options[i].name;i++)
			if (strequal(socket_options[i].name,tok))
				break;

		if (!socket_options[i].name) {
			DEBUG(0,("Unknown socket option %s\n",tok));
			continue;
		}

		switch (socket_options[i].opttype) {
		case OPT_BOOL:
		case OPT_INT:
			ret = setsockopt(fd,socket_options[i].level,
						socket_options[i].option,(char *)&value,sizeof(int));
			break;

		case OPT_ON:
			if (got_value)
				DEBUG(0,("syntax error - %s does not take a value\n",tok));

			{
				int on = socket_options[i].value;
				ret = setsockopt(fd,socket_options[i].level,
							socket_options[i].option,(char *)&on,sizeof(int));
			}
			break;
		}

		if (ret != 0)
			DEBUG(0,("Failed to set socket option %s (Error %s)\n",tok, strerror(errno) ));
	}
}

/****************************************************************************
 Close the socket communication.
****************************************************************************/

void close_sockets(void )
{
#ifdef WITH_SSL
  sslutil_disconnect(Client);
#endif /* WITH_SSL */

  close(Client);
  Client = -1;
}

/****************************************************************************
 Read from a socket.
****************************************************************************/

ssize_t read_udp_socket(int fd,char *buf,size_t len)
{
  ssize_t ret;
  struct sockaddr_in sock;
  int socklen;

  socklen = sizeof(sock);
  memset((char *)&sock,'\0',socklen);
  memset((char *)&lastip,'\0',sizeof(lastip));
  ret = (ssize_t)recvfrom(fd,buf,len,0,(struct sockaddr *)&sock,&socklen);
  if (ret <= 0) {
    DEBUG(2,("read socket failed. ERRNO=%s\n",strerror(errno)));
    return(0);
  }

  lastip = sock.sin_addr;
  lastport = ntohs(sock.sin_port);

  DEBUG(10,("read_udp_socket: lastip %s lastport %d read: %d\n",
             inet_ntoa(lastip), lastport, ret));

  return(ret);
}

/****************************************************************************
 Read data from a socket with a timout in msec.
 mincount = if timeout, minimum to read before returning
 maxcount = number to be read.
 time_out = timeout in milliseconds
****************************************************************************/

static ssize_t read_socket_with_timeout(int fd,char *buf,size_t mincnt,size_t maxcnt,unsigned int time_out)
{
  fd_set fds;
  int selrtn;
  ssize_t readret;
  size_t nread = 0;
  struct timeval timeout;

  /* just checking .... */
  if (maxcnt <= 0)
    return(0);

  smb_read_error = 0;

  /* Blocking read */
  if (time_out <= 0) {
    if (mincnt == 0) mincnt = maxcnt;

    while (nread < mincnt) {
#ifdef WITH_SSL
      if(fd == sslFd){
        readret = SSL_read(ssl, buf + nread, maxcnt - nread);
      }else{
        readret = read(fd, buf + nread, maxcnt - nread);
      }
#else /* WITH_SSL */
      readret = read(fd, buf + nread, maxcnt - nread);
#endif /* WITH_SSL */

      if (readret == 0) {
        DEBUG(5,("read_socket_with_timeout: blocking read. EOF from client.\n"));
        smb_read_error = READ_EOF;
        return -1;
      }

      if (readret == -1) {
        DEBUG(0,("read_socket_with_timeout: read error = %s.\n", strerror(errno) ));
        smb_read_error = READ_ERROR;
        return -1;
      }
      nread += readret;
    }
    return((ssize_t)nread);
  }

  /* Most difficult - timeout read */
  /* If this is ever called on a disk file and
     mincnt is greater then the filesize then
     system performance will suffer severely as
     select always returns true on disk files */

  /* Set initial timeout */
  timeout.tv_sec = (time_t)(time_out / 1000);
  timeout.tv_usec = (long)(1000 * (time_out % 1000));

  for (nread=0; nread < mincnt; ) {
    FD_ZERO(&fds);
    FD_SET(fd,&fds);

    selrtn = sys_select(fd+1,&fds,&timeout);

    /* Check if error */
    if(selrtn == -1) {
      /* something is wrong. Maybe the socket is dead? */
      DEBUG(0,("read_socket_with_timeout: timeout read. select error = %s.\n", strerror(errno) ));
      smb_read_error = READ_ERROR;
      return -1;
    }

    /* Did we timeout ? */
    if (selrtn == 0) {
      DEBUG(10,("read_socket_with_timeout: timeout read. select timed out.\n"));
      smb_read_error = READ_TIMEOUT;
      return -1;
    }

#ifdef WITH_SSL
    if(fd == sslFd){
      readret = SSL_read(ssl, buf + nread, maxcnt - nread);
    }else{
      readret = read(fd, buf + nread, maxcnt - nread);
    }
#else /* WITH_SSL */
    readret = read(fd, buf+nread, maxcnt-nread);
#endif /* WITH_SSL */

    if (readret == 0) {
      /* we got EOF on the file descriptor */
      DEBUG(5,("read_socket_with_timeout: timeout read. EOF from client.\n"));
      smb_read_error = READ_EOF;
      return -1;
    }

    if (readret == -1) {
      /* the descriptor is probably dead */
      DEBUG(0,("read_socket_with_timeout: timeout read. read error = %s.\n", strerror(errno) ));
      smb_read_error = READ_ERROR;
      return -1;
    }

    nread += readret;
  }

  /* Return the number we got */
  return((ssize_t)nread);
}

/****************************************************************************
 Read data from a fd with a timout in msec.
 mincount = if timeout, minimum to read before returning
 maxcount = number to be read.
 time_out = timeout in milliseconds
****************************************************************************/

ssize_t read_with_timeout(int fd,char *buf,size_t mincnt,size_t maxcnt,unsigned int time_out)
{
  fd_set fds;
  int selrtn;
  ssize_t readret;
  size_t nread = 0;
  struct timeval timeout;

  /* just checking .... */
  if (maxcnt <= 0)
    return(0);

  /* Blocking read */
  if (time_out <= 0) {
    if (mincnt == 0) mincnt = maxcnt;

    while (nread < mincnt) {
#ifdef WITH_SSL
      if(fd == sslFd){
        readret = SSL_read(ssl, buf + nread, maxcnt - nread);
      }else{
        readret = read(fd, buf + nread, maxcnt - nread);
      }
#else /* WITH_SSL */
      readret = read(fd, buf + nread, maxcnt - nread);
#endif /* WITH_SSL */

      if (readret <= 0)
	return readret;

      nread += readret;
    }
    return((ssize_t)nread);
  }

  /* Most difficult - timeout read */
  /* If this is ever called on a disk file and
     mincnt is greater then the filesize then
     system performance will suffer severely as
     select always returns true on disk files */

  /* Set initial timeout */
  timeout.tv_sec = (time_t)(time_out / 1000);
  timeout.tv_usec = (long)(1000 * (time_out % 1000));

  for (nread=0; nread < mincnt; ) {
    FD_ZERO(&fds);
    FD_SET(fd,&fds);

    selrtn = sys_select(fd+1,&fds,&timeout);

    if(selrtn <= 0)
      return selrtn;

#ifdef WITH_SSL
    if(fd == sslFd){
      readret = SSL_read(ssl, buf + nread, maxcnt - nread);
    }else{
      readret = read(fd, buf + nread, maxcnt - nread);
    }
#else /* WITH_SSL */
    readret = read(fd, buf+nread, maxcnt-nread);
#endif /* WITH_SSL */

    if (readret <= 0)
      return readret;

    nread += readret;
  }

  /* Return the number we got */
  return((ssize_t)nread);
}

/****************************************************************************
send a keepalive packet (rfc1002)
****************************************************************************/

BOOL send_keepalive(int client)
{
  unsigned char buf[4];

  buf[0] = 0x85;
  buf[1] = buf[2] = buf[3] = 0;

  return(write_socket_data(client,(char *)buf,4) == 4);
}

/****************************************************************************
  read data from the client, reading exactly N bytes.
****************************************************************************/

ssize_t read_data(int fd,char *buffer,size_t N)
{
  ssize_t  ret;
  size_t total=0;

  smb_read_error = 0;

  while (total < N)
  {
#ifdef WITH_SSL
    if(fd == sslFd){
      ret = SSL_read(ssl, buffer + total, N - total);
    }else{
      ret = read(fd,buffer + total,N - total);
    }
#else /* WITH_SSL */
    ret = read(fd,buffer + total,N - total);
#endif /* WITH_SSL */

    if (ret == 0)
    {
      DEBUG(10,("read_data: read of %d returned 0. Error = %s\n", (int)(N - total), strerror(errno) ));
      smb_read_error = READ_EOF;
      return 0;
    }
    if (ret == -1)
    {
      DEBUG(0,("read_data: read failure for %d. Error = %s\n", (int)(N - total), strerror(errno) ));
      smb_read_error = READ_ERROR;
      return -1;
    }
    total += ret;
  }
  return (ssize_t)total;
}

/****************************************************************************
 Read data from a socket, reading exactly N bytes.
****************************************************************************/

static ssize_t read_socket_data(int fd,char *buffer,size_t N)
{
  ssize_t  ret;
  size_t total=0;

  smb_read_error = 0;

  while (total < N)
  {
#ifdef WITH_SSL
    if(fd == sslFd){
      ret = SSL_read(ssl, buffer + total, N - total);
    }else{
      ret = read(fd,buffer + total,N - total);
    }
#else /* WITH_SSL */
    ret = read(fd,buffer + total,N - total);
#endif /* WITH_SSL */

    if (ret == 0)
    {
      DEBUG(10,("read_socket_data: recv of %d returned 0. Error = %s\n", (int)(N - total), strerror(errno) ));
      smb_read_error = READ_EOF;
      return 0;
    }
    if (ret == -1)
    {
      DEBUG(0,("read_socket_data: recv failure for %d. Error = %s\n", (int)(N - total), strerror(errno) ));
      smb_read_error = READ_ERROR;
      return -1;
    }
    total += ret;
  }
  return (ssize_t)total;
}

/****************************************************************************
 Write data to a fd.
****************************************************************************/

ssize_t write_data(int fd,char *buffer,size_t N)
{
  size_t total=0;
  ssize_t ret;

  while (total < N)
  {
#ifdef WITH_SSL
    if(fd == sslFd){
      ret = SSL_write(ssl,buffer + total,N - total);
    }else{
      ret = write(fd,buffer + total,N - total);
    }
#else /* WITH_SSL */
    ret = write(fd,buffer + total,N - total);
#endif /* WITH_SSL */

    if (ret == -1) {
      DEBUG(0,("write_data: write failure. Error = %s\n", strerror(errno) ));
      return -1;
    }
    if (ret == 0) return total;

    total += ret;
  }
  return (ssize_t)total;
}

/****************************************************************************
 Write data to a socket - use send rather than write.
****************************************************************************/

ssize_t write_socket_data(int fd,char *buffer,size_t N)
{
  size_t total=0;
  ssize_t ret;

  while (total < N)
  {
#ifdef WITH_SSL
    if(fd == sslFd){
      ret = SSL_write(ssl,buffer + total,N - total);
    }else{
      ret = send(fd,buffer + total,N - total, 0);
    }
#else /* WITH_SSL */
    ret = send(fd,buffer + total,N - total,0);
#endif /* WITH_SSL */

    if (ret == -1) {
      DEBUG(0,("write_socket_data: write failure. Error = %s\n", strerror(errno) ));
      return -1;
    }
    if (ret == 0) return total;

    total += ret;
  }
  return (ssize_t)total;
}

/****************************************************************************
write to a socket
****************************************************************************/

ssize_t write_socket(int fd,char *buf,size_t len)
{
  ssize_t ret=0;

  if (passive)
    return(len);
  DEBUG(6,("write_socket(%d,%d)\n",fd,(int)len));
  ret = write_socket_data(fd,buf,len);

  DEBUG(6,("write_socket(%d,%d) wrote %d\n",fd,(int)len,(int)ret));
  if(ret <= 0)
    DEBUG(0,("write_socket: Error writing %d bytes to socket %d: ERRNO = %s\n",
       (int)len, fd, strerror(errno) ));

  return(ret);
}

/****************************************************************************
read 4 bytes of a smb packet and return the smb length of the packet
store the result in the buffer
This version of the function will return a length of zero on receiving
a keepalive packet.
timeout is in milliseconds.
****************************************************************************/

static ssize_t read_smb_length_return_keepalive(int fd,char *inbuf,unsigned int timeout)
{
  ssize_t len=0;
  int msg_type;
  BOOL ok = False;

  while (!ok)
  {
    if (timeout > 0)
      ok = (read_socket_with_timeout(fd,inbuf,4,4,timeout) == 4);
    else
      ok = (read_socket_data(fd,inbuf,4) == 4);

    if (!ok)
      return(-1);

    len = smb_len(inbuf);
    msg_type = CVAL(inbuf,0);

    if (msg_type == 0x85)
      DEBUG(5,("Got keepalive packet\n"));
  }

  DEBUG(10,("got smb length of %d\n",len));

  return(len);
}

/****************************************************************************
read 4 bytes of a smb packet and return the smb length of the packet
store the result in the buffer. This version of the function will
never return a session keepalive (length of zero).
timeout is in milliseconds.
****************************************************************************/

ssize_t read_smb_length(int fd,char *inbuf,unsigned int timeout)
{
  ssize_t len;

  for(;;)
  {
    len = read_smb_length_return_keepalive(fd, inbuf, timeout);

    if(len < 0)
      return len;

    /* Ignore session keepalives. */
    if(CVAL(inbuf,0) != 0x85)
      break;
  }

  DEBUG(10,("read_smb_length: got smb length of %d\n",len));

  return len;
}

/****************************************************************************
  read an smb from a fd. Note that the buffer *MUST* be of size
  BUFFER_SIZE+SAFETY_MARGIN.
  The timeout is in milliseconds.
  This function will return on a
  receipt of a session keepalive packet.
****************************************************************************/

BOOL receive_smb(int fd,char *buffer, unsigned int timeout)
{
  ssize_t len,ret;

  smb_read_error = 0;

  memset(buffer,'\0',smb_size + 100);

  len = read_smb_length_return_keepalive(fd,buffer,timeout);
  if (len < 0)
  {
    DEBUG(10,("receive_smb: length < 0!\n"));
    return(False);
  }

  if (len > BUFFER_SIZE) {
    DEBUG(0,("Invalid packet length! (%d bytes).\n",len));
    if (len > BUFFER_SIZE + (SAFETY_MARGIN/2))
    {
	exit(1);
    }
  }

  if(len > 0) {
    ret = read_socket_data(fd,buffer+4,len);
    if (ret != len) {
      smb_read_error = READ_ERROR;
      return False;
    }
  }
  return(True);
}

/****************************************************************************
  read an smb from a fd ignoring all keepalive packets. Note that the buffer
  *MUST* be of size BUFFER_SIZE+SAFETY_MARGIN.
  The timeout is in milliseconds

  This is exactly the same as receive_smb except that it never returns
  a session keepalive packet (just as receive_smb used to do).
  receive_smb was changed to return keepalives as the oplock processing means this call
  should never go into a blocking read.
****************************************************************************/

BOOL client_receive_smb(int fd,char *buffer, unsigned int timeout)
{
  BOOL ret;

  for(;;)
  {
    ret = receive_smb(fd, buffer, timeout);

    if (!ret)
    {
      DEBUG(10,("client_receive_smb failed\n"));
      show_msg(buffer);
      return ret;
    }

    /* Ignore session keepalive packets. */
    if(CVAL(buffer,0) != 0x85)
      break;
  }
  show_msg(buffer);
  return ret;
}

/****************************************************************************
  send an null session message to a fd
****************************************************************************/

BOOL send_null_session_msg(int fd)
{
  ssize_t ret;
  uint32 blank = 0;
  size_t len = 4;
  size_t nwritten=0;
  char *buffer = (char *)␣

  while (nwritten < len)
  {
    ret = write_socket(fd,buffer+nwritten,len - nwritten);
    if (ret <= 0)
    {
      DEBUG(0,("send_null_session_msg: Error writing %d bytes to client. %d. Exiting\n",(int)len,(int)ret));
      close_sockets();
      exit(1);
    }
    nwritten += ret;
  }

  DEBUG(10,("send_null_session_msg: sent 4 null bytes to client.\n"));
  return True;
}

/****************************************************************************
  send an smb to a fd
****************************************************************************/

BOOL send_smb(int fd,char *buffer)
{
  size_t len;
  size_t nwritten=0;
  ssize_t ret;
  len = smb_len(buffer) + 4;

  while (nwritten < len)
  {
    ret = write_socket(fd,buffer+nwritten,len - nwritten);
    if (ret <= 0)
    {
      DEBUG(0,("Error writing %d bytes to client. %d. Exiting\n",(int)len,(int)ret));
      close_sockets();
      exit(1);
    }
    nwritten += ret;
  }

  return True;
}

/****************************************************************************
send a single packet to a port on another machine
****************************************************************************/

BOOL send_one_packet(char *buf,int len,struct in_addr ip,int port,int type)
{
  BOOL ret;
  int out_fd;
  struct sockaddr_in sock_out;

  if (passive)
    return(True);

  /* create a socket to write to */
  out_fd = socket(AF_INET, type, 0);
  if (out_fd == -1)
    {
      DEBUG(0,("socket failed"));
      return False;
    }

  /* set the address and port */
  memset((char *)&sock_out,'\0',sizeof(sock_out));
  putip((char *)&sock_out.sin_addr,(char *)&ip);
  sock_out.sin_port = htons( port );
  sock_out.sin_family = AF_INET;

  if (DEBUGLEVEL > 0)
    DEBUG(3,("sending a packet of len %d to (%s) on port %d of type %s\n",
	     len,inet_ntoa(ip),port,type==SOCK_DGRAM?"DGRAM":"STREAM"));

  /* send it */
  ret = (sendto(out_fd,buf,len,0,(struct sockaddr *)&sock_out,sizeof(sock_out)) >= 0);

  if (!ret)
    DEBUG(0,("Packet send to %s(%d) failed ERRNO=%s\n",
	     inet_ntoa(ip),port,strerror(errno)));

  close(out_fd);
  return(ret);
}

/****************************************************************************
open a socket of the specified type, port and address for incoming data
****************************************************************************/

int open_socket_in(int type, int port, int dlevel,uint32 socket_addr, BOOL rebind)
{
#ifndef EMBED
  struct hostent *hp;
  pstring host_name;
#endif
  struct sockaddr_in sock;
  int res;

#ifndef EMBED
  /* get my host name */
  if (gethostname(host_name, MAXHOSTNAMELEN) == -1)
    { DEBUG(0,("gethostname failed\n")); return -1; }

  /* get host info */
  if ((hp = Get_Hostbyname(host_name)) == 0)
    {
      DEBUG(0,( "Get_Hostbyname: Unknown host %s\n",host_name));
      return -1;
    }
#endif

  memset((char *)&sock,'\0',sizeof(sock));
#ifdef EMBED
  sock.sin_addr.s_addr = htonl(INADDR_ANY);
#else
  memcpy((char *)&sock.sin_addr,(char *)hp->h_addr, hp->h_length);
#endif

#ifdef HAVE_SOCK_SIN_LEN
  sock.sin_len = sizeof(sock);
#endif
  sock.sin_port = htons( port );
#ifdef EMBED
  sock.sin_family = AF_INET;
#else
  sock.sin_family = hp->h_addrtype;
#endif
  sock.sin_addr.s_addr = socket_addr;
#ifdef EMBED
  res = socket(AF_INET, type, 0);
#else
  res = socket(hp->h_addrtype, type, 0);
#endif
  if (res == -1)
    { DEBUG(0,("socket failed\n")); return -1; }

  {
    int val=1;
	if(rebind)
		val=1;
	else
		val=0;
    if(setsockopt(res,SOL_SOCKET,SO_REUSEADDR,(char *)&val,sizeof(val)) == -1)
		DEBUG(dlevel,("setsockopt: SO_REUSEADDR=%d on port %d failed with error = %s\n",
			val, port, strerror(errno) ));
#ifdef SO_REUSEPORT
    if(setsockopt(res,SOL_SOCKET,SO_REUSEPORT,(char *)&val,sizeof(val)) == -1)
		DEBUG(dlevel,("setsockopt: SO_REUSEPORT=%d on port %d failed with error = %s\n",
			val, port, strerror(errno) ));
#endif /* SO_REUSEPORT */
  }

  /* now we've got a socket - we need to bind it */
  if (bind(res, (struct sockaddr * ) &sock,sizeof(sock)) < 0)
    {
      if (port) {
	if (port == SMB_PORT || port == NMB_PORT)
	  DEBUG(dlevel,("bind failed on port %d socket_addr=%s (%s)\n",
			port,inet_ntoa(sock.sin_addr),strerror(errno)));
	close(res);

	if (dlevel > 0 && port < 1000)
	  port = 7999;

	if (port >= 1000 && port < 9000)
	  return(open_socket_in(type,port+1,dlevel,socket_addr,rebind));
      }

      return(-1);
    }
  DEBUG(3,("bind succeeded on port %d\n",port));

  return res;
}

/****************************************************************************
  create an outgoing socket. timeout is in milliseconds.
  **************************************************************************/

int open_socket_out(int type, struct in_addr *addr, int port ,int timeout)
{
  struct sockaddr_in sock_out;
  int res,ret;
  int connect_loop = 250; /* 250 milliseconds */
  int loops = (timeout) / connect_loop;

  /* create a socket to write to */
  res = socket(PF_INET, type, 0);
  if (res == -1)
    { DEBUG(0,("socket error\n")); return -1; }

  if (type != SOCK_STREAM) return(res);

  memset((char *)&sock_out,'\0',sizeof(sock_out));
  putip((char *)&sock_out.sin_addr,(char *)addr);

  sock_out.sin_port = htons( port );
  sock_out.sin_family = PF_INET;

  /* set it non-blocking */
  set_blocking(res,False);

  DEBUG(3,("Connecting to %s at port %d\n",inet_ntoa(*addr),port));

  /* and connect it to the destination */
connect_again:
  ret = connect(res,(struct sockaddr *)&sock_out,sizeof(sock_out));

  /* Some systems return EAGAIN when they mean EINPROGRESS */
  if (ret < 0 && (errno == EINPROGRESS || errno == EALREADY ||
        errno == EAGAIN) && loops--) {
    msleep(connect_loop);
    goto connect_again;
  }

  if (ret < 0 && (errno == EINPROGRESS || errno == EALREADY ||
         errno == EAGAIN)) {
      DEBUG(1,("timeout connecting to %s:%d\n",inet_ntoa(*addr),port));
      close(res);
      return -1;
  }

#ifdef EISCONN
  if (ret < 0 && errno == EISCONN) {
    errno = 0;
    ret = 0;
  }
#endif

  if (ret < 0) {
    DEBUG(1,("error connecting to %s:%d (%s)\n",
	     inet_ntoa(*addr),port,strerror(errno)));
    close(res);
    return -1;
  }

  /* set it blocking again */
  set_blocking(res,True);

  return res;
}

/*******************************************************************
 Reset the 'done' variables so after a client process is created
 from a fork call these calls will be re-done. This should be
 expanded if more variables need reseting.
 ******************************************************************/

static BOOL global_client_name_done = False;
static BOOL global_client_addr_done = False;

void reset_globals_after_fork(void)
{
  global_client_name_done = False;
  global_client_addr_done = False;

  /*
   * Re-seed the random crypto generator, so all smbd's
   * started from the same parent won't generate the same
   * sequence.
   */
  {
    unsigned char dummy;
    generate_random_buffer( &dummy, 1, True);
  }
}

/*******************************************************************
 return the DNS name of the client
 ******************************************************************/

char *client_name(int fd)
{
	struct sockaddr sa;
	struct sockaddr_in *sockin = (struct sockaddr_in *) (&sa);
	int     length = sizeof(sa);
	static pstring name_buf;
	struct hostent *hp;
	static int last_fd=-1;

	if (global_client_name_done && last_fd == fd)
		return name_buf;

	last_fd = fd;
	global_client_name_done = False;

	pstrcpy(name_buf,"UNKNOWN");

	if (fd == -1) {
		return name_buf;
	}

	if (getpeername(fd, &sa, &length) < 0) {
		DEBUG(0,("getpeername failed. Error was %s\n", strerror(errno) ));
		return name_buf;
	}

	/* Look up the remote host name. */
	if ((hp = gethostbyaddr((char *) &sockin->sin_addr,
				sizeof(sockin->sin_addr),
				AF_INET)) == 0) {
		DEBUG(1,("Gethostbyaddr failed for %s\n",client_addr(fd)));
		StrnCpy(name_buf,client_addr(fd),sizeof(name_buf) - 1);
	} else {
		StrnCpy(name_buf,(char *)hp->h_name,sizeof(name_buf) - 1);
		if (!matchname(name_buf, sockin->sin_addr)) {
			DEBUG(0,("Matchname failed on %s %s\n",name_buf,client_addr(fd)));
			pstrcpy(name_buf,"UNKNOWN");
		}
	}
	global_client_name_done = True;
	return name_buf;
}

/*******************************************************************
 return the IP addr of the client as a string
 ******************************************************************/

char *client_addr(int fd)
{
	struct sockaddr sa;
	struct sockaddr_in *sockin = (struct sockaddr_in *) (&sa);
	int     length = sizeof(sa);
	static fstring addr_buf;
	static int last_fd = -1;

	if (global_client_addr_done && fd == last_fd)
		return addr_buf;

	last_fd = fd;
	global_client_addr_done = False;

	fstrcpy(addr_buf,"0.0.0.0");

	if (fd == -1) {
		return addr_buf;
	}

	if (getpeername(fd, &sa, &length) < 0) {
		DEBUG(0,("getpeername failed. Error was %s\n", strerror(errno) ));
		return addr_buf;
	}

	fstrcpy(addr_buf,(char *)inet_ntoa(sockin->sin_addr));

	global_client_addr_done = True;
	return addr_buf;
}


text:
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	errorHandler = require('./errors'),
	Story = mongoose.model('Story'),
	_ = require('lodash');

/**
 * Create a Story
 */
exports.create = function(req, res) {
	var story = new Story(req.body);
	story.user = req.user;

	story.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(story);
		}
	});
};

/**
 * Show the current Story
 */
exports.read = function(req, res) {
	res.jsonp(req.story);
};

/**
 * Update a Story
 */
exports.update = function(req, res) {
	var story = req.story ;

	story = _.extend(story , req.body);

	story.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(story);
		}
	});
};

/**
 * Delete an Story
 */
exports.delete = function(req, res) {
	var story = req.story ;

	story.remove(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(story);
		}
	});
};

/**
 * List of Stories
 */
exports.list = function(req, res) { Story.find().sort('-created').limit(20).
	populate('user', 'displayName').exec(function(err, stories) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(stories);
		}
	});
};

/**
 * Story middleware
 */
exports.storyByID = function(req, res, next, id) { Story.findById(id).populate('user', 'displayName').exec(function(err, story) {
		if (err) return next(err);
		if (! story) return next(new Error('Failed to load Story ' + id));
		req.story = story ;
		next();
	});
};

/**
 * Story authorization middleware
 */
exports.hasAuthorization = function(req, res, next) {
	if (req.story.user.id !== req.user.id) {
		return res.status(403).send('User is not authorized');
	}
	next();
};

redpajama_set_name: RedPajamaGithub


text:
package org.openspaces.admin.internal.support;

import groovy.lang.Closure;

/**
 * @author kimchy
 */
public class AbstractClosureEventListener {

    private final Closure closure;

    public AbstractClosureEventListener(Object closure) {
        this.closure = (Closure) closure;
    }

    protected Closure getClosure() {
        return this.closure;
    }

    @Override
    public int hashCode() {
        return closure.hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        return closure.equals(((AbstractClosureEventListener) obj).closure);
    }
}


text:
[
	object,
	uuid("0D61AA35-48D5-47F5-8249-F685F75250FD"),
	dual,	helpstring("ICertStore Interface"),
	pointer_default(unique)
]
__interface ICertStore : IDispatch
{
	[id(1), helpstring("method GetCertificateList")] HRESULT GetCertificateList([out] ULONG* certCount, [out,retval] BSTR *certArray);
	[propput, id(2), helpstring("property NetscapeStorePassword")] HRESULT NetscapeStorePassword([in] BSTR newVal);
	[id(3), helpstring("method ExportNetscapeCert")] HRESULT ExportNetscapeCert([in] BSTR certSerialNumber, [out,retval] BSTR* pfxFilePath);
};

// CCertStore

[
	coclass,
	threading("apartment"),
	vi_progid("NetscapeCert.CertStore"),
	progid("NetscapeCert.CertStore.1"),
	version(1.0),
	uuid("0A06154B-8FF9-48B2-A819-B68C327FC773"),
	helpstring("CertStore Class")
]
class ATL_NO_VTABLE CCertStore :
	public ICertStore
{
public:
	CCertStore();
	~CCertStore();

	char *nsStoreHandle;
	char nsStorePassword[MAX_PATH];
	PCERT_DESCR *certList;
	int certListSize;

	DECLARE_PROTECT_FINAL_CONSTRUCT()

	HRESULT FinalConstruct()
	{
		return S_OK;
	}

	void FinalRelease()
	{
	}

public:

	STDMETHOD(GetCertificateList)(ULONG* certCount, BSTR* certArray);
	STDMETHOD(put_NetscapeStorePassword)(BSTR newVal);
	STDMETHOD(ExportNetscapeCert)(BSTR certSerialNumber, BSTR* pfxFilePath);
};


text:
<?php
/*宜信*/
class easemob{

	private $org_name 	= 'easemob-playground';
	private $app_name 	= 'test1';
	private $client_id 	= 'YXA6wDs-MARqEeSO0VcBzaqg5A';
	private $client_secret  = 'YXA6JOMWlLap_YbI_ucz77j-4-mI0JA';
	private $url;
	function __construct()
	{
		if (! empty ( $this->org_name ) && ! empty ( $this->app_name )) {
			$this->url    = 'https://a1.easemob.com/' . $this->org_name . '/' . $this->app_name . '/';
		}
		$this->authHeader = 'Authorization: Bearer ' . $this->token();
	}

	/**
	*	注册IM用户[单个] || 授权注册模式 || 批量注册
	*	HTTP Method : POST
	* @param $options['username'] 用户名
	* @param $options['password'] 密码
	*		批量注册传二维数组
	*	http://test.com/easemob/reg/username/name/password/123456
	*/
	public function reg($parameters_array)
	{

		$options=['username'=>'wt55347','password'=>'123456'];
		$url = $this->url. 'users';
		return $this->handelUrl($url,$options);
	}
	/**
	* 	获取指定用户详情 GET || 删除用户 DELETE || 修改密码 PUT || 修改昵称 PUT || 查看用户在线状态 GET
	*	HTTP Method : GET
	* @param $username 用户名
	* @param $method 操作类型  默认GET 、DELETE 、PUT  STATUS(状态)
	*	http://test.com/easemob/userinfo/username/wt55345/password/password/method/STATUS
	*
	*/
	public function userinfo($parameters_array)
	{
		$url = $this->url . "users/" . trim($parameters_array['username']);
		// $parameters_array['username']='wt55345';

		$method = $parameters_array['method'] ? strtoupper(trim($parameters_array['method'])) : 'GET';

		if ($parameters_array['nickname']) {
			$method = 'PUT';
			$options['nickname'] = trim($parameters_array['nickname']);
		}elseif($parameters_array['password']){
			$method = 'PUT';
			$options['newpassword'] = trim($parameters_array['password']);//有疑问的地方!是password or newpassword
		}
		if ($method=='STATUS') {
			$method = 'GET';
			$url = $this->url . "users/" . trim($parameters_array['username']).'/status';

		}

		return $this->handelUrl($url,$options,$method);
	}
	/**
	* 	用户好友管理 添加一个好友POST || 解除IM用户的好友关系DELETE || 查看好友GET
	*
	* @param $owner_username
	* @param $friend_username
	*	http://test.com/easemob/friend/username/{}/method/get
	*/
	public function friend($parameters_array)
	{
		$method = $parameters_array['method'] ? strtoupper(trim($parameters_array['method'])) : 'GET';

		if (!$parameters_array['username']) {return false;}

		$url = $this->url . "users/" . trim($parameters_array['username']) . "/contacts/users/";

		if (($method == 'POST' || $method == 'DELETE' ) && $parameters_array['friendUsername']) {
			$url  = $url. trim($parameters_array['friendUsername']);
		}

  		return $this->handelUrl($url,$options,$method);

	}

 /*
 	获取IM用户的黑名单GET || 往IM用户的黑名单中加人POST || 从IM用户的黑名单中减人DELETE
 */
	public function blacklist($parameters_array)
	{
		$url = $this->url . "users/" . trim($parameters_array['username']) . "/blocks/users";

		$method = $parameters_array['method'] ? strtoupper(trim($parameters_array['method'])) : 'GET';

		if ($method == 'POST') {
			$options['usernames'] = $parameters_array['usernames'];
		}elseif($method == 'DELETE')
		{
			$options['usernames'] = $parameters_array['usernames'];
			$url  		      = $url. trim($parameters_array['usernames'][0]);
		}

		return $this->handelUrl($url,$options,$method);
	}

	//访问url
	protected function handelUrl($url,$options='',$method='POST')
	{
		$result = $this->curl($url, $options,$method);
		print_r($result);
		return $result;
	}

	//获取access_tonke 内部使用方法
	protected function token()
	{

		$array['grant_method'] 	= "client_credentials";
		$array['client_id'] 	= $this->client_id;
		$array['client_secret'] = $this->client_secret;

		$url 			= $this->url . "token";
		$data 			= json_decode(bigsea()->get('/wotaotao/easemob/token'),1);
        	$expire			= 600000;// 7d = 604800s

        if (time()-$data['time']<$expire) {
        	// echo $data['token']['access_token'];
        	return $data['token']['access_token'];
        }else{
	      	$token 				= json_decode($this->curl($url,$array),1);
			unset($data['old']);
			$key = ['token'=>$token, 'time'=>time(), 'duration'=>$expire, 'old'=>$data];
	        bigsea()->put('/wotaotao/easemob/token',json_encode($key));
	        // echo $token['access_token'];
	        return $token['access_token'];
        }
	}

	protected function curl($url,$options = null,$method='POST'){
		$header = ['Accept:application/json','Content-method: application/json'];
		array_push($header, $this->authHeader);

		$ch = curl_init();
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1);

		if ($options){
	    	$data = json_encode($options);
	        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
	    }
		curl_setopt($ch, CURLOPT_HTTPHEADER, $header);

		$ret 	= curl_exec($ch);
		$code 	= curl_getinfo($ch,CURLINFO_HTTP_CODE); //curl 状态码
		curl_close($ch);

		$return = json_decode($ret,1);

		if ($code != 200) {
			return json_encode(['code'=>0, 'statuscode'=>$code, 'msg'=>$return['error_description'] ]);
		}
		$return['code']=1;
		$return['statuscode']=200;
		$return['msg']='success';

		return json_encode($return);

	}

}


text:
<?php

namespace Contrast\RaidAdmin\ApplicationBundle\View;

use Contrast\RaidAdmin\BattleNetBundle\Entity\Player;
use Contrast\RaidAdmin\BattleNetBundle\Entity\Character;
use Contrast\RaidAdmin\BattleNetBundle\Entity\RaidEvent;

/**
 * Class AttendanceTableRow
 *
 * @package Contrast\RaidAdmin\ApplicationBundle\View
 * @author Tim Fennis <tim@isset.nl>
 */
class AttendanceTableRow
{

    /**
     * @var string
     */
    protected $id;

    /**
     * @var Player
     */
    protected $player;

    /**
     * @var Character[]
     */
    protected $characters;

    /**
     * @param Player|Character $object
     */
    public function __construct($object)
    {
        $this->id = spl_object_hash($object);
        if ($object instanceof Player) {
            $this->player = $object;
            $this->characters = $this->player->getCharacters()->toArray();
        } else if ($object instanceof Character) {
            $this->player = null;
            $this->characters = [$object];
        }
    }

    /**
     * @return string
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @param RaidEvent[] $events
     * @return AttendanceCell[]
     */
    public function getAttendanceForEvents($events)
    {
        $cells = [];
        foreach ($events as $event) {
            $found = false; // Every amazing algorithm ever has a found boolean :'(
            foreach ($this->characters as $character) {
                if ($character->attendEvent($event) && $found === false) { //?!?!?!?
                    $cells[] = new AttendanceCell($character->getAttendanceForEvent($event));
                    $found = true;

                }
            }

            if ($found === false) {
                $cells[] = new AttendanceCell(null);
            }
        }

        return $cells;
    }

    /**
     * @return Character
     */
    public function getMainCharacter()
    {
        //@todo implement better logic for main characters
        return reset($this->characters);
    }
}


text:
<?php

namespace robote13\catalog\backend\controllers;

use Yii;
use yii\helpers\Url;
use yii\base\Model;
use yii\web\NotFoundHttpException;
use robote13\catalog\models\DynamicAttributes;
use robote13\catalog\models\ProductType;
use robote13\yii2components\web\CrudControllerAbstract;

/**
 * ProductController implements the CRUD actions for Product model.
 */
class ProductController extends CrudControllerAbstract
{

    public function getModelClass()
    {
        return 'robote13\catalog\models\Product';
    }

    public function getSearchClass()
    {
        return 'robote13\catalog\forms\ProductSearch';
    }

    public function actions()
    {
        return[
            'update-editable'=>[
                'class'=> \robote13\yii2components\web\EditableAction::className(),
                'modelClass'=> \robote13\catalog\models\Product::className()
            ],
            'fileapi-upload' => [
                'class' => \vova07\fileapi\actions\UploadAction::className(),
            ]
        ];
    }

    public function init()
    {
        $this->indexViewParams = function($searchModel,$dataProvider){
            $dataProvider->query->with('type');
            return['dataProvider'=>$dataProvider];
        };
        parent::init();
    }

    public function actionCreate()
    {
        $typeId = Yii::$app->request->get('type_id');
        $productType = ProductType::findOne($typeId);
        $model = Yii::createObject(['class'=>$this->modelClass,'type_id'=> $productType->id]);
        $attributes = Yii::createObject(DynamicAttributes::className());

        DynamicAttributes::$table = $productType->dynamicTableName;
        $dynamicLoaded = $attributes->load(Yii::$app->request->post());
        if ($model->load(Yii::$app->request->post()) && Model::validateMultiple([$model,$attributes]))
        {
            $model->save(false);
            if($dynamicLoaded){
                $attributes->link('product',$model);
            }
            return $this->redirect(['index']);
        }
        return $this->render('create',compact('model','attributes'));
    }

    /**
     * Updates an existing model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param mixed $id
     * @return mixed
     */
    public function actionUpdate()
    {
        $id = Yii::$app->getRequest()->get('id');
        $model = $this->findModel($id);
        $models = ['model'=>$model];
        $attributes = $model->dynamicAttributes;
        if(isset($attributes))
        {
            $attributes->load(Yii::$app->request->post());
            $models['attributes']=$attributes;
        }

        if ($model->load(Yii::$app->request->post()) && Model::validateMultiple($models))
        {
            foreach ($models as $item)
            {
                $item->save(false);
            }
            return $this->redirect(Url::previous("{$this->id}-index"));
        }

        return $this->render('update', $models);
    }

    /**
     * Displays a single Product model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        throw new NotFoundHttpException('The requested page does not exist.');
    }
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<artifactId>jpa</artifactId>
	<packaging>jar</packaging>
	<name>jpa</name>
	<description>Using Native JPA and Hibernate API in Spring</description>
	<parent>
		<groupId>com.hantsylabs.example.spring4</groupId>
		<artifactId>spring4-sandbox</artifactId>
		<version>0.1.0.BUILD-SNAPSHOT</version>
		<relativePath>../</relativePath>
	</parent>
	<dependencies>
		<!-- General dependencies for standard applications -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>

		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>

		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>

		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>

		</dependency>
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>

		</dependency>
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>

		</dependency>

		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
		</dependency>
		<!-- ROO dependencies -->
		<!-- <dependency> <groupId>org.springframework.roo</groupId> <artifactId>org.springframework.roo.annotations</artifactId>
			<version>${roo.version}</version> <scope>provided</scope> </dependency> -->
		<!-- Spring dependencies -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>

		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aop</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aspects</artifactId>
		</dependency>

		<dependency>
			<groupId>com.h2database</groupId>
			<artifactId>h2</artifactId>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-entitymanager</artifactId>
			<exclusions>
				<exclusion>
					<groupId>cglib</groupId>
					<artifactId>cglib</artifactId>
				</exclusion>
				<exclusion>
					<groupId>dom4j</groupId>
					<artifactId>dom4j</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.hibernate.javax.persistence</groupId>
			<artifactId>hibernate-jpa-2.1-api</artifactId>
		</dependency>
		<dependency>
			<groupId>commons-collections</groupId>
			<artifactId>commons-collections</artifactId>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-validator</artifactId>
		</dependency>
		<dependency>
			<groupId>javax.validation</groupId>
			<artifactId>validation-api</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
		</dependency>
		<dependency>
			<groupId>commons-pool</groupId>
			<artifactId>commons-pool</artifactId>
		</dependency>
		<dependency>
			<groupId>commons-dbcp</groupId>
			<artifactId>commons-dbcp</artifactId>
		</dependency>

		<dependency>
			<groupId>commons-digester</groupId>
			<artifactId>commons-digester</artifactId>
		</dependency>
		<dependency>
			<groupId>javax.inject</groupId>
			<artifactId>javax.inject</artifactId>
		</dependency>
		<dependency>
			<groupId>javax.annotation</groupId>
			<artifactId>jsr250-api</artifactId>
		</dependency>

	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
			</plugin>
			<plugin>
				<groupId>org.bsc.maven</groupId>
				<artifactId>maven-processor-plugin</artifactId>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-resources-plugin</artifactId>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-plugin</artifactId>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-assembly-plugin</artifactId>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-deploy-plugin</artifactId>
			</plugin>
			<!-- IDE -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-eclipse-plugin</artifactId>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-idea-plugin</artifactId>
			</plugin>
			<plugin>
				<groupId>org.apache.tomcat.maven</groupId>
				<artifactId>tomcat7-maven-plugin</artifactId>
			</plugin>
			<plugin>
				<groupId>org.eclipse.jetty</groupId>
				<artifactId>jetty-maven-plugin</artifactId>
			</plugin>
			<!-- <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>selenium-maven-plugin</artifactId>
				<version>2.3</version> <configuration> <browser>*firefox</browser> <suite>src/main/webapp/selenium/test-suite.xhtml</suite>
				<results>${project.build.directory}/selenium.html</results> <startURL>http://localhost:4444/</startURL>
				</configuration> <dependencies> <dependency> <groupId>org.seleniumhq.selenium</groupId>
				<artifactId>selenium-server</artifactId> <version>2.25.0</version> </dependency>
				</dependencies> </plugin> -->
		</plugins>
	</build>
</project>


text:
<?php
/**
 * Empty class to get stub for tests
 * User: Alex Gusev <alex@flancer64.com>
 */
namespace Praxigento\BonusRetail\Setup;

use Praxigento\Core\Lib\Context;

include_once(__DIR__ . '/../phpunit_bootstrap.php');

class InstallSchema_UnitTest extends \Praxigento\Core\Lib\Test\BaseTestCase {

    public function test_constructor() {
        /** === Test Data === */
        /** === Mocks === */
        /** === Test itself === */
        /** @var  $obj InstallSchema */
        $obj = new InstallSchema();
    }
}


text:
package org.apache.hadoop.hive.ql.udf.generic;

import org.apache.hadoop.hive.ql.exec.FunctionRegistry;
import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.exec.UDFArgumentTypeException;
import org.apache.hadoop.hive.serde2.io.ByteWritable;
import org.apache.hadoop.hive.serde2.io.DoubleWritable;
import org.apache.hadoop.hive.serde2.io.HiveDecimalWritable;
import org.apache.hadoop.hive.serde2.io.ShortWritable;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector.Category;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorConverters;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorConverters.Converter;
import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.typeinfo.PrimitiveTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoFactory;
import org.apache.hadoop.io.FloatWritable;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;

public abstract class GenericUDFBaseUnary extends GenericUDF {
  protected String opName;
  protected String opDisplayName;

  private transient PrimitiveObjectInspector inputOI;
  protected transient PrimitiveObjectInspector resultOI;

  protected transient Converter converter;

  protected ByteWritable byteWritable = new ByteWritable();
  protected ShortWritable shortWritable = new ShortWritable();
  protected IntWritable intWritable = new IntWritable();
  protected LongWritable longWritable = new LongWritable();
  protected FloatWritable floatWritable = new FloatWritable();
  protected DoubleWritable doubleWritable = new DoubleWritable();
  protected HiveDecimalWritable decimalWritable = new HiveDecimalWritable();

  public GenericUDFBaseUnary() {
    opName = getClass().getSimpleName();
  }

  @Override
  public ObjectInspector initialize(ObjectInspector[] arguments) throws UDFArgumentException {
    if (arguments.length != 1) {
      throw new UDFArgumentException(opName + " requires one argument.");
    }

    Category category = arguments[0].getCategory();
    if (category != Category.PRIMITIVE) {
      throw new UDFArgumentTypeException(0, "The "
          + GenericUDFUtils.getOrdinal(1)
          + " argument of " + opName + "  is expected to a "
          + Category.PRIMITIVE.toString().toLowerCase() + " type, but "
          + category.toString().toLowerCase() + " is found");
    }

    inputOI = (PrimitiveObjectInspector) arguments[0];
    if (!FunctionRegistry.isNumericType(inputOI.getTypeInfo())) {
      throw new UDFArgumentTypeException(0, "The "
          + GenericUDFUtils.getOrdinal(1)
          + " argument of " + opName + "  is expected to a "
          + "numeric type, but "
          + inputOI.getTypeName() + " is found");
    }

    PrimitiveTypeInfo resultTypeInfo = deriveResultTypeInfo(inputOI.getTypeInfo());
    resultOI = PrimitiveObjectInspectorFactory.getPrimitiveWritableObjectInspector(resultTypeInfo);
    converter = ObjectInspectorConverters.getConverter(inputOI, resultOI);
    return resultOI;
  }

  private PrimitiveTypeInfo deriveResultTypeInfo(PrimitiveTypeInfo typeInfo) {
    switch(typeInfo.getPrimitiveCategory()) {
    case STRING:
    case VARCHAR:
    case CHAR:
      return TypeInfoFactory.doubleTypeInfo;
    default:
      return typeInfo;
    }
  }

  @Override
  public String getDisplayString(String[] children) {
    assert (children.length == 1);
    return "(" + opDisplayName + " " + children[0] + ")";
  }

}


text:
using System.Security;
using System;
using System.Runtime.InteropServices; // For SafeHandle

[SecurityCritical]
public class MySafeValidHandle : SafeHandle
{
	  [SecurityCritical]
    public MySafeValidHandle()
        : base(IntPtr.Zero, true)
    {
    }

    public override bool IsInvalid
    {
        [SecurityCritical]
        get { return false; }
    }

    [SecurityCritical]
    protected override bool ReleaseHandle()
    {
        return true;
    }
}

[SecurityCritical]
public class MySafeInValidHandle : SafeHandle
{

[SecurityCritical]
    public MySafeInValidHandle()
        : base(IntPtr.Zero, true)
    {
    }

    public override bool IsInvalid
    {
        [SecurityCritical]
        get { return true; }
    }

    [SecurityCritical]
    protected override bool ReleaseHandle()
    {
        return true;
    }
}

/// <summary>
/// DangerousAddRef(System.Boolean@)
/// </summary>
public class SafeHandleDangerousAddRef
{
    #region Public Methods

    [SecuritySafeCritical]
    public bool RunTests()
    {
        bool retVal = true;

        TestLibrary.TestFramework.LogInformation("[Positive]");
        retVal = PosTest1() && retVal;
        retVal = PosTest2() && retVal;
        retVal = PosTest3() && retVal;
        retVal = PosTest4() && retVal;

        return retVal;
    }

    #region Positive Test Cases

    [SecuritySafeCritical]
    public bool PosTest1()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest1: Call DangerousAddRef on a valid handle");

        try
        {
            SafeHandle handle = new MySafeValidHandle();
            bool success = false;

            handle.DangerousAddRef(ref success);
            if (!success)
            {
                TestLibrary.TestFramework.LogInformation("success returns false after calling DangerousAddRef");
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("001", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }

    [SecuritySafeCritical]
    public bool PosTest2()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest2: Call DangerousAddRef on an invalid handle");

        try
        {
            SafeHandle handle = new MySafeInValidHandle();
            bool success = false;

            handle.DangerousAddRef(ref success);
            if (!success)
            {
                TestLibrary.TestFramework.LogInformation("success returns false after calling DangerousAddRef");
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }

    [SecuritySafeCritical]
    public bool PosTest3()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest3: Call DangerousAddRef twice on a valid handle");

        try
        {
            SafeHandle handle = new MySafeValidHandle();
            bool success = false;

            handle.DangerousAddRef(ref success);
            if (!success)
            {
                TestLibrary.TestFramework.LogInformation("success returns false after calling DangerousAddRef");
            }
            handle.DangerousAddRef(ref success);
            if (!success)
            {
                TestLibrary.TestFramework.LogInformation("success returns false after calling DangerousAddRef");
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("003", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }

    [SecuritySafeCritical]
    public bool PosTest4()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest4: Call DangerousAddRef twice on an invalid handle");

        try
        {
            SafeHandle handle = new MySafeInValidHandle();
            bool success = false;

            handle.DangerousAddRef(ref success);
            if (!success)
            {
                TestLibrary.TestFramework.LogInformation("success returns false after calling DangerousAddRef");
            }

            handle.DangerousAddRef(ref success);
            if (!success)
            {
                TestLibrary.TestFramework.LogInformation("success returns false after calling DangerousAddRef");
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
    #endregion
    #endregion

    [SecuritySafeCritical]
    public static int Main()
    {
        SafeHandleDangerousAddRef test = new SafeHandleDangerousAddRef();

        TestLibrary.TestFramework.BeginTestCase("SafeHandleDangerousAddRef");

        if (test.RunTests())
        {
            TestLibrary.TestFramework.EndTestCase();
            TestLibrary.TestFramework.LogInformation("PASS");
            return 100;
        }
        else
        {
            TestLibrary.TestFramework.EndTestCase();
            TestLibrary.TestFramework.LogInformation("FAIL");
            return 0;
        }
    }
}


text:
import types from './types';

export function getGameTitlesRequest() {
  return {
    type: types.GET_GAME_TITLES_REQUEST,
    isLoading: true
  };
}

export function getGameTitlesSuccess(gameTitles) {
  return {
    type: types.GET_GAME_TITLES_SUCCESS,
    payload: gameTitles,
    isLoading: false,
    error: false,
    errorMsg: ''
  };
}

export function getGameTitlesFailure() {
  return {
    type: types.GET_GAME_TITLES_FAILURE,
    isLoading: false,
    error: true,
    errorMsg: 'Failed to retrived all TC supported game titles.'
  };
}


text:
require File.expand_path('../../../spec_helper', __FILE__)
require File.expand_path('../fixtures/classes', __FILE__)

describe "Kernel#clone" do
  before :each do
    ScratchPad.clear
    @obj = KernelSpecs::Duplicate.new 1, :a
  end

  it "calls #initialize_copy on the new instance" do
    clone = @obj.clone
    ScratchPad.recorded.should_not == @obj.object_id
    ScratchPad.recorded.should == clone.object_id
  end

  it "copies instance variables" do
    clone = @obj.clone
    clone.one.should == 1
    clone.two.should == :a
  end

  it "copies singleton methods" do
    def @obj.special() :the_one end
    clone = @obj.clone
    clone.special.should == :the_one
  end

  it "copies modules included in the singleton class" do
    class << @obj
      include KernelSpecs::DuplicateM
    end

    clone = @obj.clone
    clone.repr.should == "KernelSpecs::Duplicate"
  end

  it "copies constants defined in the singleton class" do
    class << @obj
      CLONE = :clone
    end

    clone = @obj.clone
    class << clone
      CLONE.should == :clone
    end
  end

  it "raises TypeError when called on nil" do
    lambda {
      nil.clone
    }.should raise_error(TypeError)
  end
end


text:
"use strict";

var login = login || {};

/**
 * This function allows us to load up the game service via the discovery doc
 * and makes calls directly through the client library instead of needing
 * to specify the REST endpoints.
 */
login.loadClient = function() {

  // Load up /games/v1
  gapi.client.load('games','v1',function(response) {
    player.loadLocalPlayer();
    achManager.loadData();
    leadManager.preloadData();
    welcome.loadUp();
    game.init();
    challenge.tryToLoad();
  });

  // Load up v1management
  gapi.client.load('gamesManagement','v1management', function(response) {
    welcome.dataLoaded(welcome.ENUM_MANAGEMENT_API);
  });

  // Load up /plus/v1
  gapi.client.load('plus','v1', function(response) {
    welcome.dataLoaded(welcome.ENUM_PLUS_API)
  });

};

login.handleAuthResult = function(auth) {
  console.log('We are in handle auth result', auth);
  if (auth && auth.error == null) {
    console.log('Hooray! You\'re logged in! ', auth );
    $('#loginDiv').fadeOut();
    login.loadClient();
  } else {
    if (auth && auth.hasOwnProperty('error')) {
      console.log('Login failed because: ', auth.error);
    }
    $('#loginDiv').fadeIn();
  }
};

login.showLoginDialog=function() {
  console.log('Trying not-so-silent auth');
  gapi.auth.signIn();
};

login.logout = function() {
  gapi.auth.signOut();
  achManager.clearData();
  friendsTable.clearData();
  leadManager.clearData();
  challenge.clearData();
  player.clearData();
  welcome.userSignOut();
  $('#loginDiv').fadeIn();
};


text:
let owner;
if (window.HTMLImports && !window.HTMLImports.useNative) {
  owner = document._currentScript.ownerDocument; // eslint-disable-line
} else {
  owner = document.currentScript.ownerDocument;
}

export const emptySquare = owner.querySelector('#emptyTemplate');

export const pieces = {
  P: owner.querySelector('#whitePawnTemplate'),      // ♙ white
  N: owner.querySelector('#whiteKnightTemplate'),    // ♘
  B: owner.querySelector('#whiteBishopTemplate'),    // ♗
  R: owner.querySelector('#whiteRookTemplate'),      // ♖
  Q: owner.querySelector('#whiteQueenTemplate'),     // ♕
  K: owner.querySelector('#whiteKingTemplate'),      // ♔
  p: owner.querySelector('#blackPawnTemplate'),      // ♟ black
  n: owner.querySelector('#blackKnightTemplate'),    // ♞
  b: owner.querySelector('#blackBishopTemplate'),    // ♝
  r: owner.querySelector('#blackRookTemplate'),      // ♜
  q: owner.querySelector('#blackQueenTemplate'),     // ♛
  k: owner.querySelector('#blackKingTemplate'),      // ♚
};

export const svgPieces = {
  P: owner.querySelector('#whitePawnSvgTemplate'),   // ♙ white
  N: owner.querySelector('#whiteKnightSvgTemplate'), // ♘
  B: owner.querySelector('#whiteBishopSvgTemplate'), // ♗
  R: owner.querySelector('#whiteRookSvgTemplate'),   // ♖
  Q: owner.querySelector('#whiteQueenSvgTemplate'),  // ♕
  K: owner.querySelector('#whiteKingSvgTemplate'),   // ♔
  p: owner.querySelector('#blackPawnSvgTemplate'),   // ♟ black
  n: owner.querySelector('#blackKnightSvgTemplate'), // ♞
  b: owner.querySelector('#blackBishopSvgTemplate'), // ♝
  r: owner.querySelector('#blackRookSvgTemplate'),   // ♜
  q: owner.querySelector('#blackQueenSvgTemplate'),  // ♛
  k: owner.querySelector('#blackKingSvgTemplate'),   // ♚
};

export const template = owner.querySelector('#chessBoardTemplate');

export function getPieceClone(piece, unicode = false) {
  let clone;
  if (pieces[piece]) {
    if (!unicode) {
      clone = svgPieces[piece].content.cloneNode(true);
    } else {
      clone = pieces[piece].content.cloneNode(true);
    }
  } else {
    clone = emptySquare.content.cloneNode(true);
  }
  return clone;
}


text:
namespace RS {

    template <typename T>
    class RingBuffer {
    public:
        class iterator: public RandomAccessIterator<iterator, const T> {
        public:
            iterator() = default;
            const T& operator*() const noexcept { return (*buf)[ofs]; }
            iterator& operator+=(ptrdiff_t rhs) noexcept { ofs += rhs; return *this; }
            ptrdiff_t operator-(const iterator& rhs) const noexcept { return ptrdiff_t(ofs) - ptrdiff_t(rhs.ofs); }
        private:
            friend class RingBuffer;
            const RingBuffer* buf;
            size_t ofs;
            iterator(const RingBuffer* r, size_t i) noexcept: buf(r), ofs(i) {}
        };
        using value_type = T;
        RingBuffer() = default;
        explicit RingBuffer(size_t n): vec(n), pos(0), len(0) {}
        RingBuffer(const RingBuffer& r);
        RingBuffer(RingBuffer&& r) noexcept;
        ~RingBuffer() noexcept { clear(); }
        RingBuffer& operator=(const RingBuffer& r);
        RingBuffer& operator=(RingBuffer&& r) noexcept;
        const T& operator[](size_t i) const noexcept { return ptr()[index(i)]; }
        iterator begin() const noexcept { return {this, 0}; }
        iterator end() const noexcept { return {this, len}; }
        const T& front() const noexcept { return ptr()[pos]; }
        const T& back() const noexcept { return ptr()[index(len - 1)]; }
        size_t size() const noexcept { return len; }
        size_t capacity() const noexcept { return vec.size(); }
        bool empty() const noexcept { return len == 0; }
        bool full() const noexcept { return len == vec.size(); }
        void push(T&& t);
        T pop() noexcept;
        void clear() noexcept;
        void swap(RingBuffer& r) noexcept;
    private:
        using cell = typename std::aligned_union<1, T>::type;
        static_assert(sizeof(cell) == sizeof(T));
        std::vector<cell> vec;
        size_t pos = 0;
        size_t len = 0;
        size_t index(ptrdiff_t i) const noexcept { return rem((ptrdiff_t(pos) + i), ptrdiff_t(capacity())); }
        T* ptr() noexcept { return reinterpret_cast<T*>(vec.data()); }
        const T* ptr() const noexcept { return reinterpret_cast<const T*>(vec.data()); }
    };

    template <typename T>
    RingBuffer<T>::RingBuffer(const RingBuffer& r):
    vec(r.capacity()), pos(r.pos), len(r.len) {
        if (pos + len > capacity()) {
            size_t extra = pos + len - capacity();
            for (size_t i = pos; i < capacity(); ++i)
                new (vec.data() + i) T(r.ptr()[i]);
            for (size_t i = 0; i < extra; ++i)
                new (vec.data() + i) T(r.ptr()[i]);
        } else if (len) {
            for (size_t i = pos; i < pos + len; ++i)
                new (vec.data() + i) T(r.ptr()[i]);
        }
    }

    template <typename T>
    RingBuffer<T>::RingBuffer(RingBuffer&& r) noexcept {
        if (pos + len > capacity()) {
            size_t extra = pos + len - capacity();
            for (size_t i = pos; i < capacity(); ++i)
                new (vec.data() + i) T(std::move(r.ptr()[i]));
            for (size_t i = 0; i < extra; ++i)
                new (vec.data() + i) T(std::move(r.ptr()[i]));
        } else if (len) {
            for (size_t i = pos; i < pos + len; ++i)
                new (vec.data() + i) T(std::move(r.ptr()[i]));
        }
        r.clear();
    }

    template <typename T>
    RingBuffer<T>& RingBuffer<T>::operator=(const RingBuffer& r) {
        RingBuffer r2(r);
        swap(r2);
        return *this;
    }

    template <typename T>
    RingBuffer<T>& RingBuffer<T>::operator=(RingBuffer&& r) noexcept {
        swap(r);
        r.clear();
        return *this;
    }

    template <typename T>
    void RingBuffer<T>::push(T&& t) {
        if (full()) {
            ptr()[pos] = std::forward<T>(t);
            pos = index(1);
        } else {
            new (vec.data() + index(len)) T(std::forward<T>(t));
            ++len;
        }
    }

    template <typename T>
    T RingBuffer<T>::pop() noexcept {
        T t = std::move(ptr()[pos]);
        ptr()[pos].~T();
        if (len == 1) {
            pos = len = 0;
        } else {
            pos = index(1);
            --len;
        }
        return t;
    }

    template <typename T>
    void RingBuffer<T>::clear() noexcept {
        if (pos + len > capacity()) {
            size_t extra = pos + len - capacity();
            for (size_t i = pos; i < capacity(); ++i)
                ptr()[i].~T();
            for (size_t i = 0; i < extra; ++i)
                ptr()[i].~T();
        } else if (len) {
            for (size_t i = pos; i < pos + len; ++i)
                ptr()[i].~T();
        }
        pos = len = 0;
    }

    template <typename T>
    void RingBuffer<T>::swap(RingBuffer& r) noexcept {
        vec.swap(r.vec);
        std::swap(pos, r.pos);
        std::swap(len, r.len);
    }

    template <typename T>
    void swap(RingBuffer<T>& r1, RingBuffer<T>& r2) noexcept {
        r1.swap(r2);
    }

}


text:
@interface SCRefreshView : UIView

@property (nonatomic, assign) BOOL isLoadMore;
@property (nonatomic, strong) UIColor *bubleColor;
@property (nonatomic, assign) CGFloat timeOffset;  // 0.0 ~ 1.0

- (instancetype)initWithFrame:(CGRect)frame bubleColor:(UIColor *)bubleColor;

- (void)beginRefreshing;
- (void)endRefreshing;

@end


text:
Usage
=====

The CLI defaults to the `server.start` method.

  burlesque cmd [subcmd] [--flag value]

## Options

* `-g/--git-repo`       path to repository
* `-c/--commit-range`   commit revision range (see `man gitrevisions`)
* `-t/--theme`          reveal.js theme to use
* `-p/--port`           port that the web server runs on

## Example

Create a slideshow starting from `master` to `my_branch`, using the
`solarized` reveal.js theme, on `http://localhost:5050`.

    burlesque -g my_repo -c master..my_branch -t solarized -p 5050


text:
/**
 * Insertion Sort
 * Author: Kendal Harland
 */

#ifndef INSERTION_SORT_H
#define INSERTION_SORT_H

template<typename Element, typename Comparator = std::less<Element> >
void insertion_sort(Element *list, size_t size)
{
  /* allow override of type comparison */
  Comparator comp = Comparator();

  /**
   * i is the position of key in the array. j is the backward iterator that
   * find's key's proper place in the list.
   */
  int i,j;

  /* The item to be reloacted */
  Element key;

  for (i = 1; i < size; i++) {
    key = list[i];
    /**
     * Start j at index i-1 and iterate toward the front of the list moving
     * items that belong after key forward in the list.
     */
    j = i-1;
    while (j >= 0 && comp(key, list[j])) {
      list[j+1] = list[j];
      j--;
    }

    /**
     * We've either hit index 0 or we've found an element that comes before
     * key in list. Place key after this item
     */
    list[j+1] = key;
  }
}

#endif//INSERTION_SORT_H


text:
namespace CacheManager.Core.Internal
{
#if !PORTABLE
    using System;
    using System.Diagnostics;
    using System.Threading;

    internal class CachePerformanceCounters<T> : IDisposable
    {
        private const string Category = ".NET CacheManager";
        private const string Entries = "Total cache items";
        private const string HitRatio = "Hit ratio";
        private const string HitRatioBase = "Cache hit ratio Base";
        private const string Hits = "Total hits";
        private const string HitsPerSecond = "Avg hits per second";
        private const string Misses = "Total misses";
        private const string ReadsPerSecond = "Avg gets per second";
        private const string Writes = "Total cache writes";
        private const string WritesPerSecond = "Avg writes per second";
        private static readonly int NumStatsCounters = Enum.GetValues(typeof(CacheStatsCounterType)).Length;

        private readonly Timer counterTimer;
        private readonly string instanceName = string.Empty;
        private readonly CacheStats<T> stats;
        private readonly long[] statsCounts;
        private PerformanceCounter[] counters;
        private bool enabled = true;
        private object updateLock = new object();

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Mobility", "CA1601:DoNotUseTimersThatPreventPowerStateChanges", Justification = "If perfCounters are enabled, we can live with the power consumption...")]
        public CachePerformanceCounters(string cacheName, string handleName, CacheStats<T> stats)
        {
            if (string.IsNullOrWhiteSpace(cacheName))
            {
                throw new ArgumentNullException("cacheName");
            }

            if (string.IsNullOrWhiteSpace(handleName))
            {
                throw new ArgumentNullException("handleName");
            }

            string processName = Process.GetCurrentProcess().ProcessName;

            this.instanceName = string.Concat(processName + ":" + cacheName + ":" + handleName);

            var invalidInstanceChars = new string[] { "(", ")", "#", "\\", "/" };

            foreach (var ichar in invalidInstanceChars)
            {
                this.instanceName = this.instanceName.Replace(ichar, string.Empty);
            }

            if (this.instanceName.Length > 128)
            {
                this.instanceName = this.instanceName.Substring(0, 128);
            }

            this.InitializeCounters();
            this.stats = stats;
            this.statsCounts = new long[NumStatsCounters];

            if (this.enabled)
            {
                this.counterTimer = new Timer(new TimerCallback(this.PerformanceCounterWorker), null, 450L, 450L);
            }
        }

        ~CachePerformanceCounters()
        {
            this.Dispose(false);
        }

        public void Decrement(CachePerformanceCounterType type)
        {
            this.GetCounter(type).Decrement();
        }

        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        public void Increment(CachePerformanceCounterType type)
        {
            this.GetCounter(type).Increment();
        }

        public void IncrementBy(CachePerformanceCounterType type, long value)
        {
            this.GetCounter(type).IncrementBy(value);
        }

        public void SetValue(CachePerformanceCounterType type, long value)
        {
            this.GetCounter(type).RawValue = value < 0 ? 0 : value;
        }

        private static void InitializeCategory()
        {
            if (PerformanceCounterCategory.Exists(Category))
            {
                return;
            }

            PerformanceCounterCategory.Create(
                Category,
                "CacheManager counters per handle",
                PerformanceCounterCategoryType.MultiInstance,
                new CounterCreationDataCollection
                {
                    new CounterCreationData
                    {
                        CounterName = Entries,
                        CounterHelp = "Current number of cache items stored within the cache handle",
                        CounterType = PerformanceCounterType.NumberOfItems64
                    },
                    new CounterCreationData
                    {
                        CounterName = HitRatio,
                        CounterHelp = "Cache hit ratio of the cache handle",
                        CounterType = PerformanceCounterType.AverageCount64
                    },
                    new CounterCreationData
                    {
                        CounterName = HitRatioBase,
                        CounterHelp = HitRatioBase,
                        CounterType = PerformanceCounterType.AverageBase
                    },
                    new CounterCreationData
                    {
                        CounterName = Hits,
                        CounterHelp = "Total number of cache hits of the cache handle",
                        CounterType = PerformanceCounterType.NumberOfItems64
                    },
                    new CounterCreationData
                    {
                        CounterName = Misses,
                        CounterHelp = "Total number of cache misses of the cache handle",
                        CounterType = PerformanceCounterType.NumberOfItems64
                    },
                    new CounterCreationData
                    {
                        CounterName = Writes,
                        CounterHelp = "Total number of cache writes (add,put,remove) of the cache handle",
                        CounterType = PerformanceCounterType.NumberOfItems64
                    },
                    new CounterCreationData
                    {
                        CounterName = WritesPerSecond,
                        CounterHelp = WritesPerSecond,
                        CounterType = PerformanceCounterType.RateOfCountsPerSecond64
                    },
                    new CounterCreationData
                    {
                        CounterName = ReadsPerSecond,
                        CounterHelp = ReadsPerSecond,
                        CounterType = PerformanceCounterType.RateOfCountsPerSecond64
                    },
                    new CounterCreationData
                    {
                        CounterName = HitsPerSecond,
                        CounterHelp = HitsPerSecond,
                        CounterType = PerformanceCounterType.RateOfCountsPerSecond64
                    },
                });
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "On Dispose the catch is just for safety...")]
        private void Dispose(bool disposeManaged)
        {
            if (disposeManaged)
            {
                try
                {
                    this.ResetCounters();

                    if (this.counterTimer != null)
                    {
                        this.counterTimer.Dispose();
                    }
                    foreach (var counter in this.counters)
                    {
                        counter.Dispose();
                    }
                }
                catch
                {
                }
            }
        }

        private PerformanceCounter GetCounter(CachePerformanceCounterType type)
        {
            return this.counters[(int)type];
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "At this point its fine")]
        private void InitializeCounters()
        {
            try
            {
                InitializeCategory();

                this.counters = new PerformanceCounter[9];
                this.counters[0] = new PerformanceCounter(Category, Entries, this.instanceName, false);
                this.counters[1] = new PerformanceCounter(Category, HitRatio, this.instanceName, false);
                this.counters[2] = new PerformanceCounter(Category, HitRatioBase, this.instanceName, false);
                this.counters[3] = new PerformanceCounter(Category, Hits, this.instanceName, false);
                this.counters[4] = new PerformanceCounter(Category, Misses, this.instanceName, false);
                this.counters[5] = new PerformanceCounter(Category, Writes, this.instanceName, false);
                this.counters[6] = new PerformanceCounter(Category, ReadsPerSecond, this.instanceName, false);
                this.counters[7] = new PerformanceCounter(Category, WritesPerSecond, this.instanceName, false);
                this.counters[8] = new PerformanceCounter(Category, HitsPerSecond, this.instanceName, false);

                // resetting them cleans up previous runs on the same category, which will otherwise
                // stay in perfmon forever
                this.ResetCounters();
            }
            catch
            {
                this.enabled = false;
            }
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Is just fine at that point.")]
        private void PerformanceCounterWorker(object state)
        {
            if (this.enabled && Monitor.TryEnter(this.updateLock))
            {
                try
                {
                    long[] previousCounts = new long[NumStatsCounters];
                    Array.Copy(this.statsCounts, previousCounts, NumStatsCounters);

                    for (int i = 0; i < NumStatsCounters; i++)
                    {
                        this.statsCounts[i] = this.stats.GetStatistic((CacheStatsCounterType)i);
                    }

                    var writes = this.statsCounts[4] + this.statsCounts[5] + this.statsCounts[7] + this.statsCounts[8];
                    var previousWrites = previousCounts[4] + previousCounts[5] + previousCounts[7] + previousCounts[8];
                    var hits = this.statsCounts[0] - previousCounts[0];

                    this.SetValue(CachePerformanceCounterType.Items, this.statsCounts[2]);

                    this.IncrementBy(CachePerformanceCounterType.HitRatioBase, this.statsCounts[6] - previousCounts[6]);
                    this.IncrementBy(CachePerformanceCounterType.HitRatio, hits);
                    this.IncrementBy(CachePerformanceCounterType.TotalHits, hits);
                    this.IncrementBy(CachePerformanceCounterType.TotalMisses, this.statsCounts[1] - previousCounts[1]);
                    this.IncrementBy(CachePerformanceCounterType.TotalWrites, writes - previousWrites);
                    this.IncrementBy(CachePerformanceCounterType.ReadsPerSecond, this.statsCounts[6] - previousCounts[6]);
                    this.IncrementBy(CachePerformanceCounterType.WritesPerSecond, writes - previousWrites);
                    this.IncrementBy(CachePerformanceCounterType.HitsPerSecond, hits);
                }
                catch (Exception e)
                {
                    this.enabled = false;
                    Trace.TraceError(e.Message + "\n" + e.StackTrace);
                }
                finally
                {
                    Monitor.Exit(this.updateLock);
                }
            }
        }

        private void ResetCounters()
        {
            for (int i = 0; i < Enum.GetValues(typeof(CachePerformanceCounterType)).Length; i++)
            {
                this.SetValue((CachePerformanceCounterType)i, 0L);
            }
        }
    }
#endif
}


text:
<?php

namespace Google\Cloud\Translate\V2\Connection;

use Google\Cloud\Core\RequestBuilder;
use Google\Cloud\Core\RequestWrapper;
use Google\Cloud\Core\RestTrait;
use Google\Cloud\Core\UriTrait;
use Google\Cloud\Translate\V2\TranslateClient;

/**
 * Implementation of the
 * [Google Cloud Translation REST API](https://cloud.google.com/translation/docs/how-to).
 */
class Rest implements ConnectionInterface
{
    use RestTrait;
    use UriTrait;

    /**
     * @deprecated
     */
    const BASE_URI = 'https://translation.googleapis.com/language/translate/';

    const DEFAULT_API_ENDPOINT = 'https://translation.googleapis.com';

    /**
     * @param array $config
     */
    public function __construct(array $config = [])
    {
        $config += [
            'serviceDefinitionPath' => __DIR__ . '/ServiceDefinition/translate-v2.json',
            'componentVersion' => TranslateClient::VERSION
        ];

        $this->setRequestWrapper(new RequestWrapper($config));
        $this->setRequestBuilder(new RequestBuilder(
            $config['serviceDefinitionPath'],
            $this->getApiEndpoint(self::DEFAULT_API_ENDPOINT, $config)
        ));
    }

    /**
     * @param array $args
     * @return array
     */
    public function listDetections(array $args = [])
    {
        return $this->send('detections', 'detect', $args);
    }

    /**
     * @param array $args
     * @return array
     */
    public function listLanguages(array $args = [])
    {
        return $this->send('languages', 'list', $args);
    }

    /**
     * @param array $args
     * @return array
     */
    public function listTranslations(array $args = [])
    {
        return $this->send('translations', 'translate', $args);
    }
}

//@codingStandardsIgnoreStart
// Adding a class alias for backwards compatibility with the previous class name.
class_alias(Rest::class, \Google\Cloud\Translate\Connection\Rest::class);
//@codingStandardsIgnoreEnd


text:
from __future__ import print_function, absolute_import, unicode_literals

import cloud_maker
import cloud_maker.py_version

cloud_maker.py_version.check()
print("cloud-maker {}: Python version check succeeded.".format(cloud_maker.VERSION))


text:
from __future__ import division

import re

def compact_query(query):
    return re.sub(r'\s+', ' ', query.strip())

def positive(*numbers):
    return max(0, *numbers)

def compute_percent(partial, total):
    if total:
        return partial / total * 100

    return 0


text:
Changelog
=========

3.0.0
 - Minimum supported Node version is now 14


text:
transport-me
============

Transportation app


text:
{% extends "account/base.html" %}

{% load i18n %}
{% load account %}
{% load url from future %}
{% load crispy_forms_tags %}

{% block head_title %}{% trans "Sign In" %}{% endblock %}

{% block content %}

{% trans "Sign In" %}

      {% if socialaccount.providers  %}

{% blocktrans with site.name as site_name %}Please sign in with one
      of your existing third party accounts. Or, sign up
      for a {{site_name}} account and sign in below:{% endblocktrans %}

          {% include "socialaccount/snippets/provider_list.html" with process="login" %}

{% trans 'or' %}

      {% include "socialaccount/snippets/login_extra.html" %}

      {% endif %}

      <form class="login" method="POST" action="{% url 'account_login' %}">
        {% csrf_token %}
        {{ form|crispy }}
        {% if redirect_field_value %}
        <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" />
        {% endif %}
        {% trans "Forgot Password?" %}
        <button class="btn btn-primary" type="submit">{% trans "Sign In" %}</button>
      </form>

Not already a member? Sign up!

{% endblock %}


text:
<BroadcastMonitor>
  <updated>2015-08-07T15:53:49</updated>
  <stationName>Radio 6</stationName>
  <Current>
    <startTime>2015-08-07T15:53:07</startTime>
    <itemId>1000080586:0</itemId>
    <titleId>216046174</titleId>
    <itemCode>MS943</itemCode>
    <itemReference></itemReference>
    <titleName>Boondigga</titleName>
    <artistName>Fat Freddy's Drop</artistName>
    <albumName></albumName>
    <CategoryCode>736</CategoryCode>
    <CategoryName>SOUL</CategoryName>
    <itemDuration>357</itemDuration>
    <MultiMedia1></MultiMedia1>
    <MultiMedia2></MultiMedia2>
    <MultiMedia3></MultiMedia3>
    <MultiMedia4></MultiMedia4>
  </Current>
  <Next>
    <startTime>2015-08-07T15:58:58</startTime>
    <itemId>1000080586:1244644</itemId>
    <titleId>190155817</titleId>
    <itemCode>JK52790-0004</itemCode>
    <itemReference>JK52790-0004</itemReference>
    <titleName>Ain't That A Bitch</titleName>
    <artistName>Johnny Guitar Watson</artistName>
    <albumName></albumName>
    <CategoryCode>736</CategoryCode>
    <CategoryName>SOUL</CategoryName>
    <itemDuration>302</itemDuration>
    <MultiMedia1></MultiMedia1>
    <MultiMedia2></MultiMedia2>
    <MultiMedia3></MultiMedia3>
    <MultiMedia4></MultiMedia4>
  </Next>
</BroadcastMonitor>


text:
namespace CampusSystem.Data.Migrations
{
    using System.Data.Entity.Migrations;

    public partial class ModifiedRoomAndUser : DbMigration
    {
        public override void Up()
        {
           this.DropForeignKey("dbo.Rooms", "UserId", "dbo.AspNetUsers");
           this.DropIndex("dbo.Rooms", new[] { "UserId" });
           this.AddColumn("dbo.AspNetUsers", "RoomId", c => c.Int(nullable: false));
           this.CreateIndex("dbo.AspNetUsers", "RoomId");
           this.AddForeignKey("dbo.AspNetUsers", "RoomId", "dbo.Rooms", "Id", cascadeDelete: true);
           this.DropColumn("dbo.Rooms", "UserId");
        }

        public override void Down()
        {
           this.AddColumn("dbo.Rooms", "UserId", c => c.String(maxLength: 128));
           this.DropForeignKey("dbo.AspNetUsers", "RoomId", "dbo.Rooms");
           this.DropIndex("dbo.AspNetUsers", new[] { "RoomId" });
           this.DropColumn("dbo.AspNetUsers", "RoomId");
           this.CreateIndex("dbo.Rooms", "UserId");
           this.AddForeignKey("dbo.Rooms", "UserId", "dbo.AspNetUsers", "Id");
        }
    }
}


text:
require('../styles/application.scss');

// Render the top-level React component
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore } from 'redux';

import App from './App.jsx';
import reducers from './reducers';

ReactDOM.render(
  <Provider store={createStore(reducers)}>
    <App />
  </Provider>
  , document.getElementById('react-root'));


text:
$hmmalign     = shift;
$eslreformat  = shift;
$testsuitedir = shift;
$tmppfx       = shift;

if (! -x "$hmmalign")                    { print "FAIL: didn't find hmmalign binary $hmmalign\n";        exit 1; }
if (! -x "$eslreformat")                 { print "FAIL: didn't find esl-reformat binary $eslreformat\n"; exit 1; }
if (! -r "$testsuitedir/Caudal_act.hmm") { print "FAIL: didn't find $testsuitedir/Caudal_act.hmm\n";     exit 1; }
if (! -r "$testsuitedir/Caudal_act.sto") { print "FAIL: didn't find $testsuitedir/Caudal_act.sto\n";     exit 1; }

system("$eslreformat -u --rename foo fasta $testsuitedir/Caudal_act.sto > $tmppfx.fa");
if ($? != 0)   { print "FAIL: esl-reformat failed unexpectedly\n"; exit 1; }

system("$hmmalign -o $tmppfx.sto  --mapali $testsuitedir/Caudal_act.sto $testsuitedir/Caudal_act.hmm $tmppfx.fa");
if ($? != 0)   { print "FAIL: hmmalign failed unexpectedly\n"; exit 1; }

system("$eslreformat -u fasta $tmppfx.sto > $tmppfx.2.fa");
if ($? != 0)   { print "FAIL: esl-reformat failed unexpectedly\n"; exit 1; }

system("$eslreformat -u fasta $testsuitedir/Caudal_act.sto > $tmppfx.3.fa");
if ($? != 0)   { print "FAIL: esl-reformat failed unexpectedly\n"; exit 1; }

system("cat $tmppfx.fa >> $tmppfx.3.fa");
if ($? != 0)   { print "FAIL: cat failed unexpectedly\n"; exit 1; }

system("diff $tmppfx.2.fa $tmppfx.3.fa");
if ($? != 0)   { print "FAIL: --mapali doesn't produce expected sequences\n"; exit 1; }

print "ok\n";
unlink "$tmppfx.fa";
unlink "$tmppfx.sto";
unlink "$tmppfx.2.fa";
unlink "$tmppfx.3.fa";
exit 0;


text:
.. _intro-tutorials-results:

===================================
Comparison between Scrapple & Ducky
===================================

From the experiments performed with the Scrapple framework, we see that correctly written configuration files give accurate results. In the :ref:`single page linear extractor <intro-tutorials-single-linear>` example and :ref:`link crawler <intro-tutorials-link-crawler>` example (where over 2800 pages were crawled through), an accuracy level of 100% was achieved.

The accuracy of the implementation of the Scrapple framework is dependent on the user's understanding of :ref:`web structure <concepts-structure>` and the ability to write correct :ref:`selector expressions <concepts-selectors>`.

On comparison with Ducky [1], it can be seen that Ducky also provides an accuracy of 100%. The primary difference between the Scrapple framework and the Ducky framework is the features provided.

+----------------------------------+------------+------------+
| Feature                          | Scrapple   | Ducky      |
|                                  |            |            |
+==================================+============+============+
| Configuration file               |    YES     |    YES     |
+----------------------------------+------------+------------+
| CSS selectors                    |    YES     |    YES     |
+----------------------------------+------------+------------+
| XPath selectors                  |    YES     |    NO      |
+----------------------------------+------------+------------+
| CSV output                       |    YES     |    YES     |
+----------------------------------+------------+------------+
| JSON output                      |    YES     |    YES     |
+----------------------------------+------------+------------+
| XML output                       |    NO      |    YES     |
+----------------------------------+------------+------------+
| Generation of extractor script   |    YES     |    NO      |
+----------------------------------+------------+------------+