问:
User Defined Function performance tuning PostgreSQL
I have the following function which is taking around 6secs time to complete the execution on 25,000 records.

Function:

```<code>CREATE OR REPLACE FUNCTION public.fun_getData
(
    p_pin VARCHAR(15),
    p_datetime TIMESTAMP
)
RETURNS NUMERIC(5,1)
AS
$BODY$
DECLARE v_pfcode        VARCHAR(20);
DECLARE v_starttime     TIMESTAMP;
DECLARE v_endtime       TIMESTAMP;
DECLARE v_num           NUMERIC(5,2);
DECLARE v_gpdata        NUMERIC(5,2);
DECLARE v_timedata      NUMERIC(5,2);
DECLARE v_sales         VARCHAR(10);

BEGIN

    SELECT col_sale INTO v_sales FROM public.tbl_Sales WHERE sales_id ='A01';

    IF v_sales = '-'
    THEN
        RETURN 0;
    END IF;

    SELECT pfcode, gpdata INTO v_pfcode,v_gpdata
    FROM public.tbl_fdata
    WHERE fpin=p_pin;

    v_gpdata := COALESCE(v_gpdata,0);

    IF v_pfcode IS NULL
    THEN
        RETURN v_gpdata;
    END IF;

    SELECT StartTime, EndTime, num INTO v_starttime,v_endtime,v_num
    FROM public.salesyears
    WHERE s_pfcode =v_pfcode AND y.year = date_part('year',p_datetime);

    IF v_starttime IS NULL OR v_endtime IS NULL
    THEN
        RETURN v_gpdata;
    END IF;

    IF v_starttime < v_endtime
    THEN
        IF p_datetime >= v_starttime AND p_datetime < v_endtime THEN
          v_timedata :=  v_gpdata + v_num;
        ELSE
            v_timedata := v_gpdata;
        END IF;
    ELSE
    IF p_datetime >= v_endtime AND p_datetime < v_starttime THEN
        v_timedata := v_gpdata;
    ELSE
        v_timedata := v_gpdata + v_num;
    END IF;
    END IF;

    RETURN v_timedata;
    END;
$BODY$
LANGUAGE plpgsql;
</code>```

Function Call:

```<code>select 120*public.fun_getData(col_pin, modifieddate)
from public.tbl_prddata
where code = 'XMOP';
</code>```

Taking around 00:00:06 time to execute.

Note: Same function I have created in SQL Server environment on same data set, it gets executed with second.

Execution Plan: explain(analyze,verbose,buffers)

```<code>"Seq Scan on public.tbl_prddata  (cost=0.00..8141.61 rows=23647 width=32) (actual time=0.253..5970.663 rows=25011 loops=1)"
"  Output: ('120'::numeric * public.fun_getData((col_pin)::character varying, (modifieddate)::timestamp without time zone))"
"  Filter: ((tbl_prddata.code)::sys.""varchar"" = 'XMOP'::sys.""varchar"")"
"  Rows Removed by Filter: 86508"
"  Buffers: shared hit=116845"
"Query Identifier: 5592079453045444499"
"Planning Time: 0.076 ms"
"Execution Time: 5980.916 ms"
</code>```

Edit: Added more execution plan's:

Query 1:

```<code>EXPLAIN(ANALYZE, VERBOSE, BUFFERS)
SELECT col_sale FROM public.tbl_Sales WHERE sales_id ='A01';
</code>```

--Output:

```<code>"Index Scan using idx_tbl_Sales_colob on public.tbl_Sales  (cost=0.14..8.16 rows=1 width=7) (actual time=0.250..0.251 rows=1 loops=1)"
"  Output: col_sale"
"  Index Cond: ((tbl_Sales.sales_id)::sys.""varchar"" = 'A01'::sys.""varchar"")"
"  Buffers: shared hit=9"
"Query Identifier: 6306884246769163476"
"Planning:"
"  Buffers: shared hit=50"
"Planning Time: 0.183 ms"
"Execution Time: 0.266 ms"
</code>```

Query 2:

```<code>EXPLAIN(ANALYZE, VERBOSE, BUFFERS)
SELECT pfcode, gpdata FROM public.tbl_fdata WHERE fpin='PRD01';
</code>```

--Output:

```<code>"Index Scan using idx_tbl_fdata_colx on public.tbl_fdata  (cost=0.12..8.14 rows=1 width=46) (actual time=0.027..0.027 rows=1 loops=1)"
"  Output: pfcode, gpdata"
"  Index Cond: ((tbl_fdata.fpin)::sys.""varchar"" = 'PRD01'::sys.""varchar"")"
"  Buffers: shared hit=2"
"Query Identifier: -4137289472330654813"
"Planning:"
"  Buffers: shared hit=655"
"Planning Time: 1.415 ms"
"Execution Time: 0.047 ms"
</code>```

Query 3:

```<code>EXPLAIN(ANALYZE, VERBOSE, BUFFERS)
SELECT StartTime, EndTime, num
FROM public.salesyears
WHERE s_pfcode ='all' AND year = date_part('year','2023-01-01 00:20:00');
</code>```

--Output:

```<code>"Seq Scan on public.salesyears y  (cost=0.00..1.47 rows=1 width=30) (actual time=0.064..0.064 rows=0 loops=1)"
"  Output: StartTime, EndTime, num"
"  Filter: (((s_pfcode)::sys.""varchar"" = 'all'::sys.""varchar"") AND ((year)::double precision = '2023'::double precision))"
"  Rows Removed by Filter: 27"
"  Buffers: shared hit=1"
"Query Identifier: 7071532767670856741"
"Planning:"
"  Buffers: shared hit=56"
"Planning Time: 0.280 ms"
"Execution Time: 0.074 ms"
</code>```

Query 4:

```<code>explain(analyze,verbose,buffers)
select * from public.tbl_prddata
where code= 'XMOP';
</code>```

--Output:

```<code>"Seq Scan on public.tbl_prddata  (cost=0.00..2372.74 rows=22847 width=263) (actual time=0.075..104.757 rows=23031 loops=1)"
"  Output: cola,colb,colc,cold,cole,colf,colg,colh"
"  Filter: ((tbl_prddata.code)::sys.""varchar"" = 'XMOP'::sys.""varchar"")"
"  Rows Removed by Filter: 31588"
"  Buffers: shared hit=1690"
"Query Identifier: 7714647889345744025"
"Planning Time: 0.093 ms"
"Execution Time: 106.360 ms"
</code>```

Body:
I have the following function which is taking around 6secs time to complete the execution on 25,000 records.

Function:

CREATE OR REPLACE FUNCTION public.fun_getData
(
    p_pin VARCHAR(15),
    p_datetime TIMESTAMP
)
RETURNS NUMERIC(5,1)
AS
$BODY$
DECLARE v_pfcode        VARCHAR(20);
DECLARE v_starttime     TIMESTAMP;
DECLARE v_endtime       TIMESTAMP;
DECLARE v_num           NUMERIC(5,2);
DECLARE v_gpdata        NUMERIC(5,2);
DECLARE v_timedata      NUMERIC(5,2);
DECLARE v_sales         VARCHAR(10);

BEGIN

    SELECT col_sale INTO v_sales FROM public.tbl_Sales WHERE sales_id ='A01';

    IF v_sales = '-'
    THEN
        RETURN 0;
    END IF;

    SELECT pfcode, gpdata INTO v_pfcode,v_gpdata
    FROM public.tbl_fdata
    WHERE fpin=p_pin;

    v_gpdata := COALESCE(v_gpdata,0);

    IF v_pfcode IS NULL
    THEN
        RETURN v_gpdata;
    END IF;

    SELECT StartTime, EndTime, num INTO v_starttime,v_endtime,v_num
    FROM public.salesyears
    WHERE s_pfcode =v_pfcode AND y.year = date_part('year',p_datetime);

    IF v_starttime IS NULL OR v_endtime IS NULL
    THEN
        RETURN v_gpdata;
    END IF;

    IF v_starttime < v_endtime
    THEN
        IF p_datetime >= v_starttime AND p_datetime < v_endtime THEN
          v_timedata :=  v_gpdata + v_num;
        ELSE
            v_timedata := v_gpdata;
        END IF;
    ELSE
    IF p_datetime >= v_endtime AND p_datetime < v_starttime THEN
        v_timedata := v_gpdata;
    ELSE
        v_timedata := v_gpdata + v_num;
    END IF;
    END IF;

    RETURN v_timedata;
    END;
$BODY$
LANGUAGE plpgsql;

Function Call:

select 120*public.fun_getData(col_pin, modifieddate)
from public.tbl_prddata
where code = 'XMOP';

Taking around 00:00:06 time to execute.

Note: Same function I have created in SQL Server environment on same data set, it gets executed with second.

Execution Plan: explain(analyze,verbose,buffers)

"Seq Scan on public.tbl_prddata  (cost=0.00..8141.61 rows=23647 width=32) (actual time=0.253..5970.663 rows=25011 loops=1)"
"  Output: ('120'::numeric * public.fun_getData((col_pin)::character varying, (modifieddate)::timestamp without time zone))"
"  Filter: ((tbl_prddata.code)::sys.""varchar"" = 'XMOP'::sys.""varchar"")"
"  Rows Removed by Filter: 86508"
"  Buffers: shared hit=116845"
"Query Identifier: 5592079453045444499"
"Planning Time: 0.076 ms"
"Execution Time: 5980.916 ms"

Edit: Added more execution plan's:

Query 1:

EXPLAIN(ANALYZE, VERBOSE, BUFFERS)
SELECT col_sale FROM public.tbl_Sales WHERE sales_id ='A01';

--Output:

"Index Scan using idx_tbl_Sales_colob on public.tbl_Sales  (cost=0.14..8.16 rows=1 width=7) (actual time=0.250..0.251 rows=1 loops=1)"
"  Output: col_sale"
"  Index Cond: ((tbl_Sales.sales_id)::sys.""varchar"" = 'A01'::sys.""varchar"")"
"  Buffers: shared hit=9"
"Query Identifier: 6306884246769163476"
"Planning:"
"  Buffers: shared hit=50"
"Planning Time: 0.183 ms"
"Execution Time: 0.266 ms"

Query 2:

EXPLAIN(ANALYZE, VERBOSE, BUFFERS)
SELECT pfcode, gpdata FROM public.tbl_fdata WHERE fpin='PRD01';

--Output:

"Index Scan using idx_tbl_fdata_colx on public.tbl_fdata  (cost=0.12..8.14 rows=1 width=46) (actual time=0.027..0.027 rows=1 loops=1)"
"  Output: pfcode, gpdata"
"  Index Cond: ((tbl_fdata.fpin)::sys.""varchar"" = 'PRD01'::sys.""varchar"")"
"  Buffers: shared hit=2"
"Query Identifier: -4137289472330654813"
"Planning:"
"  Buffers: shared hit=655"
"Planning Time: 1.415 ms"
"Execution Time: 0.047 ms"

