/* Includes ------------------------------------------------------------------*/

#include "usbh_ioreq.h"
#include "usb_bsp.h"
#include "usbh_hcs.h"
#include "usbh_stdreq.h"
#include "usbh_core.h"
#include "usb_hcd_int.h"

/** @addtogroup USBH_LIB
  * @{
  */

/** @addtogroup USBH_LIB_CORE
* @{
*/

/** @defgroup USBH_CORE
  * @brief TThis file handles the basic enumaration when a device is connected
  *          to the host.
  * @{
  */

/** @defgroup USBH_CORE_Private_TypesDefinitions
  * @{
  */
uint8_t USBH_Disconnected (USB_OTG_CORE_HANDLE *pdev);
uint8_t USBH_Connected (USB_OTG_CORE_HANDLE *pdev);
uint8_t USBH_SOF (USB_OTG_CORE_HANDLE *pdev);

USBH_HCD_INT_cb_TypeDef USBH_HCD_INT_cb =
{
  USBH_SOF,
  USBH_Connected,
  USBH_Disconnected,
};

USBH_HCD_INT_cb_TypeDef  *USBH_HCD_INT_fops = &USBH_HCD_INT_cb;
/**
  * @}
  */

/** @defgroup USBH_CORE_Private_Defines
  * @{
  */
/**
  * @}
  */

/** @defgroup USBH_CORE_Private_Macros
  * @{
  */
/**
  * @}
  */

/** @defgroup USBH_CORE_Private_Variables
  * @{
  */
/**
  * @}
  */

/** @defgroup USBH_CORE_Private_FunctionPrototypes
  * @{
  */
static USBH_Status USBH_HandleEnum(USB_OTG_CORE_HANDLE *pdev, USBH_HOST *phost);
USBH_Status USBH_HandleControl (USB_OTG_CORE_HANDLE *pdev, USBH_HOST *phost);

/**
  * @}
  */

/** @defgroup USBH_CORE_Private_Functions
  * @{
  */

/**
  * @brief  USBH_Connected
  *         USB Connect callback function from the Interrupt.
  * @param  selected device
  * @retval Status
*/
uint8_t USBH_Connected (USB_OTG_CORE_HANDLE *pdev)
{
  pdev->host.ConnSts = 1;
  return 0;
}

/**
* @brief  USBH_Disconnected
*         USB Disconnect callback function from the Interrupt.
* @param  selected device
* @retval Status
*/

uint8_t USBH_Disconnected (USB_OTG_CORE_HANDLE *pdev)
{
  pdev->host.ConnSts = 0;
  return 0;
}

/**
  * @brief  USBH_SOF
  *         USB SOF callback function from the Interrupt.
  * @param  selected device
  * @retval Status
  */

uint8_t USBH_SOF (USB_OTG_CORE_HANDLE *pdev)
{
  /* This callback could be used to implement a scheduler process */
  return 0;
}
/**
  * @brief  USBH_Init
  *         Host hardware and stack initializations
  * @param  class_cb: Class callback structure address
  * @param  usr_cb: User callback structure address
  * @retval None
  */
void USBH_Init(USB_OTG_CORE_HANDLE *pdev,
               USB_OTG_CORE_ID_TypeDef coreID,
               USBH_HOST *phost,
               USBH_Class_cb_TypeDef *class_cb,
               USBH_Usr_cb_TypeDef *usr_cb)
{

  /* Hardware Init */
  USB_OTG_BSP_Init(pdev);

  /* configure GPIO pin used for switching VBUS power */
  USB_OTG_BSP_ConfigVBUS(0);

  /* Host de-initializations */
  USBH_DeInit(pdev, phost);

  /*Register class and user callbacks */
  phost->class_cb = class_cb;
  phost->usr_cb = usr_cb;

  /* Start the USB OTG core */
   HCD_Init(pdev , coreID);

  /* Upon Init call usr call back */
  phost->usr_cb->Init();

  /* Enable Interrupts */
  USB_OTG_BSP_EnableInterrupt(pdev);
}

/**
  * @brief  USBH_DeInit
  *         Re-Initialize Host
  * @param  None
  * @retval status: USBH_Status
  */
USBH_Status USBH_DeInit(USB_OTG_CORE_HANDLE *pdev, USBH_HOST *phost)
{
  /* Software Init */

  phost->gState = HOST_IDLE;
  phost->gStateBkp = HOST_IDLE;
  phost->EnumState = ENUM_IDLE;
  phost->RequestState = CMD_SEND;

  phost->Control.state = CTRL_SETUP;
  phost->Control.ep0size = USB_OTG_MAX_EP0_SIZE;

  phost->device_prop.address = USBH_DEVICE_ADDRESS_DEFAULT;
  phost->device_prop.speed = HPRT0_PRTSPD_FULL_SPEED;

  USBH_Free_Channel  (pdev, phost->Control.hc_num_in);
  USBH_Free_Channel  (pdev, phost->Control.hc_num_out);
  return USBH_OK;
}

