text:
Q: Oracle Apex Pl/SQL - Canonical String from JSON Format I am using Oracle Apex 22.2 and Oracle Database XE 21c on CentOS 7. I want to loop through all the nested elements in a JSON document/CLOB and achieve the Canonical String (shown below). Also, any suggestions on improving my procedure or on a different solution to handle this would be appreciated. I wrote my own procedure shown below following the algorithm shown below. All help and suggestions are really appreciated.
Algorithm Pseudo Code
function string Serialize(documentStructure)

    if documentStructure is simple value type
        return """ + documentStructure.value + """
    end if

    var serializedString = ""

    foreach element in the structure:

        if element is not array type
            serializeString.Append (""" + element.name.uppercase + """)
            serializeString.Append ( Serialize(element.value) )
        end if

        if element is of array type
            serializeString.Append (""" + element.name.uppercase + """)
            foreach array element in element:
                // use below line for JSON because subelements of array in JSON do not have own names
                serializeString.Append (""" + element.name.uppercase + """)
                serializeString.Append ( Serialize(arrayelement.value) )
            end foreach
        end if

    end foreach

    return serializedString
end function

Procedure Code
create or replace PROCEDURE ETA_JSON_SERIALIZE (json_in IN JSON_ELEMENT_T, can_str IN OUT VARCHAR2)
IS
    l_object    JSON_OBJECT_T;
    l_array     JSON_ARRAY_T;
    l_keys      JSON_KEY_LIST;
    l_str       VARCHAR2(32767);
BEGIN
    FOR i IN 1 .. json_in.get_Size LOOP
        IF json_in.is_Scalar() THEN
            IF json_in.is_String() THEN
                l_str := '"' || json_in.to_String() || '" 1st Line Break' || CHR(10);
                DBMS_OUTPUT.PUT_LINE(l_str);
                RETURN;
            ELSIF json_in.is_Number() THEN
                l_str := '"' || json_in.to_Number() || '" 2nd Line Break' || CHR(10);
                DBMS_OUTPUT.PUT_LINE(l_str);
                RETURN;
            ELSE
                l_str := 'Other Scalar' || ' 3rd Line Break' || CHR(10);
                DBMS_OUTPUT.PUT_LINE(l_str);
            END IF;
        ELSIF json_in.is_Object() THEN
            -- l_str := 'Object:' || CHR(10);
            -- DBMS_OUTPUT.PUT_LINE(l_str);
            l_object := JSON_OBJECT_T( json_in );
            -- l_object.on_Error(1);
            l_keys := l_object.get_Keys();
            -- l_str := '     Element Size: ' || json_in.get_Size || CHR(10);
            -- l_str := '     Key Count: ' || l_keys.COUNT || CHR(10);
            -- DBMS_OUTPUT.PUT_LINE(l_str);
            l_str := UPPER(l_keys(i)) || ' 4th Line Break' || CHR(10);
            DBMS_OUTPUT.PUT_LINE(l_str);
            ETA_JSON_SERIALIZE( l_object.get( l_keys(i) ), l_str );
        ELSIF json_in.is_Array() THEN
            -- l_str := l_str || 'Array:' || CHR(10);
            -- DBMS_OUTPUT.PUT_LINE(l_str);
            l_array := JSON_ARRAY_T( json_in );
            -- l_array.on_Error(1);
            -- l_str := '     Element Size: ' || json_in.get_Size || CHR(10);
            -- DBMS_OUTPUT.PUT_LINE(l_str);
            -- l_str := '     Array Size: ' || l_array.get_Size || CHR(10);
            -- DBMS_OUTPUT.PUT_LINE(l_str);
            -- FOR j IN 0 .. l_array.get_Size - 1 LOOP
                ETA_JSON_SERIALIZE( l_array.get(i - 1), l_str );
            -- END LOOP;
        ELSE
            l_str := 'Other Type' || CHR(10)  || '5th Line Break' || CHR(10);
            DBMS_OUTPUT.PUT_LINE(l_str);
        END IF;
    END LOOP;
    can_str := l_str;
END;

PL/SQL Block
SET SERVEROUTPUT ON
DECLARE
   can_str     VARCHAR2(32767);
   l_element   JSON_ELEMENT_T;
   l_element1  JSON_ELEMENT_T;
   l_object    JSON_OBJECT_T;
   l_keys      JSON_KEY_LIST;
   l_doc       CLOB := '{a:100, b:200, c:300}';
   l_doc1      CLOB := '{
   "department": "Accounting",
   "employees": [
   {
   "name": "Shelley,Higgins",
   "job": "Accounting Manager"
   },
   {
   "name": "William,Gietz",
   "job": "Public Accountant"
   }
   ]
   }';

   l_doc2      CLOB := '{
   "REQS": {
   "INDICATOR": "Y",
   "NUMBER": 0,
   "CATEGORY": "TU",
   "ID_R": 10888,
   "SUPPL_VAL": 0,
   "LINE_ITEMSSUB": {
   "QTY": 0,
   "TOTAL_QTY": 1,
   "PIPE": {
   "P_CODE": 9801,
   "P_ID": 7500030,
   "CC_CODE": "C6AJG4"
   }
   }
   },
   "Name": "Rajesh",
   "Age": 47
   }';
   l_doc3      CLOB := '{
   "documents": [{
      "issuer": {
         "type": "B",
         "id": "301188475",
         "name": "Hakim Misr Paco (POS-0)",
         "address": {
            "branchID": "-1",
            "country": "EG",
            "governate": "Cairo",
            "regionCity": "Nasr City",
            "street": "Mostafa El Nahas",
            "buildingNumber": "65"
         }
      },
      "receiver": {
         "type": "P",
         "id": " 29409200104255",
         "name": "Karim Ahmed Abdelhakim Hashem",
         "address": {
            "country": "EG",
            "governate": "Cairo",
            "regionCity": "Nasr City",
            "street": "Mostafa El Nahas",
            "buildingNumber": "65"
         }
      },
      "documentType": "I",
      "documentTypeVersion": "0.9",
      "dateTimeIssued": "2022-11-19T23:59:59Z",
      "taxpayerActivityCode": "2220",
      "internalID": "0-1",
      "invoiceLines": [{
         "description": "KFC_Test",
         "itemType": "GS1",
         "itemCode": "10006331",
         "unitType": "EA",
         "quantity": 1000,
         "unitValue": {
            "currencySold": "EGP",
            "amountEGP": 0.10000,
            "amountSold": 0
         },
         "salesTotal": 100,
         "total": 114,
         "valueDifference": 0,
         "totalTaxableFees": 0,
         "netTotal": 100,
         "itemsDiscount": 0,
         "discount": {
            "rate": 0,
            "amount": 0
         },
         "taxableItems": [{
            "taxType": "T1",
            "amount": 14,
            "subType": "V009",
            "rate": 14
         }],
         "internalCode": "Test_110"
      }],
      "totalSalesAmount": 100,
      "totalDiscountAmount": 0,
      "netAmount": 100,
      "taxTotals": [{
         "taxType": "T1",
         "amount": 14
      }],
      "extraDiscountAmount": 0,
      "totalItemsDiscountAmount": 0,
      "totalAmount": 114,
      "signatures": [{
         "signatureType": "I",
         "value": "NA"
      }]
   }]
}';

BEGIN
   l_element := JSON_ELEMENT_T.parse( l_doc3 );
   ETA_JSON_SERIALIZE(l_element, can_str);
   DBMS_OUTPUT.PUT_LINE(can_str);
END;
/

JSON Format
<pre>
{
    "issuer": {
        "address": {
            "branchID": "1",
            "country": "EG",
            "governate": "Cairo",
            "regionCity": "Nasr City",
            "street": "580 Clementina Key",
            "buildingNumber": "Bldg. 0",
            "postalCode": "68030",
            "floor": "1",
            "room": "123",
            "landmark": "7660 Melody Trail",
            "additionalInformation": "beside Townhall"
        },
        "type": "B",
        "id": "113317713",
        "name": "Issuer Company"
    },
    "receiver": {
        "address": {
            "country": "EG",
            "governate": "Egypt",
            "regionCity": "Mufazat al Ismlyah",
            "street": "580 Clementina Key",
            "buildingNumber": "Bldg. 0",
            "postalCode": "68030",
            "floor": "1",
            "room": "123",
            "landmark": "7660 Melody Trail",
            "additionalInformation": "beside Townhall"
        },
        "type": "B",
        "id": "313717919",
        "name": "Receiver"
    },
    "documentType": "I",
    "documentTypeVersion": "0.9",
    "dateTimeIssued": "2020-10-27T23:59:59Z",
    "taxpayerActivityCode": "4620",
    "internalID": "IID1",
    "purchaseOrderReference": "P-233-A6375",
    "purchaseOrderDescription": "purchase Order description",
    "salesOrderReference": "1231",
    "salesOrderDescription": "Sales Order description",
    "proformaInvoiceNumber": "SomeValue",
    "payment": {
        "bankName": "SomeValue",
        "bankAddress": "SomeValue",
        "bankAccountNo": "SomeValue",
        "bankAccountIBAN": "",
        "swiftCode": "",
        "terms": "SomeValue"
    },
    "delivery": {
        "approach": "SomeValue",
        "packaging": "SomeValue",
        "dateValidity": "2020-09-28T09:30:10Z",
        "exportPort": "SomeValue",
        "countryOfOrigin": "EG",
        "grossWeight": 10.50,
        "netWeight": 20.50,
        "terms": "SomeValue"
    },
    "invoiceLines": [
        {
            "description": "Computer1",
            "itemType": "GPC",
            "itemCode": "10001774",
            "unitType": "EA",
            "quantity": 5,
            "internalCode": "IC0",
            "salesTotal": 947.00,
            "total": 2969.89,
            "valueDifference": 7.00,
            "totalTaxableFees": 817.42,
            "netTotal": 880.71,
            "itemsDiscount": 5.00,
            "unitValue": {
                "currencySold": "EUR",
                "amountEGP": 189.40,
                "amountSold": 10.00,
                "currencyExchangeRate": 18.94
            },
            "discount": {
                "rate": 7,
                "amount": 66.29
            },
            "taxableItems": [
                {
                    "taxType": "T1",
                    "amount": 272.07,
                    "subType": "T1",
                    "rate": 14.00
                },
                {
                    "taxType": "T2",
                    "amount": 208.22,
                    "subType": "T2",
                    "rate": 12
                },
                {
                    "taxType": "T3",
                    "amount": 30.00,
                    "subType": "T3",
                    "rate": 0.00
                },
                {
                    "taxType": "T4",
                    "amount": 43.79,
                    "subType": "T4",
                    "rate": 5.00
                },
                {
                    "taxType": "T5",
                    "amount": 123.30,
                    "subType": "T5",
                    "rate": 14.00
                },
                {
                    "taxType": "T6",
                    "amount": 60.00,
                    "subType": "T6",
                    "rate": 0.00
                },
                {
                    "taxType": "T7",
                    "amount": 88.07,
                    "subType": "T7",
                    "rate": 10.00
                },
                {
                    "taxType": "T8",
                    "amount": 123.30,
                    "subType": "T8",
                    "rate": 14.00
                },
                {
                    "taxType": "T9",
                    "amount": 105.69,
                    "subType": "T9",
                    "rate": 12.00
                },
                {
                    "taxType": "T10",
                    "amount": 88.07,
                    "subType": "T10",
                    "rate": 10.00
                },
                {
                    "taxType": "T11",
                    "amount": 123.30,
                    "subType": "T11",
                    "rate": 14.00
                },
                {
                    "taxType": "T12",
                    "amount": 105.69,
                    "subType": "T12",
                    "rate": 12.00
                },
                {
                    "taxType": "T13",
                    "amount": 88.07,
                    "subType": "T13",
                    "rate": 10.00
                },
                {
                    "taxType": "T14",
                    "amount": 123.30,
                    "subType": "T14",
                    "rate": 14.00
                },
                {
                    "taxType": "T15",
                    "amount": 105.69,
                    "subType": "T15",
                    "rate": 12.00
                },
                {
                    "taxType": "T16",
                    "amount": 88.07,
                    "subType": "T16",
                    "rate": 10.00
                },
                {
                    "taxType": "T17",
                    "amount": 88.07,
                    "subType": "T17",
                    "rate": 10.00
                },
                {
                    "taxType": "T18",
                    "amount": 123.30,
                    "subType": "T18",
                    "rate": 14.00
                },
                {
                    "taxType": "T19",
                    "amount": 105.69,
                    "subType": "T19",
                    "rate": 12.00
                },
                {
                    "taxType": "T20",
                    "amount": 88.07,
                    "subType": "T20",
                    "rate": 10.00
                }
            ]
        },
        {
            "description": "Computer2",
            "itemType": "GPC",
            "itemCode": "10003752",
            "unitType": "EA",
            "quantity": 7,
            "internalCode": "IC0",
            "salesTotal": 662.90,
            "total": 2226.61,
            "valueDifference": 6.00,
            "totalTaxableFees": 621.51,
            "netTotal": 652.90,
            "itemsDiscount": 9.00,
            "unitValue": {
                "currencySold": "EUR",
                "amountEGP": 94.70,
                "amountSold": 5.00,
                "currencyExchangeRate": 18.94
            },
            "discount": {
                "rate": 0,
                "amount": 10.00
            },
            "taxableItems": [
                {
                    "taxType": "T1",
                    "amount": 205.47,
                    "subType": "T1",
                    "rate": 14.00
                },
                {
                    "taxType": "T2",
                    "amount": 157.25,
                    "subType": "T2",
                    "rate": 12
                },
                {
                    "taxType": "T3",
                    "amount": 30.00,
                    "subType": "T3",
                    "rate": 0.00
                },
                {
                    "taxType": "T4",
                    "amount": 32.20,
                    "subType": "T4",
                    "rate": 5.00
                },
                {
                    "taxType": "T5",
                    "amount": 91.41,
                    "subType": "T5",
                    "rate": 14.00
                },
                {
                    "taxType": "T6",
                    "amount": 60.00,
                    "subType": "T6",
                    "rate": 0.00
                },
                {
                    "taxType": "T7",
                    "amount": 65.29,
                    "subType": "T7",
                    "rate": 10.00
                },
                {
                    "taxType": "T8",
                    "amount": 91.41,
                    "subType": "T8",
                    "rate": 14.00
                },
                {
                    "taxType": "T9",
                    "amount": 78.35,
                    "subType": "T9",
                    "rate": 12.00
                },
                {
                    "taxType": "T10",
                    "amount": 65.29,
                    "subType": "T10",
                    "rate": 10.00
                },
                {
                    "taxType": "T11",
                    "amount": 91.41,
                    "subType": "T11",
                    "rate": 14.00
                },
                {
                    "taxType": "T12",
                    "amount": 78.35,
                    "subType": "T12",
                    "rate": 12.00
                },
                {
                    "taxType": "T13",
                    "amount": 65.29,
                    "subType": "T13",
                    "rate": 10.00
                },
                {
                    "taxType": "T14",
                    "amount": 91.41,
                    "subType": "T14",
                    "rate": 14.00
                },
                {
                    "taxType": "T15",
                    "amount": 78.35,
                    "subType": "T15",
                    "rate": 12.00
                },
                {
                    "taxType": "T16",
                    "amount": 65.29,
                    "subType": "T16",
                    "rate": 10.00
                },
                {
                    "taxType": "T17",
                    "amount": 65.29,
                    "subType": "T17",
                    "rate": 10.00
                },
                {
                    "taxType": "T18",
                    "amount": 91.41,
                    "subType": "T18",
                    "rate": 14.00
                },
                {
                    "taxType": "T19",
                    "amount": 78.35,
                    "subType": "T19",
                    "rate": 12.00
                },
                {
                    "taxType": "T20",
                    "amount": 65.29,
                    "subType": "T20",
                    "rate": 10.00
                }
            ]
        }
    ],
    "totalDiscountAmount": 76.29,
    "totalSalesAmount": 1609.90,
    "netAmount": 1533.61,
    "taxTotals": [
        {
            "taxType": "T1",
            "amount": 477.54
        },
        {
            "taxType": "T2",
            "amount": 365.47
        },
        {
            "taxType": "T3",
            "amount": 60.00
        },
        {
            "taxType": "T4",
            "amount": 75.99
        },
        {
            "taxType": "T5",
            "amount": 214.71
        },
        {
            "taxType": "T6",
            "amount": 120.00
        },
        {
            "taxType": "T7",
            "amount": 153.36
        },
        {
            "taxType": "T8",
            "amount": 214.71
        },
        {
            "taxType": "T9",
            "amount": 184.04
        },
        {
            "taxType": "T10",
            "amount": 153.36
        },
        {
            "taxType": "T11",
            "amount": 214.71
        },
        {
            "taxType": "T12",
            "amount": 184.04
        },
        {
            "taxType": "T13",
            "amount": 153.36
        },
        {
            "taxType": "T14",
            "amount": 214.71
        },
        {
            "taxType": "T15",
            "amount": 184.04
        },
        {
            "taxType": "T16",
            "amount": 153.36
        },
        {
            "taxType": "T17",
            "amount": 153.36
        },
        {
            "taxType": "T18",
            "amount": 214.71
        },
        {
            "taxType": "T19",
            "amount": 184.04
        },
        {
            "taxType": "T20",
            "amount": 153.36
        }
    ],
    "totalAmount": 5191.50,
    "extraDiscountAmount": 5.00,
    "totalItemsDiscountAmount": 14.00
}