Query 3:

EXPLAIN(ANALYZE, VERBOSE, BUFFERS)
SELECT StartTime, EndTime, num
FROM public.salesyears
WHERE s_pfcode ='all' AND year = date_part('year','2023-01-01 00:20:00');

--Output:

"Seq Scan on public.salesyears y  (cost=0.00..1.47 rows=1 width=30) (actual time=0.064..0.064 rows=0 loops=1)"
"  Output: StartTime, EndTime, num"
"  Filter: (((s_pfcode)::sys.""varchar"" = 'all'::sys.""varchar"") AND ((year)::double precision = '2023'::double precision))"
"  Rows Removed by Filter: 27"
"  Buffers: shared hit=1"
"Query Identifier: 7071532767670856741"
"Planning:"
"  Buffers: shared hit=56"
"Planning Time: 0.280 ms"
"Execution Time: 0.074 ms"

Query 4:

explain(analyze,verbose,buffers)
select * from public.tbl_prddata
where code= 'XMOP';

--Output:

"Seq Scan on public.tbl_prddata  (cost=0.00..2372.74 rows=22847 width=263) (actual time=0.075..104.757 rows=23031 loops=1)"
"  Output: cola,colb,colc,cold,cole,colf,colg,colh"
"  Filter: ((tbl_prddata.code)::sys.""varchar"" = 'XMOP'::sys.""varchar"")"
"  Rows Removed by Filter: 31588"
"  Buffers: shared hit=1690"
"Query Identifier: 7714647889345744025"
"Planning Time: 0.093 ms"
"Execution Time: 106.360 ms"


来源: stackexchange

问:
Derived state lagging
I have a Column with remember scroll state. I am using a derived state as follows.

```<code> val isHidden = remember {
            derivedStateOf {
                columnState.value > 400
            }
        }
</code>```

I want to display a search bar whenever it scrolls beyond 400 pixels.
Another approach i used is to create a state based on offset of first item in Column using function onGloballyPositioned.
The modifier of first item is as follows:

```<code> Box(modifier = Modifier
        .graphicsLayer { translationX = horizontalOffset.value }
        .onGloballyPositioned { coordinates ->
            isHidden.value = coordinates.boundsInRoot().top == 0f
        }) {
</code>```

The problem is no matter which approach i choose it always lags when  the state is changed (when the value checks for < or > 400) or in case of onGloballyPositioned if the Compose reaches top of the screen i.e. y coordinate of view == 0.

In both of the approaches isHidden is going to be true. Changing is hidden in both cases causing lag at the point of change.
I can't use lazy row because of some restrictions. Is there any solution to implement this without the lag.

ContentLicense: CC BY-SA 4.0

Title: Derived state lagging

Body:
I have a Column with remember scroll state. I am using a derived state as follows.

 val isHidden = remember {
            derivedStateOf {
                columnState.value > 400
            }
        }

I want to display a search bar whenever it scrolls beyond 400 pixels.
Another approach i used is to create a state based on offset of first item in Column using function onGloballyPositioned.
The modifier of first item is as follows:

 Box(modifier = Modifier
        .graphicsLayer { translationX = horizontalOffset.value }
        .onGloballyPositioned { coordinates ->
            isHidden.value = coordinates.boundsInRoot().top == 0f
        }) {

The problem is no matter which approach i choose it always lags when  the state is changed (when the value checks for < or > 400) or in case of onGloballyPositioned if the Compose reaches top of the screen i.e. y coordinate of view == 0.

In both of the approaches isHidden is going to be true. Changing is hidden in both cases causing lag at the point of change.
I can't use lazy row because of some restrictions. Is there any solution to implement this without the lag.


问:
Node (express, fs) streaming multiple large videos
I am building a server that serves a video to a user. The server works as expected, but when I try to switch to a different video (going to different URL), the previous video continues to play (i have more explanation). I can't use HTML  because user needs to dowload the whole video before playing.

Here is my server code:

```<code>const express = require("express")
const fs = require("fs")

let app = express();
var server = require("http").createServer(app);
server.listen(3000, () =>
    console.log("Server started on port 3000, and listening for requests")
);
app.use(express.static('public'));

var videoPath = "F:/Videos/harh.mkv"
var videoSize = fs.statSync(videoPath).size;

var videoSize
var videoPath, start, end;
app.get('*', function(req, res){
    var url = req.originalUrl;
    url = decodeURIComponent(url)
    if(!(url === "/api/video")){
        console.log("Accessed from " + url);
        videoPath = `F:/Videos${url}`;
        console.log(videoPath + " <--- this is the video path");
        res.sendFile(__dirname + '/public/index.html');
        start=0; end=0;
    }else{
        videoSize = fs.statSync(videoPath).size;
        var range = req.headers.range;
        if(!range) res.status(400).send("Requires a valid range")
        var CHUNK_SIZE = 10 ** 6
        start = Number(range.replace(/\D/g, ""))
        end  = Math.min(start + CHUNK_SIZE, videoSize-1);
        var contentLength = end - start + 1
        var headers = {
            "Content-Range": `bytes ${start}-${end}/${videoSize}`,
            "Accept-Ranges" : "bytes",
            "Content-Lenght": contentLength,
            "Content-Type": "multipart/byteranges; boundary=MY_BOUNDARY",
        }
        res.writeHead(206, headers)
        var videoStream = fs.createReadStream(videoPath, {start, end});
        videoStream.pipe(res);
    }
});
</code>```

and here is my Html:

```<code><body>
    <video src="/api/video" controls class="video">

    </video>
</body>
</code>```

What is the Main problem:
This works as expected But if i change the video ( going to another url) the previous video plays.

Example:
http://localhost:3000/test.mkv (10 sec vid) loads this page. if we go to http://localhost:3000/nyancat.mkv (30sec vid) first few second the previous video plays (test.mkv) but after some time nyancat.mkv starts to play.

Each URL needs to play different video.

Body:
I am building a server that serves a video to a user. The server works as expected, but when I try to switch to a different video (going to different URL), the previous video continues to play (i have more explanation). I can't use HTML  because user needs to dowload the whole video before playing.

Here is my server code:

const express = require("express")
const fs = require("fs")

let app = express();
var server = require("http").createServer(app);
server.listen(3000, () =>
    console.log("Server started on port 3000, and listening for requests")
);
app.use(express.static('public'));

var videoPath = "F:/Videos/harh.mkv"
var videoSize = fs.statSync(videoPath).size;

var videoSize
var videoPath, start, end;
app.get('*', function(req, res){
    var url = req.originalUrl;
    url = decodeURIComponent(url)
    if(!(url === "/api/video")){
        console.log("Accessed from " + url);
        videoPath = `F:/Videos${url}`;
        console.log(videoPath + " <--- this is the video path");
        res.sendFile(__dirname + '/public/index.html');
        start=0; end=0;
    }else{
        videoSize = fs.statSync(videoPath).size;
        var range = req.headers.range;
        if(!range) res.status(400).send("Requires a valid range")
        var CHUNK_SIZE = 10 ** 6
        start = Number(range.replace(/\D/g, ""))
        end  = Math.min(start + CHUNK_SIZE, videoSize-1);
        var contentLength = end - start + 1
        var headers = {
            "Content-Range": `bytes ${start}-${end}/${videoSize}`,
            "Accept-Ranges" : "bytes",
            "Content-Lenght": contentLength,
            "Content-Type": "multipart/byteranges; boundary=MY_BOUNDARY",
        }
        res.writeHead(206, headers)
        var videoStream = fs.createReadStream(videoPath, {start, end});
        videoStream.pipe(res);
    }
});

and here is my Html:

    <video src="/api/video" controls class="video">

    </video>

What is the Main problem:
This works as expected But if i change the video ( going to another url) the previous video plays.

Example:
http://localhost:3000/test.mkv (10 sec vid) loads this page. if we go to http://localhost:3000/nyancat.mkv (30sec vid) first few second the previous video plays (test.mkv) but after some time nyancat.mkv starts to play.

Each URL needs to play different video.


问:
Using lookup in aggregate
I have 2 collections: Order, OrderItem. I'm trying to use lookup to get the OrderItem, and then get the inside them. I followed the docs, and looked at other stackoverflow questions, but nothing worked!

Order schema:

```<code>const orderSchema = new mongoose.Schema({
    order_items: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'OrderItem',
        required: true
    }],
    total_price: {
        type: Number
    }
});
</code>```

module.exports = mongoose.model('Order', orderSchema);

OrderItem schema:

```<code>const orderItemSchema = new mongoose.Schema({
    product_id: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Product',
        required: true
    },
    quantity: {
        type: Number,
        required: true
    },
    unit_price: {
        type: Number,
        required: true
    }
});
</code>```

module.exports = mongoose.model('OrderItem', orderItemSchema);

And here's my approach:

```<code>const totalOrders = await Order.aggregate([
  {
    $lookup: {
      from: "OrderItem",
      localField: "order_items",
      foreignField: "_id",
      as: "ordersItems"
    }
  }
]);
</code>```

I'm getting ordersItems as an empty array!

Can anyone tell me what I'm wrong?
Thanks

Title: Using lookup in aggregate

Body:
I have 2 collections: Order, OrderItem. I'm trying to use lookup to get the OrderItem, and then get the inside them. I followed the docs, and looked at other stackoverflow questions, but nothing worked!

Order schema:

const orderSchema = new mongoose.Schema({
    order_items: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'OrderItem',
        required: true
    }],
    total_price: {
        type: Number
    }
});

module.exports = mongoose.model('Order', orderSchema);

OrderItem schema:

const orderItemSchema = new mongoose.Schema({
    product_id: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Product',
        required: true
    },
    quantity: {
        type: Number,
        required: true
    },
    unit_price: {
        type: Number,
        required: true
    }
});

module.exports = mongoose.model('OrderItem', orderItemSchema);

And here's my approach:

const totalOrders = await Order.aggregate([
  {
    $lookup: {
      from: "OrderItem",
      localField: "order_items",
      foreignField: "_id",
      as: "ordersItems"
    }
  }
]);

I'm getting ordersItems as an empty array!

Can anyone tell me what I'm wrong?
Thanks


问:
Iframe head's script only working when pasted in the console
I have a calculator that is inside of an iframe.

 <iframe id="tool_iframe" scrolling="no" height="750" srcdoc="

          0

          <button onclick="pushBtn(this);">AC</button>
          <button onclick="pushBtn(this);">/</button>

          <button onclick="pushBtn(this);">7</button>
          <button onclick="pushBtn(this);">8</button>
          <button onclick="pushBtn(this);">9</button>
          <button onclick="pushBtn(this);">*</button>

          <button onclick="pushBtn(this);">4</button>
          <button onclick="pushBtn(this);">5</button>
          <button onclick="pushBtn(this);">6</button>
          <button onclick="pushBtn(this);">-</button>

          <button onclick="pushBtn(this);">1</button>
          <button onclick="pushBtn(this);">2</button>
          <button onclick="pushBtn(this);">3</button>
          <button onclick="pushBtn(this);">+</button>

          <button onclick="pushBtn(this);">0</button>
          <button onclick="pushBtn(this);">.</button>
          <button onclick="pushBtn(this);">=</button>

   ">