/**
* @brief  USBH_Process
*         USB Host core main state machine process
* @param  None
* @retval None
*/
void USBH_Process(USB_OTG_CORE_HANDLE *pdev , USBH_HOST *phost)
{
  volatile USBH_Status status = USBH_FAIL;

  /* check for Host port events */
  if ((HCD_IsDeviceConnected(pdev) == 0)&& (phost->gState != HOST_IDLE))
  {
    if(phost->gState != HOST_DEV_DISCONNECTED)
    {
      phost->gState = HOST_DEV_DISCONNECTED;
    }
  }

  switch (phost->gState)
  {

  case HOST_IDLE :

    if (HCD_IsDeviceConnected(pdev))
    {
      phost->gState = HOST_DEV_ATTACHED;
      USB_OTG_BSP_mDelay(100);
    }
    break;

  case HOST_DEV_ATTACHED :

    phost->usr_cb->DeviceAttached();
    phost->Control.hc_num_out = USBH_Alloc_Channel(pdev, 0x00);
    phost->Control.hc_num_in = USBH_Alloc_Channel(pdev, 0x80);

    /* Reset USB Device */
    if ( HCD_ResetPort(pdev) == 0)
    {
      phost->usr_cb->ResetDevice();
      /*  Wait for USB USBH_ISR_PrtEnDisableChange()
      Host is Now ready to start the Enumeration
      */

      phost->device_prop.speed = HCD_GetCurrentSpeed(pdev);

      phost->gState = HOST_ENUMERATION;
      phost->usr_cb->DeviceSpeedDetected(phost->device_prop.speed);

      /* Open Control pipes */
      USBH_Open_Channel (pdev,
                           phost->Control.hc_num_in,
                           phost->device_prop.address,
                           phost->device_prop.speed,
                           EP_TYPE_CTRL,
                           phost->Control.ep0size);

      /* Open Control pipes */
      USBH_Open_Channel (pdev,
                           phost->Control.hc_num_out,
                           phost->device_prop.address,
                           phost->device_prop.speed,
                           EP_TYPE_CTRL,
                           phost->Control.ep0size);
   }
    break;

  case HOST_ENUMERATION:
    /* Check for enumeration status */
    if ( USBH_HandleEnum(pdev , phost) == USBH_OK)
    {
      /* The function shall return USBH_OK when full enumeration is complete */

      /* user callback for end of device basic enumeration */
      phost->usr_cb->EnumerationDone();

      phost->gState  = HOST_USR_INPUT;
    }
    break;

  case HOST_USR_INPUT:
    /*The function should return user response true to move to class state */
    if ( phost->usr_cb->UserInput() == USBH_USR_RESP_OK)
    {
      if((phost->class_cb->Init(pdev, phost))\
        == USBH_OK)
      {
        phost->gState  = HOST_CLASS_REQUEST;
      }
    }
    break;

  case HOST_CLASS_REQUEST:
    /* process class standard contol requests state machine */
    status = phost->class_cb->Requests(pdev, phost);

     if(status == USBH_OK)
     {
       phost->gState  = HOST_CLASS;
     }

     else
     {
       USBH_ErrorHandle(phost, status);
     }

    break;
  case HOST_CLASS:
    /* process class state machine */
    status = phost->class_cb->Machine(pdev, phost);
    USBH_ErrorHandle(phost, status);
    break;

  case HOST_CTRL_XFER:
    /* process control transfer state machine */
    USBH_HandleControl(pdev, phost);
    break;

  case HOST_SUSPENDED:
    break;

  case HOST_ERROR_STATE:
    /* Re-Initilaize Host for new Enumeration */
    USBH_DeInit(pdev, phost);
    phost->usr_cb->DeInit();
    phost->class_cb->DeInit(pdev, &phost->device_prop);
    break;

  case HOST_DEV_DISCONNECTED :

    /* Manage User disconnect operations*/
    phost->usr_cb->DeviceDisconnected();

    /* Re-Initilaize Host for new Enumeration */
    USBH_DeInit(pdev, phost);
    phost->usr_cb->DeInit();
    phost->class_cb->DeInit(pdev, &phost->device_prop);
    USBH_DeAllocate_AllChannel(pdev);
    phost->gState = HOST_IDLE;

    break;

  default :
    break;
  }

}

/**
  * @brief  USBH_ErrorHandle
  *         This function handles the Error on Host side.
  * @param  errType : Type of Error or Busy/OK state
  * @retval None
  */
void USBH_ErrorHandle(USBH_HOST *phost, USBH_Status errType)
{
  /* Error unrecovered or not supported device speed */
  if ( (errType == USBH_ERROR_SPEED_UNKNOWN) ||
       (errType == USBH_UNRECOVERED_ERROR) )
  {
    phost->usr_cb->UnrecoveredError();
    phost->gState = HOST_ERROR_STATE;
  }
  /* USB host restart requested from application layer */
  else if(errType == USBH_APPLY_DEINIT)
  {
    phost->gState = HOST_ERROR_STATE;
    /* user callback for initalization */
    phost->usr_cb->Init();
  }
}

/**
  * @brief  USBH_HandleEnum
  *         This function includes the complete enumeration process
  * @param  pdev: Selected device
  * @retval USBH_Status
  */
static USBH_Status USBH_HandleEnum(USB_OTG_CORE_HANDLE *pdev, USBH_HOST *phost)
{
  USBH_Status Status = USBH_BUSY;
  uint8_t Local_Buffer[64];

  switch (phost->EnumState)
  {
  case ENUM_IDLE:
    /* Get Device Desc for only 1st 8 bytes : To get EP0 MaxPacketSize */
    if ( USBH_Get_DevDesc(pdev , phost, 8) == USBH_OK)
    {
      phost->Control.ep0size = phost->device_prop.Dev_Desc.bMaxPacketSize;

      /* Issue Reset  */
      HCD_ResetPort(pdev);
      phost->EnumState = ENUM_GET_FULL_DEV_DESC;

      /* modify control channels configuration for MaxPacket size */
      USBH_Modify_Channel (pdev,
                           phost->Control.hc_num_out,
                           0,
                           0,
                           0,
                           phost->Control.ep0size);

      USBH_Modify_Channel (pdev,
                           phost->Control.hc_num_in,
                           0,
                           0,
                           0,
                           phost->Control.ep0size);
    }
    break;

  case ENUM_GET_FULL_DEV_DESC:
    /* Get FULL Device Desc  */
    if ( USBH_Get_DevDesc(pdev, phost, USB_DEVICE_DESC_SIZE)\
      == USBH_OK)
    {
      /* user callback for device descriptor available */
      phost->usr_cb->DeviceDescAvailable(&phost->device_prop.Dev_Desc);
      phost->EnumState = ENUM_SET_ADDR;
    }
    break;

  case ENUM_SET_ADDR:
    /* set address */
    if ( USBH_SetAddress(pdev, phost, USBH_DEVICE_ADDRESS) == USBH_OK)
    {
      USB_OTG_BSP_mDelay(2);
      phost->device_prop.address = USBH_DEVICE_ADDRESS;

      /* user callback for device address assigned */
      phost->usr_cb->DeviceAddressAssigned();
      phost->EnumState = ENUM_GET_CFG_DESC;

      /* modify control channels to update device address */
      USBH_Modify_Channel (pdev,
                           phost->Control.hc_num_in,
                           phost->device_prop.address,
                           0,
                           0,
                           0);

      USBH_Modify_Channel (pdev,
                           phost->Control.hc_num_out,
                           phost->device_prop.address,
                           0,
                           0,
                           0);
    }
    break;

  case ENUM_GET_CFG_DESC:
    /* get standard configuration descriptor */
    if ( USBH_Get_CfgDesc(pdev,
                          phost,
                          USB_CONFIGURATION_DESC_SIZE) == USBH_OK)
    {
      phost->EnumState = ENUM_GET_FULL_CFG_DESC;
    }
    break;

  case ENUM_GET_FULL_CFG_DESC:
    /* get FULL config descriptor (config, interface, endpoints) */
    if (USBH_Get_CfgDesc(pdev,
                         phost,
                         phost->device_prop.Cfg_Desc.wTotalLength) == USBH_OK)
    {
      /* User callback for configuration descriptors available */
      phost->usr_cb->ConfigurationDescAvailable(&phost->device_prop.Cfg_Desc,
                                                      phost->device_prop.Itf_Desc,
                                                      phost->device_prop.Ep_Desc[0]);

      phost->EnumState = ENUM_GET_MFC_STRING_DESC;
    }
    break;

  case ENUM_GET_MFC_STRING_DESC:
    if (phost->device_prop.Dev_Desc.iManufacturer != 0)
    { /* Check that Manufacturer String is available */

      if ( USBH_Get_StringDesc(pdev,
                               phost,
                               phost->device_prop.Dev_Desc.iManufacturer,
                               Local_Buffer ,
                               0xff) == USBH_OK)
      {
        /* User callback for Manufacturing string */
        phost->usr_cb->ManufacturerString(Local_Buffer);
        phost->EnumState = ENUM_GET_PRODUCT_STRING_DESC;
      }
    }
    else
    {
      phost->usr_cb->ManufacturerString("N/A");
      phost->EnumState = ENUM_GET_PRODUCT_STRING_DESC;
    }
    break;

  case ENUM_GET_PRODUCT_STRING_DESC:
    if (phost->device_prop.Dev_Desc.iProduct != 0)
    { /* Check that Product string is available */
      if ( USBH_Get_StringDesc(pdev,
                               phost,
                               phost->device_prop.Dev_Desc.iProduct,
                               Local_Buffer,
                               0xff) == USBH_OK)
      {
        /* User callback for Product string */
        phost->usr_cb->ProductString(Local_Buffer);
        phost->EnumState = ENUM_GET_SERIALNUM_STRING_DESC;
      }
    }
    else
    {
      phost->usr_cb->ProductString("N/A");
      phost->EnumState = ENUM_GET_SERIALNUM_STRING_DESC;
    }
    break;

  case ENUM_GET_SERIALNUM_STRING_DESC:
    if (phost->device_prop.Dev_Desc.iSerialNumber != 0)
    { /* Check that Serial number string is available */
      if ( USBH_Get_StringDesc(pdev,
                               phost,
                               phost->device_prop.Dev_Desc.iSerialNumber,
                               Local_Buffer,
                               0xff) == USBH_OK)
      {
        /* User callback for Serial number string */
        phost->usr_cb->SerialNumString(Local_Buffer);
        phost->EnumState = ENUM_SET_CONFIGURATION;
      }
    }
    else
    {
      phost->usr_cb->SerialNumString("N/A");
      phost->EnumState = ENUM_SET_CONFIGURATION;
    }
    break;

  case ENUM_SET_CONFIGURATION:
    /* set configuration  (default config) */
    if (USBH_SetCfg(pdev,
                    phost,
                    phost->device_prop.Cfg_Desc.bConfigurationValue) == USBH_OK)
    {
      phost->EnumState = ENUM_DEV_CONFIGURED;
    }
    break;

  case ENUM_DEV_CONFIGURED:
    /* user callback for enumeration done */
    Status = USBH_OK;
    break;

  default:
    break;
  }
  return Status;
}