Canonical String

    "ISSUER""ADDRESS""BRANCHID""1""COUNTRY""EG""GOVERNATE""Cairo""REGIONCITY""Nasr City""STREET""580 Clementina Key""BUILDINGNUMBER""Bldg. 0""POSTALCODE""68030""FLOOR""1""ROOM""123""LANDMARK""7660 Melody Trail""ADDITIONALINFORMATION""beside Townhall""TYPE""B""ID""113317713""NAME""Issuer Company""RECEIVER""ADDRESS""COUNTRY""EG""GOVERNATE""Egypt""REGIONCITY""Mufazat al Ismlyah""STREET""580 Clementina Key""BUILDINGNUMBER""Bldg. 0""POSTALCODE""68030""FLOOR""1""ROOM""123""LANDMARK""7660 Melody Trail""ADDITIONALINFORMATION""beside Townhall""TYPE""B""ID""313717919""NAME""Receiver""DOCUMENTTYPE""I""DOCUMENTTYPEVERSION""0.9""DATETIMEISSUED""2020-10-27T23:59:59Z""TAXPAYERACTIVITYCODE""4620""INTERNALID""IID1""PURCHASEORDERREFERENCE""P-233-A6375""PURCHASEORDERDESCRIPTION""purchase Order description""SALESORDERREFERENCE""1231""SALESORDERDESCRIPTION""Sales Order description""PROFORMAINVOICENUMBER""SomeValue""PAYMENT""BANKNAME""SomeValue""BANKADDRESS""SomeValue""BANKACCOUNTNO""SomeValue""BANKACCOUNTIBAN""""SWIFTCODE""""TERMS""SomeValue""DELIVERY""APPROACH""SomeValue""PACKAGING""SomeValue""DATEVALIDITY""2020-09-28T09:30:10Z""EXPORTPORT""SomeValue""COUNTRYOFORIGIN""EG""GROSSWEIGHT""10.50""NETWEIGHT""20.50""TERMS""SomeValue""INVOICELINES""INVOICELINES""DESCRIPTION""Computer1""ITEMTYPE""GPC""ITEMCODE""10001774""UNITTYPE""EA""QUANTITY""5""INTERNALCODE""IC0""SALESTOTAL""947.00""TOTAL""2969.89""VALUEDIFFERENCE""7.00""TOTALTAXABLEFEES""817.42""NETTOTAL""880.71""ITEMSDISCOUNT""5.00""UNITVALUE""CURRENCYSOLD""EUR""AMOUNTEGP""189.40""AMOUNTSOLD""10.00""CURRENCYEXCHANGERATE""18.94""DISCOUNT""RATE""7""AMOUNT""66.29""TAXABLEITEMS""TAXABLEITEMS""TAXTYPE""T1""AMOUNT""272.07""SUBTYPE""T1""RATE""14.00""TAXABLEITEMS""TAXTYPE""T2""AMOUNT""208.22""SUBTYPE""T2""RATE""12""TAXABLEITEMS""TAXTYPE""T3""AMOUNT""30.00""SUBTYPE""T3""RATE""0.00""TAXABLEITEMS""TAXTYPE""T4""AMOUNT""43.79""SUBTYPE""T4""RATE""5.00""TAXABLEITEMS""TAXTYPE""T5""AMOUNT""123.30""SUBTYPE""T5""RATE""14.00""TAXABLEITEMS""TAXTYPE""T6""AMOUNT""60.00""SUBTYPE""T6""RATE""0.00""TAXABLEITEMS""TAXTYPE""T7""AMOUNT""88.07""SUBTYPE""T7""RATE""10.00""TAXABLEITEMS""TAXTYPE""T8""AMOUNT""123.30""SUBTYPE""T8""RATE""14.00""TAXABLEITEMS""TAXTYPE""T9""AMOUNT""105.69""SUBTYPE""T9""RATE""12.00""TAXABLEITEMS""TAXTYPE""T10""AMOUNT""88.07""SUBTYPE""T10""RATE""10.00""TAXABLEITEMS""TAXTYPE""T11""AMOUNT""123.30""SUBTYPE""T11""RATE""14.00""TAXABLEITEMS""TAXTYPE""T12""AMOUNT""105.69""SUBTYPE""T12""RATE""12.00""TAXABLEITEMS""TAXTYPE""T13""AMOUNT""88.07""SUBTYPE""T13""RATE""10.00""TAXABLEITEMS""TAXTYPE""T14""AMOUNT""123.30""SUBTYPE""T14""RATE""14.00""TAXABLEITEMS""TAXTYPE""T15""AMOUNT""105.69""SUBTYPE""T15""RATE""12.00""TAXABLEITEMS""TAXTYPE""T16""AMOUNT""88.07""SUBTYPE""T16""RATE""10.00""TAXABLEITEMS""TAXTYPE""T17""AMOUNT""88.07""SUBTYPE""T17""RATE""10.00""TAXABLEITEMS""TAXTYPE""T18""AMOUNT""123.30""SUBTYPE""T18""RATE""14.00""TAXABLEITEMS""TAXTYPE""T19""AMOUNT""105.69""SUBTYPE""T19""RATE""12.00""TAXABLEITEMS""TAXTYPE""T20""AMOUNT""88.07""SUBTYPE""T20""RATE""10.00""INVOICELINES""DESCRIPTION""Computer2""ITEMTYPE""GPC""ITEMCODE""10003752""UNITTYPE""EA""QUANTITY""7""INTERNALCODE""IC0""SALESTOTAL""662.90""TOTAL""2226.61""VALUEDIFFERENCE""6.00""TOTALTAXABLEFEES""621.51""NETTOTAL""652.90""ITEMSDISCOUNT""9.00""UNITVALUE""CURRENCYSOLD""EUR""AMOUNTEGP""94.70""AMOUNTSOLD""5.00""CURRENCYEXCHANGERATE""18.94""DISCOUNT""RATE""0""AMOUNT""10.00""TAXABLEITEMS""TAXABLEITEMS""TAXTYPE""T1""AMOUNT""205.47""SUBTYPE""T1""RATE""14.00""TAXABLEITEMS""TAXTYPE""T2""AMOUNT""157.25""SUBTYPE""T2""RATE""12""TAXABLEITEMS""TAXTYPE""T3""AMOUNT""30.00""SUBTYPE""T3""RATE""0.00""TAXABLEITEMS""TAXTYPE""T4""AMOUNT""32.20""SUBTYPE""T4""RATE""5.00""TAXABLEITEMS""TAXTYPE""T5""AMOUNT""91.41""SUBTYPE""T5""RATE""14.00""TAXABLEITEMS""TAXTYPE""T6""AMOUNT""60.00""SUBTYPE""T6""RATE""0.00""TAXABLEITEMS""TAXTYPE""T7""AMOUNT""65.29""SUBTYPE""T7""RATE""10.00""TAXABLEITEMS""TAXTYPE""T8""AMOUNT""91.41""SUBTYPE""T8""RATE""14.00""TAXABLEITEMS""TAXTYPE""T9""AMOUNT""78.35""SUBTYPE""T9""RATE""12.00""TAXABLEITEMS""TAXTYPE""T10""AMOUNT""65.29""SUBTYPE""T10""RATE""10.00""TAXABLEITEMS""TAXTYPE""T11""AMOUNT""91.41""SUBTYPE""T11""RATE""14.00""TAXABLEITEMS""TAXTYPE""T12""AMOUNT""78.35""SUBTYPE""T12""RATE""12.00""TAXABLEITEMS""TAXTYPE""T13""AMOUNT""65.29""SUBTYPE""T13""RATE""10.00""TAXABLEITEMS""TAXTYPE""T14""AMOUNT""91.41""SUBTYPE""T14""RATE""14.00""TAXABLEITEMS""TAXTYPE""T15""AMOUNT""78.35""SUBTYPE""T15""RATE""12.00""TAXABLEITEMS""TAXTYPE""T16""AMOUNT""65.29""SUBTYPE""T16""RATE""10.00""TAXABLEITEMS""TAXTYPE""T17""AMOUNT""65.29""SUBTYPE""T17""RATE""10.00""TAXABLEITEMS""TAXTYPE""T18""AMOUNT""91.41""SUBTYPE""T18""RATE""14.00""TAXABLEITEMS""TAXTYPE""T19""AMOUNT""78.35""SUBTYPE""T19""RATE""12.00""TAXABLEITEMS""TAXTYPE""T20""AMOUNT""65.29""SUBTYPE""T20""RATE""10.00""TOTALDISCOUNTAMOUNT""76.29""TOTALSALESAMOUNT""1609.90""NETAMOUNT""1533.61""TAXTOTALS""TAXTOTALS""TAXTYPE""T1""AMOUNT""477.54""TAXTOTALS""TAXTYPE""T2""AMOUNT""365.47""TAXTOTALS""TAXTYPE""T3""AMOUNT""60.00""TAXTOTALS""TAXTYPE""T4""AMOUNT""75.99""TAXTOTALS""TAXTYPE""T5""AMOUNT""214.71""TAXTOTALS""TAXTYPE""T6""AMOUNT""120.00""TAXTOTALS""TAXTYPE""T7""AMOUNT""153.36""TAXTOTALS""TAXTYPE""T8""AMOUNT""214.71""TAXTOTALS""TAXTYPE""T9""AMOUNT""184.04""TAXTOTALS""TAXTYPE""T10""AMOUNT""153.36""TAXTOTALS""TAXTYPE""T11""AMOUNT""214.71""TAXTOTALS""TAXTYPE""T12""AMOUNT""184.04""TAXTOTALS""TAXTYPE""T13""AMOUNT""153.36""TAXTOTALS""TAXTYPE""T14""AMOUNT""214.71""TAXTOTALS""TAXTYPE""T15""AMOUNT""184.04""TAXTOTALS""TAXTYPE""T16""AMOUNT""153.36""TAXTOTALS""TAXTYPE""T17""AMOUNT""153.36""TAXTOTALS""TAXTYPE""T18""AMOUNT""214.71""TAXTOTALS""TAXTYPE""T19""AMOUNT""184.04""TAXTOTALS""TAXTYPE""T20""AMOUNT""153.36""TOTALAMOUNT""5191.50""EXTRADISCOUNTAMOUNT""5.00""TOTALITEMSDISCOUNTAMOUNT""14.00"