```

The actual website is https://tropical.team/tool/calculator/ if you want to take a look for yourself. You can see when you load in everything loads fine but the calculator just doesn't work, i know the code is valid because when i copy the script from the head of the iframe and paste it into the consxole it workks. This must mean that it's a problem with the document.reference not working inside the iframe. The calculkator code is user made which means i can only modify it automaticaly in minor ways, like changing all document references to something else. What could i chage them to that would generally fix this?

Body:
I have a calculator that is inside of an iframe.

 <iframe id="tool_iframe" scrolling="no" height="750" srcdoc="

          0

          <button onclick="pushBtn(this);">AC</button>
          <button onclick="pushBtn(this);">/</button>

          <button onclick="pushBtn(this);">7</button>
          <button onclick="pushBtn(this);">8</button>
          <button onclick="pushBtn(this);">9</button>
          <button onclick="pushBtn(this);">*</button>

          <button onclick="pushBtn(this);">4</button>
          <button onclick="pushBtn(this);">5</button>
          <button onclick="pushBtn(this);">6</button>
          <button onclick="pushBtn(this);">-</button>

          <button onclick="pushBtn(this);">1</button>
          <button onclick="pushBtn(this);">2</button>
          <button onclick="pushBtn(this);">3</button>
          <button onclick="pushBtn(this);">+</button>

          <button onclick="pushBtn(this);">0</button>
          <button onclick="pushBtn(this);">.</button>
          <button onclick="pushBtn(this);">=</button>

   ">

The actual website is https://tropical.team/tool/calculator/ if you want to take a look for yourself. You can see when you load in everything loads fine but the calculator just doesn't work, i know the code is valid because when i copy the script from the head of the iframe and paste it into the consxole it workks. This must mean that it's a problem with the document.reference not working inside the iframe. The calculkator code is user made which means i can only modify it automaticaly in minor ways, like changing all document references to something else. What could i chage them to that would generally fix this?


问:
Started making a clone of the delivroo app by using react-native for andorid and sanity as the backend and it shows below errors :
Invariant Violation: Failed to call into JavaScript module method AppRegistry.runApplication(). Module has not been registered as callable. Registered callable JavaScript modules (n = 11): Systrace, JSTimers, HeapCapture, SamplingProfiler, RCTLog, RCTDeviceEventEmitter, RCTNativeAppEventEmitter, GlobalPerformanceLogger, JSDevSupportModule, HMRClient, RCTEventEmitter.

TypeError: (0, _client.sanityClient) is not a function. (In '(0, _client.sanityClient)({
projectId: '2mq4euwar',
dataset: 'production',
useCdn: true,
APIversion: '2021-10-21'
})', '(0, _client.sanityClient)' is undefined)

this is my sanity.js file:

```<code>import { sanityClient } from '@sanity/client'
import { imageUrlBuilder } from '@sanity/image-url'

const client = sanityClient({
  projectId: '2mq4euwar',
  dataset: 'production',
  useCdn: true,
  APIversion: '2021-10-21',
})

const builder = imageUrlBuilder(client)
export const urlFor = (source) => builder.image(source)

export default client

</code>```

this is where I am using this ... in HomeScreen.js:

```<code>type hereimport { View, Text, Image, TextInput, ScrollView } from 'react-native'
import { SafeAreaView } from 'react-native-safe-area-context'
import React, { useEffect, useLayoutEffect, useState } from 'react'
import { useNavigation } from '@react-navigation/native'
import client from '../sanity'

import {
  UserIcon,
  ChevronDownIcon,
  MagnifyingGlassIcon,
  AdjustmentsHorizontalIcon,
} from 'react-native-heroicons/outline'
import Categories from '../components/Categories'
import FeaturedRow from '../components/FeaturedRow'

const HomeScreen = () => {
  const navigation = useNavigation()
  const [featuredCategories, setFeaturedCategories] = useState([])
  useLayoutEffect(() => {
    navigation.setOptions({
      headerShown: false,
    })
  }, [])

  useEffect(() => {
    client
      .fetch(
        `*[_type == 'featured' ]{
          ...,
          restaurents[]->{
            ...,
            dishes[]->
          }
        }`
      )
      .then((data) => {
        setFeaturedCategories(data)
      })
      .catch((error) => {
        console.error(error)
      })
  }, [])
  console.log(featuredCategories)
  return (
    <SafeAreaView className="bg-white pt-5">
      {/*header*/}
      <View className="flex-row pb-3 items-center mx-4 space-x-2 ">
        <Image
          source={{
            uri: 'https://links.papareact.com/wru',
          }}
          className="h-7 w-7 bg-gray-300 p-4 rounded-full"
        />
        <View className="flex-1">
          <Text className="font-bold text-gray-400 text-xs">Deliver now !</Text>
          <Text className="font-bold text-xl">
            Current location
            <ChevronDownIcon size={20} color="#00CCBB" />
          </Text>
        </View>
        <UserIcon size={35} color="#00CCBB"></UserIcon>
      </View>
      {/*search box*/}
      <View className="flex-row mx-4 pb-2 items-center space-x-2 ">
        <View className="flex-row flex-1 bg-gray-200 space-x-2">
          <MagnifyingGlassIcon color="#00CCBB" size={26} />
          <TextInput
            placeholder="Restaurants and cuisines"
            keyboardType="default"
          ></TextInput>
        </View>
        <AdjustmentsHorizontalIcon
          color={'#00CCBB'}
        ></AdjustmentsHorizontalIcon>
      </View>
      {/*search box*/}
      <ScrollView
        className="bg-gray-100"
        contentContainerStyle={{
          paddingBottom: 100,
        }}
      >
        {/*categories*/}
        <Categories></Categories>

        {/*featured rows*/}

        <FeaturedRow
          id="123"
          title="Featured"
          description="Paid placements from our partners"
        />
        {/*tasty Discounts*/}
        <FeaturedRow
          id="1234"
          title="Tasty Discounts"
          description="Everyone's been enjoying these juicy discounts!"
        />
        {/*offers near you*/}
        <FeaturedRow
          id="12345"
          title="Offers near you"
          description="Why not support your local Restaurant tonight!"
        />
      </ScrollView>
    </SafeAreaView>
  )
}

export default HomeScreen

</code>```

Body:
Invariant Violation: Failed to call into JavaScript module method AppRegistry.runApplication(). Module has not been registered as callable. Registered callable JavaScript modules (n = 11): Systrace, JSTimers, HeapCapture, SamplingProfiler, RCTLog, RCTDeviceEventEmitter, RCTNativeAppEventEmitter, GlobalPerformanceLogger, JSDevSupportModule, HMRClient, RCTEventEmitter.

TypeError: (0, _client.sanityClient) is not a function. (In '(0, _client.sanityClient)({
projectId: '2mq4euwar',
dataset: 'production',
useCdn: true,
APIversion: '2021-10-21'
})', '(0, _client.sanityClient)' is undefined)

this is my sanity.js file:

import { sanityClient } from '@sanity/client'
import { imageUrlBuilder } from '@sanity/image-url'

const client = sanityClient({
  projectId: '2mq4euwar',
  dataset: 'production',
  useCdn: true,
  APIversion: '2021-10-21',
})

const builder = imageUrlBuilder(client)
export const urlFor = (source) => builder.image(source)

export default client

this is where I am using this ... in HomeScreen.js:

type hereimport { View, Text, Image, TextInput, ScrollView } from 'react-native'
import { SafeAreaView } from 'react-native-safe-area-context'
import React, { useEffect, useLayoutEffect, useState } from 'react'
import { useNavigation } from '@react-navigation/native'
import client from '../sanity'

import {
  UserIcon,
  ChevronDownIcon,
  MagnifyingGlassIcon,
  AdjustmentsHorizontalIcon,
} from 'react-native-heroicons/outline'
import Categories from '../components/Categories'
import FeaturedRow from '../components/FeaturedRow'

const HomeScreen = () => {
  const navigation = useNavigation()
  const [featuredCategories, setFeaturedCategories] = useState([])
  useLayoutEffect(() => {
    navigation.setOptions({
      headerShown: false,
    })
  }, [])

  useEffect(() => {
    client
      .fetch(
        `*[_type == 'featured' ]{
          ...,
          restaurents[]->{
            ...,
            dishes[]->
          }
        }`
      )
      .then((data) => {
        setFeaturedCategories(data)
      })
      .catch((error) => {
        console.error(error)
      })
  }, [])
  console.log(featuredCategories)
  return (
    <SafeAreaView className="bg-white pt-5">
      {/*header*/}
      <View className="flex-row pb-3 items-center mx-4 space-x-2 ">
        <Image
          source={{
            uri: 'https://links.papareact.com/wru',
          }}
          className="h-7 w-7 bg-gray-300 p-4 rounded-full"
        />
        <View className="flex-1">
          <Text className="font-bold text-gray-400 text-xs">Deliver now !</Text>
          <Text className="font-bold text-xl">
            Current location
            <ChevronDownIcon size={20} color="#00CCBB" />
          </Text>
        </View>
        <UserIcon size={35} color="#00CCBB"></UserIcon>
      </View>
      {/*search box*/}
      <View className="flex-row mx-4 pb-2 items-center space-x-2 ">
        <View className="flex-row flex-1 bg-gray-200 space-x-2">
          <MagnifyingGlassIcon color="#00CCBB" size={26} />
          <TextInput
            placeholder="Restaurants and cuisines"
            keyboardType="default"
          ></TextInput>
        </View>
        <AdjustmentsHorizontalIcon
          color={'#00CCBB'}
        ></AdjustmentsHorizontalIcon>
      </View>
      {/*search box*/}
      <ScrollView
        className="bg-gray-100"
        contentContainerStyle={{
          paddingBottom: 100,
        }}
      >
        {/*categories*/}
        <Categories></Categories>

        {/*featured rows*/}

        <FeaturedRow
          id="123"
          title="Featured"
          description="Paid placements from our partners"
        />
        {/*tasty Discounts*/}
        <FeaturedRow
          id="1234"
          title="Tasty Discounts"
          description="Everyone's been enjoying these juicy discounts!"
        />
        {/*offers near you*/}
        <FeaturedRow
          id="12345"
          title="Offers near you"
          description="Why not support your local Restaurant tonight!"
        />
      </ScrollView>
    </SafeAreaView>
  )
}

export default HomeScreen


问:
How to convert nested group in Excel from SAP report painter export into tabular form?
SAP report painter exports a n-dimensional table in excel as a nested group format (columns A:B). I need to get this onto tabular form (columns D:I) as a summarized table. Ideally I would get a direct data feed onto a summarized table, but that solution is quite far ahead.

Attached photo is a modified snippet for illustration purposes.

I have written a loop in VBA which does it using a variant approach. For approximately 15.000 rows, this takes around 40 seconds for 7 dimensions. I am wondering if any built-in excel functions could do that more efficiently?


问:
Can I use Flutter to create a microsoft Excel task pane UI and if so how can I do it?
I know you can create an Excel task pane UI with React and Angular, the Microsoft official docs explain how to. https://learn.microsoft.com/en-us/office/dev/add-ins/quickstarts/excel-quickstart-react.

I am trying to accomplish the same with Flutter.

I followed this Microsoft article for creating an Excel task pane ui WITHOUT using Flutter and it worked as expected and as explained in the article. https://learn.microsoft.com/en-us/office/dev/add-ins/quickstarts/excel-quickstart-jquery?tabs=yeomangenerator

I then created a web build of the sample Flutter counter app.

I copied the Flutter web build files to the src/taskpane folder that yeoman creates and simply changed the Flutter web index.html file name to taskpane.html, hoping this way I would not have to touch the manifest.xml file.

When I do 'npm start' Excel launches and I can open the taskpane and it seems to load, but the taskpane is blank, it does not show the Flutter counter app.

This is an image example that may help clarify what an excel task pane web add-in is like example excel web add-in


问:
Slide-In Animation Glitching after adding Slide-out animation
I built a Drop-down Menu LP from frontend mentor.io alongside some custom animations & colours.

The animation on the mobile version(width<= 600px) is not loading properly when I click the button second time around.

Link to the video:(https://twitter.com/centered_div/status/1610577488270213120?t=yku-cbPuHeC6ngdUCix4Ug&s=#19)
Link to the code:
(https://github.com/itse4elhaam/ResponsiveDPM-1.0)

Can anyone help me out ?

When I add the slideOut(going down) animation class in JS using an event listener it doesn't get removed properly and is causing issues for the slide in(going up) animation.


问:
Which rolling window size to pick for rolling mean and rolling standard deviation?
I have a dataset with about 60.000 rows which includes temperature data for a fridge over 3 days measured every 3 seconds. I'm trying to create a prediction which is why I want to use a seasonal ARIMA model (If you think another model would work better for this data feel free to correct me). If I understood correctly the first step would be to check if my data is stationary. I already did the Dickey-Fuller-Test and know my data is non stationary. But I would also like to visualize the rolling mean and rolling standard deviation. I tried to do it as mentioned here (https://www.seanabu.com/2016/03/22/time-series-seasonal-ARIMA-model-in-python/) but the windows size is not really explained in the article. My understanding would be that when I pick a window size of 300 300 datapoints are selected and the mean and standard deviation of that area gets calculated. So because my dataset is way bigger than the example I also need to pick a bigger window size. I am just struggling to understand which would be a good size. Please bear with me I'm pretty new to machine learning.

/rzZlF.png


问:
Make PhpStorm favor @param instead of type declaration when using generics
In a post on the software engineering forum me and the community agreed that one of my architecture problems might be best solved using generics. Since in PHP generics are only supported via doc tags, my interface declarations always have two param types hinted: The @param tag and the PHP type declaration:

```<code><?php