/**
  * @brief  USBH_HandleControl
  *         Handles the USB control transfer state machine
  * @param  pdev: Selected device
  * @retval Status
  */
USBH_Status USBH_HandleControl (USB_OTG_CORE_HANDLE *pdev, USBH_HOST *phost)
{
  uint8_t direction;
  static uint16_t timeout = 0;
  USBH_Status status = USBH_OK;
  URB_STATE URB_Status = URB_IDLE;

  phost->Control.status = CTRL_START;

  switch (phost->Control.state)
  {
  case CTRL_SETUP:
    /* send a SETUP packet */
    USBH_CtlSendSetup     (pdev,
	                   phost->Control.setup.d8 ,
	                   phost->Control.hc_num_out);
    phost->Control.state = CTRL_SETUP_WAIT;
    break;

  case CTRL_SETUP_WAIT:

    URB_Status = HCD_GetURB_State(pdev , phost->Control.hc_num_out);
    /* case SETUP packet sent successfully */
    if(URB_Status == URB_DONE)
    {
      direction = (phost->Control.setup.b.bmRequestType & USB_REQ_DIR_MASK);

      /* check if there is a data stage */
      if (phost->Control.setup.b.wLength.w != 0 )
      {
        timeout = DATA_STAGE_TIMEOUT;
        if (direction == USB_D2H)
        {
          /* Data Direction is IN */
          phost->Control.state = CTRL_DATA_IN;
        }
        else
        {
          /* Data Direction is OUT */
          phost->Control.state = CTRL_DATA_OUT;
        }
      }
      /* No DATA stage */
      else
      {
        timeout = NODATA_STAGE_TIMEOUT;

        /* If there is No Data Transfer Stage */
        if (direction == USB_D2H)
        {
          /* Data Direction is IN */
          phost->Control.state = CTRL_STATUS_OUT;
        }
        else
        {
          /* Data Direction is OUT */
          phost->Control.state = CTRL_STATUS_IN;
        }
      }
      /* Set the delay timer to enable timeout for data stage completion */
      phost->Control.timer = HCD_GetCurrentFrame(pdev);
    }
    else if(URB_Status == URB_ERROR)
    {
      phost->Control.state = CTRL_ERROR;
      phost->Control.status = CTRL_XACTERR;
    }
    break;

  case CTRL_DATA_IN:
    /* Issue an IN token */
    USBH_CtlReceiveData(pdev,
                        phost->Control.buff,
                        phost->Control.length,
                        phost->Control.hc_num_in);

    phost->Control.state = CTRL_DATA_IN_WAIT;
    break;

  case CTRL_DATA_IN_WAIT:

    URB_Status = HCD_GetURB_State(pdev , phost->Control.hc_num_in);

    /* check is DATA packet transfered successfully */
    if  (URB_Status == URB_DONE)
    {
      phost->Control.state = CTRL_STATUS_OUT;
    }

    /* manage error cases*/
    if  (URB_Status == URB_STALL)
    {
      /* In stall case, return to previous machine state*/
      phost->gState =   phost->gStateBkp;
    }
    else if (URB_Status == URB_ERROR)
    {
      /* Device error */
      phost->Control.state = CTRL_ERROR;
    }
    else if ((HCD_GetCurrentFrame(pdev)- phost->Control.timer) > timeout)
    {
      /* timeout for IN transfer */
      phost->Control.state = CTRL_ERROR;
    }
    break;

  case CTRL_DATA_OUT:
    /* Start DATA out transfer (only one DATA packet)*/
    pdev->host.hc[phost->Control.hc_num_out].toggle_out = 1;

    USBH_CtlSendData (pdev,
                      phost->Control.buff,
                      phost->Control.length ,
                      phost->Control.hc_num_out);

    phost->Control.state = CTRL_DATA_OUT_WAIT;
    break;

  case CTRL_DATA_OUT_WAIT:

    URB_Status = HCD_GetURB_State(pdev , phost->Control.hc_num_out);
    if  (URB_Status == URB_DONE)
    { /* If the Setup Pkt is sent successful, then change the state */
      phost->Control.state = CTRL_STATUS_IN;
    }

    /* handle error cases */
    else if  (URB_Status == URB_STALL)
    {
      /* In stall case, return to previous machine state*/
      phost->gState =   phost->gStateBkp;
      phost->Control.state = CTRL_STALLED;
    }
    else if  (URB_Status == URB_NOTREADY)
    {
      /* Nack received from device */
      phost->Control.state = CTRL_DATA_OUT;
    }
    else if (URB_Status == URB_ERROR)
    {
      /* device error */
      phost->Control.state = CTRL_ERROR;
    }
    break;

  case CTRL_STATUS_IN:
    /* Send 0 bytes out packet */
    USBH_CtlReceiveData (pdev,
                         0,
                         0,
                         phost->Control.hc_num_in);

    phost->Control.state = CTRL_STATUS_IN_WAIT;

    break;

  case CTRL_STATUS_IN_WAIT:

    URB_Status = HCD_GetURB_State(pdev , phost->Control.hc_num_in);

    if  ( URB_Status == URB_DONE)
    { /* Control transfers completed, Exit the State Machine */
      phost->gState =   phost->gStateBkp;
      phost->Control.state = CTRL_COMPLETE;
    }

    else if (URB_Status == URB_ERROR)
    {
      phost->Control.state = CTRL_ERROR;
    }

    else if((HCD_GetCurrentFrame(pdev)\
      - phost->Control.timer) > timeout)
    {
      phost->Control.state = CTRL_ERROR;
    }
     else if(URB_Status == URB_STALL)
    {
      /* Control transfers completed, Exit the State Machine */
      phost->gState =   phost->gStateBkp;
      phost->Control.status = CTRL_STALL;
      status = USBH_NOT_SUPPORTED;
    }
    break;

  case CTRL_STATUS_OUT:
    pdev->host.hc[phost->Control.hc_num_out].toggle_out ^= 1;
    USBH_CtlSendData (pdev,
                      0,
                      0,
                      phost->Control.hc_num_out);

    phost->Control.state = CTRL_STATUS_OUT_WAIT;
    break;

  case CTRL_STATUS_OUT_WAIT:

    URB_Status = HCD_GetURB_State(pdev , phost->Control.hc_num_out);
    if  (URB_Status == URB_DONE)
    {
      phost->gState =   phost->gStateBkp;
      phost->Control.state = CTRL_COMPLETE;
    }
    else if  (URB_Status == URB_NOTREADY)
    {
      phost->Control.state = CTRL_STATUS_OUT;
    }
    else if (URB_Status == URB_ERROR)
    {
      phost->Control.state = CTRL_ERROR;
    }
    break;

  case CTRL_ERROR:
    /*
    After a halt condition is encountered or an error is detected by the
    host, a control endpoint is allowed to recover by accepting the next Setup
    PID; i.e., recovery actions via some other pipe are not required for control
    endpoints. For the Default Control Pipe, a device reset will ultimately be
    required to clear the halt or error condition if the next Setup PID is not
    accepted.
    */
    if (++ phost->Control.errorcount <= USBH_MAX_ERROR_COUNT)
    {
      /* Do the transmission again, starting from SETUP Packet */
      phost->Control.state = CTRL_SETUP;
    }
    else
    {
      phost->Control.status = CTRL_FAIL;
      phost->gState =   phost->gStateBkp;

      status = USBH_FAIL;
    }
    break;

  default:
    break;
  }
  return status;
}