A: You can use:
create or replace PROCEDURE ETA_JSON_SERIALIZE (
  json_in    IN     JSON_ELEMENT_T,
  can_str    IN OUT VARCHAR2,
  object_key IN     VARCHAR2 DEFAULT NULL
)
IS
BEGIN
  IF json_in.is_Object() THEN
    DECLARE
      l_object JSON_OBJECT_T := TREAT(json_in AS JSON_OBJECT_T);
      l_keys   JSON_KEY_LIST := l_object.get_Keys();
    BEGIN
      FOR i IN 1 .. l_keys.COUNT LOOP
        can_str := can_str || '"'||UPPER(l_keys(i))||'"';
        ETA_JSON_SERIALIZE(l_object.get(l_keys(i)), can_str, l_keys(i));
      END LOOP;
    END;
  ELSIF json_in.is_Array() THEN
    DECLARE
      l_array JSON_ARRAY_T := TREAT(json_in AS JSON_ARRAY_T);
    BEGIN
      FOR i IN 0 .. l_array.get_size -1 LOOP
        IF i > 0 AND object_key IS NOT NULL THEN
          can_str := can_str || '"'||UPPER(object_key)||'"';
        END IF;
        ETA_JSON_SERIALIZE(l_array.get(i), can_str);
      END LOOP;
    END;
  ELSIF json_in.is_Scalar() THEN
    can_str := can_str || json_in.to_String();
  END IF;
END;
/

Which, for the sample data:
DECLARE
   can_str     VARCHAR2(32767);
   l_element   JSON_ELEMENT_T;
   l_doc       CLOB :=  '{
   "documents": [{
      "issuer": {
         "type": "B",
         "id": "301188475",
         "name": "Hakim Misr Paco (POS-0)",
         "address": {
            "branchID": "-1",
            "country": "EG",
            "governate": "Cairo",
            "regionCity": "Nasr City",
            "street": "Mostafa El Nahas",
            "buildingNumber": "65"
         }
      },
      "receiver": {
         "type": "P",
         "id": " 29409200104255",
         "name": "Karim Ahmed Abdelhakim Hashem",
         "address": {
            "country": "EG",
            "governate": "Cairo",
            "regionCity": "Nasr City",
            "street": "Mostafa El Nahas",
            "buildingNumber": "65"
         }
      },
      "documentType": "I",
      "documentTypeVersion": "0.9",
      "dateTimeIssued": "2022-11-19T23:59:59Z",
      "taxpayerActivityCode": "2220",
      "internalID": "0-1",
      "invoiceLines": [{
         "description": "KFC_Test",
         "itemType": "GS1",
         "itemCode": "10006331",
         "unitType": "EA",
         "quantity": 1000,
         "unitValue": {
            "currencySold": "EGP",
            "amountEGP": 0.10000,
            "amountSold": 0
         },
         "salesTotal": 100,
         "total": 114,
         "valueDifference": 0,
         "totalTaxableFees": 0,
         "netTotal": 100,
         "itemsDiscount": 0,
         "discount": {
            "rate": 0,
            "amount": 0
         },
         "taxableItems": [{
            "taxType": "T1",
            "amount": 14,
            "subType": "V009",
            "rate": 14
         }],
         "internalCode": "Test_110"
      }],
      "totalSalesAmount": 100,
      "totalDiscountAmount": 0,
      "netAmount": 100,
      "taxTotals": [{
         "taxType": "T1",
         "amount": 14
      }],
      "extraDiscountAmount": 0,
      "totalItemsDiscountAmount": 0,
      "totalAmount": 114,
      "signatures": [{
         "signatureType": "I",
         "value": "NA"
      }]
   }]
}';
BEGIN
   ETA_JSON_SERIALIZE(JSON_ELEMENT_T.parse( l_doc ), can_str);
   DBMS_OUTPUT.PUT_LINE(can_str);
END;
/

Outputs:
"DOCUMENTS""ISSUER""TYPE""B""ID""301188475""NAME""Hakim Misr Paco (POS-0)""ADDRESS""BRANCHID""-1""COUNTRY""EG""GOVERNATE""Cairo""REGIONCITY""Nasr City""STREET""Mostafa El Nahas""BUILDINGNUMBER""65""RECEIVER""TYPE""P""ID"" 29409200104255""NAME""Karim Ahmed Abdelhakim Hashem""ADDRESS""COUNTRY""EG""GOVERNATE""Cairo""REGIONCITY""Nasr City""STREET""Mostafa El Nahas""BUILDINGNUMBER""65""DOCUMENTTYPE""I""DOCUMENTTYPEVERSION""0.9""DATETIMEISSUED""2022-11-19T23:59:59Z""TAXPAYERACTIVITYCODE""2220""INTERNALID""0-1""INVOICELINES""DESCRIPTION""KFC_Test""ITEMTYPE""GS1""ITEMCODE""10006331""UNITTYPE""EA""QUANTITY"1000"UNITVALUE""CURRENCYSOLD""EGP""AMOUNTEGP"0.10000"AMOUNTSOLD"0"SALESTOTAL"100"TOTAL"114"VALUEDIFFERENCE"0"TOTALTAXABLEFEES"0"NETTOTAL"100"ITEMSDISCOUNT"0"DISCOUNT""RATE"0"AMOUNT"0"TAXABLEITEMS""TAXTYPE""T1""AMOUNT"14"SUBTYPE""V009""RATE"14"INTERNALCODE""Test_110""TOTALSALESAMOUNT"100"TOTALDISCOUNTAMOUNT"0"NETAMOUNT"100"TAXTOTALS""TAXTYPE""T1""AMOUNT"14"EXTRADISCOUNTAMOUNT"0"TOTALITEMSDISCOUNTAMOUNT"0"TOTALAMOUNT"114"SIGNATURES""SIGNATURETYPE""I""VALUE""NA"

fiddle


text:
Q: Can I define an EntityType but not make it available as a Feed? I'm using Odata/Olingo v2.  I have several Entity Types defined including Product and Category. A Product can have many Categories.
I would like to ONLY make Products available as a Feed/Resource.  I thought I could accomplish this by defining a Category Entity Type and Association but not adding the Categories EntitySet and AssociationSet to the EntityContainer.  I also created a NavigationProperty between Product and Category.
This appears to be valid EDMX, at least Olingo's EdmxProvider.parse() does not object.  However, when I post a Product with a collection of Categories to the Products feed Olingo throws an exception from EdmEntityContainerImplProv.getAssociationSet() because it expects to find an AssociationSet for Categories
Is there a way to accomplish this in OData/Olingo v2?
Edit: It's not an option to make Category a ComplexType because I need to have a collection of them and that's not possible in OData/Olingo v2

A: I am not familiar with olingo implementations, so cant point you to methods/whatever.
But in general: if you want an entity to be accessible as a set (be it as /Product('123')/ToCategories or just /CategorySet), you need the according EntitySet in your metadata and in your implementation.
You can, however, limit your implementation to only respond when used via navigation property.
As an example: on an Abap implementation, the method implementing category get_entityset has the information, that it is accessed via navigation property from another entity (or even a path) including keys. Here, you can throw an exception or just return an empty set, if you decide you don't want to offer direct access to /CategorySet

redpajama_set_name: RedPajamaStackExchange


text:
Q: Catch the absence of a pattern (Updated) following another one (INSERT / UPDATE / DELETE) How could we detect error cases in log files such as:
[DEBUG][2016-08-02 17:11:22,047][DbConn] - [INSERT INTO table1 ...]
[DEBUG][2016-08-02 17:11:22,461][DbConn] - [Updated: 16282 records]
[DEBUG][2016-08-02 17:11:22,465][DbConn] - [ UPDATE table2 SET ...]
[DEBUG][2016-08-02 17:11:22,616][DbConn] - [Updated: 3 records]
[DEBUG][2016-08-02 17:11:22,620][DbConn] - [ DELETE FROM table3 WHERE ...]
[DEBUG][2016-08-02 17:11:22,786][DbConn] - [Updated: 1 records]
[DEBUG][2016-08-02 17:11:23,723][DbConn] - [INSERT INTO table4 ...]
[DEBUG][2016-08-02 17:11:24,442][DbConn] - [SELECT * FROM table5 ...]

where the absence of Updated: X records shows that the request wasn't correctly executed?
In this example, line 7 (INSERT INTO table4 ...) should be outputted as something wrong happened when executing that SQL request.
I'm sure it's almost possible to write a one-liner for this, but I don't see the right way to begin.  Any tip?

A: Assuming we expect Updated every even numbered line,
awk 'NR%2==0{if (!/Updated/) print a} {a=$0}' log

A more generic one:
awk 'NR>1{if (!/Updated/ && a ~ /INSERT|UPDATE|DELETE/) print a} {a=$0}' log