/**
 * @template T of NodeInterface
 */
interface DirectedLinkInterface
{
    /**
     * @param T $startNode
     */
    public function setStartNode(NodeInterface $startNode);
}
</code>```

The problem is that whenever I use PHP's type declaration, PhpStorm ignores the more specific template variable.

Example:

I have a class that implements a specific version of the generic interface:

```<code>/**
 * @template-implements DirectedLinkInterface<DrawActionNode>
 */
class DirectedImageProcessingLink implements DirectedLinkInterface, FollowLinkInterface
{
    /**
     * @param DrawActionNode $startNode
     */
    public function setStartNode(NodeInterface $startNode): void
    {
        $this->startNode = $startNode;
    }

}
</code>```

But when I use this class incorrectly, PhpStorm doesn't find the error, UNLESS I remove the type declarations:

```<code>$node = new WhateverNodeInterface();
$link = new DirectedImageProcessingLink();
$link->setStartNode($node); //No error found by PhpStorm
</code>```

The above code will only be considered as faulty when I remove the type declaration, which I don't really want since a missing type declaration looks kind of old school php hackish, even if the hinted type is more generic than the PHPDoc.

```<code><?php

/**
 * @template T of NodeInterface
 */
interface DirectedLinkInterface
{
    /**
     * @param T $startNode
     */
    public function setStartNode(/*No type declaration here*/ $startNode);
//Removing the type declaration as done above makes PhpStorm use the actual template
//variable which, in the interface user's code, will be more specific and thus errors can be better found
}
</code>```

Do you know any way to convince PhpStorm to use the @param tag even though there is a type declaration? Or do you think that type declarations aren't that necessary if you use @param tags in combination with generics?

Body:
In a post on the software engineering forum me and the community agreed that one of my architecture problems might be best solved using generics. Since in PHP generics are only supported via doc tags, my interface declarations always have two param types hinted: The @param tag and the PHP type declaration:

<?php

/**
 * @template T of NodeInterface
 */
interface DirectedLinkInterface
{
    /**
     * @param T $startNode
     */
    public function setStartNode(NodeInterface $startNode);
}

The problem is that whenever I use PHP's type declaration, PhpStorm ignores the more specific template variable.

Example:

I have a class that implements a specific version of the generic interface:

/**
 * @template-implements DirectedLinkInterface<DrawActionNode>
 */
class DirectedImageProcessingLink implements DirectedLinkInterface, FollowLinkInterface
{
    /**
     * @param DrawActionNode $startNode
     */
    public function setStartNode(NodeInterface $startNode): void
    {
        $this->startNode = $startNode;
    }

}

But when I use this class incorrectly, PhpStorm doesn't find the error, UNLESS I remove the type declarations:

$node = new WhateverNodeInterface();
$link = new DirectedImageProcessingLink();
$link->setStartNode($node); //No error found by PhpStorm

The above code will only be considered as faulty when I remove the type declaration, which I don't really want since a missing type declaration looks kind of old school php hackish, even if the hinted type is more generic than the PHPDoc.

<?php

/**
 * @template T of NodeInterface
 */
interface DirectedLinkInterface
{
    /**
     * @param T $startNode
     */
    public function setStartNode(/*No type declaration here*/ $startNode);
//Removing the type declaration as done above makes PhpStorm use the actual template
//variable which, in the interface user's code, will be more specific and thus errors can be better found
}

Do you know any way to convince PhpStorm to use the @param tag even though there is a type declaration? Or do you think that type declarations aren't that necessary if you use @param tags in combination with generics?


问:
How to call HTTPS webservie URL from oracle ADF with certificates
I am using the below script to call the https webservice URL with certificates.
The certificate is imported into glassfish server and keytool, I have created keystore.jks in the particular location. Below is the code to call the certificates and passwords

```<code>System.setProperty("java.protocol.handler.pkgs","com.sun.net.ssl.internal.www.protocol");
                String KEYSTORE = "", truststore = "";
                KEYSTORE = "keystore.jks";
                final String KEYSTOREPASS = "test123";
                truststore  = "/u01/home/odadmin/erpwallet/";
                final String TRUESTOREPASS= "test123";

                KeyStore ks = KeyStore.getInstance("pkcs12");

                ks.load(new FileInputStream(KEYSTORE), KEYSTOREPASS.toCharArray());
                KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
                kmf.init(ks, KEYSTOREPASS.toCharArray());

                SSLContext sslctx2 = SSLContext.getInstance("SSLv3");
                sslctx2.init(kmf.getKeyManagers(), null, null);

                KeyStore ksTrust = KeyStore.getInstance("JKS");
                ksTrust.load(new FileInputStream(truststore), TRUESTOREPASS.toCharArray());
                //just tested if my certificate was imported in root Cacert
                java.security.cert.Certificate cert = ksTrust.getCertificate("addcertificate");
                //TrustManager's decide whether to allow connections.
                TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
                tmf.init(ksTrust);

                System.setProperty("javax.net.ssl.keyStoreType", "pkcs12");
                System.setProperty("javax.net.ssl.trustStoreType", "jks");
                System.setProperty("javax.net.ssl.keyStore", KEYSTORE);
                System.setProperty("javax.net.ssl.trustStore", truststore);
                System.setProperty("javax.net.debug", "ssl");
                System.setProperty("javax.net.ssl.keyStorePassword", KEYSTOREPASS);
                System.setProperty("javax.net.ssl.trustStorePassword", TRUESTOREPASS);

                sslctx2.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
//                byte[] buffer = file.getBytes("UTF-8");
                //******
                HttpsURLConnection.setDefaultSSLSocketFactory(sslctx2.getSocketFactory());`

</code>```

I am getting the below error. Can anyone tell me whether this is correct or not?.