/**
* @}
*/

/**
* @}
*/

/**
* @}
*/

/**
* @}
*/

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/


module Waitress

  # The DirHandler class is an instance of +Waitress::Handler+ that is responsible
  # for loading files from the filesystem and serving them if they exist in the VHost's
  # root. It automatically handles mimetypes, evaluation and almost everything about
  # the serving process for files in the FileSystem.
  class DirHandler < Handler

    attr_accessor :priority
    attr_accessor :directory

    # Get the instance of DirHandler that will load Waitress' resources
    # such as the default 404 and index pages, as well as CSS and JS
    def self.resources_handler
      @@resources_handler ||= Waitress::DirHandler.new(Waitress::Chef.resources_http, -1000)
      @@resources_handler
    end

    # Create a new DirHandler, with the given FileSystem directory as a root
    # and priority.
    def initialize directory, priority=50
      @directory = File.absolute_path(directory)
      @priority = priority
    end

    def respond? request, vhost
      path = File.expand_path File.join("#{directory}", request.path)
      res = Waitress::Chef.find_file(path)[:result]
      path.include?(directory) && (res == :ok)
    end

    def serve request, response, client, vhost
      path = File.expand_path File.join("#{directory}", request.path)
      file = Waitress::Chef.find_file(path)[:file]
      Waitress::Chef.serve_file request, response, client, vhost, file
    end

  end
end


.class public abstract Landroid/app/ActivityView$ActivityViewCallback;
.super Ljava/lang/Object;
.source "ActivityView.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/app/ActivityView;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x409
    name = "ActivityViewCallback"
.end annotation

# direct methods
.method public constructor <init>()V
    .locals 0

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public abstract onAllActivitiesComplete(Landroid/app/ActivityView;)V
.end method

.method public abstract onSurfaceAvailable(Landroid/app/ActivityView;)V
.end method

.method public abstract onSurfaceDestroyed(Landroid/app/ActivityView;)V
.end method


package io.jvertx.core.eb;

import io.vertx.core.Vertx;
import io.vertx.core.eventbus.EventBus;

/**
 * @author YYL on 2017/7/19
 */
public class App {

    public static void main(String[] args) {
        Vertx vertx = Vertx.vertx();
        EventBus eb = vertx.eventBus();
        eb.consumer("im.msg", message ->{
            System.out.println(message.body());
            message.reply("ok");
        });
//        eb.publish("im.msg", "first message !");
//        eb.send("im.msg", "second message !", result ->{
//            if (result.succeeded()){
//                System.out.println(result.result().body());
//            }
//        });
        EventBus bus = vertx.eventBus();
        bus.send("im.msg", "other bus");
    }
}


from setuptools import setup

with open('README.rst') as readme_file:
    readme = readme_file.read()

with open('HISTORY.rst') as history_file:
    history = history_file.read()

requirements = [
    'docopt',
    'python-wordpress-xmlrpc',
    'requests',
    # TODO: put package requirements here
]

test_requirements = [
    # TODO: put package test requirements here
]

setup(
    name='wordpress_importer',
    version='0.1.0',
    description="Utility to import data into wordpress from CSV using a template.",
    long_description=readme + '\n\n' + history,
    author="James Brink",
    author_email='brink.james@gmail.com',
    url='https://github.com/jamesbrink/wordpress_importer',
    packages=[
        'wordpress_importer',
    ],
    package_dir={'wordpress_importer':
                 'wordpress_importer'},
    include_package_data=True,
    install_requires=requirements,
    license="MIT license",
    zip_safe=False,
    keywords='wordpress_importer',
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: English',
        "Programming Language :: Python :: 2",
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
    ],
    scripts=['scripts/wordpress_importer', ],
    test_suite='tests',
    tests_require=test_requirements
)


/**
 * Autogenerated by Thrift Compiler (0.10.0)
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */
#include "credential_store_data_models_constants.h"

const credential_store_data_modelsConstants g_credential_store_data_models_constants;

credential_store_data_modelsConstants::credential_store_data_modelsConstants() {
  DEFAULT_ID = "DO_NOT_SET_AT_CLIENTS";

}


