text:
/**
 * @file
 * @brief Connection definitions
 */

#include "common.h"

/*
 * Private declarations
 */

/**
 * @addtogroup gearman_con_private Private Connection Functions
 * @ingroup gearman_con
 * @{
 */

/**
 * Set socket options for a connection.
 */
static gearman_return_t _con_setsockopt(gearman_con_st *con);

/**
 * Read data from a connection.
 */
static size_t _con_read(gearman_con_st *con, void *data, size_t data_size,
                        gearman_return_t *ret_ptr);

/** @} */

/*
 * Public definitions
 */

gearman_con_st *gearman_con_add(gearman_st *gearman, gearman_con_st *con,
                                const char *host, in_port_t port)
{
  con= gearman_con_create(gearman, con);
  if (con == NULL)
    return NULL;

  gearman_con_set_host(con, host);
  gearman_con_set_port(con, port);

  return con;
}

gearman_con_st *gearman_con_create(gearman_st *gearman, gearman_con_st *con)
{
  if (con == NULL)
  {
    con= malloc(sizeof(gearman_con_st));
    if (con == NULL)
    {
      GEARMAN_ERROR_SET(gearman, "gearman_con_create", "malloc")
      return NULL;
    }

    memset(con, 0, sizeof(gearman_con_st));
    con->options|= GEARMAN_CON_ALLOCATED;
  }
  else
    memset(con, 0, sizeof(gearman_con_st));

  con->gearman= gearman;

  GEARMAN_LIST_ADD(gearman->con, con,)

  con->fd= -1;
  con->send_buffer_ptr= con->send_buffer;

  return con;
}

gearman_con_st *gearman_con_clone(gearman_st *gearman, gearman_con_st *con,
                                  gearman_con_st *from)
{
  con= gearman_con_create(gearman, con);
  if (con == NULL)
    return NULL;

  con->options|= (from->options & ~GEARMAN_CON_ALLOCATED);
  strcpy(con->host, from->host);
  con->port= from->port;

  return con;
}

void gearman_con_free(gearman_con_st *con)
{
  if (con->fd != -1)
    gearman_con_close(con);

  gearman_con_reset_addrinfo(con);

  GEARMAN_LIST_DEL(con->gearman->con, con,)

  if (con->options & GEARMAN_CON_PACKET_IN_USE)
    gearman_packet_free(&(con->packet));

  if (con->options & GEARMAN_CON_ALLOCATED)
    free(con);
}

void gearman_con_set_host(gearman_con_st *con, const char *host)
{
  gearman_con_reset_addrinfo(con);

  strncpy(con->host, host == NULL ? GEARMAN_DEFAULT_TCP_HOST : host,
          NI_MAXHOST);
  con->host[NI_MAXHOST - 1]= 0;
}

void gearman_con_set_port(gearman_con_st *con, in_port_t port)
{
  gearman_con_reset_addrinfo(con);

  con->port= port == 0 ? GEARMAN_DEFAULT_TCP_PORT : port;
}

void gearman_con_set_options(gearman_con_st *con, gearman_con_options_t options,
                             uint32_t data)
{
  if (data)
    con->options|= options;
  else
    con->options&= ~options;
}

gearman_return_t gearman_con_set_fd(gearman_con_st *con, int fd)
{
  gearman_return_t ret;

  con->options|= GEARMAN_CON_EXTERNAL_FD;
  con->fd= fd;
  con->state= GEARMAN_CON_STATE_CONNECTED;

  ret= _con_setsockopt(con);
  if (ret != GEARMAN_SUCCESS)
  {
    con->gearman->last_errno= errno;
    return ret;
  }

  return GEARMAN_SUCCESS;
}

void *gearman_con_data(gearman_con_st *con)
{
  return con->data;
}

void gearman_con_set_data(gearman_con_st *con, void *data)
{
  con->data= data;
}

gearman_return_t gearman_con_connect(gearman_con_st *con)
{
  return gearman_con_flush(con);
}

void gearman_con_close(gearman_con_st *con)
{
  if (con->fd == -1)
    return;

  if (con->options & GEARMAN_CON_EXTERNAL_FD)
    con->options&= ~GEARMAN_CON_EXTERNAL_FD;
  else
    (void)close(con->fd);

  con->state= GEARMAN_CON_STATE_ADDRINFO;
  con->fd= -1;
  con->events= 0;
  con->revents= 0;

  con->send_state= GEARMAN_CON_SEND_STATE_NONE;
  con->send_buffer_ptr= con->send_buffer;
  con->send_buffer_size= 0;
  con->send_data_size= 0;
  con->send_data_offset= 0;

  con->recv_state= GEARMAN_CON_RECV_STATE_NONE;
  if (con->recv_packet != NULL)
    gearman_packet_free(con->recv_packet);
  con->recv_buffer_ptr= con->recv_buffer;
  con->recv_buffer_size= 0;
}

void gearman_con_reset_addrinfo(gearman_con_st *con)
{
  if (con->addrinfo != NULL)
  {
    freeaddrinfo(con->addrinfo);
    con->addrinfo= NULL;
  }

  con->addrinfo_next= NULL;
}

gearman_return_t gearman_con_send(gearman_con_st *con,
                                  gearman_packet_st *packet, bool flush)
{
  gearman_return_t ret;

  switch (con->send_state)
  {
  case GEARMAN_CON_SEND_STATE_NONE:
    if (!(packet->options & GEARMAN_PACKET_COMPLETE))
    {
      GEARMAN_ERROR_SET(con->gearman, "gearman_con_send", "packet not complete")
      return GEARMAN_INVALID_PACKET;
    }

    /* Flush buffer now if args wont' fit in. */
    if (packet->args_size > (GEARMAN_SEND_BUFFER_SIZE - con->send_buffer_size))
    {
      con->send_state= GEARMAN_CON_SEND_STATE_PRE_FLUSH;

  case GEARMAN_CON_SEND_STATE_PRE_FLUSH:
      ret= gearman_con_flush(con);
      if (ret != GEARMAN_SUCCESS)
        return ret;
    }

    memcpy(con->send_buffer + con->send_buffer_size, packet->args,
           packet->args_size);
    con->send_buffer_size+= packet->args_size;

    /* Return here if we have no data to send. */
    if (packet->data_size == 0)
      break;

    /* If there is any room in the buffer, copy in data. */
    if (packet->data != NULL &&
        (GEARMAN_SEND_BUFFER_SIZE - con->send_buffer_size) > 0)
    {
      con->send_data_offset= GEARMAN_SEND_BUFFER_SIZE - con->send_buffer_size;
      if (con->send_data_offset > packet->data_size)
        con->send_data_offset= packet->data_size;

      memcpy(con->send_buffer + con->send_buffer_size, packet->data,
             con->send_data_offset);
      con->send_buffer_size+= con->send_data_offset;

      /* Return if all data fit in the send buffer. */
      if (con->send_data_offset == packet->data_size)
      {
        con->send_data_offset= 0;
        break;
      }
    }

    /* Flush buffer now so we can start writing directly from data buffer. */
    con->send_state= GEARMAN_CON_SEND_STATE_FORCE_FLUSH;

  case GEARMAN_CON_SEND_STATE_FORCE_FLUSH:
    ret= gearman_con_flush(con);
    if (ret != GEARMAN_SUCCESS)
      return ret;

    con->send_data_size= packet->data_size;

    /* If this is NULL, then gearman_con_send_data function will be used. */
    if (packet->data == NULL)
    {
      con->send_state= GEARMAN_CON_SEND_STATE_FLUSH_DATA;
      return GEARMAN_SUCCESS;
    }

    /* Copy into the buffer if it fits, otherwise flush from packet buffer. */
    con->send_buffer_size= packet->data_size - con->send_data_offset;
    if (con->send_buffer_size < GEARMAN_SEND_BUFFER_SIZE)
    {
      memcpy(con->send_buffer,
             ((uint8_t *)(packet->data)) + con->send_data_offset,
             con->send_buffer_size);
      con->send_data_size= 0;
      con->send_data_offset= 0;
      break;
    }

    con->send_buffer_ptr= ((uint8_t *)(packet->data)) + con->send_data_offset;
    con->send_state= GEARMAN_CON_SEND_STATE_FLUSH_DATA;

  case GEARMAN_CON_SEND_STATE_FLUSH:
  case GEARMAN_CON_SEND_STATE_FLUSH_DATA:
    return gearman_con_flush(con);

  default:
    GEARMAN_ERROR_SET(con->gearman, "gearman_con_send", "unknown state: %u",
                      con->send_state)
    return GEARMAN_UNKNOWN_STATE;
  }

  if (flush)
  {
    con->send_state= GEARMAN_CON_SEND_STATE_FLUSH;
    return gearman_con_flush(con);
  }

  con->send_state= GEARMAN_CON_SEND_STATE_NONE;
  return GEARMAN_SUCCESS;
}

size_t gearman_con_send_data(gearman_con_st *con, const void *data,
                             size_t data_size, gearman_return_t *ret_ptr)
{
  if (con->send_state != GEARMAN_CON_SEND_STATE_FLUSH_DATA)
  {
    GEARMAN_ERROR_SET(con->gearman, "gearman_con_send_data", "not flushing")
    return GEARMAN_NOT_FLUSHING;
  }

  if (data_size > (con->send_data_size - con->send_data_offset))
  {
    GEARMAN_ERROR_SET(con->gearman, "gearman_con_send_data", "data too large")
    return GEARMAN_DATA_TOO_LARGE;
  }

  con->send_buffer_ptr= (uint8_t *)data;
  con->send_buffer_size= data_size;

  *ret_ptr= gearman_con_flush(con);

  return data_size - con->send_buffer_size;
}