```<code>java.io.IOException: DerInputStream.getLength(): lengthTag=109, too big.
    at sun.security.util.DerInputStream.getLength(DerInputStream.java:561)
    at sun.security.util.DerValue.init(DerValue.java:365)
    at sun.security.util.DerValue.<init>(DerValue.java:320)
    at sun.security.pkcs12.PKCS12KeyStore.engineLoad(PKCS12KeyStore.java:1233)
    at java.security.KeyStore.load(KeyStore.java:1214)
    at ooredoo.view.backing.customer.CustomerRegistrationBean.submitCustomerNTF(CustomerRegistrationBean.java:369)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.sun.el.parser.AstValue.invoke(AstValue.java:254)
    at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:302)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    at javax.faces.event.MethodExpressionActionListener.processAction(MethodExpressionActionListener.java:148)
    at javax.faces.event.ActionEvent.processListener(ActionEvent.java:88)
    at org.apache.myfaces.trinidad.component.UIXComponentBase.broadcast(UIXComponentBase.java:1113)
    at org.apache.myfaces.trinidad.component.UIXCommand.broadcast(UIXCommand.java:179)
    at org.apache.myfaces.trinidad.component.UIXComponent.broadcastInContext(UIXComponent.java:364)
    at oracle.adf.view.rich.event.ProxyEvent.broadcastWrappedEvent(ProxyEvent.java:72)
    at oracle.adf.view.rich.component.fragment.UIXRegion.broadcast(UIXRegion.java:124)
    at org.apache.myfaces.trinidad.component.UIXComponent.broadcastInContext(UIXComponent.java:364)
    at org.apache.myfaces.trinidad.component.WrapperEvent.broadcastWrappedEvent(WrapperEvent.java:82)
    at oracle.adf.view.rich.component.fragment.ContextSwitchingComponent$1.run(ContextSwitchingComponent.java:168)
    at oracle.adf.view.rich.component.fragment.ContextSwitchingComponent._processPhase(ContextSwitchingComponent.java:510)
    at oracle.adf.view.rich.component.fragment.ContextSwitchingComponent.broadcast(ContextSwitchingComponent.java:171)
    at org.apache.myfaces.trinidad.component.UIXComponent.broadcastInContext(UIXComponent.java:364)
    at org.apache.myfaces.trinidad.component.WrapperEvent.broadcastWrappedEvent(WrapperEvent.java:82)
    at oracle.adf.view.rich.component.fragment.UIXInclude.broadcast(UIXInclude.java:111)
    at org.apache.myfaces.trinidad.component.UIXComponent.broadcastInContext(UIXComponent.java:364)
    at org.apache.myfaces.trinidad.component.WrapperEvent.broadcastWrappedEvent(WrapperEvent.java:82)
    at oracle.adf.view.rich.component.fragment.ContextSwitchingComponent$1.run(ContextSwitchingComponent.java:168)
    at oracle.adf.view.rich.component.fragment.ContextSwitchingComponent._processPhase(ContextSwitchingComponent.java:510)
    at oracle.adf.view.rich.component.fragment.ContextSwitchingComponent.broadcast(ContextSwitchingComponent.java:171)
    at oracle.adf.view.rich.component.fragment.UIXInclude.broadcast(UIXInclude.java:115)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259)
    at oracle.adfinternal.view.faces.lifecycle.LifecycleImpl._invokeApplication(LifecycleImpl.java:1074)
    at oracle.adfinternal.view.faces.lifecycle.LifecycleImpl._executePhase(LifecycleImpl.java:402)
    at oracle.adfinternal.view.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:225)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1550)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:343)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
    at ooredoo.view.backing.filter.SessionExpiryFilter.doFilter(SessionExpiryFilter.java:76)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
    at oracle.adf.model.servlet.ADFBindingFilter.doFilter(ADFBindingFilter.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
    at oracle.adfinternal.view.faces.webapp.rich.RegistrationFilter.doFilter(RegistrationFilter.java:105)
    at org.apache.myfaces.trinidadinternal.webapp.TrinidadFilterImpl$FilterListChain.doFilter(TrinidadFilterImpl.java:502)
    at oracle.adfinternal.view.faces.activedata.AdsFilter.doFilter(AdsFilter.java:60)
    at org.apache.myfaces.trinidadinternal.webapp.TrinidadFilterImpl$FilterListChain.doFilter(TrinidadFilterImpl.java:502)
    at org.apache.myfaces.trinidadinternal.webapp.TrinidadFilterImpl._doFilterImpl(TrinidadFilterImpl.java:327)
    at org.apache.myfaces.trinidadinternal.webapp.TrinidadFilterImpl.doFilter(TrinidadFilterImpl.java:229)
    at org.apache.myfaces.trinidad.webapp.TrinidadFilter.doFilter(TrinidadFilter.java:92)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
    at oracle.adf.library.webapp.LibraryFilter.doFilter(LibraryFilter.java:202)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:279)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
    at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
    at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
    at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
    at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
    at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
    at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
    at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
    at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
    at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
    at java.lang.Thread.run(Thread.java:745)
</code>```

Body:
I am using the below script to call the https webservice URL with certificates.
The certificate is imported into glassfish server and keytool, I have created keystore.jks in the particular location. Below is the code to call the certificates and passwords

System.setProperty("java.protocol.handler.pkgs","com.sun.net.ssl.internal.www.protocol");
                String KEYSTORE = "", truststore = "";
                KEYSTORE = "keystore.jks";
                final String KEYSTOREPASS = "test123";
                truststore  = "/u01/home/odadmin/erpwallet/";
                final String TRUESTOREPASS= "test123";

                KeyStore ks = KeyStore.getInstance("pkcs12");

                ks.load(new FileInputStream(KEYSTORE), KEYSTOREPASS.toCharArray());
                KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
                kmf.init(ks, KEYSTOREPASS.toCharArray());

                SSLContext sslctx2 = SSLContext.getInstance("SSLv3");
                sslctx2.init(kmf.getKeyManagers(), null, null);

                KeyStore ksTrust = KeyStore.getInstance("JKS");
                ksTrust.load(new FileInputStream(truststore), TRUESTOREPASS.toCharArray());
                //just tested if my certificate was imported in root Cacert
                java.security.cert.Certificate cert = ksTrust.getCertificate("addcertificate");
                //TrustManager's decide whether to allow connections.
                TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
                tmf.init(ksTrust);

                System.setProperty("javax.net.ssl.keyStoreType", "pkcs12");
                System.setProperty("javax.net.ssl.trustStoreType", "jks");
                System.setProperty("javax.net.ssl.keyStore", KEYSTORE);
                System.setProperty("javax.net.ssl.trustStore", truststore);
                System.setProperty("javax.net.debug", "ssl");
                System.setProperty("javax.net.ssl.keyStorePassword", KEYSTOREPASS);
                System.setProperty("javax.net.ssl.trustStorePassword", TRUESTOREPASS);

                sslctx2.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
//                byte[] buffer = file.getBytes("UTF-8");
                //******
                HttpsURLConnection.setDefaultSSLSocketFactory(sslctx2.getSocketFactory());`

I am getting the below error. Can anyone tell me whether this is correct or not?.

java.io.IOException: DerInputStream.getLength(): lengthTag=109, too big.
    at sun.security.util.DerInputStream.getLength(DerInputStream.java:561)
    at sun.security.util.DerValue.init(DerValue.java:365)
    at sun.security.util.DerValue.<init>(DerValue.java:320)
    at sun.security.pkcs12.PKCS12KeyStore.engineLoad(PKCS12KeyStore.java:1233)
    at java.security.KeyStore.load(KeyStore.java:1214)
    at ooredoo.view.backing.customer.CustomerRegistrationBean.submitCustomerNTF(CustomerRegistrationBean.java:369)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.sun.el.parser.AstValue.invoke(AstValue.java:254)
    at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:302)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    at javax.faces.event.MethodExpressionActionListener.processAction(MethodExpressionActionListener.java:148)
    at javax.faces.event.ActionEvent.processListener(ActionEvent.java:88)
    at org.apache.myfaces.trinidad.component.UIXComponentBase.broadcast(UIXComponentBase.java:1113)
    at org.apache.myfaces.trinidad.component.UIXCommand.broadcast(UIXCommand.java:179)
    at org.apache.myfaces.trinidad.component.UIXComponent.broadcastInContext(UIXComponent.java:364)
    at oracle.adf.view.rich.event.ProxyEvent.broadcastWrappedEvent(ProxyEvent.java:72)
    at oracle.adf.view.rich.component.fragment.UIXRegion.broadcast(UIXRegion.java:124)
    at org.apache.myfaces.trinidad.component.UIXComponent.broadcastInContext(UIXComponent.java:364)
    at org.apache.myfaces.trinidad.component.WrapperEvent.broadcastWrappedEvent(WrapperEvent.java:82)
    at oracle.adf.view.rich.component.fragment.ContextSwitchingComponent$1.run(ContextSwitchingComponent.java:168)
    at oracle.adf.view.rich.component.fragment.ContextSwitchingComponent._processPhase(ContextSwitchingComponent.java:510)
    at oracle.adf.view.rich.component.fragment.ContextSwitchingComponent.broadcast(ContextSwitchingComponent.java:171)
    at org.apache.myfaces.trinidad.component.UIXComponent.broadcastInContext(UIXComponent.java:364)
    at org.apache.myfaces.trinidad.component.WrapperEvent.broadcastWrappedEvent(WrapperEvent.java:82)
    at oracle.adf.view.rich.component.fragment.UIXInclude.broadcast(UIXInclude.java:111)
    at org.apache.myfaces.trinidad.component.UIXComponent.broadcastInContext(UIXComponent.java:364)
    at org.apache.myfaces.trinidad.component.WrapperEvent.broadcastWrappedEvent(WrapperEvent.java:82)
    at oracle.adf.view.rich.component.fragment.ContextSwitchingComponent$1.run(ContextSwitchingComponent.java:168)
    at oracle.adf.view.rich.component.fragment.ContextSwitchingComponent._processPhase(ContextSwitchingComponent.java:510)
    at oracle.adf.view.rich.component.fragment.ContextSwitchingComponent.broadcast(ContextSwitchingComponent.java:171)
    at oracle.adf.view.rich.component.fragment.UIXInclude.broadcast(UIXInclude.java:115)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259)
    at oracle.adfinternal.view.faces.lifecycle.LifecycleImpl._invokeApplication(LifecycleImpl.java:1074)
    at oracle.adfinternal.view.faces.lifecycle.LifecycleImpl._executePhase(LifecycleImpl.java:402)
    at oracle.adfinternal.view.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:225)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1550)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:343)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
    at ooredoo.view.backing.filter.SessionExpiryFilter.doFilter(SessionExpiryFilter.java:76)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
    at oracle.adf.model.servlet.ADFBindingFilter.doFilter(ADFBindingFilter.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
    at oracle.adfinternal.view.faces.webapp.rich.RegistrationFilter.doFilter(RegistrationFilter.java:105)
    at org.apache.myfaces.trinidadinternal.webapp.TrinidadFilterImpl$FilterListChain.doFilter(TrinidadFilterImpl.java:502)
    at oracle.adfinternal.view.faces.activedata.AdsFilter.doFilter(AdsFilter.java:60)
    at org.apache.myfaces.trinidadinternal.webapp.TrinidadFilterImpl$FilterListChain.doFilter(TrinidadFilterImpl.java:502)
    at org.apache.myfaces.trinidadinternal.webapp.TrinidadFilterImpl._doFilterImpl(TrinidadFilterImpl.java:327)
    at org.apache.myfaces.trinidadinternal.webapp.TrinidadFilterImpl.doFilter(TrinidadFilterImpl.java:229)
    at org.apache.myfaces.trinidad.webapp.TrinidadFilter.doFilter(TrinidadFilter.java:92)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
    at oracle.adf.library.webapp.LibraryFilter.doFilter(LibraryFilter.java:202)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:279)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
    at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
    at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
    at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
    at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
    at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
    at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
    at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
    at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
    at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
    at java.lang.Thread.run(Thread.java:745)


问:
Flutter detect number sequence with camera
I want to detect a code of 9 numbers with the device camera with Flutter (iOS and Android). The perfect solution would be that I could click on the detected number sequence because it could be that the camera detects multiple ones.

How could I implement this?


问:
HBase TTL and MIN_VERSIONS Behavior
Currently, I read from these two links

http://www.devdoc.net/bigdata/hbase-0.98.7-hadoop1/book/ttl.html

http://www.devdoc.net/bigdata/hbase-0.98.7-hadoop1/book/schema.versions.html#schema.minversions

From these two links, I understand that TTL is not apply to min_versions. (It will only expire all version and keep the number of min version)

But when I try it, I face a weird behavior.

I test this config. What I expected is that, TTL will not work in this case. All cells will remain on table

```<code>VERSIONS=1
MIN_VERSIONS=1
TTL=500
</code>```

Result: After 3,4hour. Some of my cells disappear. Is there any default setting in Hbase that cost this behavior (because I'm not an admin of Hbase so I don't know the default/global setting of Hbase)

Title: HBase TTL and MIN_VERSIONS Behavior

Body:
Currently, I read from these two links

http://www.devdoc.net/bigdata/hbase-0.98.7-hadoop1/book/ttl.html

http://www.devdoc.net/bigdata/hbase-0.98.7-hadoop1/book/schema.versions.html#schema.minversions

From these two links, I understand that TTL is not apply to min_versions. (It will only expire all version and keep the number of min version)

But when I try it, I face a weird behavior.

I test this config. What I expected is that, TTL will not work in this case. All cells will remain on table

VERSIONS=1
MIN_VERSIONS=1
TTL=500

Result: After 3,4hour. Some of my cells disappear. Is there any default setting in Hbase that cost this behavior (because I'm not an admin of Hbase so I don't know the default/global setting of Hbase)


问:
Unable to write dataframe as xslx format in spark scala
```<code>df
 .coalesce(1)
 .write
 .format("com.crealytics.spark.excel")
 .option("useHeader", "true")
 .option("header", "true")
 .mode(SaveMode.Append)
 .save(s"s3://$bucket/$etlFolderPrefix/a.xlsx")