package org.asynchttpclient.providers.netty4;

import org.asynchttpclient.AsyncHttpClient;
import org.asynchttpclient.AsyncHttpClientConfig;
import org.asynchttpclient.async.IdleStateHandlerTest;

public class NettyIdleStateHandlerTest extends IdleStateHandlerTest {
    @Override
    public AsyncHttpClient getAsyncHttpClient(AsyncHttpClientConfig config) {
        return NettyProviderUtil.nettyProvider(config);
    }
}


#ifndef HISTOGRAMS_HH
#define HISTOGRAMS_HH

#include <vector>

/**
 * Save histogram data to file.
 *
 * Will save file with four data points for each histogram bin:
 *  bin_start     Low edge of bin
 *  bin_end       High edge of bin
 *  count         Absolute count of values in bin
 *  relcount      Relative count (i.e., divided by total number of values)
 *
 * Arguments:
 *  v           - Vector containing all values
 *  dm          - Bin width
 *  filename    - Name of file to save to
**/
void save_histogram(const std::vector<double> &v, double dm, const char *filename);

#endif


package com.bq.corbel.iam.service;

import com.google.common.collect.Sets;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import com.bq.corbel.iam.auth.AuthorizationRequestContextFactory;
import com.bq.corbel.iam.exception.UnauthorizedException;
import com.bq.corbel.iam.model.Scope;
import com.bq.corbel.iam.model.UserToken;
import com.bq.corbel.iam.repository.UserTokenRepository;
import com.bq.corbel.lib.token.TokenInfo;
import com.bq.corbel.lib.token.reader.TokenReader;
import net.oauth.jsontoken.JsonToken;
import net.oauth.jsontoken.JsonTokenParser;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import java.security.SignatureException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static org.mockito.Mockito.*;

@RunWith(MockitoJUnitRunner.class) public class DefaultUpgradeTokenServiceTest {

    private static final String TEST_ASSERTION = "123.456.789";
    private static final String TEST_TOKEN = "the_access_token";
    private static final String TEST_CLIENT = "client";
    private static final String TEST_DOMAIN = "domain";
    private static final String TEST_USER = "user";
    private static final String TEST_SCOPES = "SCOPE_1 SCOPE_2";

    @Mock private JsonTokenParser jsonTokenParser;
    @Mock private AuthorizationRequestContextFactory contextFactory;
    @Mock private ScopeService scopeServiceMock;
    @Mock private TokenInfo accessToken;
    @Mock private TokenReader tokenReader;
    @Mock private UserTokenRepository userTokenRepositoryMock;

    private UpgradeTokenService upgradeTokenService;

    @Before
    public void setUp() {
        upgradeTokenService = new DefaultUpgradeTokenService(jsonTokenParser, scopeServiceMock, userTokenRepositoryMock);
        when(accessToken.getClientId()).thenReturn(TEST_CLIENT);
        when(accessToken.getUserId()).thenReturn(TEST_USER);
        when(accessToken.getDomainId()).thenReturn(TEST_DOMAIN);
        when(accessToken.toString()).thenReturn(TEST_TOKEN);
        when(tokenReader.getInfo()).thenReturn(accessToken);
        when(tokenReader.getToken()).thenReturn(TEST_TOKEN);
    }

    @Test
    public void upgradeTokenTest() throws SignatureException, UnauthorizedException {
        JsonToken validJsonToken = mock(JsonToken.class);
        JsonObject json = new JsonObject();
        json.add("scope", new JsonPrimitive(TEST_SCOPES));
        when(validJsonToken.getPayloadAsJsonObject()).thenReturn(json);
        Scope scope1 = mock(Scope.class);
        Scope scope2 = mock(Scope.class);
        Set<Scope> scopes = new HashSet<Scope>(Arrays.asList(scope1, scope2));
        Set<String> scopesIds = new HashSet<String>(Arrays.asList("SCOPE_1", "SCOPE_2"));
        UserToken userToken = new UserToken();
        userToken.setScopes(new HashSet<>());

        when(scopeServiceMock.expandScopes(scopesIds)).thenReturn(scopes);
        when(scopeServiceMock.fillScopes(scopes, TEST_USER, TEST_CLIENT, TEST_DOMAIN)).thenReturn(scopes);
        when(userTokenRepositoryMock.findByToken(TEST_TOKEN)).thenReturn(userToken);

        when(jsonTokenParser.verifyAndDeserialize(TEST_ASSERTION)).thenReturn(validJsonToken);

        Set<String> scopesToAdd = upgradeTokenService.getScopesFromTokenToUpgrade(TEST_ASSERTION);
        upgradeTokenService.upgradeToken(TEST_ASSERTION, tokenReader, scopesToAdd);

        verify(scopeServiceMock).fillScopes(scopes, TEST_USER, TEST_CLIENT, TEST_DOMAIN);
        verify(scopeServiceMock).addAuthorizationRules(TEST_TOKEN, scopes);
    }

    @Test(expected = UnauthorizedException.class)
    public void upgradeTokenNonexistentScopeTest() throws SignatureException, UnauthorizedException {
        JsonToken validJsonToken = mock(JsonToken.class);
        JsonObject json = new JsonObject();
        json.add("scope", new JsonPrimitive(TEST_SCOPES));
        when(validJsonToken.getPayloadAsJsonObject()).thenReturn(json);

        doThrow(new IllegalStateException("Nonexistent scope scopeId")).when(scopeServiceMock).addAuthorizationRules(anyString(), anySet());

        when(jsonTokenParser.verifyAndDeserialize(TEST_ASSERTION)).thenReturn(validJsonToken);

        Set<String> scopes = upgradeTokenService.getScopesFromTokenToUpgrade(TEST_ASSERTION);
        upgradeTokenService.upgradeToken(TEST_ASSERTION, tokenReader, scopes);
    }

    @Test
    public void upgradeTokenEmptyScopeTest() throws SignatureException, UnauthorizedException {
        Set<Scope> scopes = new HashSet<>();
        JsonToken validJsonToken = mock(JsonToken.class);
        JsonObject json = new JsonObject();
        json.add("scope", new JsonPrimitive(""));
        UserToken userToken = new UserToken();
        userToken.setScopes(new HashSet<>());
        when(validJsonToken.getPayloadAsJsonObject()).thenReturn(json);
        when(jsonTokenParser.verifyAndDeserialize(TEST_ASSERTION)).thenReturn(validJsonToken);
        when(userTokenRepositoryMock.findByToken(TEST_TOKEN)).thenReturn(userToken);
        when(scopeServiceMock.fillScopes(any(), any(), any(), any())).thenReturn(Sets.newHashSet());

        Set<String> scopesToAdd = upgradeTokenService.getScopesFromTokenToUpgrade(TEST_ASSERTION);
        upgradeTokenService.upgradeToken(TEST_ASSERTION, tokenReader, scopesToAdd);

        verify(scopeServiceMock).fillScopes(scopes, TEST_USER, TEST_CLIENT, TEST_DOMAIN);
        verify(scopeServiceMock).addAuthorizationRules(TEST_TOKEN, scopes);
    }
}


