text:
<?php
//ini_set('display_errors', 'on');
//ini_set('error_reporting', E_ALL);
if (!empty($_POST['printID'])) {
    $printID = $_POST['printID'];
    $EmpID = $_POST['EmpID'];
    $ReceiptCode = "";
    $splt = ",";
    $i = 0 ;
    foreach($printID as $x => $x_value) {
        if ($i != 0) {
          $ReceiptCode .= ",";
        }
        $i++;
        $ReceiptCode .= $x_value;
    }

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,"http://app.thiensurat.co.th/tsr_ASP_tsr_SaleAdvance/webservice.asmx/Insert_AddReceiptCode");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, "empid=$EmpID&datalist=$ReceiptCode&splt=$splt");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec ($ch);
    curl_close ($ch);
    /*
    $WHERE1 = "WHERE R.ReceiptCode IN ($ReceiptCode)";

    $SQLPrint = "SELECT distinct e.empid,
    (select TSRData_Source.dbo.fn_convertDatetothai(R.DatePayment)) as PaymentDueDate,
    R.ReceiptCode
    ,R.ZoneCode,E.FirstName+' '+E.LastName AS EmpName
    ,C.CONTNO ,C.SALES,C.ProductSerialNumber,C.MODEL,C.MODE
    ,P.ProductName
    ,DC.CustomerName
    ,SP.PaymentPeriodNumber , R.TotalPayment AS NetAmount
    ,REPLACE(REPLACE(REPLACE(AD.AddressDetail+ ' หมู่ ' + AD.AddressDetail2 + ' ซอย ' + AD.AddressDetail3 + ' ถนน ' + AD.AddressDetail4
    ,'หมู่ -',' '),'ซอย -',' '),'ถนน -',' ') AS ADDRESS1
    ,' ต. ' +(SELECT SubDistrictName FROM Bighead_Mobile.dbo.SubDistrict WHERE SubDistrictCode = AD.SubDistrictCode)
    + ' อ. ' +(SELECT DistrictName FROM Bighead_Mobile.dbo.District WHERE DistrictCode = AD.DistrictCode)
    + ' จ. ' +(SELECT ProvinceName FROM Bighead_Mobile.dbo.Province WHERE ProvinceCode = AD.ProvinceCode)
    +' รหัสไปรษณีย์ ' + Zipcode AS ADDRESS2
    ,ISNULL(CASE WHEN SP.PaymentComplete = 1 THEN (SELECT SUM(NetAmount) FROM Bighead_Mobile.dbo.SalePaymentPeriod WHERE refno = C.RefNo AND PaymentPeriodNumber > Sp.PaymentPeriodNumber) ELSE SP.NetAmount - R.TotalPayment + (SELECT SUM(NetAmount) FROM Bighead_Mobile.dbo.SalePaymentPeriod WHERE refno = C.RefNo AND PaymentPeriodNumber > Sp.PaymentPeriodNumber) END,0) AS Balance
    FROM TSRData_Source.dbo.vw_ReceiptWithZone AS R
    INNER JOIN Bighead_Mobile.dbo.Contract AS C ON R.RefNo = C.RefNo
    INNER JOIN Bighead_Mobile.dbo.DebtorCustomer AS DC ON C.CustomerID = DC.CustomerID
    INNER JOIN Bighead_Mobile.dbo.Employee AS E ON R.CreateBy = EmpID
    LEFT JOIN Bighead_Mobile.dbo.Product AS P ON P.ProductID = C.ProductID
    LEFT JOIN Bighead_Mobile.dbo.SalePaymentPeriodPayment AS SPP ON SPP.ReceiptID = R.ReceiptID
    LEFT JOIN Bighead_Mobile.dbo.SalePaymentPeriod AS SP ON SPP.SalePaymentPeriodID = SP.SalePaymentPeriodID
    LEFT JOIN Bighead_Mobile.dbo.MigrateReportDailyReceiptB AS B ON B.InvNo = R.ReceiptCode
    LEFT JOIN Bighead_Mobile.dbo.Address AS AD ON AD.RefNo = C.RefNo AND AD.AddressTypeCode = 'AddressPayment'
    $WHERE1";
    //ECHO $SQLPrint;

    $conns = connectDB_TSR();
    // เพิ่มลงฐานข้อมูล
    $sql_insert = "INSERT INTO TSR_Application.dbo.TSS_ReportCredit_2_sys (Empid,[SQLtext],addtime,rpttype) VALUES (?,?,GETDATE(),99)";
    //echo $sql_insert;

    $params = array($_POST['EmpID'],$SQLPrint);
    //print_r($params);

    $stmt_insert = sqlsrv_query( $conns, $sql_insert, $params);

    if( $stmt_insert === false ) {
       die( print_r( sqlsrv_errors(), true));
    }
    sqlsrv_close($conns);
    */
    $conns = connectDB_BigHead();
    foreach($printID as $y => $y_value) {
        // เพิ่มลงฐานข้อมูล
        $sql_insert = "INSERT INTO TSRData_Source.dbo.TSSM_LOG_PrintReceipt_BOF (Empid,ReceiptCode,StampTime) VALUES (?,?,GETDATE())";
        //echo $sql_insert;

        $params = array($_POST['EmpID'],$y_value);
        //print_r($params);

        $stmt_insert = sqlsrv_query( $conns, $sql_insert, $params);

        if( $stmt_insert === false ) {
           die( print_r( sqlsrv_errors(), true));
        }
    }
    sqlsrv_close($conns);

    ?>
    <META HTTP-EQUIV="Refresh" CONTENT="0;URL=http://app.thiensurat.co.th/tsr_ASP_tsr_SaleAdvance/frm_PrintReceipt_D.aspx?empid=<?=$_POST['EmpID']?>">
    <?PHP
  }

if (empty($_REQUEST['searchDate'])) {
  $searchDate = DateThai(date('Y-m-d'));
  $WHERE = " datediff(DAY,R.DatePayment,GETDATE())=0 ";
  $top = "TOP 10";
}else {
  $searchDate = DateThai(DateEng($_REQUEST['searchDate']));
  $WHERE = " R.DatePayment BETWEEN '".DateEng($_REQUEST['searchDate'])." 00:00' AND '".DateEng($_REQUEST['searchDate'])." 23:59'";
  $top = "";
}

if (empty($_REQUEST['startDate']) && empty($_REQUEST['endDate'])) {
  $searchDate = DateThai(date('Y-m-d'));
  $WHERE = " datediff(DAY,R.DatePayment,GETDATE())=0 ";
  $top = "TOP 10";
}else {
  $searchDate = DateThai(DateEng($_REQUEST['startDate']))." - ".DateThai(DateEng($_REQUEST['endDate']));
  $WHERE = " R.DatePayment BETWEEN '".DateEng($_REQUEST['startDate'])." 00:00' AND '".DateEng($_REQUEST['endDate'])." 23:59'";
  $top = "";
}