</code>```

ERROR [main] glue.ProcessLauncher (Logging.scala:logError(94)): Exception in User Class java.lang.NoSuchMethodError: org.apache.commons.io.IOUtils.byteArray(I)[B  at org.apache.commons.io.output.AbstractByteArrayOutputStream.needNewBuffer(AbstractByteArrayOutputStream.java:104)     at org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream.(UnsynchronizedByteArrayOutputStream.java:51)     at org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream.(UnsynchronizedByteArrayOutputStream.java:38)     at shadeio.poi.xssf.usermodel.XSSFWorkbook.newPackage(XSSFWorkbook.java:528)    at shadeio.poi.xssf.usermodel.XSSFWorkbook.(XSSFWorkbook.java:245)    at shadeio.poi.xssf.usermodel.XSSFWorkbook.(XSSFWorkbook.java:241)    at shadeio.poi.xssf.usermodel.XSSFWorkbook.(XSSFWorkbook.java:229)    at com.crealytics.spark.excel.ExcelFileSaver.save(ExcelFileSaver.scala:45)  at com.crealytics.spark.excel.DefaultSource.createRelation Exception in User Class: java.lang.NoClassDefFoundError : org/apache/commons/io/output/UnsynchronizedByteArrayOutputStream

Tried with different versions, currently using spark version 2.12

Body:
df
 .coalesce(1)
 .write
 .format("com.crealytics.spark.excel")
 .option("useHeader", "true")
 .option("header", "true")
 .mode(SaveMode.Append)
 .save(s"s3://$bucket/$etlFolderPrefix/a.xlsx")

ERROR [main] glue.ProcessLauncher (Logging.scala:logError(94)): Exception in User Class java.lang.NoSuchMethodError: org.apache.commons.io.IOUtils.byteArray(I)[B  at org.apache.commons.io.output.AbstractByteArrayOutputStream.needNewBuffer(AbstractByteArrayOutputStream.java:104)     at org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream.(UnsynchronizedByteArrayOutputStream.java:51)     at org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream.(UnsynchronizedByteArrayOutputStream.java:38)     at shadeio.poi.xssf.usermodel.XSSFWorkbook.newPackage(XSSFWorkbook.java:528)    at shadeio.poi.xssf.usermodel.XSSFWorkbook.(XSSFWorkbook.java:245)    at shadeio.poi.xssf.usermodel.XSSFWorkbook.(XSSFWorkbook.java:241)    at shadeio.poi.xssf.usermodel.XSSFWorkbook.(XSSFWorkbook.java:229)    at com.crealytics.spark.excel.ExcelFileSaver.save(ExcelFileSaver.scala:45)  at com.crealytics.spark.excel.DefaultSource.createRelation Exception in User Class: java.lang.NoClassDefFoundError : org/apache/commons/io/output/UnsynchronizedByteArrayOutputStream

Tried with different versions, currently using spark version 2.12


问:
Send uploaded files with multer to another API from my own typescript API using axios
I'm working on a Node Typescript Rest API with Express. I did an uploadFiles middleware using multer that store all the files uploaded on a diskStorage, and this works fine.
But then, I want to immediately send these same files to another API to process them and extract data.

I am stuck here because I can't achieve to send these files with axios in a formData.

I first tried to access my files on req.files, and then send them with axios like this :

const filesMulter = req.files as Express.Multer.File[];

for await (const cvFile of filesMulter) {
  const formData = new FormData();
  formData.append("file", cvFile);

  const extractRes = await axios.post(
      `${process.env.API_EXTRACT_BASEURL}/cv/`,
      formData,
      {
        headers: {
          "Content-Type": "multipart/form-data",
         },
       }
   );
}

```
<p>But I got this error in the append() :</p>
```Argument of type 'File' is not assignable to parameter of type 'string | Blob'.
```
<p>So I tried to convert the file to a Blob, so the file is accepted in the formData.append(), but then I get this axios error :</p>
```AxiosError: Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream
```
<p>I tried to convert the file in different formats (Buffer, Stream, string...) but I get the append() error or the Axios error mentionned before...</p>
<p>I even tried to get again the file from the disk by using</p>
<pre class="lang-js prettyprint-override"><code>import fs from "fs";

const getFile = async (filePath: string): Promise<Buffer> => {
    return await new Promise((resolve, reject) => {
        fs.readFile(filePath, (error, data) => {
            if (error != null) {
                reject(error);
            } else {
                resolve(data);
            }
        });
    });
};

export default getFile;
</code>```

And then :

const cvFileOnDisk = await getFile("/path/to/my/file/hardcoded/example.pdf");
```

This return a Buffer, but again I cannot add it to the formData with append()...

Any idea how I could solve this ?
Thanks a lot !

Body:
I'm working on a Node Typescript Rest API with Express. I did an uploadFiles middleware using multer that store all the files uploaded on a diskStorage, and this works fine.
But then, I want to immediately send these same files to another API to process them and extract data.

I am stuck here because I can't achieve to send these files with axios in a formData.

I first tried to access my files on req.files, and then send them with axios like this :

const filesMulter = req.files as Express.Multer.File[];

for await (const cvFile of filesMulter) {
  const formData = new FormData();
  formData.append("file", cvFile);

  const extractRes = await axios.post(
      `${process.env.API_EXTRACT_BASEURL}/cv/`,
      formData,
      {
        headers: {
          "Content-Type": "multipart/form-data",
         },
       }
   );
}

But I got this error in the append() :

Argument of type 'File' is not assignable to parameter of type 'string | Blob'.

So I tried to convert the file to a Blob, so the file is accepted in the formData.append(), but then I get this axios error :

AxiosError: Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream

I tried to convert the file in different formats (Buffer, Stream, string...) but I get the append() error or the Axios error mentionned before...

I even tried to get again the file from the disk by using

import fs from "fs";

const getFile = async (filePath: string): Promise<Buffer> => {
    return await new Promise((resolve, reject) => {
        fs.readFile(filePath, (error, data) => {
            if (error != null) {
                reject(error);
            } else {
                resolve(data);
            }
        });
    });
};

export default getFile;

And then :

const cvFileOnDisk = await getFile("/path/to/my/file/hardcoded/example.pdf");

This return a Buffer, but again I cannot add it to the formData with append()...

Any idea how I could solve this ?
Thanks a lot !


问:
After a rollback in blue-green deployment, how to automate the deletion of green (newly created) environment?
I am trying to do a blue-green deployment in AWS using an Auto-Scaling Group (ASG). The deployment fails and rollback happens because I enabled it during deployment. But, even after rollback, the newly created ASG ("green" environment) stays there, I have to manually delete it.

Is there any way to automate the process of its deletion?

I didn't try anything, but I expected it to be deleted as soon as rollback happens.


问:
Isomorphic Render wont get my css or styling
I am using react as the client side and node.js as the server side, and using webpack to transpile. When I start the website on local host it is missing all of its styling and css. Any Ideas?
This is my frontend webpack that handles the transpiling of my frontend code

```<code>
const path = require('path');
const nodeExternals = require('webpack-node-externals');

module.exports = {
  target: 'node',
  externals: [nodeExternals()],
  entry: './frontend/src/App',
  output: {
    path: path.resolve(__dirname, 'backend/build'),
    filename: 'bundle.js',
    libraryTarget: 'commonjs2',
    libraryExport: 'default'
  },
  module: {
    rules: [
      {
        test: /\.jsx$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env', '@babel/preset-react']
          }
        }
      },
      {
        test: /\.(png|jpe?g|gif)$/i,
        use: [
          {
            loader: 'file-loader',
          },
        ],
      },

      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env', '@babel/preset-react']
          }
        }
      },

      {
        test: /\.css$/,
        use: [ 'css-loader'],
        sideEffects: true
      }
    ]
  }
};
</code>```

This is my backend/server.js that handles server rendering

```<code>const express = require('express');
const React = require('react');
const { renderToString } = require('react-dom/server');
const App = require('../backend/build/bundle');
const { matchPath } = require('react-router-dom');

const app = express();

// This is the middleware that will handle all routes
app.get('*', (req, res) => {
  // We create a context object that will be passed to the StaticRouter
  const context = {};

  // Render the app component to a string
  const html = renderToString(
    React.createElement(App, {
      location: req.url,
      context,
    })
  );

  // If the app component set a context.url value, it means the user
  // tried to access a protected route that they are not authenticated for.
  // In this case, we redirect them to the login page.
  if (context.url) {
    res.redirect(context.url);
  } else {
    // Send the rendered HTML as the response
    res.send(`
      <!DOCTYPE html>
      <html>
        <head>
          <title>My App</title>
        </head>
        <body>
          <div id="root">${html}</div>
          <script src="/build/bundle.js"></script>
        </body>
      </html>
    `);
  }
});

app.listen(3000, () =\> {
console.log('Server is listening on port 3000');
});

</code>```

This is my frontend App.js

```<code>
import React from "react";
import { StaticRouter } from "react-router-dom/server";
import { Footer, Contact, Who, Header } from "./containers";
import { Navbar, Background } from "./components";
import { Route, Routes } from "react-router-dom";
import "./App.css";

const App = (props) =\> {
return (
\<StaticRouter location={props.location} context={props.context}\>
\<Navbar /\>
\<Routes\>
\<Route exact path="/" element={\<Header /\>} /\>
\<Route path="/about" element={\<Who /\>} /\>
\<Route path="/contact" element={\<Contact /\>} /\>
\</Routes\>
\<Footer /\>
\</StaticRouter\>
);
};

export default App;

</code>```