package com.nebhale.buildmonitor.web;

import com.nebhale.buildmonitor.ApplicationConfiguration;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.jdbc.JdbcTestUtils;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.util.StringUtils;
import org.springframework.web.context.WebApplicationContext;

import javax.sql.DataSource;
import javax.transaction.Transactional;
import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;

import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = ApplicationConfiguration.class)
@Transactional
@WebAppConfiguration
public abstract class AbstractControllerTest {

    private volatile JdbcTemplate jdbcTemplate;

    volatile MockMvc mockMvc;

    @Autowired
    final void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

    @Autowired
    final void setWebApplicationContext(WebApplicationContext webApplicationContext) {
        this.mockMvc = webAppContextSetup(webApplicationContext).build();
    }

    final int countRowsInTable(String tableName) {
        return JdbcTestUtils.countRowsInTable(this.jdbcTemplate, tableName);
    }

    final String toJson(String... pairs) {
        StringBuilder sb = new StringBuilder("{ ");

        Set<String> entries = Arrays.stream(pairs).map(pair -> {
            String[] parts = StringUtils.split(pair, ":");
            return String.format("\"%s\" : \"%s\"", parts[0], parts[1]);
        }).collect(Collectors.toSet());

        sb.append(StringUtils.collectionToDelimitedString(entries, ", "));

        return sb.append(" }").toString();
    }

}


.. _manual:

User Guide
==========

.. include:: installation.rst

.. include:: basic_usage.rst

.. include:: formats.rst

.. include:: piped_output.rst

.. include:: jupyter_notebooks.rst

.. include:: styling.rst

.. _attributes:
.. include:: attributes.rst

.. _node-ports-compass:
.. include:: node_ports.rst

.. _backslash-escapes:
.. include:: escapes.rst

.. _quoting-and-html-like-labels:
.. include:: quoting.rst

.. _subgraphs-clusters:
.. include:: subgraphs_and_clusters.rst

.. _engines:
.. include:: engines.rst

.. include:: neato_no_op.rst

.. include:: unflatten.rst

.. include:: custom_dot.rst

.. _using-raw-dot:
.. include:: raw_dot.rst

.. include:: existing_files.rst

.. include:: integration_with_viewers.rst


/* ** GENEREATED FILE - DO NOT MODIFY ** */
package com.wilutions.mslib.outlook.impl;
import com.wilutions.com.*;

@SuppressWarnings("all")
@CoClass(guid="{C091A9EE-A463-DB41-5DAE-69E7A5F7FCBC}")
public class SyncObjectEventsImpl extends Dispatch implements com.wilutions.mslib.outlook.SyncObjectEvents {
  @DeclDISPID(61441)  public void onSyncStart() throws ComException {
    this._dispatchCall(61441,"SyncStart", DISPATCH_METHOD,null);
  }
  @DeclDISPID(61442)  public void onProgress(final com.wilutions.mslib.outlook.OlSyncState State, final String Description, final Integer Value, final Integer Max) throws ComException {
    assert(State != null);
    assert(Description != null);
    assert(Value != null);
    assert(Max != null);
    this._dispatchCall(61442,"Progress", DISPATCH_METHOD,null,State.value,Description,Value,Max);
  }
  @DeclDISPID(61443)  public void onOnError(final Integer Code, final String Description) throws ComException {
    assert(Code != null);
    assert(Description != null);
    this._dispatchCall(61443,"OnError", DISPATCH_METHOD,null,Code,Description);
  }
  @DeclDISPID(61444)  public void onSyncEnd() throws ComException {
    this._dispatchCall(61444,"SyncEnd", DISPATCH_METHOD,null);
  }
  public SyncObjectEventsImpl(String progId) throws ComException {
    super(progId, "{00063085-0000-0000-C000-000000000046}");
  }
  protected SyncObjectEventsImpl(long ndisp) {
    super(ndisp);
  }
  public String toString() {
    return "[SyncObjectEventsImpl" + super.toString() + "]";
  }
}


<?php
namespace PHPServices;

class Module
{
    public function getConfig()
    {
        return include __DIR__ . '/../../config/module.config.php';
    }
}


'------------------------------------------------------------------------------
' <auto-generated>
'     This code was generated by a tool.
'     Runtime Version:4.0.30319.42000
'
'     Changes to this file may cause incorrect behavior and will be lost if
'     the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------

Option Strict On
Option Explicit On

Imports System

Namespace My.Resources

    'This class was auto-generated by the StronglyTypedResourceBuilder
    'class via a tool like ResGen or Visual Studio.
    'To add or remove a member, edit your .ResX file then rerun ResGen
    'with the /str option, or rebuild your VS project.
    '''
    '''  A strongly-typed resource class, for looking up localized strings, etc.
    '''
    <Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0"),  _
     Global.System.Diagnostics.DebuggerNonUserCodeAttribute(),  _
     Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(),  _
     Global.Microsoft.VisualBasic.HideModuleNameAttribute()>  _
    Friend Module Resources

        Private resourceMan As Global.System.Resources.ResourceManager

        Private resourceCulture As Global.System.Globalization.CultureInfo

        '''
        '''  Returns the cached ResourceManager instance used by this class.
        '''
        <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)>  _
        Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager
            Get
                If Object.ReferenceEquals(resourceMan, Nothing) Then
                    Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("Runtime.Shared.Resources", GetType(Resources).Assembly)
                    resourceMan = temp
                End If
                Return resourceMan
            End Get
        End Property

        '''
        '''  Overrides the current thread's CurrentUICulture property for all
        '''  resource lookups using this strongly typed resource class.
        '''
        <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)>  _
        Friend Property Culture() As Global.System.Globalization.CultureInfo
            Get
                Return resourceCulture
            End Get
            Set
                resourceCulture = value
            End Set
        End Property
    End Module
End Namespace


import json
import re
import requests
from datetime import datetime, timedelta
import os
from dateutil import parser
from src.sgd.frontend import config

BLOG_BASE_URL = 'https://public-api.wordpress.com/rest/v1.1/sites/yeastgenomeblog.wordpress.com/posts'
BLOG_PAGE_SIZE = 10
HOMEPAGE_REQUEST_TIMEOUT = 2
URL_REGEX = 'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+'