if (($_COOKIE['tsr_emp_permit'] == 4 )) {
  if (substr($_COOKIE['tsr_emp_id'],0,1) == "0") {
    $EmpID['0'] = "A".substr($_COOKIE['tsr_emp_id'],1,5);
    $EmpID['1'] = $_COOKIE['tsr_emp_name'];

    $connss = connectDB_BigHead();
    $sql_Empid = "SELECT SaleCode FROM Bighead_Mobile.dbo.EmployeeDetail WHERE EmployeeCode = '".$EmpID['0']."' AND salecode is not null";

    //echo $sql_Empid;

    $stmt = sqlsrv_query($connss,$sql_Empid);
    while ($rowss = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)) {
      $EmpID['2'] = $rowss['SaleCode'];
    }

    sqlsrv_close($connss);

    $WHERE .= " AND R.ZoneCode = '".$EmpID['2']."'";

  }
}else {
  //echo $_REQUEST['EmpID'];
  if (!empty($_REQUEST['EmpID'])) {
    //$EmpID = array('0','-');
    $EmpID = explode("_",$_REQUEST['EmpID']);
    $WHERE .= " AND R.ZoneCode = '".$EmpID['2']."'";
  }

}
  $conn = connectDB_BigHead();
 ?>

        <form role="form" data-toggle="validator" id="formSearch" name="formSearch" method="post" action="index.php?pages=reportOperPrintReceipt">

            รายงานใบเสร็จรายบุคคล

          <?php
          if (($_COOKIE['tsr_emp_permit'] != 4)) {
           ?>

            <select class="form-control select2 group-sm" name="EmpID" >
              <optgroup label="พนักงานเก็บเงิน">
                <?php
                $EmployeeCode = "A".substr($_COOKIE['tsr_emp_id'],1,5);
                  if (($_COOKIE['tsr_emp_id'] == '031218') || ($_COOKIE['tsr_emp_id'] == '031584') || ($_COOKIE['tsr_emp_id'] == '031584')) {
                    $sql_case = "SELECT SaleCode as mcode,EmployeeName AS Name ,EmployeeCode AS EmpID,case when SaleCode is null then '-' else SaleCode end as SaleCode ,SupervisorCode FROM Bighead_Mobile.dbo.EmployeeDetail WHERE  salecode is not null AND SupervisorCode is not null AND EmployeeCode = '".$EmployeeCode."' ORDER BY mcode";

                    //echo $sql_case;
                    $stmt = sqlsrv_query($conn,$sql_case);
                    while ($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)) {
                      ?>
                    <option value="<?=$row['EmpID']?>_<?=$row['Name']?>_<?=$row['SaleCode']?>_<?=$row['mcode']?>"><?=$row['EmpID']?> (<?=$row['SaleCode']?>) <?=$row['Name']?> </option>
                      <?php
                    }
                  }else{
                ?>
                <option value="0"> ทั้งหมด </option>
                  <?php
                $sql_case = "SELECT SaleCode as mcode,EmployeeName AS Name ,EmployeeCode AS EmpID,case when SaleCode is null then '-' else SaleCode end as SaleCode ,SupervisorCode FROM Bighead_Mobile.dbo.EmployeeDetail WHERE  salecode is not null AND SupervisorCode is not null ORDER BY mcode";

                //echo $sql_case;
                $stmt = sqlsrv_query($conn,$sql_case);
                while ($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)) {
                ?>
              <option value="<?=$row['EmpID']?>_<?=$row['Name']?>_<?=$row['SaleCode']?>_<?=$row['mcode']?>"><?=$row['EmpID']?> (<?=$row['SaleCode']?>) <?=$row['Name']?> </option>
                <?php
                  }
                }
                ?>
              </optgroup>
            </select>

          <?php
        }
           ?>

                    <input type="text" class="form-control" name="startDate" autocomplete="off" value="<?php if(isset($_REQUEST['startDate'])) {echo $_REQUEST['startDate'];}?>" placeholder="วันเริ่มต้น .." required>
                    ถึง
                    <input type="text" class="form-control" name="endDate" autocomplete="off" value="<?php if(isset($_REQUEST['endDate'])) {echo $_REQUEST['endDate'];}?>" placeholder="วันสิ้นสุด .." required>

              <button type="submit" class="btn btn-default"></button>

        </form>

          <?php
            if (!empty($_REQUEST['searchDate']) || ((!empty($_REQUEST['startDate']) && !empty($_REQUEST['endDate'])))) {

           ?>

            <form role="form" data-toggle="validator" id="formPrint" name="formPrint" method="post" action="index.php?pages=reportOperPrintReceipt">
              <button type="submit" class="btn btn-default"></button>

                ลำดับ
                เลขที่ใบเสร็จ
                เวลาออกใบเสร็จ
                งวดที่
                เลขที่สัญญา
                ชื่อ - สกุล
                จำนวนเงิน
                ค่างวด
                <input name="CheckAll" type="checkbox" id="CheckAll" value="Y" onclick="checkAll('chkbox');">

              <?php
                $httpExcel2 = "";
              $sql_select = "SELECT ReceiptCode
              ,CONVERT(varchar,PaymentDueDate) as PaymentDueDate
              ,case when count(ReceiptCode) = 1 then convert(varchar,min(PaymentPeriodNumber)) else convert(varchar,min(PaymentPeriodNumber)) + ' - ' + convert(varchar,Max(PaymentPeriodNumber)) end as PaymentPeriodNumber
              ,CONTNO
              ,CustomerName
              ,case when count(ReceiptCode) = 1 then SUM(PAYAMT) else SUM(PAYAMT) end as PAYAMT
              ,case when count(ReceiptCode) = 1 then SUM(PAYAMT) else SUM(PAYAMT) end as PAYAMTS
              ,EmpID
              ,Names
              ,Paydate
              ,PrintName
              ,SaleCode
              , 'รายงานสรุปการเก็บเงิน' AS printHead,PaymentAmount
              from (SELECT DISTINCT ReceiptCode
              ,CONVERT(varchar(20),R.DatePayment,105) +' '+ CONVERT(varchar(5),R.DatePayment,108) as PaymentDueDate
              ,Right('000'+Convert(Varchar,S.PaymentPeriodNumber),2) As PaymentPeriodNumber,c.CONTNO AS CONTNO,CustomerName,Sy.Amount AS PAYAMT
              , Em.FirstName + ' ' + Em.LastName AS Names , '".$searchDate."' AS Paydate , '".$_COOKIE['tsr_emp_name']."' AS PrintName,R.CreateBy as EmpID,R.ZoneCode as SaleCode,s.PaymentAmount ";

              $sql_body = " FROM TSRData_Source.dbo.vw_ReceiptWithZone AS R WITH(NOLOCK) LEFT JOIN Bighead_Mobile.dbo.Contract AS C WITH(NOLOCK) ON R.RefNo = C.RefNo
              LEFT JOIN TSRData_Source.dbo.vw_DebtorCustomer AS GC WITH(NOLOCK) ON C.CustomerID = GC.CustomerID
              LEFT JOIN SalePaymentPeriodPayment As Sy WITH(NOLOCK) ON R.PaymentID = Sy.PaymentID AND R.ReceiptID = Sy.ReceiptID
              LEFT JOIN Bighead_Mobile.dbo.SalePaymentPeriod AS S WITH(NOLOCK) ON S.SalePaymentPeriodID = Sy.SalePaymentPeriodID
              LEFT JOIN Bighead_Mobile.dbo.Employee AS Em WITH(NOLOCK) ON R.LastUpdateBy = EM.EmpID
              WHERE $WHERE AND S.SalePaymentPeriodID = Sy.SalePaymentPeriodID AND Sy.Amount > 0
              --AND R.TypeCode = 0
              ) as result GROUP BY ReceiptCode,PaymentDueDate,CONTNO,CustomerName,EmpID
              ,SaleCode,Names,Paydate,PrintName,PaymentAmount ORDER BY ReceiptCode";

              $sql_case = $sql_select." ".$sql_body;
              //echo $sql_case;

              // เพิ่มลงฐานข้อมูล
              $num_row = checkNumRow($conn,$sql_case);
              $SumTotal = 0 ;

              $i=0;
              $stmt = sqlsrv_query($conn,$sql_case);
              while ($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)) {
                $SumTotal = $SumTotal + $row['PAYAMT'];
                $i++;
              ?>

                <?=$i?>
                <?=$row['ReceiptCode']?>
                <?=DateTimeThai($row['PaymentDueDate'])?> น.
                <?=$row['PaymentPeriodNumber']?>
                <?=$row['CONTNO']?>
                <?=$row['CustomerName']?>
                <?=number_format($row['PAYAMT'],2)?>
                <?=number_format($row['PaymentAmount'],2)?>
                <input type="checkbox" id='chkbox' name="printID[<?=$row['ReceiptCode']?>]" class="flat" value="<?=$row['ReceiptCode']?>">

              <?php
                }
               ?>

            <?php
            if (substr($_COOKIE['tsr_emp_id'],0,1) == "0") {
              $EmpID = "A".substr($_COOKIE['tsr_emp_id'],1,5);
            }else {
              $EmpID = $_COOKIE['tsr_emp_id'];
            }
             ?>
            <input type="hidden" name="EmpID" value="<?=$EmpID?>">
            <button type="submit" class="btn btn-default"></button>
          </form>

            รวม

            <?=$num_row;?> ใบ
             รวมเงิน
            <?=number_format($SumTotal,2)?>

        <?php
          }
          sqlsrv_close($conn);
        ?>

  <link rel="stylesheet" href="plugins/datatables/dataTables.bootstrap.css">


text:
**Gunit** pronounced ***Gunn-itt*** . A (good enough) low ceremony, open source, zero dependency,
cross platform (specifically mobile android) testing library. Gunit includes a fluent `Verify` object comparer that provides
object property equality verification in mobile applications and libraries,
 or anywhere where other libraries like [fluentassertions]() cannot be used due to dependancy restrictions.

The package also includes `Ensure`, a debugging-friendly alernative to NUnit's `Assert.That`.

### Getting Started

Install package

```
> Install-package Verify
```

**start verifying...**

```
  var c1 = new Cat(1,"Fred", Kittens = new [] { "Slippers", "Buttons" });
  var c2 = new Cat(1,"Fred", Kittens = new [] { "Slippers", "Buttons" });

  Verify.VerifySame(c1,c2);
  // or
  c1.VerifySame(c2);

  // Deliberately change a property
  // ------------------------------
  c2.Kittens[2].Age = 20;

  // Confirm child property difference is detected
  // ---------------------------------------------
  Ensure.Throws<CompareException>(c1.VerifySame(c2));

```

 Verify will by default treverse down to 5 levels deep. This can be configured during initialisation, or passed in as a parameter.

 ```
 c1.VerifySame(c2, MaxDepth = 10);
 ```

 Default DateTime tolerance, when comparing dates, is set to 200ms, to support lazy developers (like me)
 who often don't have time to refactor customer's code to inject a DateTime provider into all classes under test.  This can also be configured globally or once per test.

 ```
 c1.VerifySame(c2, ToleranceMs = 200);
 // or configure globally
 Gunit.Config = new Config() { ToleranceMs = 200, MaxDepth = 10 };
 ```

 [More examples](docs/more-examples.md)

redpajama_set_name: RedPajamaGithub


text:
package org.sourcepit.b2.internal.generator;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.sourcepit.common.utils.io.IO.buffIn;
import static org.sourcepit.common.utils.io.IO.buffOut;
import static org.sourcepit.common.utils.io.IO.fileIn;
import static org.sourcepit.common.utils.io.IO.fileOut;
import static org.sourcepit.common.utils.io.IO.read;
import static org.sourcepit.common.utils.io.IO.write;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.junit.Test;
import org.sourcepit.b2.directory.parser.internal.module.AbstractTestEnvironmentTest;
import org.sourcepit.b2.internal.generator.p2.Require;
import org.sourcepit.common.utils.io.Read.FromStream;
import org.sourcepit.common.utils.io.Write.ToStream;
import org.sourcepit.common.utils.props.LinkedPropertiesMap;
import org.sourcepit.common.utils.props.PropertiesMap;
import org.sourcepit.common.utils.xml.XmlUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class ProductGeneratorTest extends AbstractTestEnvironmentTest {

   @Test
   public void testCopyAndFilterProductFile() throws Exception {
      final StringBuilder sb = new StringBuilder();
      sb.append("<product name=\"${name}\" uid=\"${uid}\" version=\"${version}\">\n");
      sb.append("${content}\n");
      sb.append("</product>\n");

      final File srcFile = ws.newFile("src.product");
      final File destFile = ws.newFile("dest.product");
      write(new ToStream<String>() {
         @Override
         public void write(OutputStream output, String content) throws Exception {
            IOUtils.copy(new ByteArrayInputStream(content.getBytes("UTF-8")), output);
         }
      }, buffOut(fileOut(srcFile)), sb.toString());
      assertTrue(srcFile.exists());

      PropertiesMap properties = new LinkedPropertiesMap();
      properties.put("uid", "foo.product");
      properties.put("version", "1.0.0.qualifier");
      properties.put("content", "hui");

      ProductGenerator.copyAndFilterProductFile(srcFile, destFile, properties);
      assertTrue(destFile.exists());

      String filteredContent = read(new FromStream<String>() {
         @Override
         public String read(InputStream input) throws Exception {
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            IOUtils.copy(input, output);
            return new String(output.toByteArray(), "UTF-8");
         }
      }, buffIn(fileIn(destFile)));

      assertEquals("<product name=\"${name}\" uid=\"foo.product\" version=\"1.0.0.qualifier\">\nhui\n</product>\n",
         filteredContent);
   }

   @Test
   public void testMoveStrictRequirementsToProductXML() {
      List<Require> requires = new ArrayList<Require>();
      requires.add(createRequire("1.feature.group", "0.0.0"));
      requires.add(createRequire("2.feature.group", "[1.0.0,2.0.0]"));
      requires.add(createRequire("3.feature.group", "[2.0.0,2.0.0]"));
      requires.add(createRequire("4", "0.0.0"));
      requires.add(createRequire("5", "[1.0.0,2.0.0]"));
      requires.add(createRequire("6", "[2.0.0,2.0.0]"));

      Document doc = XmlUtils.newDocument();
      Element features = doc.createElement("features");
      Element plugins = doc.createElement("plugins");

      ProductGenerator.moveStrictRequirementsToProductXML(requires, features, plugins);

      assertEquals(4, requires.size());

      NodeList childNodes;
      Element childNode;

      childNodes = features.getChildNodes();
      assertEquals(1, childNodes.getLength());
      childNode = (Element) childNodes.item(0);
      assertEquals("feature", childNode.getNodeName());
      assertEquals("3", childNode.getAttribute("id"));
      assertEquals("2.0.0", childNode.getAttribute("version"));

      childNodes = plugins.getChildNodes();
      assertEquals(1, childNodes.getLength());
      childNode = (Element) childNodes.item(0);
      assertEquals("plugin", childNode.getNodeName());
      assertEquals("6", childNode.getAttribute("id"));
      assertEquals("2.0.0", childNode.getAttribute("version"));
   }

   private static Require createRequire(String name, String range) {
      final Require require = new Require();
      require.setNamespace("org.eclipse.equinox.p2.iu");
      require.setName(name);
      require.setRange(range);
      return require;
   }
}


text:
using Aspose.Cells.GridWeb.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Aspose.Cells.GridWeb.Examples.CSharp.Worksheets
{
    public partial class ShowAddButton : System.Web.UI.Page
    {
        // ExStart:1
        protected void Page_Load(object sender, EventArgs e)
        {
            GridWeb1.SheetAdded += GridSheetAdded;
            // If first visit this page clear GridWeb1 and load data
            if (!IsPostBack && !GridWeb1.IsPostBack)
            {
                // Show button to add and delete sheet
                GridWeb1.ShowAddButton = true;
                GridWeb1.WorkSheets.Clear();
                GridWeb1.WorkSheets.Add();
                //LoadData();
            }
        }

        void GridSheetAdded(object sender, GridWorksheet sheet)
        {
            sheet.Cells.StandardHeightPixels = 30;
            sheet.Cells.StandardWidthPixels = 100;
        }
        // ExEnd:1
        private void LoadData()
        {
            // Gets the web application's path.
            string path = (this.Master as Site).GetDataDir();

            string fileName = path + "\\GridWebBasics\\SampleData.xls";

            // Imports from an excel file.
            GridWeb1.ImportExcelFile(fileName);
        }
    }
}