And this is my index.js

```<code>
import React from 'react';
import ReactDom from 'react-dom';
import './index.css';
import App from './App';
ReactDom.render(
\<BrowserRouter\>
\<App /\>
\</BrowserRouter\>,
document.getElementById('root')
)

</code>```

I have tried to add the styling-loader to the webpack config for the frontend but I end up getting an error where the document is not defined. The routing works fine, just no css or images, just basic html is being rendered`

```<code></code>```

Body:
I am using react as the client side and node.js as the server side, and using webpack to transpile. When I start the website on local host it is missing all of its styling and css. Any Ideas?
This is my frontend webpack that handles the transpiling of my frontend code

const path = require('path');
const nodeExternals = require('webpack-node-externals');

module.exports = {
  target: 'node',
  externals: [nodeExternals()],
  entry: './frontend/src/App',
  output: {
    path: path.resolve(__dirname, 'backend/build'),
    filename: 'bundle.js',
    libraryTarget: 'commonjs2',
    libraryExport: 'default'
  },
  module: {
    rules: [
      {
        test: /\.jsx$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env', '@babel/preset-react']
          }
        }
      },
      {
        test: /\.(png|jpe?g|gif)$/i,
        use: [
          {
            loader: 'file-loader',
          },
        ],
      },

      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env', '@babel/preset-react']
          }
        }
      },

      {
        test: /\.css$/,
        use: [ 'css-loader'],
        sideEffects: true
      }
    ]
  }
};

This is my backend/server.js that handles server rendering

const express = require('express');
const React = require('react');
const { renderToString } = require('react-dom/server');
const App = require('../backend/build/bundle');
const { matchPath } = require('react-router-dom');

const app = express();

// This is the middleware that will handle all routes
app.get('*', (req, res) => {
  // We create a context object that will be passed to the StaticRouter
  const context = {};

  // Render the app component to a string
  const html = renderToString(
    React.createElement(App, {
      location: req.url,
      context,
    })
  );

  // If the app component set a context.url value, it means the user
  // tried to access a protected route that they are not authenticated for.
  // In this case, we redirect them to the login page.
  if (context.url) {
    res.redirect(context.url);
  } else {
    // Send the rendered HTML as the response
    res.send(`
      <!DOCTYPE html>

          <title>My App</title>

${html}

    `);
  }
});

app.listen(3000, () =\> {
console.log('Server is listening on port 3000');
});

This is my frontend App.js

import React from "react";
import { StaticRouter } from "react-router-dom/server";
import { Footer, Contact, Who, Header } from "./containers";
import { Navbar, Background } from "./components";
import { Route, Routes } from "react-router-dom";
import "./App.css";

const App = (props) =\> {
return (
\<StaticRouter location={props.location} context={props.context}\>
\<Navbar /\>
\<Routes\>
\<Route exact path="/" element={\} /\>
\<Route path="/about" element={\<Who /\>} /\>
\<Route path="/contact" element={\<Contact /\>} /\>
\</Routes\>
\
\</StaticRouter\>
);
};

export default App;

And this is my index.js

import React from 'react';
import ReactDom from 'react-dom';
import './index.css';
import App from './App';
ReactDom.render(
\<BrowserRouter\>
\<App /\>
\</BrowserRouter\>,
document.getElementById('root')
)

I have tried to add the styling-loader to the webpack config for the frontend but I end up getting an error where the document is not defined. The routing works fine, just no css or images, just basic html is being rendered`


问:
LSTM for time series forecasting
I have created a LSTM model in Pytorch which looks like this:

LSTMNet

Now I want to build another LSTM model (NewLSTMNet) on top of it (LSTMNet) by freezing the fc1 layer. I used:

```<code>model.fc1.weight.requires_grad = False
model.fc1.bias.requires_grad = False
</code>```

and then I changed fc2 layer with a linear layer with input features = 40 and output features = 40.

So far I did:

```<code>class NewLSTMNet(nn.Module):

    def __init__(self, model, input_size, hidden_size, num_layers):
        super(NewLSTMNet, self).__init__()
        self.model = model
        self.input_size = input_size
        self.hidden_size = hidden_size
        self.num_layers = num_layers

        self.model.fc2 = nn.Linear(40, 40)
        # self.lstm = nn.LSTM(input_size, hidden_size, num_layers, batch_first=True)
        self.fc3 = nn.Sequential(
            # nn.ReLU(),
            nn.Linear (40 , 128),
            nn.ReLU(),
            nn.Linear(128, 40),
            nn.ReLU(),
            nn.Linear(40,1),
            nn.ReLU(),
            )

    def forward(self,x):
        # input = self.model(x)
        # h0 = Variable(torch.zeros(self.num_layers, input.size(0), self.hidden_size))
        # c0 = Variable(torch.zeros(self.num_layers, input.size(0), self.hidden_size))
        # _, (h_out,_) = self.lstm(input, (h0,c0))

        # h_out = h_out.view(-1, self.hidden_size)
        # print(h_out.shape)

        # out = self.fc3(out)

        out = self.model(x)
        out = self.fc3(out)

        return out
</code>```

Now my new LSTM model looks like this:

NewLSTMNet

My training loop looks like this:

```<code>for epoch in range(EPOCHS):

    model.train()

    output = model(X_train)

    train_loss = criterion(output, y_train)

    optimizer.zero_grad()

    train_loss.backward()
    optimizer.step()

    with torch.no_grad():
        model.eval()
        output_val = model(X_valid)
        valid_loss = criterion(output_val, y_valid)

        if valid_loss <= valid_loss_min:
            torch.save(model.state_dict(), './state_dict_new.pt')
            print(
                f'Epoch {epoch + 0:01}: Validation loss decreased ({valid_loss_min:.6f} --> {valid_loss:.6f}).  Saving model ...')
            valid_loss_min = valid_loss
            early_stopping_counter = 0  # reset counter if validation loss decreases
        else:
            print(f'Epoch {epoch + 0:01}: Validation loss did not decrease')
            early_stopping_counter += 1

        if early_stopping_counter > early_stopping_patience:
            print('Early stopped at epoch :', epoch)
            break

        print(f'\t Train_Loss: {train_loss:.4f} Val_Loss: {valid_loss:.4f}  BEST VAL Loss: {valid_loss_min:.4f}\n')
</code>```

Now the model is working fine. But I want to create a LSTM layer in the NewLSTMNet model. I already tried to add a LSTM layer but I was expecting a vector in the output but I am getting a matrix in the output of the prediction. So there is shape mismatch!

How should I modify my code? Any help is appreciated. Thanks in advance!

Title: LSTM for time series forecasting

Body:
I have created a LSTM model in Pytorch which looks like this:

LSTMNet

Now I want to build another LSTM model (NewLSTMNet) on top of it (LSTMNet) by freezing the fc1 layer. I used:

model.fc1.weight.requires_grad = False
model.fc1.bias.requires_grad = False

and then I changed fc2 layer with a linear layer with input features = 40 and output features = 40.

So far I did:

class NewLSTMNet(nn.Module):

    def __init__(self, model, input_size, hidden_size, num_layers):
        super(NewLSTMNet, self).__init__()
        self.model = model
        self.input_size = input_size
        self.hidden_size = hidden_size
        self.num_layers = num_layers

        self.model.fc2 = nn.Linear(40, 40)
        # self.lstm = nn.LSTM(input_size, hidden_size, num_layers, batch_first=True)
        self.fc3 = nn.Sequential(
            # nn.ReLU(),
            nn.Linear (40 , 128),
            nn.ReLU(),
            nn.Linear(128, 40),
            nn.ReLU(),
            nn.Linear(40,1),
            nn.ReLU(),
            )

    def forward(self,x):
        # input = self.model(x)
        # h0 = Variable(torch.zeros(self.num_layers, input.size(0), self.hidden_size))
        # c0 = Variable(torch.zeros(self.num_layers, input.size(0), self.hidden_size))
        # _, (h_out,_) = self.lstm(input, (h0,c0))

        # h_out = h_out.view(-1, self.hidden_size)
        # print(h_out.shape)

        # out = self.fc3(out)

        out = self.model(x)
        out = self.fc3(out)

        return out

Now my new LSTM model looks like this:

NewLSTMNet

My training loop looks like this:

for epoch in range(EPOCHS):

    model.train()

    output = model(X_train)

    train_loss = criterion(output, y_train)

    optimizer.zero_grad()

    train_loss.backward()
    optimizer.step()

    with torch.no_grad():
        model.eval()
        output_val = model(X_valid)
        valid_loss = criterion(output_val, y_valid)

        if valid_loss <= valid_loss_min:
            torch.save(model.state_dict(), './state_dict_new.pt')
            print(
                f'Epoch {epoch + 0:01}: Validation loss decreased ({valid_loss_min:.6f} --> {valid_loss:.6f}).  Saving model ...')
            valid_loss_min = valid_loss
            early_stopping_counter = 0  # reset counter if validation loss decreases
        else:
            print(f'Epoch {epoch + 0:01}: Validation loss did not decrease')
            early_stopping_counter += 1

        if early_stopping_counter > early_stopping_patience:
            print('Early stopped at epoch :', epoch)
            break

        print(f'\t Train_Loss: {train_loss:.4f} Val_Loss: {valid_loss:.4f}  BEST VAL Loss: {valid_loss_min:.4f}\n')

Now the model is working fine. But I want to create a LSTM layer in the NewLSTMNet model. I already tried to add a LSTM layer but I was expecting a vector in the output but I am getting a matrix in the output of the prediction. So there is shape mismatch!

How should I modify my code? Any help is appreciated. Thanks in advance!


问:
Getting error during on "npm install recyclerlistview" in React JS project
We plan to use Flipkart/recyclerlistview in react js web application.
react@16.0.0
react-dom@16.0.0

Getting error on npm install recyclerlistview

npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: digirecruiter@0.1.0
npm ERR! Found: react@16.14.0
npm ERR! node_modules/react
npm ERR!   react@"^16.0.0" from the root project
npm ERR!   peer react@">= 15.2.1" from recyclerlistview@4.2.0
npm ERR!   node_modules/recyclerlistview
npm ERR!     recyclerlistview@"" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer react@"18.1.0" from react-native@0.70.6
npm ERR! node_modules/react-native
npm ERR!   peer react-native@">= 0.30.0" from recyclerlistview@4.2.0
npm ERR!   node_modules/recyclerlistview
npm ERR!     recyclerlistview@"" from the root project

Does Flipkart/recyclerlistview works with react js web application?