# from https://public-api.wordpress.com/rest/v1.1/sites/sgdblogtest.wordpress.com/categories
wp_categories = [
    {
        'name': 'Conferences',
        'slug': 'conferences'
    },
    {
        'name': 'Data updates',
        'slug': 'data-updates'
    },
    {
        'name': 'Homologs',
        'slug': 'homologs'
    },
    {
        'name': 'New Data',
        'slug': 'new-data'
    },
    {
        'name': 'News and Views',
        'slug': 'news-and-views'
    },
    {
        'name': 'Newsletter',
        'slug': 'newsletter'
    },
    {
        'name': 'Research Spotlight',
        'slug': 'research-spotlight'
    },
    {
        'name': 'Sequence',
        'slug': 'sequence'
    },
    {
        'name': 'Tutorial',
        'slug': 'tutorial'
    },
    {
        'name': 'Uncategorized',
        'slug': 'uncategorized'
    },
    {
        'name': 'Website changes',
        'slug': 'website-changes'
    },
    {
        'name': 'Yeast and Human Disease',
        'slug': 'yeast-and-human-disease'
    },
    {
        'name': 'Announcements',
        'slug': 'announcements'
    }
]

def get_wp_categories():
    return sorted(wp_categories, key=lambda k: k['name'])

def get_archive_years():
    now = datetime.now()
    this_year = now.year
    archive_years = []
    for i in range(7):
        archive_years.append(this_year - i)
    return archive_years

def get_recent_blog_posts():
    wp_url = BLOG_BASE_URL + '?number=5'
    try:
        response = requests.get(wp_url, timeout=HOMEPAGE_REQUEST_TIMEOUT)
        blog_posts = json.loads(response.text)['posts']
        for post in blog_posts:
            post = add_simple_date_to_post(post)
    except Exception as e:
        blog_posts = []
    return blog_posts

# fetch "SGD Public Events" google calendar data and format as needed for homepage
def get_meetings():
    try:
        calendar_url = config.google_calendar_api_url
        response = requests.get(calendar_url, timeout=HOMEPAGE_REQUEST_TIMEOUT)
        meetings = json.loads(response.text)['items']
        # only get "all day" events
        meetings = [d for d in meetings if 'date' in list(d['start'].keys())]
        for meeting in meetings:
            if 'description' not in list(meeting.keys()):
                meeting['description'] = ''
            # get URL from description and remove URLs from description
            urls = re.findall(URL_REGEX, meeting['description'])
            if len(urls) > 0:
                url = urls[0]
            else:
                url = None
            meeting['url'] = url
            meeting['description'] = re.sub(URL_REGEX, '', meeting['description'])
            # format date as a string which is either a single day or range of dates
            start_date = datetime.strptime(meeting['start']['date'], '%Y-%m-%d')
            end_date = datetime.strptime(meeting['end']['date'], '%Y-%m-%d') - timedelta(days=1)
            meeting['start_date'] = start_date
            days_delta = (end_date - start_date).days
            if (days_delta >= 1):
                start_desc = start_date.strftime('%B %d')
                end_desc = end_date.strftime('%B %d, %Y')
                date_description = start_desc + ' to ' + end_desc
            else:
                date_description = start_date.strftime('%B %d, %Y')
            meeting['date_description'] = date_description
        # filter to only show future events
        now = datetime.now()
        meetings = [d for d in meetings if d['start_date'] > now]
        # sort by start date
        meetings = sorted(meetings, key=lambda d: d['start_date'])
    except Exception as e:
        meetings = []
    return meetings

def add_simple_date_to_post(raw):
    simple_date = parser.parse(raw['date']).strftime("%B %d, %Y")
    raw['simple_date'] = simple_date
    return raw


use super::camera::*;
use super::GameContext;
use super::event_manager::*;
use glium::glutin::{CursorState, ElementState, Event, MouseButton, VirtualKeyCode};
use std::rc::Rc;

pub struct Ghost {
    cam: Camera,
    context: Rc<GameContext>,
    speed: f32,
    forward: bool,
    backward: bool,
    left: bool,
    right: bool,
    up: bool,
    down: bool,
    mouselock: bool,
}

// Speed per second
const DEFAULT_SPEED: f32 = 12.0;
const SHIFT_SPEED: f32 = 60.0;

impl Ghost {
    pub fn new(context: Rc<GameContext>) -> Self {
        Ghost {
            cam: Camera::new(context.get_config().resolution.aspect_ratio()),
            context: context,
            speed: DEFAULT_SPEED,
            forward: false,
            backward: false,
            left: false,
            right: false,
            up: false,
            down: false,
            mouselock: false,
        }
    }
    pub fn update(&mut self, delta: f32) {
        let factored_speed = self.speed * delta;

        if self.forward {
            self.cam.move_forward(factored_speed);
        }
        if self.backward {
            self.cam.move_backward(factored_speed);
        }
        if self.left {
            self.cam.move_left(factored_speed);
        }
        if self.right {
            self.cam.move_right(factored_speed);
        }
        if self.up {
            self.cam.move_up(factored_speed);
        }
        if self.down {
            self.cam.move_down(factored_speed);
        }
    }

    pub fn get_camera(&self) -> Camera {
        self.cam
    }
    pub fn set_camera(&mut self, cam: Camera) {
        self.cam = cam;
    }
}

/// **Implements Controls**
/// *W => FORWARD
/// *A => LEFT
/// *S => BACKWARDS
/// *D => RIGHT
/// *'Space' => UP
/// *'LControl' => DOWN (only accepts one keystroke (cannot hold LControl to go
/// down))
/// *'C' => DOWN (as a replacement for 'LControl')