text:
package com.rajendarreddyj.basics.condition;

import java.util.logging.Logger;

public class LabeledContinue {
    private static final Logger logger = Logger.getAnonymousLogger();
    public static void main(final String[] args) {
        first: for (int i = 2; i < 10; i++) {
            for (int j = 1; j < 10; j++) {
                if (i == 7) {
                    // continue first;
                    break first;
                }
                logger.info(i + "*" + j + "=" + (i * j));
            }
        }
    }
}


text:
autocommit off;
select country, city, latitude, longitude
from public.location
where latitude > 10 and latitude < 25
order by 1,2 for orderby_num() between 1 and 5;

delete from all public.accommodations (except public.bed_and_breakfast)
where allows_children = 'no' and rownum <= 10;
rollback;

select hotel.name, location.country, hotel.country, cost
from public.location, public.hotel
where hotel.country = location.country and name like 'Holi%'
	and ROWNUM > 5 and ROWNUM <= 10 order by 1,2;

select country, rownum/10 as number
from public.location
where mod(rownum, 10) = 0 order by 1;

select lodging
from public.location
where country = 'Jamaica' and city = 'Montego Bay' and inst_num() = 1 order by 1;

select rownum as number, name, country, cost
from public.resort r
where cost in ( select cost
		from public.hotel
		where allows_children = r.allows_children
		and rownum <= 5
		union all
		select cost
		from public.bed_and_breakfast
		where rownum <= 5
		) order by 1,2;

select sum(n)
from (select number_of_pools
	from all public.accommodations
	where country = 'Jamaica'
	 and rownum < 4
	union all
	select number_of_restaurants
	from all public.accommodations
	where country = 'Bahamas'
	 and rownum < 3
	) as t(n) ;

select country
from public.hotel
where rownum between 1 and 10
order by country ;

select tbl.t
from (select country from public.hotel order by country) as tbl(t)
where rownum between 1 and 10 order by 1;

insert into public.snack (serving_hours)
select serving_hours
from public.dinner
where proper_attire_required = 'yes' and rownum <= 10;

update public.resort
set cost = $198.00
where name like 'T%' and rownum <= 10;

rollback;


text:
LOADING

YOUR SESSION WILL BE EXPIRED
CONTINUE

                {{session.company.companyName}}


text:
#define C_LUCY_DEBUG
#define CFISH_USE_SHORT_NAMES
#define LUCY_USE_SHORT_NAMES

#include "Lucy/Util/Debug.h"

int32_t Debug_num_allocated = 0;
int32_t Debug_num_freed     = 0;
int32_t Debug_num_globals   = 0;

#if DEBUG_ENABLED

#include <ctype.h>
#include <string.h>
#include <stdlib.h>

static char  env_cache_buf[256];
static char *env_cache            = NULL;
static char *env_cache_limit      = NULL;
static int   env_cache_is_current = 0;

// Cache the system call to getenv.
static void
S_cache_debug_env_var(char *override) {
    const char *debug_env = override ? override : getenv("DEBUG");
    if (debug_env != NULL) {
        size_t len = strlen(debug_env);
        if (len > sizeof(env_cache_buf) - 1) {
            len = sizeof(env_cache_buf) - 1;
        }
        strncpy(env_cache_buf, debug_env, len);
        env_cache       = env_cache_buf;
        env_cache_limit = env_cache + len;
    }
    env_cache_is_current = 1;
}

void
Debug_print_mess(const char *file, int line, const char *func,
                 const char *pat, ...) {
    va_list args;
    fprintf(stderr, "%s:%d %s(): ", file, line, func);
    va_start(args, pat);
    vfprintf(stderr, pat, args);
    va_end(args);
    fprintf(stderr, "\n");
}

int
Debug_debug_should_print(const char *path, const char *func) {
    if (!env_cache_is_current) {
        S_cache_debug_env_var(NULL);
    }

    if (!env_cache) {
        // Do not print if DEBUG environment var is not set.
        return 0;
    }
    else {
        const char *test, *next;
        const char *file = strrchr(path, '/');
        const int filename_len = file ? strlen(file) : 0;
        const int funcname_len = func ? strlen(func) : 0;

        // Use just file name if given path.
        if (file) { file++; }
        else      { file = path; }

        // Split criteria on commas. Bail when we run out of critieria.
        for (test = env_cache; test != NULL; test = next) {
            const char *last_char;

            // Skip whitespace.
            while (isspace(*test)) { test++; }
            if (test >= env_cache_limit) { return 0; }

            // Find end of criteria or end of string.
            next = strchr(test, ',');
            last_char = next ? next - 1 : env_cache_limit - 1;
            while (last_char > test && isspace(*last_char)) { last_char--; }

            if (*last_char == '*') {
                const int len = last_char - test;
                if (!strncmp(test, file, len)) { return 1; }
                if (!strncmp(test, func, len)) { return 1; }
            }
            else {
                if (!strncmp(test, file, filename_len)) { return 1; }
                if (!strncmp(test, func, funcname_len)) { return 1; }
            }
        }

        // No matches against the DEBUG environment var, so don't print.
        return 0;
    }
}

void
Debug_set_env_cache(char *override) {
    S_cache_debug_env_var(override);
}

#else // DEBUG

void
Debug_set_env_cache(char *override) {
    (void)override;
}

#endif // DEBUG