A: Depends on regex flavor, but
/\[DEBUG\]\[[\d\- :,]+\]\[DbConn\] - \[ *(?:INSERT|UPDATE|DELETE)(?!.*\n\[DEBUG\]\[[\d- :,]+\]\[DbConn\] - \[Updated:).*/g

should work. See demo.


text:
Q: Pivot table with sql Is possible to pivot this table directly in a single sql query? (the table is the result of a query)
From this:
| timestamp            | sensor_id | value |
|----------------------|-----------|-------|
| 2021-09-09 02:00 +02 | 58        | 31.7  |
| 2021-09-09 02:00 +02 | 60        | 45.8  |
| 2021-09-09 03:00 +02 | 58        | 81.9  |
| 2021-09-09 03:00 +02 | 60        | 100.8 |

to this:
| timestamp            | 58  | 60   |
|----------------------|-----|------|
| 2021-09-09 02:00 +02 | 31.7| 45.8 |
| 2021-09-09 03:00 +02 | 81.9| 100.8|

This is the actual query that create the first table
select TIMESTAMP AT TIME ZONE 'CETDST' AS TIMESTAMP,sensor_id,value
FROM measure
WHERE sensor_id IN (58,60)
AND TIMESTAMP AT TIME ZONE 'CETDST' BETWEEN '2021-09-09 02:00' AND '2021-09-09 03:00'
ORDER BY TIMESTAMP

Is it possible? Can you help me? PostgreSQL v.12

A: Try this - this is also solid if you have rows with sensor id 58, and no rows with sensor id 60 at the same timestamp - just by filling up the resulting NULLS with a LAST_VALUE(... IGNORE NULLS) OLAP function call:
I added some rows with gaps to your in - data:
WITH
-- your input - don't use in final query ...
indata(ts,sensor_id,val) AS (
          SELECT TIMESTAMP '2021-09-09 02:00',58, 31.7
UNION ALL SELECT TIMESTAMP '2021-09-09 02:00',60, 45.8
UNION ALL SELECT TIMESTAMP '2021-09-09 03:00',58, 81.9
UNION ALL SELECT TIMESTAMP '2021-09-09 03:00',60,100.8
UNION ALL SELECT TIMESTAMP '2021-09-09 04:00',58,131.7
UNION ALL SELECT TIMESTAMP '2021-09-09 05:00',58,181.9
UNION ALL SELECT TIMESTAMP '2021-09-09 06:00',60,200.8
UNION ALL SELECT TIMESTAMP '2021-09-09 07:00',60,245.8
)
-- REAL QUERY STARTS HERE - note "ts" and "val" as column names - avoid keywords
SELECT
  ts
, LAST_VALUE(MAX(CASE sensor_id WHEN '58' THEN val END) IGNORE NULLS) OVER w AS val_58
, LAST_VALUE(MAX(CASE sensor_id WHEN '60' THEN val END) IGNORE NULLS) OVER w AS val_60
FROM indata
GROUP BY
  ts
WINDOW w AS(ORDER BY ts)
-- out          ts          | val_58 | val_60
-- out ---------------------+--------+--------
-- out  2021-09-09 02:00:00 |   31.7 |   45.8
-- out  2021-09-09 03:00:00 |   81.9 |  100.8
-- out  2021-09-09 04:00:00 |  131.7 |  100.8
-- out  2021-09-09 05:00:00 |  181.9 |  100.8
-- out  2021-09-09 06:00:00 |  181.9 |  200.8
-- out  2021-09-09 07:00:00 |  181.9 |  245.8

A: If you use PANDAS on python you can do it easily. But in SQL you can use
SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'max(case when sensor_id = ''',
      sensor_id,
      ''' then value end) ',
      sensor_id
    )
  ) INTO @sql
FROM
  your_table;
SET @sql = CONCAT('SELECT timestamp, ', @sql, '
                  FROM your_table
                   GROUP BY timestamp');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

A: you have here below two examples for implementing a full dynamic pivot-table solution  :
https://stackoverflow.com/a/70466824/8060017
https://stackoverflow.com/a/70695023/8060017


text:
Q: When does the "Kernel functor" produce an exact row? (I apologize in advance if there's a way simpler way to formulate things, or an obvious result that I'm just missing.)
Let $\require{AMScd}\newcommand{\C}{\mathscr C}\C$ be an abelian category.
By the universal property of the kernel, a commutative diagram
\begin{align}
\begin{CD}
  X_1 @>\sigma_X>> X_2\\
  @Vf_1VV @Vf_2VV \\
  Y_1 @>\sigma_Y>> Y_2
\end{CD}
\end{align}
gives rise to a morphism $\DeclareMathOperator{\Ker}{Ker} \Ker f_1 \to \Ker f_2$.
This is done as follows:
If $\kappa_i\colon \Ker f_i\to X_i$ is the respective kernel injection and $;$ denotes covariant composition, we can consider the composition
$\kappa_1 ; \sigma_X ; f_2 = \kappa_1;f_1;\sigma_Y = 0;\sigma_Y = 0$.
Hence $\kappa_1;\sigma_X$ factors through $\kappa_2$ by means of a (unique) morphism
$\Ker(\sigma)\colon \Ker f_1 \to \Ker f_2$.
In fact, this assignment ist functorial, so $\Ker\in \C^{\ast \to \ast}$, where the superscript denotes the small category containing two objects and one non-identity morphism.

To verify that this turns into a functor, consider the diagram
\begin{align}
\begin{CD}
  \Ker f_1 @>\Ker\sigma>> \Ker f_2 @>\Ker \tau>> \Ker f_3 \\
  @V\kappa_1VV @V\kappa_2VV @V\kappa_3VV\\
  X_1 @>\sigma_X>> X_2 @>\tau_X>> X_3\\
  @Vf_1VV @Vf_2VV @Vf_3VV\\
  Y_1 @>\sigma_Y>> Y_2 @>\tau_Y>> Y_3,
\end{CD}
\end{align}
whose upper squares commute by the definition of $\Ker \sigma$.
We now see that $\Ker \sigma;\Ker \tau$ factors $\kappa_1;(\sigma_X\tau_X) = \kappa_1;(\sigma;\tau)_X$, but this is the property that uniquely defines $\Ker (\sigma;\tau)$.

Question

In the former diagram, under which condition is the top row exact?

The reason I ask is that chaining epis $\alpha;\beta\colon A\to B\to C$ gives rise to natural transformations of morphisms $\sigma\colon\alpha \to \alpha;\beta$
and $\tau\colon \alpha;\beta \to \beta$ as depicted here:
\begin{align}
\begin{CD}
  \Ker \alpha @>\Ker\sigma>> \Ker \alpha;\beta @>\Ker \tau>> \Ker \beta \\
  @V\kappa_1VV @V\kappa_2VV @V\kappa_3VV\\
  A @= A @>\alpha>> B\\
  @V\alpha VV @V\alpha;\beta VV @V\beta VV\\
  B @>\beta >> C @= C.
\end{CD}
\end{align}
Interpreting the top row e.g. in the case of $R$-modules (and treating $\Ker$ as a literal zero set) enlightens us as follows:

*

*$\Ker \sigma$ is just "subspace inclusion" since every element in the kernel of $\alpha$ is already in the kernel of $\alpha;\beta$

*$\Ker \tau$ maps an $x\in \Ker\alpha;\beta$ to $\alpha(x)\in \Ker\beta$, so we just have restriction of $\alpha$ to $\Ker\alpha;\beta = \alpha^{-1}(\Ker \beta)$.
Therefore $\Ker (\Ker \tau) = \Ker \alpha\vert_{\alpha^{-1}(\Ker \beta)} = \Ker \alpha$, so we indeed have an exact sequence.

The corresponding dual statement is very natural however:
Taking instead cokernels and monos (interpreting the monos $\beta',\alpha'$ as subspace inclusions $C\subset B \subset A$) yields an exact sequence $\DeclareMathOperator{\coker}{Coker}\coker\beta' \to \coker\beta';\alpha' \to \coker\alpha'$, which is precisely the statement that $(A/C)/(B/C)\simeq A/B$.
This suggests to me that the top row being exact gives us some sort of generalized isomorphism theorem, but I am unsure whether one can generalize the demonstrated diagram chase.  I've tried to look for something like a snake lemma, but failed to find something helpful.

A: The snake lemma tells you exactly what you want to know. The exactness of the kernel sequence on top tells you that kernel is left exact as a functor from the arrow category. The existence of the connecting morphism tells that kernel is not right exact in general.


text:
Q: Setting up an iterated integral in spherical coordinates I am instructed to convert this iterated integral in cartesian coordinates to spherical coordinates.
$$
\int^{1}_{0} \int^{\sqrt{1-x^2}}_{-\sqrt{1-x^2}} \int^{\sqrt{4-x^2-y^2}}_{\sqrt{3x^2+3y^2}}\, dzdydx
$$
This seems that the bounds of the region are between the equations $x^2+y^2+z^2=4$, $z^2=3x^2+3y^2$, and the y=axis. I think that the region is also bounded by the y-axis because of the lower bound of $x = 0$.
In spherical coordinates, I know that the $x^2+y^2+z^2=4$ is equal to $\rho = 2$.
The $z^2=3x^2+3y^2$ will be transformed into
$$
\rho^2 \cos^2\phi = 3(\rho^2-\rho^2 \cos^2\phi)\implies \phi = \frac{\pi}{6}.
$$
At the latter, I conclude that the iterated integral will be
$$
\int^{\frac{\pi}{6}}_0 \int^\pi_0\int^2_0 \rho^2 \sin\phi\, d\rho d\theta d\phi.
$$
I got the conclusion about the bounds of $\theta$ because of the sphere.
Overall, the resulting iterated integral in cartesian coordinates and the spherical coordinates is equal to $\frac{\pi}{2}$.
I want to know now if my understanding about the conversion is correct. Is there a visual representation of this integral to fully understand on how triple integral in spherical coordinates works?


text:
Q: Filter month for multiple years in ggplot I have the D data.frame below that I would like to plot using ggplot. However, I see that data for September never get plotted. Is there a better way to do the labels in scale_x_continuous or the ggplotting of entire Data.frame D?
library(lubridate)
library(tidyverse)

D <- data.frame(Date = seq(as.Date("2001-01-01"), to= as.Date("2002-12-31"), by="day"),
                A = runif(730, 1,70)) %>%
    mutate(Year = year(Date), Month = month(Date), Day = day(Date), JDay = yday(Date)) %>%
    dplyr::filter(between(Month, 5, 9)) %>%
    group_by(Year) %>%
    mutate(CumA  = cumsum(A)) %>%
  select(c(3,6,7))

ggplot(D, aes(x = JDay, y = CumA, col = as.factor(Year)))+
  geom_line()+
  scale_x_continuous(limits = c(121,273), labels = c("May", "Jun","Jul","Aug","Sep"),
                     expand = c(0,0))

A: Try by specifying breaks:
dates <- seq(as.Date("2001-05-01"), as.Date("2001-09-01"), by = "month")

ggplot(D, aes(x = JDay, y = CumA, col = as.factor(Year)))+
 geom_line()+
 scale_x_continuous(breaks = yday(dates),
                    labels = month(dates, label = TRUE),
                    expand = c(0,0))

A: I would revise as follows, to make use of the built-in support for dates by ggplot2.
D <- data.frame(Date = seq(as.Date("2001-01-01"), to= as.Date("2002-12-31"), by="day"),
                A = runif(730, 1,70)) %>%
  mutate(Year = year(Date), Month = month(Date), Day = day(Date), JDay = yday(Date)) %>%
  dplyr::filter(between(Month, 5, 9)) %>%
  group_by(Year) %>%
  mutate(
    CumA  = cumsum(A),
    plot_Date = Date
  )
year(D$plot_Date) <- 2001

ggplot(D, aes(x = plot_Date, y = CumA, col = as.factor(Year)))+
  geom_line()+
  scale_x_date(date_breaks = '1 month', date_labels = '%B', expand = c(0, 0))


text:
Q: Spring Batch Admin Home Page Is there a way to change what should be home page for spring batch admin webapp?
I tried various solutions and nothing helps. What bothers me is that RequestMapping(value = { "/", "/home" }) is bidden to HomeController inside spring-batch-resources project, and I can't override that mapping.
I didn't know what would be necessary, I first tried redefining index.jsp page to farward to "/myHomePage" instead of "/home" that is by default. No result.
I tried defining my own controller to have same RequestMapping(value = "/"). No result. Ambiguous mappings exception.
I tried extending and overriding method from HomeController in my own controller, also without result, also ambiguous mappings exception.
I even added
<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

NO RESULT!
I don't care much about "/home" mapping I just want to override "/" mapping, or to forward it to my page, or something like that. Is there a way?
P.S. I can't change HomeController implementation, since it is spring-batch-resources dependency for spring-batch-admin-sample...

A: Explanation for the answer I've given in comments, requested by @kap
It's been a long time since I worked on this, and I don't have the code available now, but as I can remember:
In one of the definitions for the application-context in XML files in resources (sorry I forgot which one) you need to add something like
<mvc:interceptor>
   <mvc:mapping path="/"/>
   <bean class="blabla.MyInterceptor" />
</mvc:interceptor>

and then create class MyInterceptor that implements HandlerInterceptor  which will redirect the request. There are 3 methods you can use to override the behavior

*

*preHandle

*postHandle

*afterCompletion
and I think that I used postHandle to implement code for redirect to my custom homepage. You can google for tutorials on redirection of requests using Spring interceptors to see how to implement that.

A: this worked for me:
adding this to web.xml
<servlet-mapping>
    <servlet-name>Batch Servlet</servlet-name>
    <url-pattern>/batch/*</url-pattern>
</servlet-mapping>

and adding this part on my own index page

<a href="<%= request.getContextPath() %>/batch/">Batch job admin


text:
Q: CoreData: No existing entry for row 0 but for row 1,2,3 I made an CoreData app which also includes an UITableView. The app loads all CoreData entries into the UITableViewCells at startup. I saved 5 entries into CoreData (of type String). If each UITableViewCell is going to be filled with the correct entries at cellForRowAtIndexPath there's no entry (nil) at indexPath.row: 0 but at row 1,2,3,4 and 5 there's an existing entry. I don't know why but each time if the cell with the indexPath.row = 0 loads the app crashes with the reason: fatal error: unexpectedly found nil while unwrapping an Optional value. The optional value is an attribute of an entity of my core data model. Does someone knows why this error occurs each time if indexPath.row = 0? If you need more informations feel free to ask me. Thanks a lot for your help.
Get value:
let object = self.fetchedResultsController.objectAtIndexPath(indexPath) as NSManagedObject
var dateFromCell = object.valueForKey("datum") as NSDate?
var dateString = Date.toString(date: dateFromCell!)

Save value:
let myDate:NSDate = NSDate()
let context = self.fetchedResultsController.managedObjectContext
let entity = self.fetchedResultsController.fetchRequest.entity!
let newManagedObject = NSEntityDescription.insertNewObjectForEntityForName(entity.name!, inManagedObjectContext: context) as NSManagedObject
newManagedObject.setValue(myDate, forKey: "datum")

// Save the context.
    var error: NSError? = nil
    if !context.save(&error) {
        abort()
    }

A: Go back and look at your array first before trying to diagnose the cell. Apparently there is no value at index 0 in your array. Place a breakpoint and view your arrays values. Using optionals will prevent a crash if used properly. (ie. ?? "" or anything similar). It's hard to diagnose without seeing your actual code so please feel free to share the problem areas.

A: If the problem is in that part of the code, it is here:
var dateFromCell = object.valueForKey("datum") as NSDate?
var dateString = Date.toString(date: dateFromCell!)
//                                               ^-- Here

dateFromCell is nil. Which leads to a crash when you force unwrap it.
This might have happened because you accidentally saved an object into Core Data without setting datum. This would only be possible if you have marked the datum attribute as optional in the data model editor.
But accidentally saving unfinished object sometimes happens during development. That's why your code has to match the attribute configuration. An optional attribute that you treat as not-optional in code is a bad idea.

You should make the attribute not-optional in the data model editor, so saves will fail if the object is not setup completely. You will find that setting in the attribute sidebar in the model editor.
Or you have to treat the attribute as optional in your code as well.
i.e.:
if let dateFromCell = object.valueForKey("datum") as? NSDate {
    var dateString = Date.toString(date: dateFromCell!)

}

A: Never use the force-unwrap operator (the exclamation mark) unless you are absolutely sure it cannot be nil.
Adding a force-unwrap is equivalent to adding a NSAssert(myVar != nil). So whenever you use an exclamation mark somewhere, you might as well write explicitly the assert. At least you'll know exactly why your program crashed.


text:
Q: Declaring class variables on as needed basis I'd like to make my class object dynamically configurable by allowing user to specify a list of parameter strings and for each of those parameter strings, I'd like my class object to have a separate variable.
The user can specify any number of parameter strings and so, the class object should have a corresponding number of variables. I'd like to do this without having to define those variables as a part of a vector but I'm not sure if and how this can be done since all class variables are defined explicitly in the class code.
For example, let's say we want the variables to be "float userVar_${parameter}".
If the user specifies N configurations 1,2,3,...,N in the config file, the class object should have N private variables userVar_1, userVar_2, userVar_3, ..., userVar_N
Thank you for your time!

A: C++ is a statically typed language. You cannot change the type of a variable nor introduce new types at runtime. And your intention involves both.
So no, it's not possible.


text:
Q: How can I change the IP and gateway addresses permanently? I recently installed Linux Ubuntu 14.04 to my computer. To enable internet connection I needed to change my IP and Gateway address.
I did the following as a root user
# ifconfig eth0 "my ip address here" netmask 255.255.255.0 up
# route add default gw " gw address here"

It works fine for a couple of minutes but then goes back to the previous settings every time.
So, How can I change the IP and the gw addresses permanently?

A: As stated by jpkotta, network-manager is likely the culprit.
You can see its status by running ps -aux | grep network-manager | grep <username>. If you get a result, it is running, otherwise it isn't.
It will keep overwriting any changes you make with ifconfig as long as it is running.
Kill network-manager by running sudo service network-manager stop.
You can bring it back up any time with sudo service network-manager start.
Once it is disabled, use ifconfig to set your static, OR edit your /etc/network/interfaces file to include something like:
auto eth0
iface eth0 inet static
address 192.168.1.2
netmask 255.255.255.0
network 192.168.1.0
broadcast 192.168.1.255
gateway 192.168.1.1
dns-nameservers 8.8.8.8

Finally, run ifup -a to bring up the interfaces you have in your /etc/network/interfaces file.
All of this can be avoided though, if you'd rather not mess around with killing network manager. Just click on its icon in the taskbar and click 'edit connections'.

A: Commands which you have to fire are:

*

*Check your NIC ifconfig

*Choose one and set it with ip which you want to give: ifconfig enp0s8 192.168.1.34

*go to cd /etc/sysconfig/network-scripts/

*edit NIC file:

vim ifcfg-enp0s8
write ---------

'IPADDR' = 192.168.1.34
'NETMASK'= 255.255.255.0
'ONBOOT' = yes
'BOOTPROTO'= 'static'

5. done


text:
Q: date range coverage I have two attendance tables:
Daily Summary:
Emp_id     | Name    | Sched        | Time_in    | Time_out
-----------+---------+--------------+------------+-----------
E123       | John    | 2019-09-02   | 2019-09-02 | 2019-09-02
E123       | John    | 2019-09-03   | 2019-09-03 | 2019-09-03
E123       | John    | 2019-09-04   |            |
E123       | John    | 2019-09-05   |            |
E123       | John    | 2019-09-06   |            |
E123       | John    | 2019-09-07   | 2019-09-07 | 2019-09-07

Leaves Summary:
Emp_id     | Name    | TYPE            | FROM       | TO
-----------+---------+-----------------+------------+-----------
E123       | John    | Paid Time Off   | 2019-09-04 | 2019-09-06

I need help to combine these two tables to identify the empty time in and time out rows from the daily summary that would result that the employee was on leave.  I can grab both From and To columns to match into the daily summary; however, I don't have a date for the 2019-09-05 since the leave summary table is a date range.
EDITED:
Apologies, here is the result that I would like to get:
Emp_id     | Name    | Sched        | Time_in    | Time_out   | Leave
-----------+---------+--------------+------------+------------+------------+
E123       | John    | 2019-09-02   | 2019-09-02 | 2019-09-02 |
E123       | John    | 2019-09-03   | 2019-09-03 | 2019-09-03 |
E123       | John    | 2019-09-04   |            |            |Paid Time off
E123       | John    | 2019-09-05   |            |            |Paid Time off
E123       | John    | 2019-09-06   |            |            |Paid Time off
E123       | John    | 2019-09-07   | 2019-09-07 | 2019-09-07 |

A: You just need a simple left outer join between the two, where the daily summary sched column is between the leave summary from and to columns (please,tell me those aren't real column names).
Something like:
select
dly.*,
lv.type
from
daily_summary dly
left join leave_summary lv
  on dly.emp_id = lv.emp_id
  and dly.sched between lv.from_date and lv.to_date


text:
Q: Unix Copy Command I am learning unix and I had a doubt which might sound silly but shooting it out.
I created a directory, let's call it dir1 & created a subdirectory of dir1 named dir2. In dir1 I created some files as well such as f1, f2, f3, f4, f5, f6, f7, f8, f9.
Now if i need to copy all the files of dir1 to dir2. I tried this command
cp f* ./dir2

and it worked.
Now what if I don't know the name of any file and want to copy all files of dir1 to dir2. I tried using the find command but it's not working:
find . -type f | xargs cp

I also tried this command:
cp * ./dir2

Help me out ;)

A: the first thing that comes to my mind is make a for loop. copy all the files, skip directories.
for in in $(ls -l|grep -v ^d|awk '{print $9}'); do cp $i dir2; done

do the same thing using find (more advanced but cleaner code)
find . -type f | xargs -I '{}' mv '{}' dir2

A: From my understanding your file structure is as follows?
dir1/
    dir2/
    f1
    f2
    f3

If you want to do a simple copy of all of the files from dir1 to dir2 you can just do the following:
cp dir1/* dir1/dir2/.

This will automatically ignore directories as you are not using the -r (recursive) flag.
If you want to silence the error message then you can redirect the STDERR to /dev/null.
cp dir1/* dir1/dir2/. 2>/dev/null


text:
Q: Merge 2 Dataframes using properties I have a dataframe df :
symbol   date          close
aa       01/02/2019    23
aa       01/03/2019    22
aa       01/04/2019    21
ab       01/02/2019    25
.
.
.

and I have another dataframe df2
symbol Oher_columns
aa        .
ab        .
ac
ad
.
.
.

There are a lot of entries in df1 about symbol that are not present in df2. I want to merge the two datasets such that I want to get the close value for each symbol for a date 01/02/2019. I am not able to understand how to use join in this case.
The output would be df3 :
symbol    close
aa          23
ab          22
ac          21

A: You need to filter df1 first
out=df2.merge(df1.loc[df1.date=='01/02/2019'],on='symbol')


text:
Q: Path optimization algorithm I have lot of coordinates (LatLng) that represents the path. Problem is that path is very detail, so I need to make an algorithm that simly reduse accuracy of the path. Here's my path in google maps
and here's what I need. As you can see yellow line represents new less accurate path.

Is there any algorithms that do what I need?
Here my own implementation, that works only on certgain situations
private ArrayList<LatLong> navCoordinates(ArrayList<LatLong> customRoutePoints){
        ArrayList<LatLong> list = new ArrayList<>();
        final double SHORT = 0.000321933695355628053669239108103283797390758991241455078125;
        int inc = 1;
        boolean sharp = false;
        for(int i=0; i<customRoutePoints.size(); i += inc){
            inc = 1;
            LatLong prevPoint = i - 1 >= 0 ? customRoutePoints.get(i - 1) : null;
            LatLong point = customRoutePoints.get(i);
            LatLong nextPoint = i + 1 < customRoutePoints.size() ? customRoutePoints.get(i + 1) : null;

            if(prevPoint == null){
                list.add(point);
            } else {
                if(nextPoint != null){
                    double prevDistance = prevPoint.distance(point);
                    double nextDistance = point.distance(nextPoint);
                    double angle = Math.toDegrees(angleBetweenTwoPointsWithFixedPoint(prevPoint.latitude,
                            prevPoint.longitude, nextPoint.latitude, nextPoint.longitude, point.latitude, point.longitude));

                    if (testAngle(angle)) {
                        if(prevDistance < SHORT || nextDistance < SHORT){
                            if(list.size() > 1 && !sharp){
                                list.remove(list.size() - 1);
                            }
                        }
                        sharp = false;
                        inc = 2;
                        list.add(nextPoint);
                    } else {
                        list.add(point);
                        sharp = true;
                    }
                } else {
                    list.add(point);
                }
            }
        }
        return list;
    }


text:
Q: Displaying null data in choropleth using ArcGIS Desktop? I am working in ArcMap and I have created a choropleth map (using a "population" attribute) that is rendering things basically correct except that when the "population" attribute is null, representing no data, it does not render the associated polygon at all.
I would like the null data polygons to render white with a grey outline, as I have the polygons with data rendering with a shade of purple (depending on the "population" value as mentioned above) and a grey outline.
Is there a better way to go about it other than copying the layer and sticking it under the choropleth layer?

A: Run a field cal. on all null values and assign them a value of -9999.  You can then assign -9999 to 0 as a separate class and change the label to Null.


text:
Q: Best service on AWS for collecting user action data What is the best service on AWS for gathering user action data? Metrics like the number of sessions, unique sessions, duration of sessions, user's search, how are they responding to the value of real-time recommendations, and where do they land.
I'm using Amplify for deploying my application.
So far I thought about extracting these metrics from CloudWatch but I was wondering if maybe there is a service that will help with this. I also looked into AWS pinpoint but I don't think that also is the right tool for what I want to achieve.

A: AWS Cloudwatch is most likely the best service for this, since it either has the information already or you can push custom metrics in.

A: Here is AWS support answer to this question:

I would like to inform you that you can Amazon Cloudwatch logs to log
user activity on your application, you can refer to the following
documentation for the same.
[+]
https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/WhatIsCloudWatchLogs.html
CloudWatch Logs enables you to centralize the logs from all of your
systems, applications, and AWS services that you use, in a single,
highly scalable service. You can then easily view them, search them
for specific error codes or patterns, filter them based on specific
fields, or archive them securely for future analysis. CloudWatch Logs
enables you to see all of your logs, regardless of their source, as a
single and consistent flow of events ordered by time, and you can
query them and sort them based on other dimensions, group them by
specific fields, create custom computations with a powerful query
language, and visualize log data in dashboards.
You can also consider using Amazon Timestream to store and analyze
events on your application. You can then ingest this data in
Quicksight to visualize and build dashboard.
[+]
https://docs.aws.amazon.com/timestream/latest/developerguide/what-is-timestream.html#what-is.use-cases
Amazon TimeStream is a fast, scalable, and serverless time series
database service for IoT and operational applications that makes it
easy to store and analyze trillions of events per day up to 1,000
times faster and at as little as 1/10th the cost of relational
databases.


text:
Q: Error not recognizing properties in react: position, sx Hello I'm facing this errors, does anybody know how to deal with it? Errors is not recognizing properties in react: 'position', 'sx'.
..............................................................................................................................................................................................................................................................................................................................................................................
Error:
ERROR in src/components/TimeLine.tsx:18:13
TS2322: Type '{ children: Element[]; position: string; }' is not assignable to type 'IntrinsicAttributes & TimelineProps'.
  Property 'position' does not exist on type 'IntrinsicAttributes & TimelineProps'.
    16 | export default function CustomizedTimeline(any: any) {
    17 |        return (
  > 18 |                <Timeline position="alternate">
       |                          ^^^^^^^^
    19 |                        <TimelineItem>
    20 |                                <TimelineOppositeContent
    21 |                                        sx={{

ERROR in src/components/TimeLine.tsx:21:6
TS2322: Type '{ children: string; sx: { m: string; align: string; variant: string; color: string; }; }' is not assignable to type 'IntrinsicAttributes & TimelineOppositeContentProps'.
  Property 'sx' does not exist on type 'IntrinsicAttributes & TimelineOppositeContentProps'.
    19 |                        <TimelineItem>
    20 |                                <TimelineOppositeContent
  > 21 |                                        sx={{
       |                                        ^^
    22 |                                                m: 'auto 0',
    23 |                                                align: 'right',
    24 |                                                variant: 'body2',

Here is the component's 'Timeline' code:
import * as React from 'react';
import Timeline from '@material-ui/lab/Timeline';
import TimelineItem from '@material-ui/lab/TimelineItem';
import TimelineSeparator from '@material-ui/lab/TimelineSeparator';
import TimelineConnector from '@material-ui/lab/TimelineConnector';
import TimelineContent from '@material-ui/lab/TimelineContent';
import TimelineOppositeContent from '@material-ui/lab/TimelineOppositeContent';
import TimelineDot from '@material-ui/lab/TimelineDot';
import FastfoodIcon from '@mui/icons-material/Fastfood';
import LaptopMacIcon from '@mui/icons-material/LaptopMac';
import HotelIcon from '@mui/icons-material/Hotel';
import RepeatIcon from '@mui/icons-material/Repeat';
import Typography from '@mui/material/Typography';

export default function CustomizedTimeline(any: any) {
    return (
        <Timeline position="alternate">
            <TimelineItem>
                <TimelineOppositeContent
                    sx={{
                        m: 'auto 0',
                        align: 'right',
                        variant: 'body2',
                        color: 'text.secondary',
                    }}
                >
                    8:00 am
                </TimelineOppositeContent>
                <TimelineSeparator>
                    <TimelineConnector />
                    <TimelineDot>
                        <FastfoodIcon />
                    </TimelineDot>
                    <TimelineConnector />
                </TimelineSeparator>
                <TimelineContent sx={{ py: '12px', px: 2 }}>
                    <Typography variant="h6" component="span">
                        Eat
                    </Typography>
                    <Typography>Because you need strength</Typography>
                </TimelineContent>
            </TimelineItem>
            <TimelineItem>
                <TimelineOppositeContent
                    sx={{ m: 'auto 0' }}
                    variant="body2"
                    color="text.secondary"
                >
                    9:00 am
                </TimelineOppositeContent>
                <TimelineSeparator>
                    <TimelineConnector />
                    <TimelineDot color="primary">
                        <LaptopMacIcon />
                    </TimelineDot>
                    <TimelineConnector />
                </TimelineSeparator>
                <TimelineContent sx={{ py: '12px', px: 2 }}>
                    <Typography variant="h6" component="span">
                        Code
                    </Typography>
                    <Typography>Because it's awesome!</Typography>
                </TimelineContent>
            </TimelineItem>
            <TimelineItem>
                <TimelineSeparator>
                    <TimelineConnector />
                    <TimelineDot color="primary" variant="outlined">
                        <HotelIcon />
                    </TimelineDot>
                    <TimelineConnector sx={{ bgcolor: 'secondary.main' }} />
                </TimelineSeparator>
                <TimelineContent sx={{ py: '12px', px: 2 }}>
                    <Typography variant="h6" component="span">
                        Sleep
                    </Typography>
                    <Typography>Because I need rest</Typography>
                </TimelineContent>
            </TimelineItem>
            <TimelineItem>
                <TimelineSeparator>
                    <TimelineConnector sx={{ bgcolor: 'secondary.main' }} />
                    <TimelineDot color="secondary">
                        <RepeatIcon />
                    </TimelineDot>
                    <TimelineConnector />
                </TimelineSeparator>
                <TimelineContent sx={{ py: '12px', px: 2 }}>
                    <Typography variant="h6" component="span">
                        Repeat
                    </Typography>
                    <Typography>Because this is the life I </Typography>
                </TimelineContent>
            </TimelineItem>
        </Timeline>
    );
}

A: You're importing from @material-ui/lab which is the package that contains v4 of the components (which do not contain the sx or position props). Here's the API for v4: https://v4.mui.com/api/timeline/
In order to make use of the sx and position props you will need to upgrade your lab package to use v5. The v5 components are in a new package @mui/lab, you can find installation info here: https://www.npmjs.com/package/@mui/lab


text:
Q: Putting the sentence in the simpler form Can somebody help me to understand what this sentence is trying to reveal?

"So these photos are far more than proxies for a single moment, or even a specific trip. They're also ways for us to freeze time for one week in October and reflect on our times and how we change from year to year, and not just physically, but in every way."

What I understand is the following:

The photos are not just the photos of a single trip or some specific trip. These photos are actually a medium (or stuff) which allows us a free week of October where we can really go back in to our past with the pictures to observe how we change from year to year, not only physically but also in attitude.

I would appreciate if you can explain me line by line so that I can follow. Thanks is advance.

A: The only possible misunderstanding I can detect in your reading is this:

... which allows us a free week of October ...

This suggests that you are confusing freeze with some sense of free. However, freeze means literally "to convert a liquid into a solid through cold" or, metaphorically, to "prevent from flowing, to arrest or immobilize".
The author says that the photographs metaphorically prevented time from flowing beyond that time at which they were taken: the past is "frozen", held immobile, like a fly in amber, so that we can discern the differences between Then and Now.

A: TED:  "So these photos are far more than proxies for a single moment, or even a specific trip."
ME:  So these photos mean far more to my daughter and me than single moments or specific trips.
TED:  "They're also ways for us to freeze time for one week in October..."
ME:  They're also a way for my daughter and me to capture one moment we are together each year in October...
TED:  "and reflect on our times and how we change from year to year, and not just physically, but in every way."
ME:  and to reflect on how we change over time, physically and in every way.
Hope this helps you.


text:
Q: How to do tensorflow segment_max in high dimension I want to be able to call tensorflow's tf.math.unsorted_segment_max
on a data tensor that is of size [N, s, K]. N is the number of channels and K is the number of filters/feature maps.
s is the size of one-channel data sample. I have segment_ids in the size of s. For example, let's say my sample size is s=6, and that I want to do a max over two elements (as if doing the usual  max pooling, so on the second, s-dimension of the whole data tensor). Then my segment_ids equals to [0,0,1,1,2,2].
I tried running
tf.math.unsorted_segment_max(data, segment_ids, num_segments)

with extended 0 and 2 dimensions for the segment_ids, but since the segment ids are then repeated, the result is of course of size [3] instead of [N,3,K] as I would like.
So my question is, how to construct a proper segment_ids tensor, to achieve what I want? I.e. to have segment max done based on the original s-sized segment_ids tensor, but in each dimension separately?
Basically, going back to the example, given the 1D segment id list seg_id=[0,0,1,1,2,2], I would like to construct something like a segment_ids tensor for which:
segment_ids[i,:,j] = seg_id + num_segments*(i*K + j)

So that when calling the tf.math.(unsorted_)segment_max with this tensor as segment ids, I will get a result of size [N, 3, K], with the same effect as if one would run the segment_max for each data[x,:,y] separately and stack the results appropriately.
Any way of doing this is okay, as long as it works with tensorflow. I would guess a combination of tf.tile, tf.reshape or tf.concat should do the trick but I can't figure out how, in what order.
Also, is there a more straightforward way to do it? Without the need of adjusting the segment_ids during each "pooling" step?

A: I think you can achieve what you want with tf.nn.pool:
import tensorflow as tf

with tf.Graph().as_default(), tf.Session() as sess:
    data = tf.constant([
        [
            [ 1, 12, 13],
            [ 2, 11, 14],
            [ 3, 10, 15],
            [ 4,  9, 16],
            [ 5,  8, 17],
            [ 6,  7, 18],
        ],
        [
            [19, 30, 31],
            [20, 29, 32],
            [21, 28, 33],
            [22, 27, 34],
            [23, 26, 35],
            [24, 25, 36],
        ]], dtype=tf.int32)
    segments = tf.constant([0, 0, 1, 1, 2, 2], dtype=tf.int32)
    pool = tf.nn.pool(data, [2], 'MAX', 'VALID', strides=[2])
    print(sess.run(pool))

Output:
[[[ 2 12 14]
  [ 4 10 16]
  [ 6  8 18]]

 [[20 30 32]
  [22 28 34]
  [24 26 36]]]

If you really want to us tf.unsorted_segment_max, you can do it as you suggest in your own answer. Here is an equivalent formulation that avoids transposing and includes the final reshaping:
import tensorflow as tf

with tf.Graph().as_default(), tf.Session() as sess:
    data = ...
    segments = ...
    shape = tf.shape(data)
    n, k = shape[0], shape[2]
    m = tf.reduce_max(segments) + 1
    grid = tf.meshgrid(tf.range(n) * m * k,
                       segments * k,
                       tf.range(k), indexing='ij')
    segment_nd = tf.add_n(grid)
    segmented = tf.unsorted_segment_max(data, segment_nd, n * m * k)
    result = tf.reshape(segmented, [n, m, k])
    print(sess.run(result))
    # Same output

Both methods should work fine in a neural network in terms of back-propagation.
EDIT: In terms of performance, pooling seems to be more scalable than the segmented sum (as one would expect):
import tensorflow as tf
import numpy as np

def method_pool(data, window):
    return tf.nn.pool(data, [window], 'MAX', 'VALID', strides=[window])

def method_segment(data, window):
    shape = tf.shape(data)
    n, s, k = shape[0], shape[1], shape[2]
    segments = tf.range(s) // window
    m = tf.reduce_max(segments) + 1
    grid = tf.meshgrid(tf.range(n) * m * k,
                       segments * k,
                       tf.range(k), indexing='ij')
    segment_nd = tf.add_n(grid)
    segmented = tf.unsorted_segment_max(data, segment_nd, n * m * k)
    return tf.reshape(segmented, [n, m, k])

np.random.seed(100)
rand_data = np.random.rand(300, 500, 100)
window = 10
with tf.Graph().as_default(), tf.Session() as sess:
    data = tf.constant(rand_data, dtype=tf.float32)
    res_pool = method_pool(data, n)
    res_segment = method_segment(data, n)
    print(np.allclose(*sess.run([res_pool, res_segment])))
    # True
    %timeit sess.run(res_pool)
    # 2.56 ms ± 80.8 µs per loop (mean ± std. dev. of 7 runs, 1 loop each)
    %timeit sess.run(res_segment)
    # 514 ms ± 6.29 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

A: I haven't come up with any more elegant solutions, but at least I figured out how to do it with the combination of tile, reshape and transpose.
I first (using the three mentioned operations, see the code below) construct a tensor of the same size as data, with repeated (but shifted) entries of the original seg_id vector in the tensor:
m = tf.reduce_max(seg_id) + 1
a = tf.constant([i*m for i in range(N*K) for j in range(s)])
b = tf.tile(seg_id, N*K)
#now reshape it:
segment_ids = tf.transpose(tf.reshape(a+b, shape=[N,K,s]), perm=[0,2,1])

With this it's possible to call the segment_max function directly:
result = tf.unsorted_segment_max(data=data, segment_ids=segment_ids, num_segments=m*N*K)

And it does what I want it too, except that the result is flattened and needs to be reshaped once again, if needed.
Equivalently, you can reshape the original data tensor to a 1d one, and cal segment_max on it with a+b as segment_ids. And again reshape the final result, if needed.
This is what it feels like a long way round to the result... Is there any better way? I also don't know if the described way is good for being used inside a NN, during backprop... could there be issues with derivatives or the computation graph?
Does anyone have a better idea on how to solve this?


text:
Q: Spring Jpa Pageable get content using Java stream I am doing a search to bring all registered cars 100 by 100 in a paginated way.
Pageable pageable = PageRequest.of(0, 100);
Page<Car> listOfcars = carService.findAll(pageable);

For me to get to the next page, I'm doing it via while:
while(listOfcars.hasNext()){
   listOfcars = carService.findAll(listOfcars.nextPageable());
   carService.start(listOfcars.getContent());
   log.info("New batch sent" + listOfcars.getTotalElements());
}

There is a way to do this via the java stream, searching for the data on a page and right after that already searching for the sequences without having to do it via while ?

A: you can try by knowing total of available pages (maybe a total count will be needed first) and store each page numeric representation in a collection (let's say pages = [1, 2, ... n] ) then you can create a method OperateListOfCars and call your logic for each page with pages.stream()... maybe create a CustomPageResult wrapper and put there the pages collection will help to have the code more clean.

A: You don't need stream or loop here, you can use getContent method to return all content in a List from Page

Returns the page content as List.

Pageable pageable = PageRequest.of(0, 100);
Page<Car> listOfcars = carService.findAll(pageable);
List<Car> cars = listOfCars.getContent();


text:
Q: SocketTimeoutException - "timeout" "read timed out" I am writing tests which run OkHttp/Retrofit requests against a MockWebServer. Among other things I'm testing timeouts. Here I noticed, that some of my timeout tests do not produce the same kind of exception all the time:
While the exception thrown is always a SocketTimeoutException, the exception message differs between two possibilities. Sometimes I get

*

*"timeout", sometimes

*"Read timed out".

There seems to be no clear pattern (it's the very same test which sometimes produces one or the other of these exception messages).
I assume that different constellations/causes lead to the differing messages... Can somebody explain to me the difference between these two cases?

Here are the corresponding stack traces:
"Read timed out"
Caused by: java.net.SocketTimeoutException: Read timed out
    at java.net.SocketInputStream.socketRead0(Native Method)
    at java.net.SocketInputStream.socketRead(SocketInputStream.java:116)
    at java.net.SocketInputStream.read(SocketInputStream.java:170)
    at java.net.SocketInputStream.read(SocketInputStream.java:141)
    at okio.Okio$2.read(Okio.java:140)
    at okio.AsyncTimeout$2.read(AsyncTimeout.java:238)
    at okio.RealBufferedSource.read(RealBufferedSource.java:45)
    at okhttp3.internal.http.Http1xStream$FixedLengthSource.read(Http1xStream.java:381)
    at okio.RealBufferedSource.read(RealBufferedSource.java:45)
    at okio.ForwardingSource.read(ForwardingSource.java:35)
    at retrofit2.OkHttpCall$ExceptionCatchingRequestBody$1.read(OkHttpCall.java:279)
    at okio.RealBufferedSource$1.read(RealBufferedSource.java:386)
    at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
    at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
    at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
    at java.io.InputStreamReader.read(InputStreamReader.java:184)
    at com.google.gson.stream.JsonReader.fillBuffer(JsonReader.java:1287)
    at com.google.gson.stream.JsonReader.nextQuotedValue(JsonReader.java:1016)
    at com.google.gson.stream.JsonReader.nextName(JsonReader.java:787)
    at com.google.gson.internal.bind.TypeAdapters$29.read(TypeAdapters.java:739)
    at com.google.gson.internal.bind.TypeAdapters$29.read(TypeAdapters.java:714)
    at com.google.gson.internal.bind.TypeAdapters$35$1.read(TypeAdapters.java:910)
    at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:37)
    at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:25)
    at retrofit2.ServiceMethod.toResponse(ServiceMethod.java:117)
    at retrofit2.OkHttpCall.parseResponse(OkHttpCall.java:211)
    at retrofit2.OkHttpCall$1.onResponse(OkHttpCall.java:106)

"timeout"
Caused by: java.net.SocketTimeoutException: timeout
    at okio.Okio$3.newTimeoutException(Okio.java:212)
    at okio.AsyncTimeout.exit(AsyncTimeout.java:288)
    at okio.AsyncTimeout$2.read(AsyncTimeout.java:242)
    at okio.RealBufferedSource.read(RealBufferedSource.java:45)
    at okhttp3.internal.http.Http1xStream$FixedLengthSource.read(Http1xStream.java:381)
    at okio.RealBufferedSource.read(RealBufferedSource.java:45)
    at okio.ForwardingSource.read(ForwardingSource.java:35)
    at retrofit2.OkHttpCall$ExceptionCatchingRequestBody$1.read(OkHttpCall.java:279)
    at okio.RealBufferedSource$1.read(RealBufferedSource.java:386)
    at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
    at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
    at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
    at java.io.InputStreamReader.read(InputStreamReader.java:184)
    at com.google.gson.stream.JsonReader.fillBuffer(JsonReader.java:1287)
    at com.google.gson.stream.JsonReader.nextQuotedValue(JsonReader.java:1016)
    at com.google.gson.stream.JsonReader.nextName(JsonReader.java:787)
    at com.google.gson.internal.bind.TypeAdapters$29.read(TypeAdapters.java:739)
    at com.google.gson.internal.bind.TypeAdapters$29.read(TypeAdapters.java:714)
    at com.google.gson.internal.bind.TypeAdapters$35$1.read(TypeAdapters.java:910)
    at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:37)
    at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:25)
    at retrofit2.ServiceMethod.toResponse(ServiceMethod.java:117)
    at retrofit2.OkHttpCall.parseResponse(OkHttpCall.java:211)
    at retrofit2.OkHttpCall$1.onResponse(OkHttpCall.java:106)


text:
Q: How to choose throughput units for event hub? From the below documentation,
Click here
It says that,
Up to 1 MB per second of ingress events (events sent into an event hub), but no more than 1000 ingress events, management operations, or control API calls per second.
If I send JSON like below to the event hub, is the single event or 2 events
[{'name':'saran'},{'name':'kumar'}]


text:
Q: Best non-CSS HTML template? This is the situation:
For my AP US Government & Politics class, we have to create wiki pages for our "countries" in the school's Diplomacy Games. I kind of want to blow the other kids out of the water with my page. I can program well, and have some experience with HTML (although not much), so modifying a template would be easy for me. The question is, where can I get a nice one-page template for a simple, yet awesome country homepage? It has to be only HTML (no CSS), so I assume it won't be able to be all that snazzy. But, does anybody have any ideas?

A: It's almost impossible to enforce a "no CSS" rule as you can always put the CSS into a <style> block in the <head> section of your HTML file.
Given a CSS file with:
table{
font-family: 'Open Sans', Helvetica, Arial, sans-serif;
width:100%;
border-collapse:collapse;
}
td, th
{
font-size:1em;
border:1px solid #98bf21;
padding:3px 7px 2px 7px;
}

You'd just copy it out of that file and stick it in the <head> section of the HTML file.
<head>
<title> My Awesome Country Page </title>
<style>
    table{
    font-family: 'Open Sans', Helvetica, Arial, sans-serif;
    width:100%;
    border-collapse:collapse;
    }
    td, th
    {
    font-size:1em;
    border:1px solid #98bf21;
    padding:3px 7px 2px 7px;
    }
</style>
</head>

Hope that helps.


text:
Q: Remove bounce on scroll in browser, issue with position:fixed div I'm trying to remove the bounce when scrolling in chrome. You'll notice the top white black is fixed and behind the second yellow block as desired.
What I need to do is remove the scroll to reveal the grey background in the browser without preventing the scroll over the top white block. Hope it makes sense
HTML

A: Bounce scroll in the browser is a feature of some versions of iOS / macOS.
To prevent it from happening on a website we can use the following:
CSS
html, body {
    height: 100%;
    overflow: hidden;
}

#main-container {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    overflow: auto;
}

HTML

        ...

Demo

A: While the accepted answer works. Here is a simpler and updated version.
body {
    overscroll-behavior-y: none;
}

It does however not work for IE and Safari which is unfortunate. Here is the browser support.

A: There's a simpler answer suggested here for a related question: OSX - disable inertia scroll for "single-page" webapp
body {
    overflow: hidden;
}

A: Just use this property on the body tag:

body{
overscroll-behavior: none;
}

Lorem ipsum dolor.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quasi recusandae assumenda veritatis dolorum minima deleniti accusantium optio incidunt excepturi ipsum? Recusandae praesentium ullam minima autem minus necessitatibus aperiam neque. Non sequi quibusdam perferendis magnam ab dicta omnis. Reiciendis earum ipsum adipisci voluptas ipsa rerum ipsam dignissimos vitae tempore enim saepe pariatur dicta officia odio a quasi amet magni id hic.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quasi recusandae assumenda veritatis dolorum minima deleniti accusantium optio incidunt excepturi ipsum? Recusandae praesentium ullam minima autem minus necessitatibus aperiam neque. Non sequi quibusdam perferendis magnam ab dicta omnis. Reiciendis earum ipsum adipisci voluptas ipsa rerum ipsam dignissimos vitae tempore enim saepe pariatur dicta officia odio a quasi amet magni id hic.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quasi recusandae assumenda veritatis dolorum minima deleniti accusantium optio incidunt excepturi ipsum? Recusandae praesentium ullam minima autem minus necessitatibus aperiam neque. Non sequi quibusdam perferendis magnam ab dicta omnis. Reiciendis earum ipsum adipisci voluptas ipsa rerum ipsam dignissimos vitae tempore enim saepe pariatur dicta officia odio a quasi amet magni id hic.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quasi recusandae assumenda veritatis dolorum minima deleniti accusantium optio incidunt excepturi ipsum? Recusandae praesentium ullam minima autem minus necessitatibus aperiam neque. Non sequi quibusdam perferendis magnam ab dicta omnis. Reiciendis earum ipsum adipisci voluptas ipsa rerum ipsam dignissimos vitae tempore enim saepe pariatur dicta officia odio a quasi amet magni id hic.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quasi recusandae assumenda veritatis dolorum minima deleniti accusantium optio incidunt excepturi ipsum? Recusandae praesentium ullam minima autem minus necessitatibus aperiam neque. Non sequi quibusdam perferendis magnam ab dicta omnis. Reiciendis earum ipsum adipisci voluptas ipsa rerum ipsam dignissimos vitae tempore enim saepe pariatur dicta officia odio a quasi amet magni id hic.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quasi recusandae assumenda veritatis dolorum minima deleniti accusantium optio incidunt excepturi ipsum? Recusandae praesentium ullam minima autem minus necessitatibus aperiam neque. Non sequi quibusdam perferendis magnam ab dicta omnis. Reiciendis earum ipsum adipisci voluptas ipsa rerum ipsam dignissimos vitae tempore enim saepe pariatur dicta officia odio a quasi amet magni id hic.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quasi recusandae assumenda veritatis dolorum minima deleniti accusantium optio incidunt excepturi ipsum? Recusandae praesentium ullam minima autem minus necessitatibus aperiam neque. Non sequi quibusdam perferendis magnam ab dicta omnis. Reiciendis earum ipsum adipisci voluptas ipsa rerum ipsam dignissimos vitae tempore enim saepe pariatur dicta officia odio a quasi amet magni id hic.

A: Modified the solution to not create a new div in the page
html {
    height: 100%;
    overflow: hidden;
}

body {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    overflow: auto;
}

Worked for me but I didn't know if it's a good way to do

A: Placing this rule on the body tag doesn't work in Firefox on MacOS for me, but placing it on the html tag does.
html {
  overscroll-behavior: none;
}


text:
Q: A question associated with inductive probability I'm confused about the following proof technique used by many research papers in probability. Let $\{X_k\}_{k=0}^\infty$ be a sequence of non-negative random variables such that $X_0\leq 1$ with probability $1$. Suppose that, for $k\geq 1$, if $X_{k-1}\leq \frac{1}{2^{k-1}}$, then
$$\mathrm{P}\Bigl(X_k\leq \frac{1}{2^k}\big)\geq 1-\epsilon$$  Here, $\epsilon\in(0,1)$ is a constant. Then one can claim that $\mathrm{P}(X_k\leq \frac{1}{2^k})\geq 1 - k\epsilon$ for $k\geq 0$ (without any conditioning). How do we get this conclusion? When $k=0,1$ the statement is trivial. If, for example, $k=2$, my though is to compute this
$$
\mathrm{P}\Bigl(X_2\leq \frac{1}{4}\big)\geq \mathrm{P}\Bigl(X_2\leq \frac{1}{4}\mid X_1\leq \frac{1}{2}\big)\mathrm{P}\Bigl(X_1\leq \frac{1}{2}\big)\geq (1-\epsilon)^2
$$
which leads to the bound $\mathrm{P}\Bigl(X_2\leq \frac{1}{4}\big)\geq 1-2\epsilon$. Any help is appreciated!


text:
Q: Element not showing on iOS form submission What I'm wanting:
When a form is submitted show a "Order Processing" element.
What I did:
$("#register").validate({
  errorPlacement: function(error, element) { },
  submitHandler: function(form) {
    $('.processing-wrapper').removeClass('hidden');
    form.submit();
  }
});

What I'm experiencing:

*

*On the desktop things work as expected -
https://www.youtube.com/watch?v=n7zOsmA6qCA

*On iOS I never see the
"Order Processing" element -
https://www.youtube.com/watch?v=t5xbYchqJpE
What I've tried:

*

*I commented out the form.submit(); just to see if the "Order Processing" element would show up on iOS, and it did. But when the form is submitted I never see the processing element.

*I tried adding setTimeout to delay the form submission to see if that would allow more time for the "Order Processing" element to show on iOS, but had trouble getting it actually submit the form.

Updated with timeout
$("#register").validate({
  errorPlacement: function(error, element) { },
  submitHandler: function(form) {
    $('.processing-wrapper').removeClass('hidden');
    setTimeout(function(form) {
      form.submit();
    }, 2500);
  }
});

With this update I do see the "Order Processing" element but also get the error "TypeError: Cannot read property 'submit' of undefined"
Recap:

*

*Any idea why it the "Order Processing" element doesn't show up on iOS?

*Any suggestions on getting the setTimeout to actually work?

Any help in pointing me in the right direction would be greatly appreciated!

A: The timeout method is the correct fix, however you're getting the error because you've set the anonymous function to accept a form parameter which is over-riding the form of the outer scope and is null, hence the error. Just remove that parameter and it should work fine:
$("#register").validate({
    errorPlacement: function(error, element) { },
    submitHandler: function(form) {
        $('.processing-wrapper').removeClass('hidden');
        setTimeout(function() { // no parameter here
            form.submit();
        }, 50);
    }
});

Note that the timer delay can be much shorter, I reduced it to 50ms in my example. All you need to do is ensure that the call to remove the class is made before the submit happens so the UI has a chance to update.


text:
Q: White screen when load to new page Hi i am new for jquery mobile 1.4.2. After i compile my application to apk and I also install to my phone which is android 4.3 . Everything is run quite smooth. But when i install to other phone which is android 4.2.Then the problem cum. When  load to other page. The screen will keep white screen while loading to new screen.
I try below solution
$(document).bind("mobileinit", function () {

    $.mobile.buttonMarkup.hoverDelay = 0;
    $.mobile.defaultPageTransition = 'none';
    $.mobile.defaultDialogTransition = 'none';
//    $.mobile.page.prototype.options.domCache = true;
    $.mobile.defaultHomeScroll = 0.

});

Change the meta
  <meta name="viewport" content="width=device-width, initial-scale=1  user-scalable=no maximum-scale=1"" >

But i still having this issue . Any solution to fix this problem?

A: To avoid white screen add following css
.ui-mobile, .ui-mobile body{
  background:url('bg_screen.png') no-repeat left top;
}

OR
Add color as you want
.ui-mobile, .ui-mobile body{
  background:#999;
}


text:
Q: How to find TypeError when position is not specified? I'm testing out some pieces of code I've found but I'm having trouble identifying the error.
The code:
import datetime as dt
from datetime import date
import pandas as pd
import pandas_datareader.data as web
import numpy as np
import time
import math
import scipy.optimize as optimize

start = dt.datetime(2016,12,1)
end = dt.datetime(2020,12,1)

tick = ['GOOG', 'AAPL', 'AMZN']

#pandas dataframe
data = web.DataReader(tick, 'yahoo', start, end)['Adj Close']
data = np.log(data/data.shift(1))

def sharpetest(wts, returns):
  weights = np.array(wts)
  port_return = np.sum(returns.mean() * weights) * 252
  port_vol = np.sqrt(np.dot(weights.T, np.dot(returns.cov() * 252, weights)))
  sharpe = port_return/port_vol
  sharpe = np.array(sharpe)
  return sharpe

num_assets = len(tick)

constraints = ({'type' : 'eq', 'fun': lambda x: np.sum(x) -1})
bounds = tuple((0,1) for x in range(num_assets))
args = (num_assets * [1./num_assets,], data)

optimal_sharpe=optimize.minimize(sharpetest,
                               args,
                               method = 'SLSQP',
                               bounds = bounds,
                               constraints = constraints)
print(optimal_sharpe)

Output:
   /usr/local/lib/python3.9/site-packages/numpy/core/_asarray.py:83:
   VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-
   or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If
   you meant to do this, you must specify 'dtype=object' when creating the ndarray
   return array(a, dtype, copy=False, order=order)
   TypeError: float() argument must be a string or a number, not 'list'

As you can see, the line where the TypeError is not specified. How do I find the error?
I apologize for asking such a rudimentary question.

A: The type error was coming from the application of the function sharpetest.  It comes from combining the weight with the data.  Here is an example of how to correct the code.
constraints = ({'type' : 'eq', 'fun': lambda x: np.sum(x) -1})
bounds = tuple((0,1) for x in range(num_assets))
x0 = num_assets * [1./num_assets,]
args =  (data)

print(sharpetest(num_assets * [1./num_assets,], data))

optimal_sharpe=optimize.minimize(sharpetest,
                               x0,
                               args,
                               method = 'SLSQP',
                               bounds = bounds,
                               constraints = constraints)
print(optimal_sharpe)

You can see that x0 is broken out to its own argument and then the additional data (the returns of the stocks) are passed in as the args. A very interesting example you have!
The output I get is
     fun: array(0.79108107)
     jac: array([-7.45058060e-09,  7.86704488e-01,  7.25132324e-01])
 message: 'Optimization terminated successfully'
    nfev: 12
     nit: 3
    njev: 3
  status: 0
 success: True
       x: array([1.00000000e+00, 1.38777878e-16, 0.00000000e+00])


text:
Q: GluProject Not showing Accurate coordinate in C I am trying to find the screen coordinates from the opengl coordinates(projected in 3D space) I have used glproject call for this purpose,i have used rotation and translation to in my code
At certain point after performing some transformation, i called glproject api to get the screen coordinate of a particular projected point P(x,y,z)
glproject(x,y,z,modelMatrix,projectionmatrix,viewport,*x_s,*y_s,*z_s);
I am able to get x screen coordinate correctly in x_s , but y coordinates are different
The only change in y which is not in x is when initially i called the glperspective to set fovy(The field of view angle, in degrees, in the y-direction). gluPerspective(60.0f, Width/Height,0.0001f,1000.0f);
Let me Rephrase the question I have created a 3D point on screen and now i am getting the 2d(x,y) coordinates of that point through GLproject they come different from the mouse coordinates What could be the possible solution to get correct coordinates.
Here is the code snippet
#include<GL/glut.h>     /* Header File For The GLUT Library */
GLint Window;              /* The number of our GLUT window */
float tmp_x,tmp_y,tmp_z;
GLfloat w = 1200;         /* Window size. Global for use in rotation routine */
GLfloat h = 1200;
GLint prevx, prevy;        /* Remember previous x and y positions */
GLfloat xt=1.0,yt=1.0,zt=1.0;   /* translate */
int width = 1600;
int height = 1200;

//This function will set windowing transformation
void transform(GLfloat Width , GLfloat Height )
{
    glViewport(0,0,  (GLfloat)Width,  (GLfloat)Height);
    glPushMatrix();
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(60.0f, Width/Height,0.0001f,1000.0f);
    glTranslatef(0.0, 0.0, -15.0f);     /* Centre and away the viewer */
    glMatrixMode(GL_MODELVIEW);
    glPopMatrix();
}

GLvoid draw_room()
{
int i;
glPushMatrix();
glShadeModel(GL_SMOOTH);
glLineWidth(1.0);
glPointSize(4.0);                             /* Add point size, to make it clear */
glBegin(GL_POINTS);                /* start drawing the cube.*/
glColor3f(0.0f,0.0f,1.0f);            /* Set The Color To Orange*/
glColor3f(1.0f,0.0f,0.0f);            /* Set The Color To Orange*/
glVertex3f(3.1f,2.1f,2.1f);
glEnd();                              /* Done Drawing The Cube*/
glEnable(GL_DEPTH_TEST);
}
//OpenGl Display  callback Function It call init room
void DrawGLScene()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    printf("%f %f %f\n",xt,yt,zt);
    glPushMatrix();
    glMatrixMode(GL_PROJECTION);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glTranslatef(xt,yt, zt);
    draw_room();
    glPopMatrix();
    glutSwapBuffers();               /* Swap buffers */
    glFlush();
}

GLvoid Mouse( int b , int s, int xx, int yy)
{

    double a1,a2,a3;
    GLint viewport[4];
    GLdouble modelview[16];
    GLdouble projection[16];
    glGetIntegerv(GL_VIEWPORT, viewport);
    glGetDoublev(GL_MODELVIEW_MATRIX, modelview);
    glGetDoublev(GL_PROJECTION_MATRIX, projection);
    //gluProject(xt+3.1f,yt+2.1f,zt+2.1f, modelview, projection, viewport, &a1, &a2, &a3);
    gluProject(3.1f,2.1f,2.1f, modelview, projection, viewport, &a1, &a2, &a3);

    printf("Mouse: %d %d\n",xx,yy);                // Both Print are giving different coordinaes.
    printf("Unproject %f %f %f\n",a1,a2,a3);
    switch (b) {
    case GLUT_LEFT_BUTTON:  /* only stash away for left mouse */
        prevx = xx - w/2;
        prevy = h/2 - yy;
        break;
    case GLUT_MIDDLE_BUTTON:
        break;
    case GLUT_RIGHT_BUTTON:
        break;
    }
}

What could be the possible solution for this?

A: OpenGL uses lower left corner of screen as coordinate system orign. Window system usually uses upper left corner as coordinate system orign. You need to handle this difference. Example:
printf("Mouse: %d %d\n",xx,yy);
printf("Unproject %f %f %f\n",a1,viewport[1]-a2,a3);

A: A side issue:

gluPerspective(60.0f, Width/Height,0.0001f,1000.0f);

You have a very large ratio between your near and far plane distance. This is very bad for depth resolution. As a general rule you should set the near clip plane distance as far as possible, as the scene allows. The far clip plane for a projection as created by gluPerspective should be set as near as possible (it's also possible to set the far clipping plane to infinity if the projection matrix is built slightly different).
Anyway, your low depth resolution will have a negative impact on your mouse pointer screen position back projection.

Let me Rephrase the question I have created a 3D point on screen and now i am getting the 2d(x,y) coordinates of that point through GLproject they come different from the mouse coordinates What could be the possible solution to get correct coordinates.

Most window systems put the pointer coordinate system origin to the upper left. OpenGL sets the viewport coordinate system origin into the lower left. So you'll have to invert the mouse position in the window along the Y=Up axis.