/// MouseMovement for changing the direction the camera looks
impl EventHandler for Ghost {
    fn handle_event(&mut self, e: &Event) -> EventResponse {
        match *e {
            Event::KeyboardInput(ElementState::Pressed, _, Some(VirtualKeyCode::W)) => {
                self.forward = true;
                EventResponse::Continue
            }
            Event::KeyboardInput(ElementState::Released, _, Some(VirtualKeyCode::W)) => {
                self.forward = false;
                EventResponse::Continue
            }
            Event::KeyboardInput(ElementState::Pressed, _, Some(VirtualKeyCode::S)) => {
                self.backward = true;
                EventResponse::Continue
            }
            Event::KeyboardInput(ElementState::Released, _, Some(VirtualKeyCode::S)) => {
                self.backward = false;
                EventResponse::Continue
            }
            Event::KeyboardInput(ElementState::Pressed, _, Some(VirtualKeyCode::A)) => {
                self.left = true;
                EventResponse::Continue
            }
            Event::KeyboardInput(ElementState::Released, _, Some(VirtualKeyCode::A)) => {
                self.left = false;
                EventResponse::Continue
            }
            Event::KeyboardInput(ElementState::Pressed, _, Some(VirtualKeyCode::D)) => {
                self.right = true;
                EventResponse::Continue
            }
            Event::KeyboardInput(ElementState::Released, _, Some(VirtualKeyCode::D)) => {
                self.right = false;
                EventResponse::Continue
            }
            Event::KeyboardInput(ElementState::Pressed, _, Some(VirtualKeyCode::Space)) => {
                self.up = true;
                EventResponse::Continue
            }
            Event::KeyboardInput(ElementState::Released, _, Some(VirtualKeyCode::Space)) => {
                self.up = false;
                EventResponse::Continue
            }
            Event::KeyboardInput(ElementState::Pressed, _, Some(VirtualKeyCode::LControl)) => {
                self.down = true;
                EventResponse::Continue
            }
            Event::KeyboardInput(ElementState::Released, _, Some(VirtualKeyCode::LControl)) => {
                self.down = false;
                EventResponse::Continue
            }
            Event::KeyboardInput(ElementState::Pressed, _, Some(VirtualKeyCode::LShift)) => {
                self.speed = SHIFT_SPEED;
                EventResponse::Continue
            }
            Event::KeyboardInput(ElementState::Released, _, Some(VirtualKeyCode::LShift)) => {
                self.speed = DEFAULT_SPEED;
                EventResponse::Continue
            }
            Event::KeyboardInput(ElementState::Released, _, Some(VirtualKeyCode::G)) => {
                EventResponse::Continue
            }
            Event::MouseInput(ElementState::Pressed, MouseButton::Left) => {
                if !self.mouselock {
                    self.mouselock = true;
                    if let Some(window) = self.context.get_facade().get_window() {
                        window.set_cursor_state(CursorState::Hide)
                            .expect("failed to set cursor state");
                    } else {
                        warn!("Failed to obtain window from facade");
                    }
                } else if self.mouselock {
                    self.mouselock = false;

                    if let Some(window) = self.context.get_facade().get_window() {
                        window.set_cursor_state(CursorState::Normal)
                            .expect("failed to set cursor state");
                    } else {
                        warn!("Failed to obtain window from facade");
                    }
                }

                EventResponse::Continue
            }

            Event::MouseMoved(x, y) => {
                if self.mouselock {
                    if let Some(window) = self.context.get_facade().get_window() {
                        // Possibility of mouse being outside of window without it resetting to the
                        // middle?
                        if let Some(middle) = window.get_inner_size_pixels() {
                            let middle_x = (middle.0 as i32) / 2;
                            let middle_y = (middle.1 as i32) / 2;
                            let x_diff = x - middle_x;
                            let y_diff = y - middle_y;
                            self.cam.change_dir(y_diff as f32 / 300.0, -x_diff as f32 / 300.0);
                            window.set_cursor_position(middle_x as i32, middle_y as i32)
                                .expect("setting cursor position failed");
                        }
                    }
                }
                EventResponse::Continue
            }
            _ => EventResponse::NotHandled,
        }
    }
}


package joshie.harvest.animals.type;

import joshie.harvest.animals.HFAnimals;
import joshie.harvest.animals.item.ItemAnimalProduct.Sizeable;
import joshie.harvest.animals.item.ItemAnimalSpawner.Spawner;
import joshie.harvest.api.animals.AnimalAction;
import joshie.harvest.api.animals.AnimalStats;
import joshie.harvest.core.helpers.SizeableHelper;
import net.minecraft.item.ItemStack;

import java.util.List;

import static joshie.harvest.api.animals.AnimalFoodType.SEED;

public class AnimalChicken extends AnimalAbstract {
    public AnimalChicken() {
        super("chicken", 3, 10, SEED);
    }

    @Override
    public ItemStack getIcon() {
        return HFAnimals.ANIMAL.getStackFromEnum(Spawner.CHICKEN);
    }

    @Override
    public int getRelationshipBonus(AnimalAction action) {
        switch (action) {
            case OUTSIDE:   return 5;
            case FEED:      return 100;
        }

        return super.getRelationshipBonus(action);
    }

    @Override
    public ItemStack getProduct(AnimalStats stats) {
        return SizeableHelper.getEgg(stats);
    }

    @Override
    public List<ItemStack> getProductsForDisplay(AnimalStats stats) {
        return SizeableHelper.getSizeablesForDisplay(stats, Sizeable.EGG);
    }

    @Override
    public int getDaysBetweenProduction() {
        return 1;
    }

    @Override
    public int getGenericTreatCount() {
        return 5;
    }

    @Override
    public int getTypeTreatCount() {
        return 26;
    }
}


require 'spec_helper'

describe Marathon::Util do

  describe '.validate_choice' do
    subject { described_class }

    it 'passes with valid value' do
      described_class.validate_choice('foo', 'bar', %w[f00 bar], false)
    end

    it 'passes with nil value' do
      described_class.validate_choice('foo', nil, %w[f00], true)
    end

    it 'fails with nil value' do
      expect {
        described_class.validate_choice('foo', nil, %w[f00], false)
      }.to raise_error(Marathon::Error::ArgumentError)
    end

    it 'fails with invalid value' do
      expect {
        described_class.validate_choice('foo', 'bar', %w[f00], false)
      }.to raise_error(Marathon::Error::ArgumentError)
    end
  end

  describe '.add_choice' do
    subject { described_class }

    it 'validates choice first' do
      expect(described_class).to receive(:validate_choice).with('foo', 'bar', %w[f00 bar], false)
      described_class.add_choice({}, 'foo', 'bar', %w[f00 bar], false)
    end

    it 'adds choice' do
      opts = {}
      described_class.add_choice(opts, 'foo', 'bar', %w[f00 bar], false)
      expect(opts['foo']).to eq('bar')
    end
  end

  describe '.keywordize_hash!' do
    subject { described_class }

    it 'keywordizes the hash' do
      hash = {
        'foo'      => 'bar',
        'f00'      => {'w00h00'  => 'yeah'},
        'bang'     => [{'tricky' => 'one'}],
        'env'      => {'foo' => 'bar'},
        'null'     => nil
      }

      expect(subject.keywordize_hash!(hash)).to eq({
        :foo  => 'bar',
        :f00  => {:w00h00  => 'yeah'},
        :bang => [{:tricky => 'one'}],
        :env  => {'foo' => 'bar'},
        :null => nil
      })
      # make sure, it changes the hash w/o creating a new one
      expect(hash[:foo]).to eq('bar')
    end
  end

  describe '.remove_keys' do
    subject { described_class }

    it 'removes keys from hash' do
      hash = {
        :foo      => 'bar',
        :deleteme => {'w00h00'  => 'yeah'},
        :blah     => [{:deleteme => :foo}, 1]
      }

      expect(subject.remove_keys(hash, [:deleteme])).to eq({
        :foo  => 'bar',
        :blah => [{}, 1]
      })
      # make sure, it does not changes the original hash
      expect(hash.size).to eq(3)
    end
  end

end


package saltchannel.dev;

public interface ServerSessionFactory {
    public ByteChannelServerSession createSession();
}


#include <CtrlLib/CtrlLib.h>

using namespace Upp;

#include <LogCtrl/LogCtrl.h>

#define LAYOUTFILE <LogCtrlTest/LogCtrlTest.lay>
#include <CtrlCore/lay.h>

class LogCtrlTest : public WithLogCtrlTestLayout<TopWindow> {
public:
	typedef LogCtrlTest CLASSNAME;
	LogCtrlTest();

	void Clear() { log.Clear(); }
	void Save() { log.Save(); }

	LogCtrl log;
};

#endif