text:
extern "C"
{
#endif

//*****************************************************************************
//
// This is the maximum number of endpoints supported by the usblib.
//
//*****************************************************************************
#define USBLIB_NUM_EP           16   // Number of supported endpoints.

//*****************************************************************************
//
// The following macro allows compiler-independent syntax to be used to
// define packed structures.  A typical structure definition using these
// macros will look similar to the following example:
//
//   #ifdef ewarm
//   #pragma pack(1)
//   #endif
//
//   typedef struct _PackedStructName
//   {
//      unsigned int ulFirstField;
//      char cCharMember;
//      unsigned short usShort;
//   }
//   USBLIB_PACKED tPackedStructName;
//
//   #ifdef ewarm
//   #pragma pack()
//   #endif
//
// The conditional blocks related to ewarm include the #pragma pack() lines
// only if the IAR Embedded Workbench compiler is being used.  Unfortunately,
// it is not possible to emit a #pragma from within a macro definition so this
// must be done explicitly.
//
//*****************************************************************************
#if defined(ccs) ||             \
    defined(codered) ||         \
    defined(gcc) ||             \
    defined(rvmdk) ||           \
    defined(__ARMCC_VERSION) || \
    defined(sourcerygxx)
#define USBLIB_PACKED __attribute__ ((packed))
#elif defined(ewarm) || defined(__IAR_SYSTEMS_ICC__)
#define USBLIB_PACKED
#elif defined(__TMS470__)
#if defined(__TI_TMS470_V7__) || (__TI_COMPILER_VERSION__ >= 5000000)
#define USBLIB_PACKED __attribute__ ((packed))
#else
#warn The packed attribute is not supported by this version of the TI ARM CGT. \
      Please upgrade to version 5.x or use an alternate toolchain instead.
#define USBLIB_PACKED
#endif
#elif defined(_TMS320C6X)
#define USBLIB_PACKED __attribute__ ((packed))
#else
#error Unrecognized COMPILER!
#endif

//*****************************************************************************
//
// Assorted language IDs from the document "USB_LANGIDs.pdf" provided by the
// USB Implementers' Forum (Version 1.0).
//
//*****************************************************************************
#define USB_LANG_CHINESE_PRC    0x0804      // Chinese (PRC)
#define USB_LANG_CHINESE_TAIWAN 0x0404      // Chinese (Taiwan)
#define USB_LANG_EN_US          0x0409      // English (United States)
#define USB_LANG_EN_UK          0x0809      // English (United Kingdom)
#define USB_LANG_EN_AUS         0x0C09      // English (Australia)
#define USB_LANG_EN_CA          0x1009      // English (Canada)
#define USB_LANG_EN_NZ          0x1409      // English (New Zealand)
#define USB_LANG_FRENCH         0x040C      // French (Standard)
#define USB_LANG_GERMAN         0x0407      // German (Standard)
#define USB_LANG_HINDI          0x0439      // Hindi
#define USB_LANG_ITALIAN        0x0410      // Italian (Standard)
#define USB_LANG_JAPANESE       0x0411      // Japanese
#define USB_LANG_KOREAN         0x0412      // Korean
#define USB_LANG_ES_TRAD        0x040A      // Spanish (Traditional)
#define USB_LANG_ES_MODERN      0x0C0A      // Spanish (Modern)
#define USB_LANG_SWAHILI        0x0441      // Swahili (Kenya)
#define USB_LANG_URDU_IN        0x0820      // Urdu (India)
#define USB_LANG_URDU_PK        0x0420      // Urdu (Pakistan)
//*****************************************************************************
//
//! \addtogroup usbchap9_src
//! @{
//
//*****************************************************************************

//*****************************************************************************
//
// Note:
//
// Structure definitions which are derived directly from the USB specification
// use field names from the specification.  Since a somewhat different version
// of Hungarian prefix notation is used from the Stellaris standard, beware of
// making assumptions about field sizes based on the field prefix when using
// these structures.  Of particular note is the difference in the meaning of
// the 'i' prefix.  In USB structures, this indicates a single byte index
// whereas in Stellaris code, this is a 32 bit integer.
//
//*****************************************************************************

//*****************************************************************************
//
// All structures defined in this section of the header require byte packing of
// fields.  This is usually accomplished using the USBLIB_PACKED macro but, for IAR
// Embedded Workbench, this requires a pragma.
//
//*****************************************************************************
#if defined(ewarm) || defined(__IAR_SYSTEMS_ICC__)
#pragma pack(1)
#endif

//*****************************************************************************
//
// Definitions related to standard USB device requests (sections 9.3 & 9.4)
//
//*****************************************************************************

//*****************************************************************************
//
//! The standard USB request header as defined in section 9.3 of the USB 2.0
//! specification.
//
//*****************************************************************************
typedef struct
{
    //
    //! Determines the type and direction of the request.
    //
    unsigned char bmRequestType;

    //
    //! Identifies the specific request being made.
    //
    unsigned char bRequest;

    //
    //! Word-sized field that varies according to the request.
    //
    unsigned short wValue;

    //
    //! Word-sized field that varies according to the request; typically used
    //! to pass an index or offset.
    //
    unsigned short wIndex;

    //
    //! The number of bytes to transfer if there is a data stage to the
    //! request.
    //
    unsigned short wLength;

}
USBLIB_PACKED tUSBRequest;

//*****************************************************************************
//
// The following defines are used with the bmRequestType member of tUSBRequest.
//
// Request types have 3 bit fields:
// 4:0 - Is the recipient type.
// 6:5 - Is the request type.
// 7 - Is the direction of the request.
//
//*****************************************************************************
#define USB_RTYPE_DIR_IN        0x80
#define USB_RTYPE_DIR_OUT       0x00

#define USB_RTYPE_TYPE_M        0x60
#define USB_RTYPE_VENDOR        0x40
#define USB_RTYPE_CLASS         0x20
#define USB_RTYPE_STANDARD      0x00

#define USB_RTYPE_RECIPIENT_M   0x1f
#define USB_RTYPE_OTHER         0x03
#define USB_RTYPE_ENDPOINT      0x02
#define USB_RTYPE_INTERFACE     0x01
#define USB_RTYPE_DEVICE        0x00

//*****************************************************************************
//
// Standard USB requests IDs used in the bRequest field of tUSBRequest.
//
//*****************************************************************************
#define USBREQ_GET_STATUS       0x00
#define USBREQ_CLEAR_FEATURE    0x01
#define USBREQ_SET_FEATURE      0x03
#define USBREQ_SET_ADDRESS      0x05
#define USBREQ_GET_DESCRIPTOR   0x06
#define USBREQ_SET_DESCRIPTOR   0x07
#define USBREQ_GET_CONFIG       0x08
#define USBREQ_SET_CONFIG       0x09
#define USBREQ_GET_INTERFACE    0x0a
#define USBREQ_SET_INTERFACE    0x0b
#define USBREQ_SYNC_FRAME       0x0c

//*****************************************************************************
//
// Data returned from a USBREQ_GET_STATUS request to a device.
//
//*****************************************************************************
#define USB_STATUS_SELF_PWR     0x0001  // Currently self powered.
#define USB_STATUS_BUS_PWR      0x0000  // Currently bus-powered.
#define USB_STATUS_PWR_M        0x0001  // Mask for power mode.
#define USB_STATUS_REMOTE_WAKE  0x0002  // Remote wake-up is currently enabled.

//*****************************************************************************
//
// Feature Selectors (tUSBRequest.wValue) passed on USBREQ_CLEAR_FEATURE and
// USBREQ_SET_FEATURE.
//
//*****************************************************************************
#define USB_FEATURE_EP_HALT     0x0000  // Endpoint halt feature.
#define USB_FEATURE_REMOTE_WAKE 0x0001  // Remote wake feature, device only.
#define USB_FEATURE_TEST_MODE   0x0002  // Test mode

//*****************************************************************************
//
// Endpoint Selectors (tUSBRequest.wIndex) passed on USBREQ_CLEAR_FEATURE,
// USBREQ_SET_FEATURE and USBREQ_GET_STATUS.
//
//*****************************************************************************
#define USB_REQ_EP_NUM_M   0x007F
#define USB_REQ_EP_DIR_M   0x0080
#define USB_REQ_EP_DIR_IN  0x0080
#define USB_REQ_EP_DIR_OUT 0x0000

//*****************************************************************************
//
// Standard USB descriptor types.  These values are passed in the upper bytes
// of tUSBRequest.wValue on USBREQ_GET_DESCRIPTOR and also appear in the
// bDescriptorType field of standard USB descriptors.
//
//*****************************************************************************
#define USB_DTYPE_DEVICE        1
#define USB_DTYPE_CONFIGURATION 2
#define USB_DTYPE_STRING        3
#define USB_DTYPE_INTERFACE     4
#define USB_DTYPE_ENDPOINT      5
#define USB_DTYPE_DEVICE_QUAL   6
#define USB_DTYPE_OSPEED_CONF   7
#define USB_DTYPE_INTERFACE_PWR 8
#define USB_DTYPE_OTG           9
#define USB_DTYPE_INTERFACE_ASC 11
#define USB_DTYPE_CS_INTERFACE  36

//*****************************************************************************
//
// Definitions related to USB descriptors (sections 9.5 & 9.6)
//
//*****************************************************************************

//*****************************************************************************
//
//! This structure describes a generic descriptor header.  These fields are to
//! be found at the beginning of all valid USB descriptors.
//
//*****************************************************************************
typedef struct
{
    //
    //! The length of this descriptor (including this length byte) expressed
    //! in bytes.
    //
    unsigned char bLength;

    //
    //! The type identifier of the descriptor whose information follows.  For
    //! standard descriptors, this field could contain, for example,
    //! USB_DTYPE_DEVICE to identify a device descriptor or USB_DTYPE_ENDPOINT
    //! to identify an endpoint descriptor.
    //
    unsigned char bDescriptorType;
}
USBLIB_PACKED tDescriptorHeader;

//*****************************************************************************
//
//! This structure describes the USB device descriptor as defined in USB
//! 2.0 specification section 9.6.1.
//
//*****************************************************************************
typedef struct
{
    //
    //! The length of this descriptor in bytes.  All device descriptors are
    //! 18 bytes long.
    //
    unsigned char bLength;

    //
    //! The type of the descriptor.  For a device descriptor, this will be
    //! USB_DTYPE_DEVICE (1).
    //
    unsigned char bDescriptorType;

    //
    //! The USB Specification Release Number in BCD format.  For USB 2.0, this
    //! will be 0x0200.
    //
    unsigned short bcdUSB;

    //
    //! The device class code.
    //
    unsigned char bDeviceClass;

    //
    //! The device subclass code.  This value qualifies the value found in the
    //! bDeviceClass field.
    //
    unsigned char bDeviceSubClass;

    //
    //! The device protocol code.  This value is qualified by the values of
    //! bDeviceClass and bDeviceSubClass.
    //
    unsigned char bDeviceProtocol;

    //
    //! The maximum packet size for endpoint zero.  Valid values are 8, 16, 32
    //! and 64.
    //
    unsigned char bMaxPacketSize0;

    //
    //! The device Vendor ID (VID) as assigned by the USB-IF.
    //
    unsigned short idVendor;

    //
    //! The device Product ID (PID) as assigned by the manufacturer.
    //
    unsigned short idProduct;

    //
    //! The device release number in BCD format.
    //
    unsigned short bcdDevice;

    //
    //! The index of a string descriptor describing the manufacturer.
    //
    unsigned char iManufacturer;

    //
    //! The index of a string descriptor describing the product.
    //
    unsigned char iProduct;

    //
    //! The index of a string descriptor describing the device's serial
    //! number.
    //
    unsigned char iSerialNumber;

    //
    //! The number of possible configurations offered by the device.  This
    //! field indicates the number of distinct configuration descriptors that
    //! the device offers.
    //
    unsigned char bNumConfigurations;
}
USBLIB_PACKED tDeviceDescriptor;

//*****************************************************************************
//
// USB Device Class codes used in the tDeviceDescriptor.bDeviceClass field.
// Definitions for the bDeviceSubClass and bDeviceProtocol fields are device
// specific and can be found in the appropriate device class header files.
//
//*****************************************************************************
#define USB_CLASS_DEVICE        0x00
#define USB_CLASS_AUDIO         0x01
#define USB_CLASS_CDC           0x02
#define USB_CLASS_HID           0x03
#define USB_CLASS_PHYSICAL      0x05
#define USB_CLASS_IMAGE         0x06
#define USB_CLASS_PRINTER       0x07
#define USB_CLASS_MASS_STORAGE  0x08
#define USB_CLASS_HUB           0x09
#define USB_CLASS_CDC_DATA      0x0a
#define USB_CLASS_SMART_CARD    0x0b
#define USB_CLASS_SECURITY      0x0d
#define USB_CLASS_VIDEO         0x0e
#define USB_CLASS_HEALTHCARE    0x0f
#define USB_CLASS_DIAG_DEVICE   0xdc
#define USB_CLASS_WIRELESS      0xe0
#define USB_CLASS_MISC          0xef
#define USB_CLASS_APP_SPECIFIC  0xfe
#define USB_CLASS_VEND_SPECIFIC 0xff
#define USB_CLASS_EVENTS        0xffffffff

//*****************************************************************************
//
// Generic values for undefined subclass and protocol.
//
//*****************************************************************************
#define USB_SUBCLASS_UNDEFINED  0x00
#define USB_PROTOCOL_UNDEFINED  0x00

//*****************************************************************************
//
// The following are the miscellaneous subclass values.
//
//*****************************************************************************
#define USB_MISC_SUBCLASS_SYNC      0x01
#define USB_MISC_SUBCLASS_COMMON    0x02

//*****************************************************************************
//
// These following are miscellaneous protocol values.
//
//*****************************************************************************
#define USB_MISC_PROTOCOL_IAD   0x01

//*****************************************************************************
//
//! This structure describes the USB device qualifier descriptor as defined in
//! the USB 2.0 specification, section 9.6.2.
//
//*****************************************************************************
typedef struct
{
    //
    //! The length of this descriptor in bytes.  All device qualifier
    //! descriptors are 10 bytes long.
    //
    unsigned char bLength;

    //
    //! The type of the descriptor.  For a device descriptor, this will be
    //! USB_DTYPE_DEVICE_QUAL (6).
    //
    unsigned char bDescriptorType;

    //
    //! The USB Specification Release Number in BCD format.  For USB 2.0, this
    //! will be 0x0200.
    //
    unsigned short bcdUSB;

    //
    //! The device class code.
    //
    unsigned char bDeviceClass;

    //
    //! The device subclass code.  This value qualifies the value found in the
    //! bDeviceClass field.
    //
    unsigned char bDeviceSubClass;

    //
    //! The device protocol code.  This value is qualified by the values of
    //! bDeviceClass and bDeviceSubClass.
    //
    unsigned char bDeviceProtocol;

    //
    //! The maximum packet size for endpoint zero when operating at a speed
    //! other than high speed.
    //
    unsigned char bMaxPacketSize0;

    //
    //! The number of other-speed configurations supported.
    //
    unsigned char bNumConfigurations;

    //
    //! Reserved for future use.  Must be set to zero.
    //
    unsigned char bReserved;
}
USBLIB_PACKED tDeviceQualifierDescriptor;

//*****************************************************************************
//
//! This structure describes the USB configuration descriptor as defined in
//! USB 2.0 specification section 9.6.3.  This structure also applies to the
//! USB other speed configuration descriptor defined in section 9.6.4.
//
//*****************************************************************************
typedef struct
{
    //
    //! The length of this descriptor in bytes.  All configuration descriptors
    //! are 9 bytes long.
    //
    unsigned char bLength;

    //
    //! The type of the descriptor.  For a configuration descriptor, this will
    //! be USB_DTYPE_CONFIGURATION (2).
    //
    unsigned char bDescriptorType;

    //
    //! The total length of data returned for this configuration.  This
    //! includes the combined length of all descriptors (configuration,
    //! interface, endpoint and class- or vendor-specific) returned for this
    //! configuration.
    //
    unsigned short wTotalLength;

    //
    //! The number of interface supported by this configuration.
    //
    unsigned char bNumInterfaces;

    //
    //! The value used as an argument to the SetConfiguration standard request
    //! to select this configuration.
    //
    unsigned char bConfigurationValue;

    //
    //! The index of a string descriptor describing this configuration.
    //
    unsigned char iConfiguration;

    //
    //! Attributes of this configuration.
    //
    unsigned char bmAttributes;

    //
    //! The maximum power consumption of the USB device from the bus in this
    //! configuration when the device is fully operational.  This is expressed
    //! in units of 2mA so, for example, 100 represents 200mA.
    //
    unsigned char bMaxPower;
}
USBLIB_PACKED tConfigDescriptor;

//*****************************************************************************
//
// Flags used in constructing the value assigned to the field
// tConfigDescriptor.bmAttributes.  Note that bit 7 is reserved and must be set
// to 1.
//
//*****************************************************************************
#define USB_CONF_ATTR_PWR_M     0xC0

#define USB_CONF_ATTR_SELF_PWR  0xC0
#define USB_CONF_ATTR_BUS_PWR   0x80
#define USB_CONF_ATTR_RWAKE     0xA0

//*****************************************************************************
//
//! This structure describes the USB interface descriptor as defined in USB
//! 2.0 specification section 9.6.5.
//
//*****************************************************************************
typedef struct
{
    //
    //! The length of this descriptor in bytes.  All interface descriptors
    //! are 9 bytes long.
    //
    unsigned char bLength;

    //
    //! The type of the descriptor.  For an interface descriptor, this will
    //! be USB_DTYPE_INTERFACE (4).
    //
    unsigned char bDescriptorType;

    //
    //! The number of this interface.  This is a zero based index into the
    //! array of concurrent interfaces supported by this configuration.
    //
    unsigned char bInterfaceNumber;

    //
    //! The value used to select this alternate setting for the interface
    //! defined in bInterfaceNumber.
    //
    unsigned char bAlternateSetting;

    //
    //! The number of endpoints used by this interface (excluding endpoint
    //! zero).
    //
    unsigned char bNumEndpoints;

    //
    //! The interface class code as assigned by the USB-IF.
    //
    unsigned char bInterfaceClass;

    //
    //! The interface subclass code as assigned by the USB-IF.
    //
    unsigned char bInterfaceSubClass;

    //
    //! The interface protocol code as assigned by the USB-IF.
    //
    unsigned char bInterfaceProtocol;

    //
    //! The index of a string descriptor describing this interface.
    //
    unsigned char iInterface;
}
USBLIB_PACKED tInterfaceDescriptor;

//*****************************************************************************
//
//! This structure describes the USB endpoint descriptor as defined in USB
//! 2.0 specification section 9.6.6.
//
//*****************************************************************************
typedef struct
{
    //
    //! The length of this descriptor in bytes.  All endpoint descriptors
    //! are 7 bytes long.
    //
    unsigned char bLength;

    //
    //! The type of the descriptor.  For an endpoint descriptor, this will
    //! be USB_DTYPE_ENDPOINT (5).
    //
    unsigned char bDescriptorType;

    //
    //! The address of the endpoint.  This field contains the endpoint number
    //! ORed with flag USB_EP_DESC_OUT or USB_EP_DESC_IN to indicate the
    //! endpoint direction.
    //
    unsigned char bEndpointAddress;

    //
    //! The endpoint transfer type, USB_EP_ATTR_CONTROL, USB_EP_ATTR_ISOC,
    //! USB_EP_ATTR_BULK or USB_EP_ATTR_INT and, if isochronous, additional
    //! flags indicating usage type and synchronization method.
    //
    unsigned char bmAttributes;

    //
    //! The maximum packet size this endpoint is capable of sending or
    //! receiving when this configuration is selected.  For high speed
    //! isochronous or interrupt endpoints, bits 11 and 12 are used to
    //! pass additional information.
    //
    unsigned short wMaxPacketSize;

    //
    //! The polling interval for data transfers expressed in frames or
    //! micro frames depending upon the operating speed.
    //
    unsigned char bInterval;
}
USBLIB_PACKED tEndpointDescriptor;

//*****************************************************************************
//
// Flags used in constructing the value assigned to the field
// tEndpointDescriptor.bEndpointAddress.
//
//*****************************************************************************
#define USB_EP_DESC_OUT                 0x00
#define USB_EP_DESC_IN                  0x80
#define USB_EP_DESC_NUM_M               0x0f

//*****************************************************************************
//
// Mask used to extract the maximum packet size (in bytes) from the
// wMaxPacketSize field of the endpoint descriptor.
//
//*****************************************************************************
#define USB_EP_MAX_PACKET_COUNT_M       0x07FF

//*****************************************************************************
//
// Endpoint attributes used in tEndpointDescriptor.bmAttributes.
//
//*****************************************************************************
#define USB_EP_ATTR_CONTROL             0x00
#define USB_EP_ATTR_ISOC                0x01
#define USB_EP_ATTR_BULK                0x02
#define USB_EP_ATTR_INT                 0x03
#define USB_EP_ATTR_TYPE_M              0x03

#define USB_EP_ATTR_ISOC_M              0x0c
#define USB_EP_ATTR_ISOC_NOSYNC         0x00
#define USB_EP_ATTR_ISOC_ASYNC          0x04
#define USB_EP_ATTR_ISOC_ADAPT          0x08
#define USB_EP_ATTR_ISOC_SYNC           0x0c
#define USB_EP_ATTR_USAGE_M             0x30
#define USB_EP_ATTR_USAGE_DATA          0x00
#define USB_EP_ATTR_USAGE_FEEDBACK      0x10
#define USB_EP_ATTR_USAGE_IMPFEEDBACK   0x20

//*****************************************************************************
//
//! This structure describes the USB string descriptor for index 0 as defined
//! in USB 2.0 specification section 9.6.7.  Note that the number of language
//! IDs is variable and can be determined by examining bLength.  The number of
//! language IDs present in the descriptor is given by ((bLength - 2) / 2).
//
//*****************************************************************************
typedef struct
{
    //
    //! The length of this descriptor in bytes.  This value will vary
    //! depending upon the number of language codes provided in the descriptor.
    //
    unsigned char bLength;

    //
    //! The type of the descriptor.  For a string descriptor, this will be
    //! USB_DTYPE_STRING (3).
    //
    unsigned char bDescriptorType;

    //
    //! The language code (LANGID) for the first supported language.  Note that
    //! this descriptor may support multiple languages, in which case, the
    //! number of elements in the wLANGID array will increase and bLength will
    //! be updated accordingly.
    //
    unsigned short wLANGID[1];
}
USBLIB_PACKED tString0Descriptor;

//*****************************************************************************
//
//! This structure describes the USB string descriptor for all string indexes
//! other than 0 as defined in USB 2.0 specification section 9.6.7.
//
//*****************************************************************************
typedef struct
{
    //
    //! The length of this descriptor in bytes.  This value will be 2 greater
    //! than the number of bytes comprising the UNICODE string that the
    //! descriptor contains.
    //
    unsigned char bLength;

    //
    //! The type of the descriptor.  For a string descriptor, this will be
    //! USB_DTYPE_STRING (3).
    //
    unsigned char bDescriptorType;

    //
    //! The first byte of the UNICODE string.  This string is not NULL
    //! terminated.  Its length (in bytes) can be computed by subtracting 2
    //! from the value in the bLength field.
    //
    unsigned char bString;
}
USBLIB_PACKED tStringDescriptor;

//*****************************************************************************
//
//! Write a 2 byte unsigned short value to a USB descriptor block.
//!
//! \param usValue is the two byte unsigned short that is to be written to
//! the descriptor.
//!
//! This helper macro is used in descriptor definitions to write two-byte
//! values.  Since the configuration descriptor contains all interface and
//! endpoint descriptors in a contiguous block of memory, these descriptors are
//! typically defined using an array of bytes rather than as packed structures.
//!
//! \return Not a function.
//
//*****************************************************************************
#define USBShort(usValue)       (usValue & 0xff), (usValue >> 8)

//*****************************************************************************
//
//! Write a 3 byte unsigned long value to a USB descriptor block.
//!
//! \param ulValue is the three byte unsigned value that is to be written to the
//! descriptor.
//!
//! This helper macro is used in descriptor definitions to write three-byte
//! values.  Since the configuration descriptor contains all interface and
//! endpoint descriptors in a contiguous block of memory, these descriptors are
//! typically defined using an array of bytes rather than as packed structures.
//!
//! \return Not a function.
//
//*****************************************************************************
#define USB3Byte(ulValue)       (ulValue & 0xff),              \
                                ((ulValue >> 8) & 0xff),       \
                                ((ulValue >> 16) & 0xff)

//*****************************************************************************
//
//! Write a 4 byte unsigned long value to a USB descriptor block.
//!
//! \param ulValue is the four byte unsigned long that is to be written to the
//! descriptor.
//!
//! This helper macro is used in descriptor definitions to write four-byte
//! values.  Since the configuration descriptor contains all interface and
//! endpoint descriptors in a contiguous block of memory, these descriptors are
//! typically defined using an array of bytes rather than as packed structures.
//!
//! \return Not a function.
//
//*****************************************************************************
#define USBLong(ulValue)        (ulValue & 0xff),              \
                                ((ulValue >> 8) & 0xff),       \
                                ((ulValue >> 16) & 0xff),      \
                                ((ulValue >> 24) & 0xff)

//*****************************************************************************
//
//! Traverse to the next USB descriptor in a block.
//!
//! \param ptr points to the first byte of a descriptor in a block of
//! USB descriptors.
//!
//! This macro aids in traversing lists of descriptors by returning a pointer
//! to the next descriptor in the list given a pointer to the current one.
//!
//! \return Returns a pointer to the next descriptor in the block following
//! \e ptr.
//!
//*****************************************************************************
#define NEXT_USB_DESCRIPTOR(ptr)                         \
        (tDescriptorHeader *)(((unsigned char *)(ptr)) + \
                              *((unsigned char *)(ptr)))

//*****************************************************************************
//
// Return to default packing when using the IAR Embedded Workbench compiler.
//
//*****************************************************************************
#if defined(ewarm) || defined(__IAR_SYSTEMS_ICC__)
#pragma pack()
#endif

//*****************************************************************************
//
// Close the usbchap9_src Doxygen group.
//! @}
//
//*****************************************************************************

//*****************************************************************************
//
//! \addtogroup device_api
//! @{
//
//*****************************************************************************

//*****************************************************************************
//
// Function prototype for any standard USB request.
//
//*****************************************************************************
typedef void (* tStdRequest)(void *pvInstance, tUSBRequest *pUSBRequest,
                                                        unsigned int ulIndex);

//*****************************************************************************
//
// Data callback for receiving data from an endpoint.
//
//*****************************************************************************
typedef void (* tInfoCallback)(void *pvInstance, unsigned int ulInfo,
                                                        unsigned int ulIndex);

//*****************************************************************************
//
// Callback made to indicate that an interface alternate setting change has
// occurred.
//
//*****************************************************************************
typedef void (* tInterfaceCallback)(void *pvInstance,
                                    unsigned char ucInterfaceNum,
                                    unsigned char ucAlternateSetting);

//*****************************************************************************
//
// Generic interrupt handler callbacks.
//
//*****************************************************************************
typedef void (* tUSBIntHandler)(void *pvInstance);

//*****************************************************************************
//
// Interrupt handler callbacks that have status information.
//
//*****************************************************************************
typedef void (* tUSBEPIntHandler)(void *pvInstance,
                                  unsigned int ulStatus, unsigned int ulIndex);

//*****************************************************************************
//
// Generic handler callbacks that are used when the callers needs to call into
// an instance of class.
//
//*****************************************************************************
typedef void (* tUSBDeviceHandler)(void *pvInstance,
                                   unsigned int ulRequest,
                                   void *pvRequestData);

//*****************************************************************************
//
//! USB event handler functions used during enumeration and operation of the
//! device stack.
//
//*****************************************************************************
typedef struct
{
    //
    //! This callback is made whenever the USB host requests a non-standard
    //! descriptor from the device.
    //
    tStdRequest pfnGetDescriptor;

    //
    //! This callback is made whenever the USB host makes a non-standard
    //! request.
    //
    tStdRequest pfnRequestHandler;

    //
    //! This callback is made in response to a SetInterface request from the
    //! host.
    //
    tInterfaceCallback pfnInterfaceChange;

    //
    //! This callback is made in response to a SetConfiguration request from
    //! the host.
    //
    tInfoCallback pfnConfigChange;

    //
    //! This callback is made when data has been received following to a call
    //! to USBDCDRequestDataEP0.
    //
    tInfoCallback pfnDataReceived;

    //
    //! This callback is made when data has been transmitted following a call
    //! to USBDCDSendDataEP0.
    //
    tInfoCallback pfnDataSent;

    //
    //! This callback is made when a USB reset is detected.
    //
    tUSBIntHandler pfnResetHandler;

    //
    //! This callback is made when the bus has been inactive long enough to
    //! trigger a suspend condition.
    //
    tUSBIntHandler pfnSuspendHandler;

    //
    //! This is called when resume signaling is detected.
    //
    tUSBIntHandler pfnResumeHandler;

    //
    //! This callback is made when the device is disconnected from the USB bus.
    //
    tUSBIntHandler pfnDisconnectHandler;

    //
    //! This callback is made to inform the device of activity on all endpoints
    //! other than endpoint zero.
    //
    tUSBEPIntHandler pfnEndpointHandler;

    //
    //! This generic handler is provided to allow requests based on
    //! a given instance to be passed into a device.  This is commonly used
    //! by a top level composite device that is using multiple instances of
    //! a class.
    //
    tUSBDeviceHandler pfnDeviceHandler;
}
tCustomHandlers;

//*****************************************************************************
//
//! This structure defines how a given endpoint's FIFO is configured in
//! relation to the maximum packet size for the endpoint as specified in the
//! endpoint descriptor.
//
//*****************************************************************************
typedef struct
{
    //
    //! The multiplier to apply to an endpoint's maximum packet size when
    //! configuring the FIFO for that endpoint.  For example, setting this
    //! value to 2 will result in a 128 byte FIFO being configured if
    //! bDoubleBuffer is false and the associated endpoint is set to use a 64
    //! byte maximum packet size.
    //
    unsigned char cMultiplier;

    //
    //! This field indicates whether to configure an endpoint's FIFO to be
    //! double- or single-buffered.  If true, a double-buffered FIFO is
    //! created and the amount of required FIFO storage is multiplied by two.
    //
    tBoolean bDoubleBuffer;

    //
    //! This field defines endpoint mode flags which cannot be deduced from
    //! the configuration descriptor, namely any in the set USB_EP_AUTO_xxx or
    //! USB_EP_DMA_MODE_x.  USBDCDConfig adds these flags to the endpoint
    //! mode and direction determined from the config descriptor before it
    //! configures the endpoint using a call to USBDevEndpointConfigSet().
    //
    unsigned short usEPFlags;
}
tFIFOEntry;

//*****************************************************************************
//
//! This structure defines endpoint and FIFO configuration information for
//! all endpoints that the device wishes to use.  This information cannot be
//! determined by examining the USB configuration descriptor and is
//! provided to USBDCDConfig by the application to allow the USB controller
//! endpoints to be correctly configured.
//
//*****************************************************************************
typedef struct
{
    //
    //! An array containing one FIFO entry for each of the IN endpoints.
    //! Note that endpoint 0 is configured and managed by the USB device stack
    //! so is excluded from this array.  The index 0 entry of the array
    //! corresponds to endpoint 1, index 1 to endpoint 2, etc.
    //
    tFIFOEntry sIn[USBLIB_NUM_EP - 1];

    //
    //! An array containing one FIFO entry for each of the OUT endpoints.
    //! Note that endpoint 0 is configured and managed by the USB device stack
    //! so is excluded from this array.  The index 0 entry of the array
    //! corresponds to endpoint 1, index 1 to endpoint 2, etc.
    //
    tFIFOEntry sOut[USBLIB_NUM_EP - 1];
}
tFIFOConfig;

//*****************************************************************************
//
//! This structure defines a contiguous block of data which contains a group
//! of descriptors that form part of a configuration descriptor for a device.
//! It is assumed that a config section contains only whole descriptors.  It is
//! not valid to split a single descriptor across multiple sections.
//!
//*****************************************************************************
typedef struct
{
    //
    //! The number of bytes of descriptor data pointed to by pucData.
    //
    unsigned char ucSize;

    //
    //! A pointer to a block of data containing an integral number of
    //! USB descriptors which form part of a larger configuration descriptor.
    //
    const unsigned char *pucData;
}
tConfigSection;

//*****************************************************************************
//
//! This is the top level structure defining a USB device configuration
//! descriptor.  A configuration descriptor contains a collection of device-
//! specific descriptors in addition to the basic config, interface and
//! endpoint descriptors.  To allow flexibility in constructing the
//! configuration, the descriptor is described in terms of a list of data
//! blocks.  The first block must contain the configuration descriptor itself
//! and the following blocks are appended to this in order to produce the
//! full descriptor sent to the host in response to a GetDescriptor request
//! for the configuration descriptor.
//!
//*****************************************************************************
typedef struct
{
    //
    //! The number of sections comprising the full descriptor for this
    //! configuration.
    //
    unsigned char ucNumSections;

    //
    //! A pointer to an array of ucNumSections section pointers which must
    //! be concatenated to form the configuration descriptor.
    //
    const tConfigSection * const *psSections;
}
tConfigHeader;

//*****************************************************************************
//
//! This structure is passed to the USB library on a call to USBDCDInit and
//! provides the library with information about the device that the
//! application is implementing.  It contains functions pointers for the
//! various USB event handlers and pointers to each of the standard device
//! descriptors.
//
//*****************************************************************************
typedef struct
{
    //
    //! A pointer to a structure containing pointers to event handler functions
    //! provided by the client to support the operation of this device.
    //
    tCustomHandlers sCallbacks;

    //
    //! A pointer to the device descriptor for this device.
    //
    const unsigned char *pDeviceDescriptor;

    //
    //! A pointer to an array of configuration descriptor pointers.  Each entry
    //! in the array corresponds to one configuration that the device may be set
    //! to use by the USB host.  The number of entries in the array must
    //! match the bNumConfigurations value in the device descriptor
    //! array, pDeviceDescriptor.
    //
    const tConfigHeader * const *ppConfigDescriptors;

    //
    //! A pointer to the string descriptor array for this device.  This array
    //! must be arranged as follows:
    //!
    //!   - [0]   - Standard descriptor containing supported language codes.
    //!   - [1]   - String 1 for the first language listed in descriptor 0.
    //!   - [2]   - String 2 for the first language listed in descriptor 0.
    //!   - ...
    //!   - [n]   - String n for the first language listed in descriptor 0.
    //!   - [n+1] - String 1 for the second language listed in descriptor 0.
    //!   - ...
    //!   - [2n]  - String n for the second language listed in descriptor 0.
    //!   - [2n+1]- String 1 for the third language listed in descriptor 0.
    //!   - ...
    //!   - [3n]  - String n for the third language listed in descriptor 0.
    //!
    //! and so on.
    //
    const unsigned char * const *ppStringDescriptors;

    //
    //! The total number of descriptors provided in the ppStringDescriptors
    //! array.
    //
    unsigned int ulNumStringDescriptors;

    //
    //! A structure defining how the USB controller FIFO is to be partitioned
    //! between the various endpoints.  This member can be set to point to
    //! g_sUSBDefaultFIFOConfig if the default FIFO configuration is acceptable
    //! This configuration sets each endpoint FIFO to be single buffered and
    //! sized to hold the maximum packet size for the endpoint.
    //
    const tFIFOConfig *psFIFOConfig;

    //
    //! This value will be passed back to all call back functions so that
    //! they have access to individual instance data based on the this pointer.
    //
    void *pvInstance;
}
tDeviceInfo;

//*****************************************************************************
//
// Close the Doxygen group.
//! @}
//
//*****************************************************************************

//*****************************************************************************
//
//! \addtogroup general_usblib_api
//! @{
//
//*****************************************************************************

//*****************************************************************************
//
// USB descriptor parsing functions found in usbdesc.c
//
//*****************************************************************************

//*****************************************************************************
//
//! The USB_DESC_ANY label is used as a wild card in several of the descriptor
//! parsing APIs to determine whether or not particular search criteria should
//! be ignored.
//
//*****************************************************************************
#define USB_DESC_ANY 0xFFFFFFFF

extern unsigned int USBDescGetNum(tDescriptorHeader *psDesc,
                                   unsigned int ulSize, unsigned int ulType);
extern tDescriptorHeader *USBDescGet(tDescriptorHeader *psDesc,
                                     unsigned int ulSize,
                                     unsigned int ulType,
                                     unsigned int ulIndex);
extern unsigned int
       USBDescGetNumAlternateInterfaces(tConfigDescriptor *psConfig,
                                        unsigned char ucInterfaceNumber);
extern tInterfaceDescriptor *USBDescGetInterface(tConfigDescriptor *psConfig,
                                                 unsigned int ulIndex,
                                                 unsigned int ulAltCfg);
extern tEndpointDescriptor *
       USBDescGetInterfaceEndpoint(tInterfaceDescriptor *psInterface,
                                   unsigned int ulIndex,
                                   unsigned int ulSize);

//*****************************************************************************
//
//! The operating mode required by the USB library client.  This type is used
//! by applications which wish to be able to switch between host and device
//! modes by calling the USBStackModeSet() API.
//
//*****************************************************************************
typedef enum
{
    //
    //! The application wishes to operate as a USB device.
    //
    USB_MODE_DEVICE = 0,

    //
    //! The application wishes to operate as a USB host.
    //
    USB_MODE_HOST,

    //
    //! The application wishes to operate as both a host and device using
    //! On-The-Go protocols to negotiate.
    //
    USB_MODE_OTG,

    //
    //! A marker indicating that no USB mode has yet been set by the
    //! application.
    //
    USB_MODE_NONE
} tUSBMode;

//*****************************************************************************
//
// A pointer to a USB mode callback function.  This function is called by the
// USB library to indicate to the application which operating mode it should
// use, host or device.
//
//*****************************************************************************
typedef void (*tUSBModeCallback)(unsigned int ulIndex, tUSBMode eMode);

//*****************************************************************************
//
// Mode selection and dual mode interrupt steering functions.
//
//*****************************************************************************
extern void USBStackModeSet(unsigned int ulIndex, tUSBMode eUSBMode,
                            tUSBModeCallback pfnCallback);
extern void USBDualModeInit(unsigned int ulIndex);
extern void USBDualModeTerm(unsigned int ulIndex);
extern void USBOTGMain(unsigned int ulMsTicks);
extern void USBOTGPollRate(unsigned int ulIndex, unsigned int ulPollRate);
extern void USBOTGModeInit(unsigned int ulIndex, unsigned int ulPollRate,
                           void *pHostData, unsigned int ulHostDataSize);
extern void USBOTGModeTerm(unsigned int ulIndex);
extern void USB0OTGModeIntHandler(void);
extern void USB0DualModeIntHandler(void);

//*****************************************************************************
//
//! USB callback function.
//!
//! \param pvCBData is the callback pointer associated with the instance
//!  generating the callback.  This is a value provided by the client during
//! initialization of the instance making the callback.
//! \param ulEvent is the identifier of the asynchronous event which is being
//! notified to the client.
//! \param ulMsgParam is an event-specific parameter.
//! \param pvMsgData is an event-specific data pointer.
//!
//! A function pointer provided to the USB layer by the application
//! which will be called to notify it of all asynchronous events relating to
//! data transmission or reception.  This callback is used by device class
//! drivers and host pipe functions.
//!
//! \return Returns an event-dependent value.
//
//*****************************************************************************
typedef unsigned int (* tUSBCallback)(void *pvCBData, unsigned int ulEvent,
                                       unsigned int ulMsgParam,
                                       void *pvMsgData);

//*****************************************************************************
//
// Base identifiers for groups of USB events.  These are used by both the
// device class drivers and host layer.
//
// USB_CLASS_EVENT_BASE is the lowest identifier that should be used for
// a class-specific event.  Individual event bases are defined for each
// of the supported device class drivers.  Events with IDs between
// USB_EVENT_BASE and USB_CLASS_EVENT_BASE are reserved for stack use.
//
//*****************************************************************************
#define USB_EVENT_BASE          0x0000
#define USB_CLASS_EVENT_BASE    0x8000

//*****************************************************************************
// The below macro defines the number USB Instances.
//
//*****************************************************************************
#if defined (am335x_15x15) || defined(am335x) || defined(c6a811x)
#define USB_NUM_INSTANCE        2
#else
#define USB_NUM_INSTANCE        1
#endif
//
// Event base identifiers for the various device classes supported in host
// and device modes.
// The first 0x800 values of a range are reserved for the device specific
// messages and the second 0x800 values of a range are used for the host
// specific messages for a given class.
//
//*****************************************************************************
#define USBD_CDC_EVENT_BASE      (USB_CLASS_EVENT_BASE + 0)
#define USBD_HID_EVENT_BASE      (USB_CLASS_EVENT_BASE + 0x1000)
#define USBD_HID_KEYB_EVENT_BASE (USBD_HID_EVENT_BASE + 0x100)
#define USBD_BULK_EVENT_BASE     (USB_CLASS_EVENT_BASE + 0x2000)
#define USBD_MSC_EVENT_BASE      (USB_CLASS_EVENT_BASE + 0x3000)
#define USBD_AUDIO_EVENT_BASE    (USB_CLASS_EVENT_BASE + 0x4000)

#define USBH_CDC_EVENT_BASE   (USBD_CDC_EVENT_BASE  + 0x800)
#define USBH_HID_EVENT_BASE   (USBD_HID_EVENT_BASE  + 0x800)
#define USBH_BULK_EVENT_BASE  (USBD_BULK_EVENT_BASE + 0x800)
#define USBH_MSC_EVENT_BASE   (USBD_MSC_EVENT_BASE  + 0x800)
#define USBH_AUDIO_EVENT_BASE (USBD_AUDIO_EVENT_BASE  + 0x800)

//*****************************************************************************
//
// General events supported by device classes and host pipes.
//
//*****************************************************************************

//
//! The device is now attached to a USB host and ready to begin sending
//! and receiving data (used by device classes only).
//
#define USB_EVENT_CONNECTED (USB_EVENT_BASE + 0)

//
//! The device has been disconnected from the USB host (used by device classes
//! only).
//!
//! Note: Due to a hardware erratum in revision A of LM3S3748, this
//! event is not posted to self-powered USB devices when they are disconnected
//! from the USB host.
//
#define USB_EVENT_DISCONNECTED (USB_EVENT_BASE + 1)

//
//! Data has been received and is in the buffer provided.
//
#define USB_EVENT_RX_AVAILABLE (USB_EVENT_BASE + 2)

//
//! This event is sent by a lower layer to inquire about the amount of
//! unprocessed data buffered in the layers above.  It is used in cases
//! where a low level driver needs to ensure that all preceding data has
//! been processed prior to performing some action or making some notification.
//! Clients receiving this event should return the number of bytes of data
//! that are unprocessed or 0 if no outstanding data remains.
//
#define USB_EVENT_DATA_REMAINING (USB_EVENT_BASE + 3)

//
//! This event is sent by a lower layer supporting DMA to request a buffer in
//! which the next received packet may be stored.  The \e ulMsgValue parameter
//! indicates the maximum size of packet that can be received in this channel
//! and \e pvMsgData points to storage which should be written with the
//! returned buffer pointer.  The return value from the callback should be the
//! size of the buffer allocated (which may be less than the maximum size
//! passed in \e ulMsgValue if the client knows that fewer bytes are expected
//! to be received) or 0 if no buffer is being returned.
//
#define USB_EVENT_REQUEST_BUFFER (USB_EVENT_BASE + 4)

//
//! Data has been sent and acknowledged.  If this event is received via the
//! USB buffer callback, the \e ulMsgValue parameter indicates the number of
//! bytes from the transmit buffer that have been successfully transmitted
//! and acknowledged.
//
#define USB_EVENT_TX_COMPLETE (USB_EVENT_BASE + 5)

//
//! An error has been reported on the channel or pipe.  The \e ulMsgValue
//! parameter indicates the source(s) of the error and is the logical OR
//! combination of "USBERR_" flags defined below.
//
#define USB_EVENT_ERROR (USB_EVENT_BASE + 6)

//
//! The bus has entered suspend state.
//
#define USB_EVENT_SUSPEND (USB_EVENT_BASE + 7)

//
//! The bus has left suspend state.
//
#define USB_EVENT_RESUME (USB_EVENT_BASE + 8)

//
//! A scheduler event has occurred.
//
#define USB_EVENT_SCHEDULER     (USB_EVENT_BASE + 9)
//
//! A device or host has detected a stall condition.
//
#define USB_EVENT_STALL         (USB_EVENT_BASE + 10)

//
//! The host detected a power fault condition.
//
#define USB_EVENT_POWER_FAULT   (USB_EVENT_BASE + 11)

//
//! The controller has detected a A-Side cable and needs power applied  This is
//! only generated on OTG parts if automatic power control is disabled.
//
#define USB_EVENT_POWER_ENABLE  (USB_EVENT_BASE + 12)

//
//! The controller needs power removed,  This is only generated on OTG parts
//! if automatic power control is disabled.
//
#define USB_EVENT_POWER_DISABLE (USB_EVENT_BASE + 13)

//
//! Used with pfnDeviceHandler handler function is classes to indicate changes
//! in the interface number by a class outside the class being accessed.
//! Typically this is when composite device class is in use.
//!
//! The \e pvInstance value should point to an instance of the device being
//! accessed.
//!
//! The \e ulRequest should be USB_EVENT_COMP_IFACE_CHANGE.
//!
//! The \e pvRequestData should point to a two byte array where the first value
//! is the old interface number and the second is the new interface number.
//
#define USB_EVENT_COMP_IFACE_CHANGE (USB_EVENT_BASE + 14)

//
//! Used with pfnDeviceHandler handler function is classes to indicate changes
//! in endpoint number by a class outside the class being accessed.
//! Typically this is when composite device class is in use.
//!
//! The \e pvInstance value should point to an instance of the device being
//! accessed.
//!
//! The \e ulRequest should be USB_EVENT_COMP_EP_CHANGE.
//!
//! The \e pvRequestData should point to a two byte array where the first value
//! is the old endpoint number and the second is the new endpoint number.  The
//! endpoint numbers should be exactly as USB specification defines them and
//! bit 7 set indicates an IN endpoint and bit 7 clear indicates an OUT
//! endpoint.
//
#define USB_EVENT_COMP_EP_CHANGE    (USB_EVENT_BASE + 15)

//
//! Used with pfnDeviceHandler handler function is classes to indicate changes
//! in string index number by a class outside the class being accessed.
//! Typically this is when composite device class is in use.
//!
//! The \e pvInstance value should point to an instance of the device being
//! accessed.
//!
//! The \e ulRequest should be USB_EVENT_COMP_STR_CHANGE.
//!
//! The \e pvRequestData should point to a two byte array where the first value
//! is the old string index and the second is the new string index.
//
#define USB_EVENT_COMP_STR_CHANGE    (USB_EVENT_BASE + 16)

//
//! Used with pfnDeviceHandler handler function is classes to allow the device
//! class to make final adjustments to the configuration descriptor.
//! This is only used when a device class is used in a composite device class
//! is in use.
//!
//! The \e pvInstance value should point to an instance of the device being
//! accessed.
//!
//! The \e ulRequest should be USB_EVENT_COMP_CONFIG.
//!
//! The \e pvRequestData should point to the beginning of the configuration
//! descriptor for the device instance.
//
#define USB_EVENT_COMP_CONFIG        (USB_EVENT_BASE + 17)
#define USB_EVENT_BABBLE_ERROR       (USB_EVENT_BASE + 18)

//*****************************************************************************
//
// Error sources reported via USB_EVENT_ERROR.
//
//*****************************************************************************

//
//! The host received an invalid PID in a transaction.
//
#define USBERR_HOST_IN_PID_ERROR   0x01000000

//
//! The host did not receive a response from a device.
//
#define USBERR_HOST_IN_NOT_COMP    0x00100000

//
//! The host received a stall on an IN endpoint.
//
#define USBERR_HOST_IN_STALL       0x00400000

//
//! The host detected a CRC or bit-stuffing error (isochronous mode).
//
#define USBERR_HOST_IN_DATA_ERROR  0x00080000

//
//! The host received NAK on an IN endpoint for longer than the specified
//! timeout period (interrupt, bulk and control modes).
//
#define USBERR_HOST_IN_NAK_TO      0x00080000

//
//! The host failed to communicate with a device via an IN endpoint.
//
#define USBERR_HOST_IN_ERROR       0x00040000

//
//! The host receive FIFO is full.
//
#define USBERR_HOST_IN_FIFO_FULL   0x00020000  // RX FIFO full
//
//! The host received NAK on an OUT endpoint for longer than the specified
//! timeout period (bulk, interrupt and control modes).
//
#define USBERR_HOST_OUT_NAK_TO     0x00000080

//
//! The host did not receive a response from a device (isochronous mode).
//
#define USBERR_HOST_OUT_NOT_COMP   0x00000080

//
//! The host received a stall on an OUT endpoint.
//
#define USBERR_HOST_OUT_STALL      0x00000020

//
//! The host failed to communicate with a device via an OUT endpoint.
//
#define USBERR_HOST_OUT_ERROR      0x00000004

//
//! The host received NAK on endpoint 0 for longer than the configured
//! timeout.
//
#define USBERR_HOST_EP0_NAK_TO     0x00000080

//
//! The host failed to communicate with a device via an endpoint zero.
//
#define USBERR_HOST_EP0_ERROR      0x00000010

//
//! The device detected a CRC error in received data.
//
#define USBERR_DEV_RX_DATA_ERROR   0x00080000

//
//! The device was unable to receive a packet from the host since the receive
//! FIFO is full.
//
#define USBERR_DEV_RX_OVERRUN      0x00040000

//
//! The device receive FIFO is full.
//
#define USBERR_DEV_RX_FIFO_FULL    0x00020000  // RX FIFO full

//*****************************************************************************
//
// Close the general_usblib_api Doxygen group.
//! @}
//
//*****************************************************************************

//*****************************************************************************
//
//! \addtogroup usblib_buffer_api
//! @{
//
//*****************************************************************************

//*****************************************************************************
//
//! A function pointer type which describes either a class driver packet read
//! or packet write function (both have the same prototype) to the USB
//! buffer object.
//
//*****************************************************************************
typedef unsigned int (* tUSBPacketTransfer)(void *pvHandle,
                                             unsigned char *pcData,
                                             unsigned int ulLength,
                                             tBoolean bLast);

//*****************************************************************************
//
//! A function pointer type which describes either a class driver transmit
//! or receive packet available function (both have the same prototype) to the
//! USB buffer object.
//
//*****************************************************************************
typedef unsigned int (* tUSBPacketAvailable)(void *pvHandle);

//*****************************************************************************
//
//! The number of bytes of workspace that each USB buffer object requires.
//! This workspace memory is provided to the buffer on USBBufferInit() in
//! the \e pvWorkspace field of the \e tUSBBuffer structure.
//
//*****************************************************************************
#define USB_BUFFER_WORKSPACE_SIZE 16

//*****************************************************************************
//
//! The structure used by the application to initialize a buffer object that
//! will provide buffered access to either a transmit or receive channel.
//
//*****************************************************************************
typedef struct
{
    //
    //! This field sets the mode of the buffer.  If true, the buffer
    //! operates as a transmit buffer and supports calls to USBBufferWrite
    //! by the client.  If false, the buffer operates as a receive buffer
    //! and supports calls to USBBufferRead.
    //
    tBoolean bTransmitBuffer;

    //
    //! A pointer to the callback function which will be called to notify
    //! the application of all asynchronous events related to the operation
    //! of the buffer.
    //
    tUSBCallback pfnCallback;

    //
    //! A pointer that the buffer will pass back to the client in the
    //! first parameter of all callbacks related to this instance.
    //
    void *pvCBData;

    //
    //! The function which should be called to transmit a packet of data
    //! in transmit mode or receive a packet in receive mode.
    //
    tUSBPacketTransfer pfnTransfer;

    //
    //! The function which should be called to determine if the endpoint is
    //! ready to accept a new packet for transmission in transmit mode or
    //! to determine the size of the buffer required to read a packet in
    //! receive mode.
    //
    tUSBPacketAvailable pfnAvailable;

    //
    //! The handle to pass to the low level function pointers
    //! provided in the pfnTransfer and pfnAvailable members.  For USB device
    //! use, this is the psDevice parameter required by the relevant device
    //! class driver APIs.  For USB host use, this is the pipe identifier
    //! returned by USBHCDPipeAlloc.
    //
    void *pvHandle;

    //
    //! A pointer to memory to be used as the ring buffer for this
    //! instance.
    //
    unsigned char *pcBuffer;

    //
    //! The size, in bytes, of the buffer pointed to by pcBuffer.
    //
    unsigned int ulBufferSize;

    //
    //! A pointer to USB_BUFFER_WORKSPACE_SIZE bytes of RAM that the buffer
    //! object can use for workspace.
    //
    void *pvWorkspace;
}
tUSBBuffer;

//*****************************************************************************
//
//! The structure used for encapsulating all the items associated with a
//! ring buffer.
//
//*****************************************************************************
typedef struct
{
    //
    //! The ring buffer size.
    //
    unsigned int ulSize;

    //
    //! The ring buffer write index.
    //
    volatile unsigned int ulWriteIndex;

    //
    //! The ring buffer read index.
    //
    volatile unsigned int ulReadIndex;

    //
    //! The ring buffer.
    //
    unsigned char *pucBuf;
}
tUSBRingBufObject;

typedef struct
{

    //
    //USB Instance Number;
    //
    unsigned int uiUSBInstance;
    //
    //Base address of the USB instance
    //
    unsigned int uiBaseAddr;
    //
    //Base address of the USB sub system
    //
    unsigned int uiSubBaseAddr;
    //
    //USB Interuppt number
    //
    unsigned int uiInterruptNum;
    //
    //USB subsystem interrupt number
    //
    unsigned int uiSubInterruptNum;
    //
    //PHY config register address
    //
    unsigned int uiPHYConfigRegAddr;

} tUSBInstanceObject;
extern tUSBInstanceObject g_USBInstance[];

typedef struct _tUSBPerfInfo_
{
	unsigned int ulBytesToTransfer;
	unsigned int ulTimeInTicks;
}tUSBPerfInfo;

extern tUSBPerfInfo g_USBPerfInfo[];
extern unsigned int ulPerfInfoCounter;
extern unsigned int fReadEnabled;
extern unsigned int fWriteEnabled;
extern unsigned int fUSBDisconnected;
//#define PROFILE_USB_MSC_READ
//#define PROFILE_USB_MSC_WRITE

//*****************************************************************************
//
// USB buffer API function prototypes.
//
//*****************************************************************************
extern const tUSBBuffer *USBBufferInit(const tUSBBuffer *psBuffer);
extern void USBBufferInfoGet(const tUSBBuffer *psBuffer,
                             tUSBRingBufObject *psRingBuf);
extern void *USBBufferCallbackDataSet(tUSBBuffer *psBuffer, void *pvCBData);
extern unsigned int USBBufferWrite(const tUSBBuffer *psBuffer,
                                    const unsigned char *pucData,
                                    unsigned int ulLength);
extern void USBBufferDataWritten(const tUSBBuffer *psBuffer,
                                 unsigned int ulLength);
extern void USBBufferDataRemoved(const tUSBBuffer *psBuffer,
                                 unsigned int ulLength);
extern void USBBufferFlush(const tUSBBuffer *psBuffer);
extern unsigned int USBBufferRead(const tUSBBuffer *psBuffer,
                                   unsigned char *pucData,
                                   unsigned int ulLength);
extern unsigned int USBBufferDataAvailable(const tUSBBuffer *psBuffer);
extern unsigned int USBBufferSpaceAvailable(const tUSBBuffer *psBuffer);
extern unsigned int USBBufferEventCallback(void *pvCBData,
                                            unsigned int ulEvent,
                                            unsigned int ulMsgValue,
                                            void *pvMsgData);
extern tBoolean USBRingBufFull(tUSBRingBufObject *ptUSBRingBuf);
extern tBoolean USBRingBufEmpty(tUSBRingBufObject *ptUSBRingBuf);
extern void USBRingBufFlush(tUSBRingBufObject *ptUSBRingBuf);
extern unsigned int USBRingBufUsed(tUSBRingBufObject *ptUSBRingBuf);
extern unsigned int USBRingBufFree(tUSBRingBufObject *ptUSBRingBuf);
extern unsigned int USBRingBufContigUsed(tUSBRingBufObject *ptUSBRingBuf);
extern unsigned int USBRingBufContigFree(tUSBRingBufObject *ptUSBRingBuf);
extern unsigned int USBRingBufSize(tUSBRingBufObject *ptUSBRingBuf);
extern unsigned char USBRingBufReadOne(tUSBRingBufObject *ptUSBRingBuf);
extern void USBRingBufRead(tUSBRingBufObject *ptUSBRingBuf,
                           unsigned char *pucData, unsigned int ulLength);
extern void USBRingBufWriteOne(tUSBRingBufObject *ptUSBRingBuf,
                               unsigned char ucData);
extern void USBRingBufWrite(tUSBRingBufObject *ptUSBRingBuf,
                            const unsigned char *pucData,
                            unsigned int ulLength);
extern void USBRingBufAdvanceWrite(tUSBRingBufObject *ptUSBRingBuf,
                                   unsigned int ulNumBytes);
extern void USBRingBufAdvanceRead(tUSBRingBufObject *ptUSBRingBuf,
                                  unsigned int ulNumBytes);
extern void USBRingBufInit(tUSBRingBufObject *ptUSBRingBuf,
                           unsigned char *pucBuf, unsigned int ulSize);

//*****************************************************************************
//
// Close the Doxygen group.
//! @}
//
//*****************************************************************************

//*****************************************************************************
//
// Mark the end of the C bindings section for C++ compilers.
//
//*****************************************************************************
#ifdef __cplusplus
}
#endif