gearman_return_t gearman_con_flush(gearman_con_st *con)
{
  char port_str[NI_MAXSERV];
  struct addrinfo ai;
  int ret;
  ssize_t write_size;
  gearman_return_t gret;

  while (1)
  {
    switch (con->state)
    {
    case GEARMAN_CON_STATE_ADDRINFO:
      if (con->addrinfo != NULL)
      {
        freeaddrinfo(con->addrinfo);
        con->addrinfo= NULL;
      }

      sprintf(port_str, "%u", con->port);

      memset(&ai, 0, sizeof(struct addrinfo));
      ai.ai_flags= (AI_V4MAPPED | AI_ADDRCONFIG);
      ai.ai_family= AF_UNSPEC;
      ai.ai_socktype= SOCK_STREAM;
      ai.ai_protocol= IPPROTO_TCP;

      ret= getaddrinfo(con->host, port_str, &ai, &(con->addrinfo));
      if (ret != 0)
      {
        GEARMAN_ERROR_SET(con->gearman, "gearman_con_flush", "getaddrinfo:%s",
                          gai_strerror(ret))
        return GEARMAN_GETADDRINFO;
      }

      con->addrinfo_next= con->addrinfo;

    case GEARMAN_CON_STATE_CONNECT:
      if (con->fd != -1)
        gearman_con_close(con);

      if (con->addrinfo_next == NULL)
      {
        con->state= GEARMAN_CON_STATE_ADDRINFO;
        GEARMAN_ERROR_SET(con->gearman, "gearman_con_flush",
                          "could not connect")
        return GEARMAN_COULD_NOT_CONNECT;
      }

      con->fd= socket(con->addrinfo_next->ai_family,
                      con->addrinfo_next->ai_socktype,
                      con->addrinfo_next->ai_protocol);
      if (con->fd == -1)
      {
        con->state= GEARMAN_CON_STATE_ADDRINFO;
        GEARMAN_ERROR_SET(con->gearman, "gearman_con_flush", "socket:%d", errno)
        con->gearman->last_errno= errno;
        return GEARMAN_ERRNO;
      }

      gret= _con_setsockopt(con);
      if (gret != GEARMAN_SUCCESS)
      {
        con->gearman->last_errno= errno;
        gearman_con_close(con);
        return gret;
      }

      while (1)
      {
        ret= connect(con->fd, con->addrinfo_next->ai_addr,
                     con->addrinfo_next->ai_addrlen);
        if (ret == 0)
        {
          con->state= GEARMAN_CON_STATE_CONNECTED;
          con->addrinfo_next= NULL;
          break;
        }

        if (errno == EAGAIN || errno == EINTR)
          continue;

        if (errno == EINPROGRESS)
        {
          con->state= GEARMAN_CON_STATE_CONNECTING;
          break;
        }

        if (errno == ECONNREFUSED || errno == ENETUNREACH || errno == ETIMEDOUT)
        {
          con->state= GEARMAN_CON_STATE_CONNECT;
          con->addrinfo_next= con->addrinfo_next->ai_next;
          break;
        }

        GEARMAN_ERROR_SET(con->gearman, "gearman_con_flush", "connect:%d",
                          errno)
        con->gearman->last_errno= errno;
        gearman_con_close(con);
        return GEARMAN_ERRNO;
      }

      if (con->state != GEARMAN_CON_STATE_CONNECTING)
        break;

    case GEARMAN_CON_STATE_CONNECTING:
      while (1)
      {
        if (con->revents & POLLOUT)
        {
          con->state= GEARMAN_CON_STATE_CONNECTED;
          break;
        }
        else if (con->revents & (POLLERR | POLLHUP | POLLNVAL))
        {
          con->state= GEARMAN_CON_STATE_CONNECT;
          con->addrinfo_next= con->addrinfo_next->ai_next;
          break;
        }

        gret= gearman_con_set_events(con, POLLOUT);
        if (gret != GEARMAN_SUCCESS)
          return gret;

        if (con->gearman->options & GEARMAN_NON_BLOCKING)
        {
          con->state= GEARMAN_CON_STATE_CONNECTING;
          return GEARMAN_IO_WAIT;
        }

        gret= gearman_con_wait(con->gearman, -1);
        if (gret != GEARMAN_SUCCESS)
          return gret;
      }

      if (con->state != GEARMAN_CON_STATE_CONNECTED)
        break;

    case GEARMAN_CON_STATE_CONNECTED:
      while (con->send_buffer_size != 0)
      {
        write_size= write(con->fd, con->send_buffer_ptr, con->send_buffer_size);
        if (write_size == 0)
        {
          GEARMAN_ERROR_SET(con->gearman, "gearman_con_flush",
                            "lost connection to server (EOF)")
          gearman_con_close(con);
          return GEARMAN_LOST_CONNECTION;
        }
        else if (write_size == -1)
        {
          if (errno == EAGAIN)
          {
            gret= gearman_con_set_events(con, POLLOUT);
            if (gret != GEARMAN_SUCCESS)
              return gret;

            if (con->gearman->options & GEARMAN_NON_BLOCKING)
              return GEARMAN_IO_WAIT;

            gret= gearman_con_wait(con->gearman, -1);
            if (gret != GEARMAN_SUCCESS)
              return gret;

            continue;
          }
          else if (errno == EINTR)
            continue;
          else if (errno == EPIPE || errno == ECONNRESET)
          {
            GEARMAN_ERROR_SET(con->gearman, "gearman_con_flush",
                              "lost connection to server (%d)", errno)
            gearman_con_close(con);
            return GEARMAN_LOST_CONNECTION;
          }

          GEARMAN_ERROR_SET(con->gearman, "gearman_con_flush", "write:%d",
                            errno)
          con->gearman->last_errno= errno;
          gearman_con_close(con);
          return GEARMAN_ERRNO;
        }

        con->send_buffer_size-= write_size;
        if (con->send_state == GEARMAN_CON_SEND_STATE_FLUSH_DATA)
        {
          con->send_data_offset+= write_size;
          if (con->send_data_offset == con->send_data_size)
          {
            con->send_data_size= 0;
            con->send_data_offset= 0;
            break;
          }

          if (con->send_buffer_size == 0)
            return GEARMAN_SUCCESS;
        }
        else if (con->send_buffer_size == 0)
          break;

        con->send_buffer_ptr+= write_size;
      }

      con->send_state= GEARMAN_CON_SEND_STATE_NONE;
      con->send_buffer_ptr= con->send_buffer;
      return GEARMAN_SUCCESS;

    default:
      GEARMAN_ERROR_SET(con->gearman, "gearman_con_flush", "unknown state: %u",
                        con->state)
      return GEARMAN_UNKNOWN_STATE;
    }
  }
}

gearman_return_t gearman_con_flush_all(gearman_st *gearman)
{
  gearman_con_st *con;
  gearman_return_t ret;

  for (con= gearman->con_list; con != NULL; con= con->next)
  {
    if (con->events & POLLOUT)
      continue;

    ret= gearman_con_flush(con);
    if (ret != GEARMAN_SUCCESS && ret != GEARMAN_IO_WAIT)
      return ret;
  }

  return GEARMAN_SUCCESS;
}

gearman_return_t gearman_con_send_all(gearman_st *gearman,
                                      gearman_packet_st *packet)
{
  gearman_return_t ret;
  gearman_con_st *con;
  gearman_options_t options= gearman->options;

  gearman->options|= GEARMAN_NON_BLOCKING;

  if (gearman->sending == 0)
  {
    for (con= gearman->con_list; con != NULL; con= con->next)
    {
      ret= gearman_con_send(con, packet, true);
      if (ret != GEARMAN_SUCCESS)
      {
        if (ret != GEARMAN_IO_WAIT)
        {
          gearman->options= options;
          return ret;
        }

        gearman->sending++;
        break;
      }
    }
  }

  while (gearman->sending != 0)
  {
    while ((con= gearman_con_ready(gearman)) != NULL)
    {
      ret= gearman_con_send(con, packet, true);
      if (ret != GEARMAN_SUCCESS)
      {
        if (ret != GEARMAN_IO_WAIT)
        {
          gearman->options= options;
          return ret;
        }

        continue;
      }

      gearman->sending--;
    }

    if (gearman->sending == 0)
      break;

    if (options & GEARMAN_NON_BLOCKING)
    {
      gearman->options= options;
      return GEARMAN_IO_WAIT;
    }

    ret= gearman_con_wait(gearman, -1);
    if (ret != GEARMAN_SUCCESS)
    {
      gearman->options= options;
      return ret;
    }
  }

  gearman->options= options;
  return GEARMAN_SUCCESS;
}

gearman_packet_st *gearman_con_recv(gearman_con_st *con,
                                    gearman_packet_st *packet,
                                    gearman_return_t *ret_ptr, bool recv_data)
{
  size_t recv_size;

  switch (con->recv_state)
  {
  case GEARMAN_CON_RECV_STATE_NONE:
    if (con->state != GEARMAN_CON_STATE_CONNECTED)
    {
      GEARMAN_ERROR_SET(con->gearman, "gearman_con_recv", "not connected")
      *ret_ptr= GEARMAN_NOT_CONNECTED;
      return NULL;
    }

    con->recv_packet= gearman_packet_create(con->gearman, packet);
    if (con->recv_packet == NULL)
    {
      *ret_ptr= GEARMAN_MEMORY_ALLOCATION_FAILURE;
      return NULL;
    }

    con->recv_state= GEARMAN_CON_RECV_STATE_READ;

  case GEARMAN_CON_RECV_STATE_READ:
    while (1)
    {
      if (con->recv_buffer_size > 0)
      {
        recv_size= gearman_packet_parse(con->recv_packet, con->recv_buffer_ptr,
                                        con->recv_buffer_size, ret_ptr);
        con->recv_buffer_ptr+= recv_size;
        con->recv_buffer_size-= recv_size;
        if (*ret_ptr == GEARMAN_SUCCESS)
          break;
        else if (*ret_ptr != GEARMAN_IO_WAIT)
        {
          gearman_con_close(con);
          return NULL;
        }
      }

      /* Shift buffer contents if needed. */
      if (con->recv_buffer_size > 0)
        memmove(con->recv_buffer, con->recv_buffer_ptr, con->recv_buffer_size);
      con->recv_buffer_ptr= con->recv_buffer;

      recv_size= _con_read(con, con->recv_buffer + con->recv_buffer_size,
                           GEARMAN_RECV_BUFFER_SIZE - con->recv_buffer_size,
                           ret_ptr);
      if (*ret_ptr != GEARMAN_SUCCESS)
        return NULL;

      con->recv_buffer_size+= recv_size;
    }

    if (packet->data_size == 0)
    {
      con->recv_state= GEARMAN_CON_RECV_STATE_NONE;
      break;
    }

    con->recv_data_size= packet->data_size;

    if (!recv_data)
    {
      con->recv_state= GEARMAN_CON_RECV_STATE_READ_DATA;
      break;
    }

    if (packet->gearman->workload_malloc == NULL)
      packet->data= malloc(packet->data_size);
    else
    {
      packet->data= packet->gearman->workload_malloc(packet->data_size,
                                (void *)(packet->gearman->workload_malloc_arg));
    }
    if (packet->data == NULL)
    {
      *ret_ptr= GEARMAN_MEMORY_ALLOCATION_FAILURE;
      gearman_con_close(con);
      return NULL;
    }

    packet->options|= GEARMAN_PACKET_FREE_DATA;
    con->recv_state= GEARMAN_CON_RECV_STATE_READ_DATA;

  case GEARMAN_CON_RECV_STATE_READ_DATA:
    while (con->recv_data_size != 0)
    {
      (void)gearman_con_recv_data(con,
                                  ((uint8_t *)(packet->data)) +
                                  con->recv_data_offset,
                                  packet->data_size -
                                  con->recv_data_offset, ret_ptr);
      if (*ret_ptr != GEARMAN_SUCCESS)
        return NULL;
    }

    con->recv_state= GEARMAN_CON_RECV_STATE_NONE;
    break;

  default:
    GEARMAN_ERROR_SET(con->gearman, "gearman_con_recv", "unknown state: %u",
                      con->recv_state)
    *ret_ptr= GEARMAN_UNKNOWN_STATE;
    return NULL;
  }

  packet= con->recv_packet;
  con->recv_packet= NULL;

  return packet;
}

size_t gearman_con_recv_data(gearman_con_st *con, void *data, size_t data_size,
                             gearman_return_t *ret_ptr)
{
  size_t recv_size= 0;

  if (con->recv_data_size == 0)
  {
    *ret_ptr= GEARMAN_SUCCESS;
    return 0;
  }

  if ((con->recv_data_size - con->recv_data_offset) < data_size)
    data_size= con->recv_data_size - con->recv_data_offset;

  if (con->recv_buffer_size > 0)
  {
    if (con->recv_buffer_size < data_size)
      recv_size= con->recv_buffer_size;
    else
      recv_size= data_size;

    memcpy(data, con->recv_buffer_ptr, recv_size);
    con->recv_buffer_ptr+= recv_size;
    con->recv_buffer_size-= recv_size;
  }

  if (data_size != recv_size)
  {
    recv_size+= _con_read(con, ((uint8_t *)data) + recv_size,
                          data_size - recv_size, ret_ptr);
    con->recv_data_offset+= recv_size;
  }
  else
  {
    con->recv_data_offset+= recv_size;
    *ret_ptr= GEARMAN_SUCCESS;
  }

  if (con->recv_data_size == con->recv_data_offset)
  {
    con->recv_data_size= 0;
    con->recv_data_offset= 0;
    con->recv_state= GEARMAN_CON_RECV_STATE_NONE;
  }

  return recv_size;
}