Steps taken:
Create a ReactJS project using create-react-app
Modify package.json for react version as recyclerlistview need 16.0.0 version

"react": "^16.0.0"

"react-dom": "^16.0.0",

npm install recyclerlistview --save

Getting mentioned error


问:
How to read Paragraph Titles and Paragraphs with Track changes like Insert and Delete in a Word Document using python-docx
I am working on a project where there is a Legal Word document in below Format and I want to extract the Paragraph titles along with the Paragraph and check if that paragraph has any track changes like Insert or Delete.

Heading

Paragraph 1 Text

Heading

Paragraph 2 Text
etc.,

I am able to extract the paragraphs individually and get the track changes from word/document.xml however the heading is also being coming as a paragraph when read with python-docx.

the Heading however is in bold text.

Is there a way to check when the paragraph 1 has any track changes, extract heading1 and assign it to a dictionary along with the paragraph text and track changes?

I tried to see if there is any particular style for headings but apparently there is nothing and the below output gave wrong results.

```<code>
    from docx import Document
    #from docx.shared import Inches

    document = Document("DOC_Example.docx")
    headings = []
    texts = []
    for paragraph in document.paragraphs:
        if paragraph.style.name == "Heading 2":
            headings.append(paragraph.text)
        elif paragraph.style.name == "Normal":
            texts.append(paragraph.text)

    for h, t in zip(headings, texts):
        print(h, t)

</code>```

I need to correlate and capture the Heading and Paragraph with the track changes in the same Dictionary.

I am a beginner in python and looking for some inputs.

Thanks in Advance.

Best Regards

Body:
I am working on a project where there is a Legal Word document in below Format and I want to extract the Paragraph titles along with the Paragraph and check if that paragraph has any track changes like Insert or Delete.

Heading

Paragraph 1 Text

Heading

Paragraph 2 Text
etc.,

I am able to extract the paragraphs individually and get the track changes from word/document.xml however the heading is also being coming as a paragraph when read with python-docx.

the Heading however is in bold text.

Is there a way to check when the paragraph 1 has any track changes, extract heading1 and assign it to a dictionary along with the paragraph text and track changes?

I tried to see if there is any particular style for headings but apparently there is nothing and the below output gave wrong results.

    from docx import Document
    #from docx.shared import Inches

    document = Document("DOC_Example.docx")
    headings = []
    texts = []
    for paragraph in document.paragraphs:
        if paragraph.style.name == "Heading 2":
            headings.append(paragraph.text)
        elif paragraph.style.name == "Normal":
            texts.append(paragraph.text)

    for h, t in zip(headings, texts):
        print(h, t)

I need to correlate and capture the Heading and Paragraph with the track changes in the same Dictionary.

I am a beginner in python and looking for some inputs.

Thanks in Advance.

Best Regards


问:
Receiving TypeError, when PandasCursor is imported from pyathena.pandas.cursor
I want to read an excel file into pandas from an AWS S3 bucket. Everything worked fine But when I import PandasCursor, which I need for another part of the code, I receive the following error message:

```<code>import pandas as pd
import s3fs
from pyathena import connect
from pyathena.pandas.cursor import PandasCursor

path = "s3://some/path/to/file.xlsx"
df = pd.read_excel(path)

>>>TypeError: S3FileSystem.__init__() missing 1 required positional argument: 'connection'
</code>```

Can anyone explain what is happening and how I can fix it?
From the pyathena docs I don't understand how PandasCursor is influencing pd.read_excel()

Body:
I want to read an excel file into pandas from an AWS S3 bucket. Everything worked fine But when I import PandasCursor, which I need for another part of the code, I receive the following error message:

import pandas as pd
import s3fs
from pyathena import connect
from pyathena.pandas.cursor import PandasCursor

path = "s3://some/path/to/file.xlsx"
df = pd.read_excel(path)

>>>TypeError: S3FileSystem.__init__() missing 1 required positional argument: 'connection'

Can anyone explain what is happening and how I can fix it?
From the pyathena docs I don't understand how PandasCursor is influencing pd.read_excel()


问:
PHP cURL Content-Length
I am trying to add a record to the database with POST operation via API and I generated the attached code from Postman.
On Postman, the process goes without any problem and user registration takes place.
But when I try to generate the code as "PHP cURL" via Postman and run it on PHP, I get the relevant error.

HTTP Error 411. The request must be chunked or have a content length.

I defined POSTFIELDS as array, calculated Content-Length using strlen function and added it to Headers. But it didn't work.

My PHP code;

```<code>$curl = curl_init();
curl_setopt_array($curl, array(
  CURLOPT_URL => 'https://xxx.xxx/xxx/xxx/xxx',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'POST',
  CURLOPT_POSTFIELDS =>'{
    "TokenKey": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    "EmployeeList": [
        {
            "Example1": "1",
            "Example2": "somedata2",
            "Example3": "somedata3",
            "Example4": "somedata4",
            "Example5": "somedata5",
            "Example6": "somedata6",
            "Example7": "somedata7",
            "Example8": "somedata8",
            "Example9": "somedata9",
            "Example10": "somedata10",
            "Example11": "somedata11",
            "Example12": "somedata12",
            "Example13": "somedata13",
            "Example14": "somedata14",
            "Example15": "somedata15",
            "Example16": "somedata16",
            "Example17": "somedata17",
            "Example18": "somedata18",
            "Example19": "somedata19",
            "Example20": "somedata20",
            "Example21": "somedata21",
            "Example22": "somedata22",
            "Example23": "somedata23",
            "Example24": "somedata24",
            "Example25": "somedata25",
            "Example26": "somedata26",
            "Example27": "somedata27",
            "Example28": "somedata28",
            "Example29": "somedata29",
            "Example30": "somedata30",
            "Example31": "somedata31",
            "Example32": null,
            "Example33": null,
            "Example34": null,
            "Example35": "2022-12-06 22:05:22",
            "Example36": false,
            "Example37": true
        }
    ]
}',
  CURLOPT_HTTPHEADER => array(
    'Content-Type: application/json'
  ),
));
$response = curl_exec($curl);

curl_close($curl);
echo $response;
echo "<br>";
echo $statusCode;````
```

Title: PHP cURL Content-Length

Body:
I am trying to add a record to the database with POST operation via API and I generated the attached code from Postman.
On Postman, the process goes without any problem and user registration takes place.
But when I try to generate the code as "PHP cURL" via Postman and run it on PHP, I get the relevant error.

HTTP Error 411. The request must be chunked or have a content length.

I defined POSTFIELDS as array, calculated Content-Length using strlen function and added it to Headers. But it didn't work.

My PHP code;

$curl = curl_init();
curl_setopt_array($curl, array(
  CURLOPT_URL => 'https://xxx.xxx/xxx/xxx/xxx',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'POST',
  CURLOPT_POSTFIELDS =>'{
    "TokenKey": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    "EmployeeList": [
        {
            "Example1": "1",
            "Example2": "somedata2",
            "Example3": "somedata3",
            "Example4": "somedata4",
            "Example5": "somedata5",
            "Example6": "somedata6",
            "Example7": "somedata7",
            "Example8": "somedata8",
            "Example9": "somedata9",
            "Example10": "somedata10",
            "Example11": "somedata11",
            "Example12": "somedata12",
            "Example13": "somedata13",
            "Example14": "somedata14",
            "Example15": "somedata15",
            "Example16": "somedata16",
            "Example17": "somedata17",
            "Example18": "somedata18",
            "Example19": "somedata19",
            "Example20": "somedata20",
            "Example21": "somedata21",
            "Example22": "somedata22",
            "Example23": "somedata23",
            "Example24": "somedata24",
            "Example25": "somedata25",
            "Example26": "somedata26",
            "Example27": "somedata27",
            "Example28": "somedata28",
            "Example29": "somedata29",
            "Example30": "somedata30",
            "Example31": "somedata31",
            "Example32": null,
            "Example33": null,
            "Example34": null,
            "Example35": "2022-12-06 22:05:22",
            "Example36": false,
            "Example37": true
        }
    ]
}',
  CURLOPT_HTTPHEADER => array(
    'Content-Type: application/json'
  ),
));
$response = curl_exec($curl);

curl_close($curl);
echo $response;
echo "
";
echo $statusCode;````


问:
How to enable JavaScript array methods in code completion in PhpStorm?
I cannot get the code completion tool for JavaScript to work properly in PhpStorm. I want array methods such as map(), filter(), etc. to show up, but they are not appearing.

Under Editor > General > Code Completion, I can't find any settings related to this. It is surprising that I can't find an answer to this.

My PhpStorm version is 2021.2.


问:
MATLAB Error code when try to acquire data from NI cDAQ9184
I would like to have some help on this error.
I using MATLAB with NI cDAQ9184.

Error code:

NI Error -201087:
Task contains physical channels on one or more devices that require you to specify the Sample Clock rate. Use the Sample Clock
Timing function/VI to specify a Sample Clock rate.
You cannot specify a Sample Clock rate if Mode is set to On Demand.
Device: cDAQ9184-182032A

Task Name: _unnamedTask

Status Code: -201087

Here is the code I use.
I use this code on the old computer before and it is run fine.
However, I have to change computer recently due to the computing power issue and the error appear.

% Set up the NI DAQ device
dq = daq("ni"); % Find avaliable NI Device
dq.Rate = 7142.8571; % Set Fequency of NI Devices

% Add an input channel for the analog input signal
ch1 = addinput(dq, "cDAQ9184-182032AMod2", "ai1", "Bridge"); % Add ai 0 input as Bridge modes
ch1.BridgeMode = "Full"; % Full mode
ch1.NominalBridgeResistance = 350; % Resisitance of the strain gauge

ch2 = addinput(dq, "cDAQ9184-182032AMod2", "ai2", "Bridge"); % Add ai 0 input as Bridge modes
ch2.BridgeMode = "Full"; % Full mode
ch2.NominalBridgeResistance = 350; % Resisitance of the strain gauge

ch3 = addinput(dq, "cDAQ9184-182032AMod2", "ai3", "Bridge"); % Add ai 0 input as Bridge modes
ch3.BridgeMode = "Full"; % Full mode
ch3.NominalBridgeResistance = 350; % Resisitance of the strain gauge

tic
while(toc<5)
Test = read(dq);
disp(Test)
pause(0.1);
end

Thank you.


问:
Add dynamic JSON LD to a script tag in Vue 3 using v-html
I have a function that returns dynamically generated JSON-LD as a string. I want to embed it in a script tag in my template.

This works:

<component :innerHTML="myJsonLdFunction(mySearchResult) :is="'script'" type="application/ld+json"></component>

But this does not work - the script tag stays empty:

<component v-html="myJsonLdFunction(mySearchResult)" :is="'script'" type="application/ld+json"></component>

What's the explanation for this difference? According to the documentation, v-html will "update the element's innerHTML". So it should work as well, right?