#endif // __USBLIB_H__


text:
package com.iluwatar.hexagonal.eventlog;

import com.iluwatar.hexagonal.domain.PlayerDetails;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;

/**
 * Mongo based event log.
 */
public class MongoEventLog implements LotteryEventLog {

  private static final String DEFAULT_DB = "lotteryDB";
  private static final String DEFAULT_EVENTS_COLLECTION = "events";

  private MongoClient mongoClient;
  private MongoDatabase database;
  private MongoCollection<Document> eventsCollection;

  private StdOutEventLog stdOutEventLog = new StdOutEventLog();

  /**
   * Constructor.
   */
  public MongoEventLog() {
    connect();
  }

  /**
   * Constructor accepting parameters.
   */
  public MongoEventLog(String dbName, String eventsCollectionName) {
    connect(dbName, eventsCollectionName);
  }

  /**
   * Connect to database with default parameters.
   */
  public void connect() {
    connect(DEFAULT_DB, DEFAULT_EVENTS_COLLECTION);
  }

  /**
   * Connect to database with given parameters.
   */
  public void connect(String dbName, String eventsCollectionName) {
    if (mongoClient != null) {
      mongoClient.close();
    }
    mongoClient = new MongoClient(System.getProperty("mongo-host"),
        Integer.parseInt(System.getProperty("mongo-port")));
    database = mongoClient.getDatabase(dbName);
    eventsCollection = database.getCollection(eventsCollectionName);
  }