gearman_return_t gearman_con_wait(gearman_st *gearman, int timeout)
{
  gearman_con_st *con;
  struct pollfd *pfds;
  int x;
  int ret;

  if (gearman->pfds_size < gearman->con_count)
  {
    pfds= realloc(gearman->pfds, gearman->con_count * sizeof(struct pollfd));
    if (pfds == NULL)
    {
      GEARMAN_ERROR_SET(gearman, "gearman_con_wait", "realloc")
      return GEARMAN_MEMORY_ALLOCATION_FAILURE;
    }

    gearman->pfds= pfds;
    gearman->pfds_size= gearman->con_count;
  }
  else
    pfds= gearman->pfds;

  x= 0;
  for (con= gearman->con_list; con != NULL; con= con->next)
  {
    if (con->events == 0)
      continue;

    pfds[x].fd= con->fd;
    pfds[x].events= con->events;
    pfds[x].revents= 0;
    x++;
  }

  if (x == 0)
  {
    GEARMAN_ERROR_SET(gearman, "gearman_con_wait", "no active file descriptors")
    return GEARMAN_NO_ACTIVE_FDS;
  }

  ret= poll(pfds, x, timeout);
  if (ret == -1)
  {
    GEARMAN_ERROR_SET(gearman, "gearman_con_wait", "poll:%d", errno)
    gearman->last_errno= errno;
    return GEARMAN_ERRNO;
  }

  x= 0;
  for (con= gearman->con_list; con != NULL; con= con->next)
  {
    if (con->events == 0)
      continue;

    gearman_con_set_revents(con, pfds[x].revents);
    x++;
  }

  return GEARMAN_SUCCESS;
}

gearman_return_t gearman_con_set_events(gearman_con_st *con, short events)
{
  gearman_return_t ret;

  if ((con->events | events) == con->events)
    return GEARMAN_SUCCESS;

  con->events|= events;

  if (con->gearman->event_watch != NULL)
  {
    ret= (con->gearman->event_watch)(con, con->events,
                                     con->gearman->event_watch_arg);
    if (ret != GEARMAN_SUCCESS)
    {
      gearman_con_close(con);
      return ret;
    }
  }

  return GEARMAN_SUCCESS;
}

void gearman_con_set_revents(gearman_con_st *con, short revents)
{
  if (revents != 0)
    con->options|= GEARMAN_CON_READY;

  con->revents= revents;
  con->events&= ~revents;
}

gearman_con_st *gearman_con_ready(gearman_st *gearman)
{
  gearman_con_st *con;

  /* We can't keep state between calls since connections may be removed during
     processing. If this list ever gets big, we may want something faster. */

  for (con= gearman->con_list; con != NULL; con= con->next)
  {
    if (con->options & GEARMAN_CON_READY)
    {
      con->options&= ~GEARMAN_CON_READY;
      return con;
    }
  }

  return NULL;
}

gearman_return_t gearman_con_echo(gearman_st *gearman, const void *workload,
                                  size_t workload_size)
{
  gearman_con_st *con;
  gearman_options_t options= gearman->options;
  gearman_packet_st packet;
  gearman_return_t ret;

  ret= gearman_packet_add(gearman, &packet, GEARMAN_MAGIC_REQUEST,
                          GEARMAN_COMMAND_ECHO_REQ, workload, workload_size,
                          NULL);
  if (ret != GEARMAN_SUCCESS)
    return ret;

  gearman->options&= ~GEARMAN_NON_BLOCKING;

  for (con= gearman->con_list; con != NULL; con= con->next)
  {
    ret= gearman_con_send(con, &packet, true);
    if (ret != GEARMAN_SUCCESS)
    {
      gearman_packet_free(&packet);
      gearman->options= options;
      return ret;
    }

    (void)gearman_con_recv(con, &(con->packet), &ret, true);
    if (ret != GEARMAN_SUCCESS)
    {
      gearman_packet_free(&packet);
      gearman->options= options;
      return ret;
    }

    if (con->packet.data_size != workload_size ||
        memcmp(workload, con->packet.data, workload_size))
    {
      gearman_packet_free(&(con->packet));
      gearman_packet_free(&packet);
      gearman->options= options;
      GEARMAN_ERROR_SET(gearman, "gearman_con_echo", "corruption during echo")
      return GEARMAN_ECHO_DATA_CORRUPTION;
    }

    gearman_packet_free(&(con->packet));
  }

  gearman_packet_free(&packet);
  gearman->options= options;
  return GEARMAN_SUCCESS;
}

/*
 * Private definitions
 */

static gearman_return_t _con_setsockopt(gearman_con_st *con)
{
  int ret;
  struct linger linger;
  struct timeval waittime;

  ret= 1;
  ret= setsockopt(con->fd, IPPROTO_TCP, TCP_NODELAY, &ret,
                  (socklen_t)sizeof(int));
  if (ret == -1)
  {
    GEARMAN_ERROR_SET(con->gearman, "_con_setsockopt",
                      "setsockopt:TCP_NODELAY:%d", errno)
    return GEARMAN_ERRNO;
  }

  linger.l_onoff= 1;
  linger.l_linger= GEARMAN_DEFAULT_SOCKET_TIMEOUT;
  ret= setsockopt(con->fd, SOL_SOCKET, SO_LINGER, &linger,
                  (socklen_t)sizeof(struct linger));
  if (ret == -1)
  {
    GEARMAN_ERROR_SET(con->gearman, "_con_setsockopt",
                      "setsockopt:SO_LINGER:%d", errno)
    return GEARMAN_ERRNO;
  }

  waittime.tv_sec= GEARMAN_DEFAULT_SOCKET_TIMEOUT;
  waittime.tv_usec= 0;
  ret= setsockopt(con->fd, SOL_SOCKET, SO_SNDTIMEO, &waittime,
                  (socklen_t)sizeof(struct timeval));
  if (ret == -1 && errno != ENOPROTOOPT)
  {
    GEARMAN_ERROR_SET(con->gearman, "_con_setsockopt",
                      "setsockopt:SO_SNDTIMEO:%d", errno)
    return GEARMAN_ERRNO;
  }

  ret= setsockopt(con->fd, SOL_SOCKET, SO_RCVTIMEO, &waittime,
                  (socklen_t)sizeof(struct timeval));
  if (ret == -1 && errno != ENOPROTOOPT)
  {
    GEARMAN_ERROR_SET(con->gearman, "_con_setsockopt",
                      "setsockopt:SO_RCVTIMEO:%d", errno)
    return GEARMAN_ERRNO;
  }

  ret= GEARMAN_DEFAULT_SOCKET_SEND_SIZE;
  ret= setsockopt(con->fd, SOL_SOCKET, SO_SNDBUF, &ret, (socklen_t)sizeof(int));
  if (ret == -1)
  {
    GEARMAN_ERROR_SET(con->gearman, "_con_setsockopt",
                      "setsockopt:SO_SNDBUF:%d", errno)
    return GEARMAN_ERRNO;
  }

  ret= GEARMAN_DEFAULT_SOCKET_RECV_SIZE;
  ret= setsockopt(con->fd, SOL_SOCKET, SO_RCVBUF, &ret, (socklen_t)sizeof(int));
  if (ret == -1)
  {
    GEARMAN_ERROR_SET(con->gearman, "_con_setsockopt",
                      "setsockopt:SO_RCVBUF:%d", errno)
    return GEARMAN_ERRNO;
  }

#ifdef FIONBIO
  ret= 1;
  ret= ioctl(con->fd, FIONBIO, &ret);
  if (ret == -1)
  {
    GEARMAN_ERROR_SET(con->gearman, "_con_setsockopt", "ioctl:FIONBIO:%d",
                      errno)
    return GEARMAN_ERRNO;
  }
#else /* !FIONBIO */
  ret= fcntl(con->fd, F_GETFL, 0);
  if (ret == -1)
  {
    GEARMAN_ERROR_SET(con->gearman, "_con_setsockopt", "fcntl:F_GETFL:%d",
                      errno)
    return GEARMAN_ERRNO;
  }

  ret= fcntl(con->fd, F_SETFL, ret | O_NONBLOCK);
  if (ret == -1)
  {
    GEARMAN_ERROR_SET(con->gearman, "_con_setsockopt", "fcntl:F_SETFL:%d",
                      errno)
    return GEARMAN_ERRNO;
  }
#endif /* FIONBIO */

  return GEARMAN_SUCCESS;
}