  /**
   * Get mongo client.
   *
   * @return mongo client
   */
  public MongoClient getMongoClient() {
    return mongoClient;
  }

  /**
   * Get mongo database.
   *
   * @return mongo database
   */
  public MongoDatabase getMongoDatabase() {
    return database;
  }

  /**
   * Get events collection.
   *
   * @return events collection
   */
  public MongoCollection<Document> getEventsCollection() {
    return eventsCollection;
  }

  @Override
  public void ticketSubmitted(PlayerDetails details) {
    var document = new Document("email", details.getEmail());
    document.put("phone", details.getPhoneNumber());
    document.put("bank", details.getBankAccount());
    document
        .put("message", "Lottery ticket was submitted and bank account was charged for 3 credits.");
    eventsCollection.insertOne(document);
    stdOutEventLog.ticketSubmitted(details);
  }

  @Override
  public void ticketSubmitError(PlayerDetails details) {
    var document = new Document("email", details.getEmail());
    document.put("phone", details.getPhoneNumber());
    document.put("bank", details.getBankAccount());
    document.put("message", "Lottery ticket could not be submitted because lack of funds.");
    eventsCollection.insertOne(document);
    stdOutEventLog.ticketSubmitError(details);
  }

  @Override
  public void ticketDidNotWin(PlayerDetails details) {
    var document = new Document("email", details.getEmail());
    document.put("phone", details.getPhoneNumber());
    document.put("bank", details.getBankAccount());
    document.put("message", "Lottery ticket was checked and unfortunately did not win this time.");
    eventsCollection.insertOne(document);
    stdOutEventLog.ticketDidNotWin(details);
  }

  @Override
  public void ticketWon(PlayerDetails details, int prizeAmount) {
    var document = new Document("email", details.getEmail());
    document.put("phone", details.getPhoneNumber());
    document.put("bank", details.getBankAccount());
    document.put("message", String
        .format("Lottery ticket won! The bank account was deposited with %d credits.",
            prizeAmount));
    eventsCollection.insertOne(document);
    stdOutEventLog.ticketWon(details, prizeAmount);
  }

  @Override
  public void prizeError(PlayerDetails details, int prizeAmount) {
    var document = new Document("email", details.getEmail());
    document.put("phone", details.getPhoneNumber());
    document.put("bank", details.getBankAccount());
    document.put("message", String
        .format("Lottery ticket won! Unfortunately the bank credit transfer of %d failed.",
            prizeAmount));
    eventsCollection.insertOne(document);
    stdOutEventLog.prizeError(details, prizeAmount);
  }
}