static size_t _con_read(gearman_con_st *con, void *data, size_t data_size,
                        gearman_return_t *ret_ptr)
{
  ssize_t read_size;

  while (1)
  {
    read_size= read(con->fd, data, data_size);
    if (read_size == 0)
    {
      GEARMAN_ERROR_SET(con->gearman, "_con_read",
                        "lost connection to server (EOF)")
      gearman_con_close(con);
      *ret_ptr= GEARMAN_LOST_CONNECTION;
      return 0;
    }
    else if (read_size == -1)
    {
      if (errno == EAGAIN)
      {
        *ret_ptr= gearman_con_set_events(con, POLLIN);
        if (*ret_ptr != GEARMAN_SUCCESS)
          return 0;

        if (con->gearman->options & GEARMAN_NON_BLOCKING)
        {
          *ret_ptr= GEARMAN_IO_WAIT;
          return 0;
        }

        *ret_ptr= gearman_con_wait(con->gearman, -1);
        if (*ret_ptr != GEARMAN_SUCCESS)
          return 0;

        continue;
      }
      else if (errno == EINTR)
        continue;
      else if (errno == EPIPE || errno == ECONNRESET)
      {
        GEARMAN_ERROR_SET(con->gearman, "_con_read",
                          "lost connection to server (%d)", errno)
        *ret_ptr= GEARMAN_LOST_CONNECTION;
      }
      else
      {
        GEARMAN_ERROR_SET(con->gearman, "_con_read", "read:%d", errno)
        con->gearman->last_errno= errno;
        *ret_ptr= GEARMAN_ERRNO;
      }

      gearman_con_close(con);
      return 0;
    }

    break;
  }

  *ret_ptr= GEARMAN_SUCCESS;
  return read_size;
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
using GtfsNet.Collections;
using GtfsNet.Entities;

namespace GtfsNet.Visitors
{
	/// <summary>
	/// This visitor decides if every required field in each object of each collection does exist or not
	/// </summary>
	public class RequiredFieldVisitor : IFeedVisitor
	{
		public event EventHandler<ValidationEventArgs> AgenciesChecked;
		public event EventHandler<ValidationEventArgs> StopsChecked;
		public event EventHandler<ValidationEventArgs> RoutesChecked;
		public event EventHandler<ValidationEventArgs> TripsChecked;
		public event EventHandler<ValidationEventArgs> StopTimesChecked;
		public event EventHandler<ValidationEventArgs> CalendarsChecked;
		public event EventHandler<ValidationEventArgs> CalendarDatesChecked;
		public event EventHandler<ValidationEventArgs> FareAttributesChecked;
		public event EventHandler<ValidationEventArgs> FareRulesChecked;
		public event EventHandler<ValidationEventArgs> ShapesChecked;
		public event EventHandler<ValidationEventArgs> FrequenciesChecked;
		public event EventHandler<ValidationEventArgs> TransfersChecked;
		public event EventHandler<ValidationEventArgs> FeedInfosChecked;

		protected virtual void OnAgenciesChecked(AgencyCollection agencies, ValidationEventArgs e)
		{
			AgenciesChecked?.Invoke(agencies, e);
		}

		protected virtual void OnStopsChecked(StopCollection stops, ValidationEventArgs e)
		{
			StopsChecked?.Invoke(stops, e);
		}

		protected virtual void OnRoutesChecked(RouteCollection routes, ValidationEventArgs e)
		{
			RoutesChecked?.Invoke(routes, e);
		}

		protected virtual void OnTripsChecked(TripCollection trips, ValidationEventArgs e)
		{
			TripsChecked?.Invoke(trips, e);
		}

		protected virtual void OnStopTimesChecked(StopTimeCollection stopTimes, ValidationEventArgs e)
		{
			StopTimesChecked?.Invoke(stopTimes, e);
		}

		protected virtual void OnCalendarsChecked(CalendarCollection calendars, ValidationEventArgs e)
		{
			CalendarsChecked?.Invoke(calendars, e);
		}

		protected virtual void OnCalendarsChecked(CalendarDateCollection calendarDates, ValidationEventArgs e)
		{
			CalendarDatesChecked?.Invoke(calendarDates, e);
		}

		protected virtual void OnFareAttributesChecked(FareAttributeCollection fareAttributes, ValidationEventArgs e)
		{
			FareAttributesChecked?.Invoke(fareAttributes, e);
		}

		protected virtual void OnFareAttributesChecked(FareRuleCollection fareRules, ValidationEventArgs e)
		{
			FareRulesChecked?.Invoke(fareRules, e);
		}

		protected virtual void OnShapesChecked(ShapeCollection shapes, ValidationEventArgs e)
		{
			ShapesChecked?.Invoke(shapes, e);
		}

		protected virtual void OnFrequenciesChecked(FrequencyCollection frequencies, ValidationEventArgs e)
		{
			FrequenciesChecked?.Invoke(frequencies, e);
		}

		protected virtual void OnTransfersChecked(TransferCollection transfers, ValidationEventArgs e)
		{
			TransfersChecked?.Invoke(transfers, e);
		}

		protected virtual void OnFeedInfosChecked(FeedInfoCollection feedInfos, ValidationEventArgs e)
		{
			FeedInfosChecked?.Invoke(feedInfos, e);
		}

		public void Visit(AgencyCollection agencies)
		{
			OnAgenciesChecked(agencies, new ValidationEventArgs(CheckValidity(agencies)));
		}

		public void Visit(StopCollection stops)
		{
			OnStopsChecked(stops, new ValidationEventArgs(CheckValidity(stops)));
		}

		public void Visit(RouteCollection routes)
		{
			OnRoutesChecked(routes, new ValidationEventArgs(CheckValidity(routes)));
		}

		public void Visit(TripCollection trips)
		{
			OnTripsChecked(trips, new ValidationEventArgs(CheckValidity(trips)));
		}

		public void Visit(StopTimeCollection stopTimes)
		{
			OnStopTimesChecked(stopTimes, new ValidationEventArgs(CheckValidity(stopTimes)));
		}

		public void Visit(CalendarCollection calendars)
		{
			OnCalendarsChecked(calendars, new ValidationEventArgs(CheckValidity(calendars)));
		}

		public void Visit(CalendarDateCollection calendarDates)
		{
			OnCalendarsChecked(calendarDates, new ValidationEventArgs(CheckValidity(calendarDates)));
		}

		public void Visit(FareAttributeCollection fareAttributes)
		{
			OnFareAttributesChecked(fareAttributes, new ValidationEventArgs(CheckValidity(fareAttributes)));
		}

		public void Visit(FareRuleCollection fareRules)
		{
			OnFareAttributesChecked(fareRules, new ValidationEventArgs(CheckValidity(fareRules)));
		}

		public void Visit(ShapeCollection shapes)
		{
			OnShapesChecked(shapes, new ValidationEventArgs(CheckValidity(shapes)));
		}

		public void Visit(FrequencyCollection frequencies)
		{
			OnFrequenciesChecked(frequencies, new ValidationEventArgs(CheckValidity(frequencies)));
		}

		public void Visit(TransferCollection transfers)
		{
			OnTransfersChecked(transfers, new ValidationEventArgs(CheckValidity(transfers)));
		}

		public void Visit(FeedInfoCollection feedInfos)
		{
			OnFeedInfosChecked(feedInfos, new ValidationEventArgs(CheckValidity(feedInfos)));
		}

		private bool CheckValidity<T>(HashSet<T> items) where T : Entity
		{
			if (items.Count <= 0)
				return false;

			foreach (T item in items)
			{
				IEnumerable<PropertyInfo> requiredProperties = GetRequiredProperties(item);
				foreach (var requiredProperty in requiredProperties)
				{
					if (requiredProperty.GetValue(item) == null)
						return false;
				}
			}

			return true;
		}

		private IEnumerable<PropertyInfo> GetRequiredProperties(Entity entity)
		{
			return entity.GetType().GetProperties().Where((pi, index) => Attribute.IsDefined(pi, typeof(RequiredAttribute)));
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
///import baidu.ui.Carousel;
///import baidu.lang.isFunction;
///import baidu.fx.scrollTo;
///import baidu.fx.current;
///import baidu.object.extend;
/**
 * 为滚动组件增加动画滚动功能
 * @name baidu.ui.Carousel.Carousel$fx
 * @addon baidu.ui.Carousel
 * @param {Object} options config参数.
 * @config {Boolean} enableFx 是否支持动画插件
 * @config {Function} scrollFx 描述组件的动画执行过程,默认是baidu.fx.scrollTo
 * @config {Object} scrollFxOptions 执行动画过程所需要的参数
 * @config {Function} onbeforestartscroll 当开始执行动画时触发该事件,该事件的event参数中可以得到四个属性:index:当前需要滚动的索引, scrollOffset:滚动到可视区域的位置, direction:滚动方向, scrollUnit:需要滚动过多少个项
 * @author linlingyu
 */
baidu.ui.Carousel.register(function(me) {
    if (!me.enableFx) {return;}
    me.addEventListener('onbeforescroll', function(evt) {
        if (baidu.fx.current(me.getBody())) {return;}
        var is = evt.direction == 'prev',
            axis = me._axis[me.orientation],
            orie = me.orientation == 'horizontal',
            val = me.getBody()[axis.scrollPos] + evt.scrollUnit * me[axis.vector].offset * (is ? -1 : 1);
        me.scrollFxOptions = baidu.object.extend(me.scrollFxOptions, {
            carousel: me,
            index: evt.index,
            scrollOffset: evt.scrollOffset,
            direction: evt.direction,
            scrollUnit: evt.scrollUnit
        });
        baidu.lang.isFunction(me.scrollFx) && me.scrollFx(me.getBody(),
            {x: orie ? val : 0, y: orie ? 0 : val}, me.scrollFxOptions);
        evt.returnValue = false;
    });
});
//
baidu.ui.Carousel.extend({
    enableFx: true,
    scrollFx: baidu.fx.scrollTo,
    scrollFxOptions: {
        duration: 500,
        onbeforestart: function(evt) {
            var timeLine = evt.target;
            evt.target.carousel.dispatchEvent('onbeforestartscroll', {
                index: timeLine.index,
                scrollOffset: timeLine.scrollOffset,
                direction: timeLine.direction,
                scrollUnit: timeLine.scrollUnit
            });
        },

        onafterfinish: function(evt) {
            var timeLine = evt.target;
            timeLine.carousel.dispatchEvent('onbeforeendscroll', {
                index: timeLine.index,
                scrollOffset: timeLine.scrollOffset,
                direction: timeLine.direction,
                scrollUnit: timeLine.scrollUnit
            });
            timeLine.carousel.dispatchEvent('onafterscroll', {
                index: timeLine.index,
                scrollOffset: timeLine.scrollOffset,
                direction: timeLine.direction,
                scrollUnit: timeLine.scrollUnit
            });
        }
    }
});


text:
void confirm_position(RobotGridStatus_t * expected, RobotGridStatus_t * actual)
{
   TEST_ASSERT_EQUAL(expected->bearing, actual->bearing);
   TEST_ASSERT_EQUAL(expected->grid.x_position, actual->grid.x_position);
   TEST_ASSERT_EQUAL(expected->grid.y_position, actual->grid.y_position);
}

// Tests...
void test_init(void)
{
   RobotGridStatus_t expected =
       { Default_Bearing, {Default_X_Coordinate, Default_Y_Coordinate} };
   RobotGridStatus_t actual = robot_init();

   confirm_position(&expected, &actual);
}

void test_invalid_initial_heading(void)
{
   RobotGridStatus_t expected =
       { Default_Bearing, {Default_X_Coordinate, Default_Y_Coordinate} };
   RobotGridStatus_t actual =
       robot_init_with_position(99, Default_X_Coordinate, Default_Y_Coordinate);

   confirm_position(&expected, &actual);
}

void test_init_with_negative_positions(void)
{
   RobotGridStatus_t expected = { Heading_South, {-1, -1} };
   RobotGridStatus_t actual = robot_init_with_position(Heading_South, -1, -1);

   confirm_position(&expected, &actual);
}

void test_turn_right(void)
{
   RobotGridStatus_t expected = { Heading_East, {0, 0} };
   RobotGridStatus_t actual = robot_init();

   robot_turn_right(&actual);
   confirm_position(&expected, &actual);

   expected.bearing = Heading_South;
   robot_turn_right(&actual);
   confirm_position(&expected, &actual);

   expected.bearing = Heading_West;
   robot_turn_right(&actual);
   confirm_position(&expected, &actual);

   expected.bearing = Heading_North;
   robot_turn_right(&actual);
   confirm_position(&expected, &actual);
}

void test_turn_left(void)
{
   RobotGridStatus_t expected = { Heading_West, {0, 0} };
   RobotGridStatus_t actual = robot_init();

   robot_turn_left(&actual);
   confirm_position(&expected, &actual);

   expected.bearing = Heading_South;
   robot_turn_left(&actual);
   confirm_position(&expected, &actual);

   expected.bearing = Heading_East;
   robot_turn_left(&actual);
   confirm_position(&expected, &actual);

   expected.bearing = Heading_North;
   robot_turn_left(&actual);
   confirm_position(&expected, &actual);
}

void test_advance_positive_north(void)
{
   RobotGridStatus_t expected = { Heading_North, {0, 1} };
   RobotGridStatus_t actual = robot_init();

   robot_advance(&actual);
   confirm_position(&expected, &actual);
}

void test_advance_positive_east(void)
{
   RobotGridStatus_t expected = { Heading_East, {1, 0} };
   RobotGridStatus_t actual = robot_init_with_position(Heading_East, 0, 0);

   robot_advance(&actual);
   confirm_position(&expected, &actual);
}

void test_advance_negative_south(void)
{
   RobotGridStatus_t expected = { Heading_South, {0, -1} };
   RobotGridStatus_t actual = robot_init_with_position(Heading_South, 0, 0);

   robot_advance(&actual);
   confirm_position(&expected, &actual);
}

void test_advance_negative_west(void)
{
   RobotGridStatus_t expected = { Heading_West, {-1, 0} };
   RobotGridStatus_t actual = robot_init_with_position(Heading_West, 0, 0);

   robot_advance(&actual);
   confirm_position(&expected, &actual);
}

void test_simulate_move_west_and_north(void)
{
   RobotGridStatus_t expected = { Heading_West, {-4, 1} };
   RobotGridStatus_t actual = robot_init();

   robot_simulator(&actual, "LAAARALA");
   confirm_position(&expected, &actual);
}

void test_simulate_move_west_and_south(void)
{
   RobotGridStatus_t expected = { Heading_South, {-3, -8} };
   RobotGridStatus_t actual = robot_init_with_position(Heading_East, 2, -7);

   robot_simulator(&actual, "RRAAAAALA");
   confirm_position(&expected, &actual);
}

void test_simulate_move_east_and_north(void)
{
   RobotGridStatus_t expected = { Heading_North, {11, 5} };
   RobotGridStatus_t actual = robot_init_with_position(Heading_South, 8, 4);

   robot_simulator(&actual, "LAAARRRALLLL");
   confirm_position(&expected, &actual);
}

int main(void)
{
   UnityBegin("test/test_word_count.c");

   RUN_TEST(test_init);
   RUN_TEST(test_invalid_initial_heading);
   RUN_TEST(test_init_with_negative_positions);
   RUN_TEST(test_turn_right);
   RUN_TEST(test_turn_left);
   RUN_TEST(test_advance_positive_north);
   RUN_TEST(test_advance_positive_east);
   RUN_TEST(test_advance_negative_south);
   RUN_TEST(test_advance_negative_west);
   RUN_TEST(test_simulate_move_west_and_north);
   RUN_TEST(test_simulate_move_west_and_south);
   RUN_TEST(test_simulate_move_east_and_north);

   UnityEnd();

   return 0;
}


text:
function render(template, data) {

  if (typeof template !== 'string') {
    throw new TypeError('Invalid template! Template should be a "string" ' +
                        'but "' + Object.prototype.toString.call(template) + '" was given as the first ' +
                        'argument for #render(template, view)');
  }

  // space stripping & preprocessing
  template = template.replace(/\n[^\S\n]*{{\s*(!|\^|#|\/)\s*((((?!}}).)+?)\s*[^}])}}[^\S\n]*\n/g,
                              function(match, $1, $2, offset, original) {
                                // mimic Mustache.js space stripping
                                var isFuncSectionStart = typeof evalProp(data, $2 = $2.trim()) === 'function' && $1 === '#';
                                return '\n{{' + $1 + $2 + '}}' + (isFuncSectionStart ? '\n' : '');
                              });

  var regExp = /{{(\^|#)(.+?)}}([^]+?){{\/\2}}/g;
  var lastIndex = regExp.lastIndex = 0;
  var result = '', match;

  while (match = regExp.exec(template)) {
    var key = match[2], flag = match[1], innerTmpl = match[3];
    var templateBetweenSections = template.substring(lastIndex, match.index);
    result += renderSingleSection(templateBetweenSections, data);

    var sectionData = evalProp(data, key);
    if (flag === '#' && sectionData) {
      var dataType = Object.prototype.toString.call(sectionData);
      if (dataType === '[object Array]') {
        sectionData.forEach(function (el) {
          result += render(innerTmpl, el);
        });
      } else if (dataType === '[object Object]') {
        sectionData.parent = data;
        result += render(innerTmpl, sectionData);
      } else if (dataType === '[object Function]') {
        result += sectionData.call(data, innerTmpl, function(template) {
          return renderSingleSection(template, data);
        });
      } else {
        result += render(innerTmpl, data);
      }
    } else if (flag === '^' && !sectionData) {
      result += render(innerTmpl, data);
    }
    lastIndex = regExp.lastIndex;
  }

  result += renderSingleSection(template.substring(lastIndex), data);

  return result;
}

function renderSingleSection(template, data) {
  var regExp = /{{{%(.+?)%}}}|{{{\s*(.+?)\s*}}}|{{&\s*(.+?)\s*}}|{{%(.+?)%}}|{{\s*(.+?)\s*}}/g;
  var lastIndex = regExp.lastIndex = 0;
  var result = '';
  var match;

  template = template;

  while (match = regExp.exec(template)) {

    result += template.substring(lastIndex, match.index);
    var matched = match[1] || match[2] || match[3] || match[4] || match[5];
    var escape = match[5] || match[4];

    var value = match[1] || match[4] || evalProp(data, matched);
    if (value !== undefined && value !== null) {
      result += escape ? escapeHtml('' + value) : value;
    }

    lastIndex = regExp.lastIndex;
  }

  result += template.substring(lastIndex);

  return result;
}

function evalProp(obj, nestedProp) {
  var context = obj, lookupHit = false, value;

  while (value = context) {
    if ((nestedProp = nestedProp.trim()) !== '.') {
      var nestedProps = nestedProp.split('.');
      for (var i = 0; i < nestedProps.length; ++i) {
        var prop = nestedProps[i].trim();
        if (i === nestedProps.length - 1) {
          lookupHit = (typeof value === 'object' && (prop in value));
        }
        value = value[prop];
        if (value === undefined || value === null) {
          break;
        }
      }
    } else {
      lookupHit = true;
    }

    if (lookupHit) break;

    context = context.parent;
  }

  return (typeof(value) === 'function' ? value.call(obj) : value);
}

var entityMap = {
  '&': '&',
  '<': '<',
  '>': '>',
  '"': '"',
  "'": ''',
  '/': '/',
  '`': '`',
  '=': '='
};

function escapeHtml (string) {
  return String(string).replace(/[&<>"'`=\/]/g, function fromEntityMap (s) {
    return entityMap[s];
  });
}


text:
using System;

using UIKit;

namespace HueWatchSample.iPhone
{
	public partial class ViewController : UIViewController
	{
		public ViewController (IntPtr handle) : base (handle)
		{
		}

		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();
			// Perform any additional setup after loading the view, typically from a nib.
		}

		public override void DidReceiveMemoryWarning ()
		{
			base.DidReceiveMemoryWarning ();
			// Release any cached data, images, etc that aren't in use.
		}
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="wrap_content"
    android:minHeight="?android:attr/listPreferredItemHeight"
    android:text="Linha vermelha"
    android:textAlignment="center"
    android:gravity="center"
    android:textSize="@dimen/abc_text_size_body_1_material"
    android:id="@+id/list_item_forecast_textview"
    android:singleLine="true"
    android:textIsSelectable="true">

</TextView>


text:
<!DOCTYPE html>

<title>Ancient Coin</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

Ancient Coin

Click below button to see ancient coin parameters

<button type="button" onclick="main()">Button</button>


text:
class MomentumCms::Menu < ActiveRecord::Base
  # == MomentumCms ==========================================================

  include MomentumCms::BelongsToSite

  self.table_name = 'momentum_cms_menus'

  # == Constants ============================================================
  # == Relationships ========================================================

  has_many :menu_items,
           dependent: :destroy

  attr_accessor :menu_json

  # == Extensions ===========================================================

  # == Validations ==========================================================

  validates :label,
            presence: true

  validates :identifier,
            presence: true,
            uniqueness: {scope: :site_id}

  # == Scopes ===============================================================
  # == Callbacks ============================================================

  after_save :update_menu_items

  # == Class Methods ========================================================
  # == Instance Methods =====================================================
  protected

  def update_menu_items
    json = JSON.parse(self.menu_json)
    MenuBuilderService.new({json: json, menu: self}).create_or_update!
  rescue

  end
end


text:
--TEST--
Test closelog() function : error conditions
--FILE--
<?php
/* Prototype  : bool closelog(void)
 * Description: Close connection to system logger
 * Source code: ext/standard/syslog.c
 * Alias to functions:
 */

echo "*** Testing closelog() : error conditions ***\n";

// One argument
echo "\n-- Testing closelog() function with one argument --\n";
$extra_arg = 10;;
var_dump( closelog($extra_arg) );

?>
===DONE===
--EXPECTF--
*** Testing closelog() : error conditions ***

-- Testing closelog() function with one argument --

Warning: closelog() expects exactly 0 parameters, 1 given in %s on line %d
NULL
===DONE===


text:
vagrant destroy
git clean -fd
rm -r .vagrant/
rm -r minecraft/
rm -r spigot/


text:
package com.iluwatar.specification.selector;

import com.iluwatar.specification.creature.Creature;
import com.iluwatar.specification.property.Movement;

/**
 * Movement selector.
 */
public class MovementSelector extends AbstractSelector<Creature> {

  private final Movement movement;

  public MovementSelector(Movement m) {
    this.movement = m;
  }

  @Override
  public boolean test(Creature t) {
    return t.getMovement().equals(movement);
  }
}


text:
namespace phi {

template <typename T>
using SubFunctor = phi::funcs::SubtractFunctor<T>;

template <typename Context, typename T, size_t D>
void SetValueCompute(const Context& dev_ctx,
                     DenseTensor* in,
                     DenseTensor* value_tensor,
                     DenseTensor* out,
                     const std::vector<int64_t>& axes,
                     std::vector<int64_t>* starts,
                     std::vector<int64_t>* ends,
                     const std::vector<int64_t>& shape) {
  std::vector<int64_t> steps = {1, 1};
  std::vector<int64_t> decrease_axes = {};
  std::vector<int64_t> none_axes = {};

  auto dtype = in->dtype();

  auto in_dims = in->dims();
  phi::funcs::CheckAndUpdateSliceAttrs<int64_t>(
      in_dims, axes, starts, ends, &steps);
  auto slice_dims =
      phi::funcs::GetSliceDims(in_dims, axes, *starts, *ends, &steps);
  auto decrease_slice_dims =
      phi::funcs::GetDecreasedDims(slice_dims, decrease_axes);

  auto slice_dims_for_assign = decrease_slice_dims;
  if (!none_axes.empty()) {
    std::vector<int64_t> slice_dims_with_none;

    size_t none_axes_cur = 0, decrease_axes_cur = 0;
    for (int i = 0; i < slice_dims.size(); ++i) {
      while (none_axes_cur < none_axes.size() &&
             none_axes[none_axes_cur] <= i) {
        slice_dims_with_none.push_back(1);
        none_axes_cur++;
      }
      if (decrease_axes_cur < decrease_axes.size() &&
          decrease_axes[decrease_axes_cur] == i) {
        decrease_axes_cur++;
      } else {
        slice_dims_with_none.push_back(slice_dims[i]);
      }
    }
    while (none_axes_cur < none_axes.size()) {
      slice_dims_with_none.push_back(1);
      none_axes_cur++;
    }

    slice_dims_for_assign = phi::make_ddim(slice_dims_with_none);
  }

  auto place = dev_ctx.GetPlace();
  auto& eigen_place = *dev_ctx.eigen_device();

  // Here copy data from input to avoid data loss at PE and Graph level.
  // TODO(liym27): Speed up in the future version.
  // - Q: Why don't call ShareDataWith to speed up?
  // - A: Because it's not supported to ShareDataWith on OP's input and output
  // https://github.com/PaddlePaddle/Paddle/wiki/ShareDataWith-and-ShareBufferWith-are-prohibited-in-OP
  // - Q: Why don't delete Input, after all, the input and output are the same
  // Tensor at program level?
  // - A: If deleting Input, the graph will be complex, such as there will
  // be two ops points to the output in graph: op1 -> output <- set_value.
  // In this case, we have to find a way to handle the running order of
  // set_value is what we want.
  phi::Copy(dev_ctx, *in, place, false, out);

  DenseTensor slice_tensor(dtype), pad_tensor(dtype);
  slice_tensor.Resize(slice_dims);
  dev_ctx.template Alloc<T>(&slice_tensor);
  pad_tensor.Resize(in_dims);
  dev_ctx.template Alloc<T>(&pad_tensor);

  auto pad_e = EigenTensor<T, D>::From(pad_tensor, in_dims);
  auto out_e = EigenTensor<T, D>::From(*out);
  auto slice_e = EigenTensor<T, D>::From(slice_tensor, slice_dims);

  // Step 1: Set the value of out at `_index` to zero
  slice_e.device(eigen_place) = slice_e.constant(T(0));

  auto starts_indices = Eigen::DSizes<Eigen::DenseIndex, D>();
  auto ends_indices = Eigen::DSizes<Eigen::DenseIndex, D>();
  auto strides_indices = Eigen::DSizes<Eigen::DenseIndex, D>();

  for (size_t i = 0; i < D; ++i) {
    starts_indices[i] = 0;
    ends_indices[i] = slice_dims[i];
    strides_indices[i] = 1;
  }
  for (size_t i = 0; i < axes.size(); i++) {
    int axis_index = axes[i];
    starts_indices[axis_index] = (*starts)[i];
    ends_indices[axis_index] = (*ends)[i];
    strides_indices[axis_index] = steps[i];
    if ((*starts)[i] ==
        (*ends)[i]) {  // slice is empty, data will not be changed
      return;
    }
  }

  out_e.stridedSlice(starts_indices, ends_indices, strides_indices)
      .device(eigen_place) = slice_e;

  // Step 2: Set a tensor with the same shape as out tensor. And its data at
  // '_index' is the same as value_tensor, and data out of '_index' to zero

  // - Step 2.1 Set slice tensor with value

  // NOTE(liym27): [ Why resize slice_tensor here? ]
  // A: When do broadcasting on slice_tensor and value_tensor, the shape of
  // slice_tensor should be decreased dims.
  // e.g.
  //  x[:,0] = value_tensor
  // x's shape = [3, 4], value_tensor's shape = [3]
  // We get slice_dims = [3, 1],  decrease_slice_dims = [3]
  // If do broadcasting on Tensor with shape [3, 1] and [3], the result's
  // shape is [3, 3], which cross the border;
  // If do broadcasting on Tensor with shape [3] and [3], the result's shape
  // is [3], which is right.

  slice_tensor.Resize(slice_dims_for_assign);
  if (value_tensor != nullptr) {
    CheckIsDimsMatch(slice_dims_for_assign, value_tensor->dims());
    phi::funcs::ElementwiseCompute<SubFunctor<T>, T, T>(dev_ctx,
                                                        slice_tensor,
                                                        *value_tensor,
                                                        -1,
                                                        SubFunctor<T>(),
                                                        &slice_tensor);
  } else {
    DenseTensor value_t(dtype);
    auto value_dims = phi::make_ddim(shape);
    CheckIsDimsMatch(slice_dims_for_assign, value_dims);

    value_t.Resize(value_dims);
    dev_ctx.template Alloc<T>(&value_t);
    phi::funcs::ElementwiseCompute<SubFunctor<T>, T, T>(
        dev_ctx, slice_tensor, value_t, -1, SubFunctor<T>(), &slice_tensor);
  }
  slice_tensor.Resize(slice_dims);

  // - Step 2.2 Pad slice tensor with 0
  pad_e.device(eigen_place) = pad_e.constant(T(0));
  pad_e.stridedSlice(starts_indices, ends_indices, strides_indices)
      .device(eigen_place) = slice_e;

  // Step 3: Set out tensor with value_tensor
  out_e.device(eigen_place) = out_e - pad_e;
}

template <typename Context, typename T>
void SetValueCompute_dispatch(const Context& dev_ctx,
                              DenseTensor* in,
                              DenseTensor* value_tensor,
                              DenseTensor* out,
                              const std::vector<int64_t>& axes,
                              std::vector<int64_t>* starts,
                              std::vector<int64_t>* ends,
                              const std::vector<int64_t>& shape,
                              int rank) {
  switch (rank) {
    case 1:
      SetValueCompute<Context, T, 1>(
          dev_ctx, in, value_tensor, out, axes, starts, ends, shape);
      break;
    case 2:
      SetValueCompute<Context, T, 2>(
          dev_ctx, in, value_tensor, out, axes, starts, ends, shape);
      break;
    case 3:
      SetValueCompute<Context, T, 3>(
          dev_ctx, in, value_tensor, out, axes, starts, ends, shape);
      break;
    case 4:
      SetValueCompute<Context, T, 4>(
          dev_ctx, in, value_tensor, out, axes, starts, ends, shape);
      break;
    case 5:
      SetValueCompute<Context, T, 5>(
          dev_ctx, in, value_tensor, out, axes, starts, ends, shape);
      break;
    case 6:
      SetValueCompute<Context, T, 6>(
          dev_ctx, in, value_tensor, out, axes, starts, ends, shape);
      break;
    default:
      PADDLE_THROW(phi::errors::InvalidArgument(
          "The rank of input should be less than 7, but received %d.", rank));
  }
}

template <typename Context, typename T>
void Tensor_Conj(const Context& dev_ctx,
                 const DenseTensor& tensor,
                 DenseTensor* out) {
  out->Resize(tensor.dims());
  phi::funcs::ForRange<Context> out_for_range(dev_ctx, tensor.numel());
  dev_ctx.template Alloc<T>(out);
  phi::funcs::ConjFunctor<T> out_functor(
      tensor.data<T>(), tensor.numel(), out->data<T>());
  out_for_range(out_functor);
}

template <typename Context, typename T>
void Tensor_Add(const Context& dev_ctx,
                const DenseTensor& src1,
                const DenseTensor& src2,
                DenseTensor* out) {
  out->Resize(src1.dims());
  dev_ctx.template Alloc<T>(out);

  phi::AddRawKernel<T, Context>(dev_ctx, src1, src2, -1, out);
}

template <typename Context, typename T>
void Tensor_Sub(const Context& dev_ctx,
                const DenseTensor& src1,
                const DenseTensor& src2,
                DenseTensor* out) {
  out->Resize(src1.dims());
  dev_ctx.template Alloc<T>(out);

  phi::SubtractRawKernel<T, Context>(dev_ctx, src1, src2, -1, out);
}

template <typename Context, typename T, size_t D>
void SliceCompute(const Context& dev_ctx,
                  const DenseTensor* in,
                  DenseTensor* out,
                  const std::vector<int>& axes_int,
                  const std::vector<int>& starts_int,
                  const std::vector<int>& ends_int) {
  std::vector<int64_t> axes(axes_int.begin(), axes_int.end());
  std::vector<int64_t> starts(starts_int.begin(), starts_int.end());
  std::vector<int64_t> ends(ends_int.begin(), ends_int.end());

  std::vector<int> decrease_axis = {};
  std::vector<int> infer_flags = {};

  PADDLE_ENFORCE_EQ(
      starts.size(),
      axes.size(),
      phi::errors::InvalidArgument(
          "The size of starts must be equal to the size of axes."));
  PADDLE_ENFORCE_EQ(ends.size(),
                    axes.size(),
                    phi::errors::InvalidArgument(
                        "The size of ends must be equal to the size of axes."));

  // Step 2: Compute output

  auto in_dims = in->dims();
  auto out_dims = out->dims();
  auto slice_dims = out_dims;

  // 2.1 Infer output dims
  for (size_t i = 0; i < axes.size(); ++i) {
    // when start == -1 && end == start+1
    if (starts[i] == -1 && ends[i] == 0 && infer_flags[i] == -1) {
      auto ret = std::find(decrease_axis.begin(), decrease_axis.end(), axes[i]);
      if (ret != decrease_axis.end()) {
        ends[i] = in_dims[axes[i]];
      }
    }
  }

  phi::funcs::CheckAndUpdateSliceAttrs(in_dims, axes, &starts, &ends);
  slice_dims = phi::funcs::GetSliceDims<int64_t>(
      in_dims, axes, starts, ends, nullptr, nullptr);
  out_dims = phi::funcs::GetDecreasedDims(slice_dims, decrease_axis);

  // 2.2 Get output
  auto offsets = Eigen::DSizes<Eigen::DenseIndex, D>();
  auto extents = Eigen::DSizes<Eigen::DenseIndex, D>();

  for (size_t i = 0; i < D; ++i) {
    offsets[i] = 0;
    extents[i] = slice_dims[i];
  }
  for (size_t i = 0; i < axes.size(); ++i) {
    offsets[axes[i]] = starts[i];
  }

  out->Resize(slice_dims);
  dev_ctx.template Alloc<T>(out);

  auto in_t = EigenTensor<T, D>::From(*in, in_dims);
  auto out_t = EigenTensor<T, D>::From(*out, slice_dims);
  auto& eigen_place = *dev_ctx.eigen_device();

  if (in->numel() <= Eigen::NumTraits<int>::highest()) {
    // similar to tf.slice:
    // if element number less than INT_MAX, change the type of index to int
    Eigen::DSizes<int, D> offsets_32bit, extents_32bit;
    for (size_t i = 0; i < D; i++) {
      offsets_32bit[i] = offsets[i];
      extents_32bit[i] = extents[i];
    }
    funcs::EigenSlice<std::decay_t<decltype(eigen_place)>, T, D>::Eval(
        eigen_place,
        To32BitIndex(out_t),
        To32BitIndex(in_t),
        offsets_32bit,
        extents_32bit);
  } else {
    funcs::EigenSlice<std::decay_t<decltype(eigen_place)>, T, D>::Eval(
        eigen_place, out_t, in_t, offsets, extents);
  }

  out->Resize(out_dims);
  dev_ctx.template Alloc<T>(out);
}

template <typename Context, typename T>
void Tensor_narrow(const Context& dev_ctx,
                   const DenseTensor* src,
                   DenseTensor* out,
                   int row_s,
                   int row_e,
                   int col_s,
                   int col_e) {
  auto rank = src->dims().size();
  std::vector<int> axes_int = {rank - 2, rank - 1};
  std::vector<int> starts_int = {row_s, col_s};
  std::vector<int> ends_int = {row_e, col_e};
  switch (rank) {
    case 1:
      SliceCompute<Context, T, 1>(
          dev_ctx, src, out, axes_int, starts_int, ends_int);
      break;
    case 2:
      SliceCompute<Context, T, 2>(
          dev_ctx, src, out, axes_int, starts_int, ends_int);
      break;
    case 3:
      SliceCompute<Context, T, 3>(
          dev_ctx, src, out, axes_int, starts_int, ends_int);
      break;
    case 4:
      SliceCompute<Context, T, 4>(
          dev_ctx, src, out, axes_int, starts_int, ends_int);
      break;
    case 5:
      SliceCompute<Context, T, 5>(
          dev_ctx, src, out, axes_int, starts_int, ends_int);
      break;
    case 6:
      SliceCompute<Context, T, 6>(
          dev_ctx, src, out, axes_int, starts_int, ends_int);
      break;
    default:
      PADDLE_THROW(phi::errors::InvalidArgument(
          "The rank of input should be less than 7, but received %d.", rank));
  }
}

template <typename Context>
void arange(const Context& dev_ctx,
            DenseTensor* tmp,
            int w,
            int batchsize = 1,
            int h = 1) {
  tmp->Resize(phi::make_ddim({batchsize * w}));
  dev_ctx.template HostAlloc<int32_t>(tmp);
  auto tmpdata = tmp->data<int32_t>();
  for (int b = 0; b < batchsize; b++) {
    for (int i = 0; i < w; i++) {
      tmpdata[b * w + i] = static_cast<int32_t>(b * h + i);
    }
  }
}

template <typename T>
struct OneFunctor {
  OneFunctor(T* output, int* idtptr, int w, int dim)
      : output_(output), idtptr_(idtptr), w_(w), dim_(dim) {}

  HOSTDEVICE void operator()(size_t idx) const {
    output_[w_ * idtptr_[idx] + idx % dim_] = static_cast<T>(1);
  }

  T* output_;
  int* idtptr_;
  int w_;
  int dim_;
};

template <typename Context, typename T>
void LU_Unpack(const Context& dev_ctx,
               const DenseTensor* LU,
               DenseTensor* L,
               DenseTensor* U) {
  const auto udims = LU->dims();
  L->Resize(udims);
  U->Resize(udims);
  const auto H = udims[udims.size() - 2];
  const auto W = udims[udims.size() - 1];
  dev_ctx.template Alloc<T>(L);
  auto L_dataptr = L->data<T>();
  phi::funcs::ForRange<Context> x_for_range(dev_ctx, LU->numel());
  phi::funcs::TrilTriuCompute<T> tril_computer(
      LU->data<T>(), -1, true, H, W, L_dataptr);
  x_for_range(tril_computer);

  dev_ctx.template Alloc<T>(U);
  phi::funcs::TrilTriuCompute<T> triu_computer(
      LU->data<T>(), 0, false, H, W, U->data<T>());
  x_for_range(triu_computer);

  // set L's diagonal 1
  auto dim = std::min(H, W);
  DenseTensor rowtensor, rt_dev;
  auto batchsize = product(phi::slice_ddim(udims, 0, udims.size() - 2));
  batchsize = std::max(static_cast<int>(batchsize), 1);
  arange<Context>(dev_ctx, &rowtensor, dim, batchsize, H);
  auto idtptr = rowtensor.data<int32_t>();
  if (phi::AllocationType::GPU == dev_ctx.GetPlace().GetType()) {
    phi::Copy(dev_ctx, rowtensor, dev_ctx.GetPlace(), false, &rt_dev);
    idtptr = rt_dev.data<int32_t>();
  }

  phi::funcs::ForRange<Context> for_range(dev_ctx, rowtensor.numel());
  OneFunctor<T> functor(L_dataptr, idtptr, W, dim);
  for_range(functor);
}

template <typename Context, typename T>
void scatterpivot(
    const Context& dev_ctx, T* out_data, DenseTensor* idlst, int w, int dim) {
  DenseTensor idlst_tmp;
  idlst_tmp.Resize(idlst->dims());
  dev_ctx.template Alloc<int32_t>(&idlst_tmp);
  phi::Copy(dev_ctx, *idlst, dev_ctx.GetPlace(), false, &idlst_tmp);
  auto idtptr = idlst_tmp.data<int32_t>();

  phi::funcs::ForRange<Context> for_range(dev_ctx, idlst_tmp.numel());
  OneFunctor<T> functor(out_data, idtptr, w, dim);
  for_range(functor);
}

template <typename Context, typename T>
void Unpack_Pivot(const Context& dev_ctx,
                  const DenseTensor& Pivot,
                  DenseTensor* P,
                  int h,
                  int w) {
  auto dims = Pivot.dims();
  auto Pdimvec = vectorize(dims);
  auto prank = Pdimvec.size();
  auto Pnum = dims[prank - 1];
  DenseTensor Pivot_cpu;
  phi::CPUPlace cpu;
  phi::Copy(dev_ctx, Pivot, cpu, false, &Pivot_cpu);
  auto pdataptr = Pivot_cpu.data<int32_t>();
  Pdimvec[prank - 1] = h;
  Pdimvec.emplace_back(h);
  auto Pdim = phi::make_ddim(Pdimvec);
  P->Resize(Pdim);
  dev_ctx.template Alloc<T>(P);
  auto pdata = P->data<T>();
  phi::funcs::SetConstant<Context, T> setter;
  setter(dev_ctx, P, static_cast<T>(0));

  auto batchsize = product(phi::slice_ddim(dims, 0, prank - 1));
  batchsize = std::max(static_cast<int>(batchsize), 1);
  DenseTensor idt;
  for (int i = 0; i < batchsize; i++) {
    arange<Context>(dev_ctx, &idt, h);
    auto idlst = idt.data<int32_t>();
    for (int j = 0; j < Pnum; j++) {
      if (idlst[pdataptr[i * Pnum + j] - 1] == idlst[j]) continue;
      auto temp = idlst[j];
      idlst[j] = idlst[pdataptr[i * Pnum + j] - 1];
      idlst[pdataptr[i * Pnum + j] - 1] = temp;
    }
    scatterpivot(dev_ctx, &(pdata[i * h * h]), &idt, h, h);
  }
}

template <typename Context, typename T>
DenseTensor Transpose2DTo6D(const Context& dev_ctx, const DenseTensor& x) {
  // transpose the last two dimision
  DenseTensor ret;
  auto x_dim = x.dims();
  auto x_vec = phi::vectorize<int>(x_dim);
  int rank = x_vec.size();
  std::swap(x_vec[rank - 1], x_vec[rank - 2]);
  std::vector<int> out_shape = x_vec;
  std::vector<int> axis(rank);
  for (int i = 0; i < rank; ++i) {
    axis[i] = i;
  }
  std::swap(axis[rank - 1], axis[rank - 2]);
  ret.Resize(phi::make_ddim(x_vec));
  dev_ctx.template Alloc<T>(&ret);
  switch (rank) {
    case 2: {
      phi::funcs::Transpose<Context, T, 2> trans;
      trans(dev_ctx, x, &ret, axis);
      break;
    }
    case 3: {
      phi::funcs::Transpose<Context, T, 3> trans;
      trans(dev_ctx, x, &ret, axis);
      break;
    }
    case 4: {
      phi::funcs::Transpose<Context, T, 4> trans;
      trans(dev_ctx, x, &ret, axis);
      break;
    }
    case 5: {
      phi::funcs::Transpose<Context, T, 5> trans;
      trans(dev_ctx, x, &ret, axis);
      break;
    }
    case 6: {
      phi::funcs::Transpose<Context, T, 6> trans;
      trans(dev_ctx, x, &ret, axis);
      break;
    }
    default: {
      PADDLE_THROW(phi::errors::InvalidArgument(
          "Invalid Rank number, "
          "currently only support rank between 2~6"));
    }
  }
  return ret;
}

}  // namespace phi


text:
 1">

     1">
     1">


text:
require 'abc/frontend/engine'

Rails.application.routes.draw do
  mount Abc::Frontend::Engine => '/'
end


text:
package net.openhft.chronicle.core.pool;

import net.openhft.chronicle.core.Maths;
import org.junit.Test;

import java.util.Arrays;

import static org.junit.Assert.assertEquals;

public class DynamicEnumPooledClassTest {
    @Test
    public void additionalEnum() {
        EnumCache<YesNo> yesNoEnumCache = EnumCache.of(YesNo.class);
        assertEquals(YesNo.Yes, yesNoEnumCache.valueOf("Yes"));
        assertEquals(YesNo.No, yesNoEnumCache.valueOf("No"));
        assertEquals("[Yes, No]", Arrays.toString(yesNoEnumCache.asArray()));

        YesNo maybe = yesNoEnumCache.valueOf("Maybe");
        assertEquals("Maybe", maybe.name());
        assertEquals(2, maybe.ordinal());
        assertEquals("[Yes, No, Maybe]", Arrays.toString(yesNoEnumCache.asArray()));

        YesNo unknown = yesNoEnumCache.valueOf("Unknown");
        assertEquals("Unknown", unknown.name());
        assertEquals(3, unknown.ordinal());
        assertEquals("[Yes, No, Maybe, Unknown]", Arrays.toString(yesNoEnumCache.asArray()));

        // check that asArray returns YesNo instances
        for (YesNo yesNo : yesNoEnumCache.asArray())
            assertEquals(yesNo.name(), yesNo.toString());

        DynamicEnumClass<YesNo> dynamicEnumClass = (DynamicEnumClass<YesNo>) yesNoEnumCache;
        dynamicEnumClass.reset();
        assertEquals("[Yes, No]", Arrays.toString(yesNoEnumCache.asArray()));
    }

    @Test
    public void testInitialSize() throws IllegalArgumentException {
        EnumCache<EcnDynamic> ecnEnumCache = EnumCache.of(EcnDynamic.class);
        assertEquals(32, Maths.nextPower2(ecnEnumCache.size(), 1));
    }
}


text:
ace.define('ace/snippets/scala', ['require', 'exports', 'module' ], function(require, exports, module) {

exports.snippetText = "";
exports.scope = "scala";

});


text:
StdOutBuffer::StdOutBuffer(StdOut *stdOut,IBuffer *buffer,IPlayer *player)
 :waveOut(stdOut)
 ,buffer(buffer)
 ,player(player)
{
#ifdef _DEBUG
	std::cerr << "StdOutBuffer::StdOutBuffer()" << std::endl;
#endif
	this->PrepareBuffer();
}

void StdOutBuffer::PrepareBuffer(){
#ifdef _DEBUG
	std::cerr << "StdOutBuffer::PrepareBuffer()" << std::endl;
#endif
}

StdOutBuffer::~StdOutBuffer(void)
{
#ifdef _DEBUG
	std::cerr << "StdOutBuffer::~StdOutBuffer()" << std::endl;
#endif
}

bool StdOutBuffer::AddToOutput(){
#ifdef _DEBUG
	std::cerr << "StdOutBuffer::AddToOutput()" << std::endl;
#endif
	void* wHandle = waveOut->getWaveHandle();
	if (wHandle == NULL) {
		printf("Error. No device handle \n");
		return false;
	}
	wHandle << (void*)data;

	return true;
}


text:
/*jshint esnext:true*/

import loader from './constant.js';

var test = loader;

export default test;


text:
"""Some common functionality for beets' test cases."""
from __future__ import (division, absolute_import, print_function,
                        unicode_literals)

import time
import sys
import os
import tempfile
import shutil
from contextlib import contextmanager

# Use unittest2 on Python < 2.7.
try:
    import unittest2 as unittest
except ImportError:
    import unittest

# Mangle the search path to include the beets sources.
sys.path.insert(0, '..')  # noqa
import beets.library
from beets import importer, logging
from beets.ui import commands
import beets

# Make sure the development versions of the plugins are used
import beetsplug
beetsplug.__path__ = [os.path.abspath(
    os.path.join(__file__, '..', '..', 'beetsplug')
)]

# Test resources path.
RSRC = os.path.join(os.path.dirname(__file__), b'rsrc')

# Propagate to root loger so nosetest can capture it
log = logging.getLogger('beets')
log.propagate = True
log.setLevel(logging.DEBUG)

# Dummy item creation.
_item_ident = 0

# OS feature test.
HAVE_SYMLINK = hasattr(os, 'symlink')

def item(lib=None):
    global _item_ident
    _item_ident += 1
    i = beets.library.Item(
        title=u'the title',
        artist=u'the artist',
        albumartist=u'the album artist',
        album=u'the album',
        genre=u'the genre',
        composer=u'the composer',
        grouping=u'the grouping',
        year=1,
        month=2,
        day=3,
        track=4,
        tracktotal=5,
        disc=6,
        disctotal=7,
        lyrics=u'the lyrics',
        comments=u'the comments',
        bpm=8,
        comp=True,
        path='somepath{0}'.format(_item_ident),
        length=60.0,
        bitrate=128000,
        format='FLAC',
        mb_trackid='someID-1',
        mb_albumid='someID-2',
        mb_artistid='someID-3',
        mb_albumartistid='someID-4',
        album_id=None,
    )
    if lib:
        lib.add(i)
    return i

_album_ident = 0

def album(lib=None):
    global _item_ident
    _item_ident += 1
    i = beets.library.Album(
        artpath=None,
        albumartist='some album artist',
        albumartist_sort='some sort album artist',
        albumartist_credit='some album artist credit',
        album='the album',
        genre='the genre',
        year=2014,
        month=2,
        day=5,
        tracktotal=0,
        disctotal=1,
        comp=False,
        mb_albumid='someID-1',
        mb_albumartistid='someID-1'
    )
    if lib:
        lib.add(i)
    return i

# Dummy import session.
def import_session(lib=None, loghandler=None, paths=[], query=[], cli=False):
    cls = commands.TerminalImportSession if cli else importer.ImportSession
    return cls(lib, loghandler, paths, query)

# A test harness for all beets tests.
# Provides temporary, isolated configuration.
class TestCase(unittest.TestCase):
    """A unittest.TestCase subclass that saves and restores beets'
    global configuration. This allows tests to make temporary
    modifications that will then be automatically removed when the test
    completes. Also provides some additional assertion methods, a
    temporary directory, and a DummyIO.
    """
    def setUp(self):
        # A "clean" source list including only the defaults.
        beets.config.sources = []
        beets.config.read(user=False, defaults=True)

        # Direct paths to a temporary directory. Tests can also use this
        # temporary directory.
        self.temp_dir = tempfile.mkdtemp()
        beets.config['statefile'] = os.path.join(self.temp_dir, 'state.pickle')
        beets.config['library'] = os.path.join(self.temp_dir, 'library.db')
        beets.config['directory'] = os.path.join(self.temp_dir, 'libdir')

        # Set $HOME, which is used by confit's `config_dir()` to create
        # directories.
        self._old_home = os.environ.get('HOME')
        os.environ['HOME'] = self.temp_dir

        # Initialize, but don't install, a DummyIO.
        self.io = DummyIO()

    def tearDown(self):
        if os.path.isdir(self.temp_dir):
            shutil.rmtree(self.temp_dir)
        if self._old_home is None:
            del os.environ['HOME']
        else:
            os.environ['HOME'] = self._old_home
        self.io.restore()

        beets.config.clear()
        beets.config._materialized = False

    def assertExists(self, path):
        self.assertTrue(os.path.exists(path),
                        'file does not exist: {!r}'.format(path))

    def assertNotExists(self, path):
        self.assertFalse(os.path.exists(path),
                         'file exists: {!r}'.format((path)))

class LibTestCase(TestCase):
    """A test case that includes an in-memory library object (`lib`) and
    an item added to the library (`i`).
    """
    def setUp(self):
        super(LibTestCase, self).setUp()
        self.lib = beets.library.Library(':memory:')
        self.i = item(self.lib)

    def tearDown(self):
        self.lib._connection().close()
        super(LibTestCase, self).tearDown()

# Mock timing.

class Timecop(object):
    """Mocks the timing system (namely time() and sleep()) for testing.
    Inspired by the Ruby timecop library.
    """
    def __init__(self):
        self.now = time.time()

    def time(self):
        return self.now

    def sleep(self, amount):
        self.now += amount

    def install(self):
        self.orig = {
            'time': time.time,
            'sleep': time.sleep,
        }
        time.time = self.time
        time.sleep = self.sleep

    def restore(self):
        time.time = self.orig['time']
        time.sleep = self.orig['sleep']

# Mock I/O.

class InputException(Exception):
    def __init__(self, output=None):
        self.output = output

    def __str__(self):
        msg = "Attempt to read with no input provided."
        if self.output is not None:
            msg += " Output: %s" % self.output
        return msg

class DummyOut(object):
    encoding = 'utf8'

    def __init__(self):
        self.buf = []

    def write(self, s):
        self.buf.append(s)

    def get(self):
        return b''.join(self.buf)

    def clear(self):
        self.buf = []

class DummyIn(object):
    encoding = 'utf8'

    def __init__(self, out=None):
        self.buf = []
        self.reads = 0
        self.out = out

    def add(self, s):
        self.buf.append(s + b'\n')

    def readline(self):
        if not self.buf:
            if self.out:
                raise InputException(self.out.get())
            else:
                raise InputException()
        self.reads += 1
        return self.buf.pop(0)

class DummyIO(object):
    """Mocks input and output streams for testing UI code."""
    def __init__(self):
        self.stdout = DummyOut()
        self.stdin = DummyIn(self.stdout)

    def addinput(self, s):
        self.stdin.add(s)

    def getoutput(self):
        res = self.stdout.get()
        self.stdout.clear()
        return res

    def readcount(self):
        return self.stdin.reads

    def install(self):
        sys.stdin = self.stdin
        sys.stdout = self.stdout

    def restore(self):
        sys.stdin = sys.__stdin__
        sys.stdout = sys.__stdout__

# Utility.

def touch(path):
    open(path, 'a').close()

class Bag(object):
    """An object that exposes a set of fields given as keyword
    arguments. Any field not found in the dictionary appears to be None.
    Used for mocking Album objects and the like.
    """
    def __init__(self, **fields):
        self.fields = fields

    def __getattr__(self, key):
        return self.fields.get(key)

# Platform mocking.

@contextmanager
def platform_windows():
    import ntpath
    old_path = os.path
    try:
        os.path = ntpath
        yield
    finally:
        os.path = old_path

@contextmanager
def platform_posix():
    import posixpath
    old_path = os.path
    try:
        os.path = posixpath
        yield
    finally:
        os.path = old_path

@contextmanager
def system_mock(name):
    import platform
    old_system = platform.system
    platform.system = lambda: name
    try:
        yield
    finally:
        platform.system = old_system


text:
if (typeof (Evented) == 'undefined') {
    // Montage Require
    if (typeof bootstrap === "function") {
        Evented = require('Evented');

    // CommonJS
    } else if (typeof exports === "object") {
        Evented = require('./evented.js');

    // RequireJS
    } else if (typeof define === "function" && define.amd) {
        Evented = require('Evented');

    // SES (Secure EcmaScript)
    } else if (typeof ses !== "undefined") {
        if (!ses.ok()) {
            return;
        } else {
            Evented = ses.Evented;
        }
    }
}

function ParentClass() {
    console.log("Parent constructor");
    this['super'](); // call super constructor
    this.test=1;
    this.otherProperty=2;
    this.on('test1.parentclass',function(arg) {
        console.log("called test event 1 in parent class of extended %s.",this.constructor.name);
    }.bind(this));
    try {
        this.on('test4.parentclass',function(arg) {
            console.log("called test event 4 in ParentClass of extended %s.",this.constructor.name);
        });
        console.log("An exception should have occurred.");
    } catch (e) {
        console.log("Correctly caught bad event request.");
    }
}
ParentClass.events = ["test1"];

ParentClass.prototype.parentFunction=function() {
    console.log("ParentFunction");
    if (!this.stop) {
        console.log("Calling inheritedFunction from parentFunction");
        this.stop=true;
        this.inheritedFunction();
        this.stop=false;
    } else {
        console.log("Not calling inheritedFunction");
    }
}

ParentClass.prototype.inheritedFunction=function() {
    console.log("Inherited function in parent class");
    this.parentFunction();
}

Evented.extend(ParentClass);

function ChildClass() {
    console.log("Child constructor");
    this['super'](); // call super constructor
    console.log("Done parent constructor");
    console.log("Should be '1': %s",this.test);
    this.parentFunction();
    this.inheritedFunction();
    this.on('test1.childclass',function(arg) {
        console.log("called test event 1 in %s.",this.constructor.name);
    }.bind(this));
    this.on('test2.childclass',function(arg) {
        console.log("called test event 2 in %s.",this.constructor.name);
    }.bind(this));
    this.on('test3.childclass',function(arg) {
        console.log("called test event 3 in %s.",this.constructor.name);
    }.bind(this));
}

ChildClass.events = ["test2","test3"];

ChildClass.prototype.inheritedFunction = function() {
    console.log("Inherited function in child class");
    if (!this.recursion) {
        console.log("Testing recursion from middle of inheritance chain.");
        this.recursion = true;
        this.inheritedFunction();
        this.recursion = false;
        console.log("Done. Now continuing up the heirarchy chain.");
    }
    this['super'].inheritedFunction();
}

ParentClass.extend(ChildClass);

function Child2Class() {
    console.log("Child constructor");
    this['super'](); // call super constructor
}

Child2Class.prototype.inheritedFunction = function() {
    console.log("Inherited function in child 2 class");
    this['super'].inheritedFunction();
}

ChildClass.extend(Child2Class);

var child = new Child2Class();
child.fire('test1');
child.fire('test2');
child.fire('test3');


text:
/* needed for usleep() */
#define _XOPEN_SOURCE 600
#include <unistd.h>
#include "libavutil/avstring.h"
#include "libavcodec/opt.h"
#include "os_support.h"
#include "avformat.h"
#if CONFIG_NETWORK
#include "network.h"
#endif

#if LIBAVFORMAT_VERSION_MAJOR >= 53
/** @name Logging context. */
/*@{*/
static const char *urlcontext_to_name(void *ptr)
{
    URLContext *h = (URLContext *)ptr;
    if(h->prot) return h->prot->name;
    else        return "NULL";
}
static const AVOption options[] = {{NULL}};
static const AVClass urlcontext_class =
        { "URLContext", urlcontext_to_name, options, LIBAVUTIL_VERSION_INT };
/*@}*/
#endif

static int default_interrupt_cb(void);

URLProtocol *first_protocol = NULL;
URLInterruptCB *url_interrupt_cb = default_interrupt_cb;

URLProtocol *av_protocol_next(URLProtocol *p)
{
    if(p) return p->next;
    else  return first_protocol;
}

int av_register_protocol(URLProtocol *protocol)
{
    URLProtocol **p;
    p = &first_protocol;
    while (*p != NULL) p = &(*p)->next;
    *p = protocol;
    protocol->next = NULL;
    return 0;
}

#if LIBAVFORMAT_VERSION_MAJOR < 53
int register_protocol(URLProtocol *protocol)
{
    return av_register_protocol(protocol);
}
#endif

int url_open_protocol (URLContext **puc, struct URLProtocol *up,
                       const char *filename, int flags)
{
    URLContext *uc;
    int err;

#if CONFIG_NETWORK
    if (!ff_network_init())
        return AVERROR(EIO);
#endif
    uc = av_mallocz(sizeof(URLContext) + strlen(filename) + 1);
    if (!uc) {
        err = AVERROR(ENOMEM);
        goto fail;
    }
#if LIBAVFORMAT_VERSION_MAJOR >= 53
    uc->av_class = &urlcontext_class;
#endif
    uc->filename = (char *) &uc[1];
    strcpy(uc->filename, filename);
    uc->prot = up;
    uc->flags = flags;
    uc->is_streamed = 0; /* default = not streamed */
    uc->max_packet_size = 0; /* default: stream file */
    err = up->url_open(uc, filename, flags);
    if (err < 0) {
        av_free(uc);
        goto fail;
    }

    //We must be careful here as url_seek() could be slow, for example for http
    if(   (flags & (URL_WRONLY | URL_RDWR))
       || !strcmp(up->name, "file"))
        if(!uc->is_streamed && url_seek(uc, 0, SEEK_SET) < 0)
            uc->is_streamed= 1;
    *puc = uc;
    return 0;
 fail:
    *puc = NULL;
#if CONFIG_NETWORK
    ff_network_close();
#endif
    return err;
}

int url_open(URLContext **puc, const char *filename, int flags)
{
    URLProtocol *up;
    const char *p;
    char proto_str[128], *q;

    p = filename;
    q = proto_str;
    while (*p != '\0' && *p != ':') {
        /* protocols can only contain alphabetic chars */
        if (!isalpha(*p))
            goto file_proto;
        if ((q - proto_str) < sizeof(proto_str) - 1)
            *q++ = *p;
        p++;
    }
    /* if the protocol has length 1, we consider it is a dos drive */
    if (*p == '\0' || is_dos_path(filename)) {
    file_proto:
        strcpy(proto_str, "file");
    } else {
        *q = '\0';
    }

    up = first_protocol;
    while (up != NULL) {
        if (!strcmp(proto_str, up->name))
            return url_open_protocol (puc, up, filename, flags);
        up = up->next;
    }
    *puc = NULL;
    return AVERROR(ENOENT);
}

int url_read(URLContext *h, unsigned char *buf, int size)
{
    int ret;
    if (h->flags & URL_WRONLY)
        return AVERROR(EIO);
    ret = h->prot->url_read(h, buf, size);
    return ret;
}

int url_read_complete(URLContext *h, unsigned char *buf, int size)
{
    int ret, len;
    int fast_retries = 5;

    len = 0;
    while (len < size) {
        ret = url_read(h, buf+len, size-len);
        if (ret == AVERROR(EAGAIN)) {
            ret = 0;
            if (fast_retries)
                fast_retries--;
            else
                usleep(1000);
        } else if (ret < 1)
            return ret < 0 ? ret : len;
        if (ret)
           fast_retries = FFMAX(fast_retries, 2);
        len += ret;
    }
    return len;
}

int url_write(URLContext *h, unsigned char *buf, int size)
{
    int ret;
    if (!(h->flags & (URL_WRONLY | URL_RDWR)))
        return AVERROR(EIO);
    /* avoid sending too big packets */
    if (h->max_packet_size && size > h->max_packet_size)
        return AVERROR(EIO);
    ret = h->prot->url_write(h, buf, size);
    return ret;
}

int64_t url_seek(URLContext *h, int64_t pos, int whence)
{
    int64_t ret;

    if (!h->prot->url_seek)
        return AVERROR(ENOSYS);
    ret = h->prot->url_seek(h, pos, whence & ~AVSEEK_FORCE);
    return ret;
}

int url_close(URLContext *h)
{
    int ret = 0;
    if (!h) return 0; /* can happen when url_open fails */

    if (h->prot->url_close)
        ret = h->prot->url_close(h);
#if CONFIG_NETWORK
    ff_network_close();
#endif
    av_free(h);
    return ret;
}

int url_exist(const char *filename)
{
    URLContext *h;
    if (url_open(&h, filename, URL_RDONLY) < 0)
        return 0;
    url_close(h);
    return 1;
}

int64_t url_filesize(URLContext *h)
{
    int64_t pos, size;

    size= url_seek(h, 0, AVSEEK_SIZE);
    if(size<0){
        pos = url_seek(h, 0, SEEK_CUR);
        if ((size = url_seek(h, -1, SEEK_END)) < 0)
            return size;
        size++;
        url_seek(h, pos, SEEK_SET);
    }
    return size;
}

int url_get_file_handle(URLContext *h)
{
    if (!h->prot->url_get_file_handle)
        return -1;
    return h->prot->url_get_file_handle(h);
}

int url_get_max_packet_size(URLContext *h)
{
    return h->max_packet_size;
}

void url_get_filename(URLContext *h, char *buf, int buf_size)
{
    av_strlcpy(buf, h->filename, buf_size);
}

static int default_interrupt_cb(void)
{
    return 0;
}

void url_set_interrupt_cb(URLInterruptCB *interrupt_cb)
{
    if (!interrupt_cb)
        interrupt_cb = default_interrupt_cb;
    url_interrupt_cb = interrupt_cb;
}

int av_url_read_pause(URLContext *h, int pause)
{
    if (!h->prot->url_read_pause)
        return AVERROR(ENOSYS);
    return h->prot->url_read_pause(h, pause);
}

int64_t av_url_read_seek(URLContext *h,
        int stream_index, int64_t timestamp, int flags)
{
    if (!h->prot->url_read_seek)
        return AVERROR(ENOSYS);
    return h->prot->url_read_seek(h, stream_index, timestamp, flags);
}