问:
QML can't call the function in .so files which created by Cython
I write a sample Qt - python script, using Pyside2 and QML. It runs fine. But after I convert .py files to .so files using Cython, QML raises such error: TypeError: Property 'say_hello' of object helloTest(0x12b9888) is not a function
Here is my code :

hello.py

```<code># hello.py

from PySide2.QtCore import QObject, Slot

class myHello(QObject):
    def __init__(self):
        super(myHello, self).__init__()

    @Slot(str)
    def say_hello(self, name):
        print('hello ' + name)
</code>```

main.py

```<code># main.py

from PySide2.QtGui import QGuiApplication
from PySide2.QtQml import QQmlApplicationEngine

import sys

from hello import myHello
import qml

if __name__ == "__main__":
    app = QGuiApplication(sys.argv)
    Engine = QQmlApplicationEngine()
    helloTest = myHello()
    Engine.rootContext().setContextProperty('helloTest', helloTest)
    Engine.load("qrc:/qml/main.qml")
    if not Engine.rootObjects():
        sys.exit(-1)
    sys.exit(app.exec_())
</code>```

qml/main.qml

```<code>// qml/main.qml
import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.5

Window {
    x:0
    y:0
    id:root
    width: 800
    height: 800
    visible: true
    color: "#000000"
    title: qsTr("TEST")

    Button {
        id: buton1
        text: "button_hello"
        width: 100
        height: 60
        x: 100
        y: 100
        onClicked: {
            helloTest.say_hello("world")
            console.log('Button Clicked')
        }
    }
}
</code>```

qml.qrc

```<code><RCC>
    <qresource prefix="/">
        <file>qml/main.qml</file>
    </qresource>
</RCC>
</code>```

First, I use pyrcc5 qml.qrc -o qml.py to get qml.py. I run the project by python main.py, it works well and print hello world.

But if I use Cython convert hello.py to hello.cpython-38-arm-linux-gnueabihf.so files, and run, it raise error:TypeError: Property 'say_hello' of object helloTest(0x12b9888) is not a function

Is there any way to let QML call the function in .so files?

note: My setup.py script is like this:

```<code>from setuptools import setup
from Cython.Build import cythonize

setup(
    name='Hello world app',
    ext_modules=cythonize("hello.py"),
    zip_safe=False,
)
</code>```

I run above all on a Linux (Armbian).

Body:
I write a sample Qt - python script, using Pyside2 and QML. It runs fine. But after I convert .py files to .so files using Cython, QML raises such error: TypeError: Property 'say_hello' of object helloTest(0x12b9888) is not a function
Here is my code :

hello.py

# hello.py

from PySide2.QtCore import QObject, Slot

class myHello(QObject):
    def __init__(self):
        super(myHello, self).__init__()

    @Slot(str)
    def say_hello(self, name):
        print('hello ' + name)

main.py

# main.py

from PySide2.QtGui import QGuiApplication
from PySide2.QtQml import QQmlApplicationEngine

import sys

from hello import myHello
import qml

if __name__ == "__main__":
    app = QGuiApplication(sys.argv)
    Engine = QQmlApplicationEngine()
    helloTest = myHello()
    Engine.rootContext().setContextProperty('helloTest', helloTest)
    Engine.load("qrc:/qml/main.qml")
    if not Engine.rootObjects():
        sys.exit(-1)
    sys.exit(app.exec_())

qml/main.qml

// qml/main.qml
import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.5

Window {
    x:0
    y:0
    id:root
    width: 800
    height: 800
    visible: true
    color: "#000000"
    title: qsTr("TEST")

    Button {
        id: buton1
        text: "button_hello"
        width: 100
        height: 60
        x: 100
        y: 100
        onClicked: {
            helloTest.say_hello("world")
            console.log('Button Clicked')
        }
    }
}

qml.qrc

<RCC>
    <qresource prefix="/">
        <file>qml/main.qml</file>
    </qresource>
</RCC>

First, I use pyrcc5 qml.qrc -o qml.py to get qml.py. I run the project by python main.py, it works well and print hello world.

But if I use Cython convert hello.py to hello.cpython-38-arm-linux-gnueabihf.so files, and run, it raise error:TypeError: Property 'say_hello' of object helloTest(0x12b9888) is not a function

Is there any way to let QML call the function in .so files?

note: My setup.py script is like this:

from setuptools import setup
from Cython.Build import cythonize

setup(
    name='Hello world app',
    ext_modules=cythonize("hello.py"),
    zip_safe=False,
)

I run above all on a Linux (Armbian).


来源: stackexchange

问:
With what can I replace the OpenCV filter2D function
I'd like to use scipy instead openCV in my code.
I'm looking for a function that operates like filter2D(img, -1, kernel) - Which I read in the documentation that

does actually compute correlation, not the convolution

But I'm unable to get the same exact results (Or even close enough) using signal.convolve2d(img, kernel, boundary='symm') or scipy.ndimage.correlate.

ContentLicense: CC BY-SA 4.0


问:
How to set http2 for a specific location block inside nginx configuration file
Question related to proxy_http_version in nginx

I have multiple location blocks inside my server block and I want to set h2 protocol on certain locations.

Ex: nginx location block which is inside a server block which has multiple location blocks is placed below.

```<code>location ~^/app$|^.*\.(js|css|woff|ttf)$ {
        proxy_cache eggstatic;
        expires 1d;
        proxy_cache_valid 200 1h;
        proxy_cache_revalidate on;
        proxy_cache_lock on;
        proxy_set_header Connection "";
        proxy_http_version 1.1; // want to change this to h2

        proxy_pass https:site_id;
    }
    ```
```

Body:
Question related to proxy_http_version in nginx

I have multiple location blocks inside my server block and I want to set h2 protocol on certain locations.

Ex: nginx location block which is inside a server block which has multiple location blocks is placed below.

location ~^/app$|^.*\.(js|css|woff|ttf)$ {
        proxy_cache eggstatic;
        expires 1d;
        proxy_cache_valid 200 1h;
        proxy_cache_revalidate on;
        proxy_cache_lock on;
        proxy_set_header Connection "";
        proxy_http_version 1.1; // want to change this to h2

        proxy_pass https:site_id;
    }
    ```


问:
I get error in the roblox studio "ServerScriptService.ToolManager:5: attempt to index nil with 'ToolActivated' "
I get error in the roblox studio

"ServerScriptService.ToolManager:5: attempt to index nil with
'ToolActivated' "

My 5 line is this:

```<code>remotes.ToolActivated.OnServerEvent:Connect(function(player: Player)
</code>```

So what I have do, that fix it?

Body:
I get error in the roblox studio

"ServerScriptService.ToolManager:5: attempt to index nil with
'ToolActivated' "

My 5 line is this:

remotes.ToolActivated.OnServerEvent:Connect(function(player: Player)

So what I have do, that fix it?


问:
Predict to a year further than the data I have
I have data from 2016 to 2021, I used multiple regression model lm() to achieve that.
What I like to have is continuing the trend to 2022 in a different line type and colour

I used prophet but the equation it uses is different from the model thus the results are different and will affect the assignment
the question is there another way to complete the trend line putting in mind the equation of the model?  `

ggplot(data=df, mapping = aes(x=Date)) +
        geom_line(mapping= aes(y=observed,
        color='ObservedCases'))+
        geom_point(mapping= aes(y=observed,
        color='ObservedCases')) +
        geom_line(mapping=aes(y=predicted,
        color='PredictedCases'), size=1) +
        geom_point(mapping=aes(y=predicted,
        color='PredictedCases'), size=1) +
        scale_x_date('Time',date_breaks='1 year',
                 date_labels="%Y") +
            labs(y='Number of Cases', colour='Trend Lines')

```
<p>#Sample of data</p>
```df <- data.frame(
  Date = structure(c(16801, 16832, 16861, 16892, 16922, 16953), class = "Date"),
  observed = c(1793, 2708, 1834, 1015, 1195, 809),
  predicted = c(3946.87980311387, 2603.21225568186, 1582.70357908881, 2788.41468480798, 862.923305922486, 268.345471468495))
```

Body:
I have data from 2016 to 2021, I used multiple regression model lm() to achieve that.
What I like to have is continuing the trend to 2022 in a different line type and colour

I used prophet but the equation it uses is different from the model thus the results are different and will affect the assignment
the question is there another way to complete the trend line putting in mind the equation of the model?  `

ggplot(data=df, mapping = aes(x=Date)) +
        geom_line(mapping= aes(y=observed,
        color='ObservedCases'))+
        geom_point(mapping= aes(y=observed,
        color='ObservedCases')) +
        geom_line(mapping=aes(y=predicted,
        color='PredictedCases'), size=1) +
        geom_point(mapping=aes(y=predicted,
        color='PredictedCases'), size=1) +
        scale_x_date('Time',date_breaks='1 year',
                 date_labels="%Y") +
            labs(y='Number of Cases', colour='Trend Lines')

#Sample of data

df <- data.frame(
  Date = structure(c(16801, 16832, 16861, 16892, 16922, 16953), class = "Date"),
  observed = c(1793, 2708, 1834, 1015, 1195, 809),
  predicted = c(3946.87980311387, 2603.21225568186, 1582.70357908881, 2788.41468480798, 862.923305922486, 268.345471468495))


问:
How can i solve Roboflow Visdrone Dataset Caching Error

I am trying to train my dataset for YOLOV5. I run this code python trainnn.py --img 416 --batch 16 --data data.yaml --weights yolov5s.pt --cache. After train started for 5 minutes, this was the only return train: Caching images (6.8GB ram): 100%|██████████| 14124/14124 00:07. My ram is 16gb.
How can i solve?


问:
Display a .OBJ 3D file on flutter from a url that returns that file (not from assets)
is there a way/package that allows us to display a .OBJ 3D file on flutter from a url that returns that file (not from assets) ?

Most of the existing ones either display a .glb file or display an obj from assets.


问:
react javascript event.target/currentTarget undefined
My problem is that when I open my modal cart where i have cartItems, i press on + sign to increase my cartItem quantity and for the first click i get undefined ([{…}]
0
:
{id: 3, quantity: undefined}
length
:
1[[Prototype]]
: Array(0))

after is set to undefined and i click again i get de incremented value.

I tried e.target.innerText, e.currentTarget.innerText... i remade the whole logic of all functions in this component, i tought it is beacause of useEffect() but everything works fine until i try to increment the value by getting the + or - sign from jsx

import React,{ useEffect, useState } from "react";
import classes from "./Modal.module.css";

export default function Modal({ setModal }) {
    const [cart,setCart] = useState([]);
    const [cartItems,setCartItems] = useState([]);
    const [qty,setQty] = useState();
    const [extracted, setExtracted] = useState([])

    console.log(extracted);
    const updateQuantity = (currentId,test) => {
        let element = extracted.filter(x=>x.id == currentId)[0];
        let filteredArray = extracted.filter(x => x!=element);
        console.log("elementtt",element.quantity)
        let newElement = {id:parseInt(currentId),quantity:qty};
        filteredArray.push(newElement);
        setExtracted(filteredArray);
    }

    const updateCartItem = (e) =>{
        // e.preventDefault();
        const currentId = e.currentTarget.id;
        let test;
        var htmlText = e.currentTarget.dataset;
        console.log("html text",htmlText)
        if(htmlText == "+"){
            setQty(99)
        }else{
            setQty("11111")
        }
        updateQuantity(currentId,test);
    }
const fetchCart = async () =>{
        const request = await fetch("http://localhost:8080/cart/get-cart")
        const response = await request.json();
        setCart(response);
        setCartItems(response.cartItems)
    }

    useEffect(()=>{
        fetchCart();
    },[])

    useEffect(()=>{
        extract();
    },[cartItems])

    const extract = () =>{
        for(let c of cartItems){
            console.log(c.product.id)
            const newObj = {id:c.product.id, quantity: c.quantity}
            setExtracted(extracted => [...extracted,newObj])
        }
    }

    const fetchDeleteItemFromCart = async (e)=>{
          const request = await fetch(`http://localhost:8080/cart/delete-cart-item/${e.target.id}`,{method:'DELETE'})
          const response = await request.json();
          setCart(response);
          setCartItems(response.cartItems);
      }

      function closeModal() {
        setModal(false);
    }
  return (
      <>

              <>

Shopping Cart

                          {cartItems && cartItems.map(item=>(

{item.product.productName}

{item.product.sellingPrice * item.quantity} $

Quantity:
                                       <button
                                       onClick={updateQuantity}
                                       id={item.product.id}
                                       data-sign={"-"}>-</button>
                                       <input
                                       onChange={(e)=> setQty(item.quantity)}
                                       value={item.quantity}/>
                                       <button
                                       onClick={e=>updateCartItem(e)}
                                       id={item.product.id}
                                       data-sign={"+"}>+</button>

                                          Remove

                                ))}

Subtotal {cart.totalPrices}

Tax {cart.totalPrices}

Shipping {cart.totalPrices}

Total {cart.totalPrices}

                          Checkout

              </>

    </>
  );
}
```


问:
(selenium) error clicking values within dropbox
```<code>user_input = input("Enter Card '6969696969696969 06/2026 666': ")

input_list = user_input.split()

text_field_1 = driver.find_element(By.CSS_SELECTOR, "input[aria-labelledby='i9']")
text_field_2 = driver.find_element(By.CSS_SELECTOR, "input[aria-labelledby='i21']")

text_field_1.send_keys(input_list[0])
text_field_2.send_keys(input_list[2])

dropdown_input = input_list[1].split('/')

month = dropdown_input[0]

dropdown_field_1 = driver.find_element(By.XPATH, "//div[contains(@class,'MocG8c HZ3kWc mhLiyf LMgvRb KKjvXb DEh1R')]")
dropdown_field_1.click()

options = driver.find_elements(By.XPATH, "//div[@jsaction and starts-with(@data-value, '0')]")
for option in options:
    time.sleep(2)
    option.click()
    break
</code>```

Error message:

```<code>Traceback (most recent call last):
line 41, in \<module\>
option.click()
</code>```

I attempted to use a selector, but it's a div class. scratching my head here. thanks!

Google form html

Body:
user_input = input("Enter Card '6969696969696969 06/2026 666': ")

input_list = user_input.split()

text_field_1 = driver.find_element(By.CSS_SELECTOR, "input[aria-labelledby='i9']")
text_field_2 = driver.find_element(By.CSS_SELECTOR, "input[aria-labelledby='i21']")

text_field_1.send_keys(input_list[0])
text_field_2.send_keys(input_list[2])

dropdown_input = input_list[1].split('/')

month = dropdown_input[0]

dropdown_field_1 = driver.find_element(By.XPATH, "//div[contains(@class,'MocG8c HZ3kWc mhLiyf LMgvRb KKjvXb DEh1R')]")
dropdown_field_1.click()

options = driver.find_elements(By.XPATH, "//div[@jsaction and starts-with(@data-value, '0')]")
for option in options:
    time.sleep(2)
    option.click()
    break

Error message:

Traceback (most recent call last):
line 41, in \<module\>
option.click()

I attempted to use a selector, but it's a div class. scratching my head here. thanks!

Google form html


问:
PHP Undefined $_POST input created via Javascript createElement and appendChild
I am creating dynamic input rows to POST it into MySQL database

the first row is mandatory, so I created the FORM and Inputs via HTML for the first row

Then created a button and addEventListener function to append any additional row dynamically

Error

Actually, all nodes and children are working normally from the DOM side without any problem

When I submit the form, only the first static row is posted but any appended rows give Undefined array key

myJsFile.js

```<code>document.getElementById('add_row').addEventListener('click',function(e){

 var my_tbody = document.querySelector('.my_tbodyClass');
 var my_tr = document.createElement('tr');
 my_tbody.appendChild(my_tr);

 var my_div = document.createElement('div');

 var my_td = document.createElement('td');
 var my_input = document.createElement('INPUT');
 my_input.setAttribute('type','number');
 my_input.setAttribute('name','myRows[]');

 my_tr.appendChild(my_td);
 my_div.appendChild(my_input);

 my_td.appendChild(my_div);

});
</code>```

myphpFile.php

```<code>function execute_dynamicRow()
{
    global $dbConnection;
    if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['submitedDynamicRows'])) {

        $myRows = $_POST['myRows'];
        $myRowsSerialized = serialize($myRows);

        $stmt = mysqli_prepare($dbConnection, "INSERT INTO all_dynamic_rows(dynamic_rows) VALUES(?)");
        $stmt_bind_param = mysqli_stmt_bind_param($stmt, 's', $myRowsSerialized);
        $stmt_execute = mysqli_stmt_execute($stmt);

        mysqli_stmt_close($stmt);

        if (!$stmt) {
            die("Query Error " . mysqli_error($dbConnection));
        }
    }
}
</code>```

myform.php

```<code><?php myform(); ?>

<form method="post">
  <table class="table table-flush">
    <thead>
      <tr>
        <th class="text-uppercase text-secondary">Add You Number</th>
        <th class="text-uppercase text-secondary">Add Row</th>
      </tr>
    </thead>
    <tbody class="my_tbodyClass">
      <tr>
        <td>
            <div>
              <input type="number" name="myRows[]">
            </div>
        </td>
        <td>
          <button class="btn btn-icon btn-3" id="add_row" type="button">
            <span class="btn-inner--text">Add New Row</span>
          </button>
        </td>
      </tr>
   </tbody>
  </table>
 <div class="input-group input-group-outline my-3">
  <input type="submit" name="submitedDynamicRows" class="btn btn-info" value="Add Tax Slab">
 </div>
</form>
</code>```

Body:
I am creating dynamic input rows to POST it into MySQL database

the first row is mandatory, so I created the FORM and Inputs via HTML for the first row

Then created a button and addEventListener function to append any additional row dynamically

Error

Actually, all nodes and children are working normally from the DOM side without any problem

When I submit the form, only the first static row is posted but any appended rows give Undefined array key

myJsFile.js

document.getElementById('add_row').addEventListener('click',function(e){

 var my_tbody = document.querySelector('.my_tbodyClass');
 var my_tr = document.createElement('tr');
 my_tbody.appendChild(my_tr);

 var my_div = document.createElement('div');

 var my_td = document.createElement('td');
 var my_input = document.createElement('INPUT');
 my_input.setAttribute('type','number');
 my_input.setAttribute('name','myRows[]');

 my_tr.appendChild(my_td);
 my_div.appendChild(my_input);

 my_td.appendChild(my_div);

});

myphpFile.php

function execute_dynamicRow()
{
    global $dbConnection;
    if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['submitedDynamicRows'])) {

        $myRows = $_POST['myRows'];
        $myRowsSerialized = serialize($myRows);

        $stmt = mysqli_prepare($dbConnection, "INSERT INTO all_dynamic_rows(dynamic_rows) VALUES(?)");
        $stmt_bind_param = mysqli_stmt_bind_param($stmt, 's', $myRowsSerialized);
        $stmt_execute = mysqli_stmt_execute($stmt);

        mysqli_stmt_close($stmt);

        if (!$stmt) {
            die("Query Error " . mysqli_error($dbConnection));
        }
    }
}

myform.php

<?php myform(); ?>

<form method="post">

        Add You Number
        Add Row

              <input type="number" name="myRows[]">

          <button class="btn btn-icon btn-3" id="add_row" type="button">
            Add New Row
          </button>

  <input type="submit" name="submitedDynamicRows" class="btn btn-info" value="Add Tax Slab">

</form>


问:
How can i make a Spectrum Distribution graph of whole music folders?
I trying to figure out how to make a Spectrum Distribution (+3dB/oct) graph from my music files.
Currently there are a free online mastering service which outputs this graph when you master a music. It's this free service. But you need to upload and master a song every time to get it.

I know there are free vst plugins which can do this, but you need to manually record the sound, and it does not analyze whole files.

Are there any linux programs which can do this, preferably +3dB/oct or 4.5dB/oct ?

I tried free vst plugins but you can't process whole folders with that.

EDIT: Okay now i think i found the source code of this graph, but i have no idea how to use this code. Could someone help with that? I am very new to programming.

SOLVED! You need to use the audio analyzer file in the github link i linked. It's working. Then you can write a script to batch process folders. You can find the build on the github page. You need to use the -spectrum_distribution_output "PATH.png" to output the image to a folder.

Source code


问:
how do you pass a parameter from post method to decorator?
I'm working a python django and django rest framework + swagger (drf-yasg) project.

I need a dynamic decorator.

how do you pass a parameter(named in this case "essource") of post method to decorator?

```<code>def xxx(esSource):

    source = {}
    if esSource == 1:
        source = {
            'field_1': openapi.Schema(type=openapi.TYPE_INTEGER)
        }
    else:
        source = {
            'field_44': openapi.Schema(type=openapi.TYPE_INTEGER)
        }

    properties = {
        'type_operator': openapi.Schema(type=openapi.TYPE_INTEGER,description="L'operatore di insieme AND(0) OR(1)"),
        'column_to_hide': openapi.Schema(type=openapi.TYPE_STRING,description="L'elenco di colonne da nascondere separato da virgola")
    }

    return properties.update(source)

class ShowResultsView(views.APIView):

    @swagger_auto_schema(
        operation_description="La prima pagina di risultati della ricerca",
        request_body=openapi.Schema(
            type=openapi.TYPE_OBJECT,
            required=['type_operator','column_to_hide'],
            properties=xxx(essource)
        ),
    )
    def post(self,request,essource,page):
        resp = {}
        resp["status"] = 0
        resp["data"] = {}
        resp["message"] = "I risultati della ricerca"
        return Response(resp,status=status.HTTP_200_OK)
</code>```

I get an error in this line code:
properties=xxx(essource)

Body:
I'm working a python django and django rest framework + swagger (drf-yasg) project.

I need a dynamic decorator.

how do you pass a parameter(named in this case "essource") of post method to decorator?

def xxx(esSource):

    source = {}
    if esSource == 1:
        source = {
            'field_1': openapi.Schema(type=openapi.TYPE_INTEGER)
        }
    else:
        source = {
            'field_44': openapi.Schema(type=openapi.TYPE_INTEGER)
        }

    properties = {
        'type_operator': openapi.Schema(type=openapi.TYPE_INTEGER,description="L'operatore di insieme AND(0) OR(1)"),
        'column_to_hide': openapi.Schema(type=openapi.TYPE_STRING,description="L'elenco di colonne da nascondere separato da virgola")
    }

    return properties.update(source)

class ShowResultsView(views.APIView):

    @swagger_auto_schema(
        operation_description="La prima pagina di risultati della ricerca",
        request_body=openapi.Schema(
            type=openapi.TYPE_OBJECT,
            required=['type_operator','column_to_hide'],
            properties=xxx(essource)
        ),
    )
    def post(self,request,essource,page):
        resp = {}
        resp["status"] = 0
        resp["data"] = {}
        resp["message"] = "I risultati della ricerca"
        return Response(resp,status=status.HTTP_200_OK)

I get an error in this line code:
properties=xxx(essource)


问:
When I run flutter gallery loaclly, I faced with exception with Syntax Error when try to pub get

Steps to Reproduce

Follow the document and switch my channel to master and upgraded.

git clone flutter/gallery project locally

follow the step run flutter pub get

pumped out:

Generating synthetic localizations package failed with 1 error:

Exception: Found syntax errors.

Logs

```<code>       Exception: Found syntax errors.
       #0      throwToolExit (package:flutter_tools/src/base/common.dart:10:3)
       #1      generateLocalizationsSyntheticPackage (package:flutter_tools/src/dart/generate_synthetic_packages.dart:67:5)
       <asynchronous suspension>
       #2      PackagesGetCommand._runPubGet (package:flutter_tools/src/commands/packages.dart:132:7)
       <asynchronous suspension>
       #3      PackagesGetCommand.runCommand (package:flutter_tools/src/commands/packages.dart:175:5)
       <asynchronous suspension>
       #4      FlutterCommand.run.<anonymous closure> (package:flutter_tools/src/runner/flutter_command.dart:1275:27)
       <asynchronous suspension>
       #5      AppContext.run.<anonymous closure> (package:flutter_tools/src/base/context.dart:150:19)
       <asynchronous suspension>
       #6      CommandRunner.runCommand (package:args/command_runner.dart:209:13)
       <asynchronous suspension>
       #7      FlutterCommandRunner.runCommand.<anonymous closure>
       (package:flutter_tools/src/runner/flutter_command_runner.dart:290:9)
       <asynchronous suspension>
       #8      AppContext.run.<anonymous closure> (package:flutter_tools/src/base/context.dart:150:19)
       <asynchronous suspension>
       #9      FlutterCommandRunner.runCommand (package:flutter_tools/src/runner/flutter_command_runner.dart:236:5)
       <asynchronous suspension>
       #10     run.<anonymous closure>.<anonymous closure> (package:flutter_tools/runner.dart:64:9)
       <asynchronous suspension>
       #11     AppContext.run.<anonymous closure> (package:flutter_tools/src/base/context.dart:150:19)
       <asynchronous suspension>
       #12     main (package:flutter_tools/executable.dart:91:3)
       <asynchronous suspension>
</code>```

Flutter doctor shows

[✓] Flutter (Channel master, 3.7.0-13.0.pre.63, on Microsoft Windows [版本 10.0.22621.963], locale zh-CN)
• Flutter version 3.7.0-13.0.pre.63 on channel master at C:\src\flutter
• Upstream repository https://git.sjtu.edu.cn/sjtug/flutter-sdk.git
• FLUTTER_GIT_URL = https://git.sjtu.edu.cn/sjtug/flutter-sdk.git
• Framework revision 393e156c23 (5 hours ago), 2022-12-23 20:38:23 -0500
• Engine revision e3edfadbda
• Dart version 3.0.0 (build 3.0.0-63.0.dev)
• DevTools version 2.20.0
• Pub download mirror https://mirror.sjtu.edu.cn/dart-pub
• Flutter download mirror https://mirror.sjtu.edu.cn

[✓] Windows Version (Installed version of Windows is version 10 or higher)

[✗] Android toolchain - develop for Android devices
✗ Unable to locate Android SDK.
Install Android Studio from:
On first launch it will assist you in installing the Android SDK components.
(or visit).
If the Android SDK has been installed to a custom location, please use
flutter config --android-sdk to update to that location.

[✓] Chrome - develop for the web
• Chrome at C:\Program Files\Google\Chrome\Application\chrome.exe

[✗] Visual Studio - develop for Windows
✗ Visual Studio not installed; this is necessary for Windows development.
Download at .
Please install the "Desktop development with C++" workload, including all of its default components

[!] Android Studio (not installed)
• Android Studio not found; download from for detailed instructions).

[✓] VS Code (version 1.74.2)
• VS Code at C:\Users\andre\AppData\Local\Programs\Microsoft VS Code
• Flutter extension version 3.56.0

[✓] Connected device (3 available)
• Windows (desktop) • windows • windows-x64    • Microsoft Windows [版本 10.0.22621.963]
• Chrome (web)      • chrome  • web-javascript • Google Chrome 108.0.5359.125
• Edge (web)        • edge    • web-javascript • Microsoft Edge 108.0.1462.54

[✓] HTTP Host Availability
• All required HTTP hosts are available

I hope that someone would tell me how to solve with those Syntax Error problems and demonstrate how did it occurred.

Body:
Steps to Reproduce

Follow the document and switch my channel to master and upgraded.

git clone flutter/gallery project locally

follow the step run flutter pub get

pumped out:

Generating synthetic localizations package failed with 1 error:

Exception: Found syntax errors.

Logs

       Exception: Found syntax errors.
       #0      throwToolExit (package:flutter_tools/src/base/common.dart:10:3)
       #1      generateLocalizationsSyntheticPackage (package:flutter_tools/src/dart/generate_synthetic_packages.dart:67:5)
       <asynchronous suspension>
       #2      PackagesGetCommand._runPubGet (package:flutter_tools/src/commands/packages.dart:132:7)
       <asynchronous suspension>
       #3      PackagesGetCommand.runCommand (package:flutter_tools/src/commands/packages.dart:175:5)
       <asynchronous suspension>
       #4      FlutterCommand.run.<anonymous closure> (package:flutter_tools/src/runner/flutter_command.dart:1275:27)
       <asynchronous suspension>
       #5      AppContext.run.<anonymous closure> (package:flutter_tools/src/base/context.dart:150:19)
       <asynchronous suspension>
       #6      CommandRunner.runCommand (package:args/command_runner.dart:209:13)
       <asynchronous suspension>
       #7      FlutterCommandRunner.runCommand.<anonymous closure>
       (package:flutter_tools/src/runner/flutter_command_runner.dart:290:9)
       <asynchronous suspension>
       #8      AppContext.run.<anonymous closure> (package:flutter_tools/src/base/context.dart:150:19)
       <asynchronous suspension>
       #9      FlutterCommandRunner.runCommand (package:flutter_tools/src/runner/flutter_command_runner.dart:236:5)
       <asynchronous suspension>
       #10     run.<anonymous closure>.<anonymous closure> (package:flutter_tools/runner.dart:64:9)
       <asynchronous suspension>
       #11     AppContext.run.<anonymous closure> (package:flutter_tools/src/base/context.dart:150:19)
       <asynchronous suspension>
       #12     main (package:flutter_tools/executable.dart:91:3)
       <asynchronous suspension>

Flutter doctor shows

[✓] Flutter (Channel master, 3.7.0-13.0.pre.63, on Microsoft Windows [版本 10.0.22621.963], locale zh-CN)
• Flutter version 3.7.0-13.0.pre.63 on channel master at C:\src\flutter
• Upstream repository https://git.sjtu.edu.cn/sjtug/flutter-sdk.git
• FLUTTER_GIT_URL = https://git.sjtu.edu.cn/sjtug/flutter-sdk.git
• Framework revision 393e156c23 (5 hours ago), 2022-12-23 20:38:23 -0500
• Engine revision e3edfadbda
• Dart version 3.0.0 (build 3.0.0-63.0.dev)
• DevTools version 2.20.0
• Pub download mirror https://mirror.sjtu.edu.cn/dart-pub
• Flutter download mirror https://mirror.sjtu.edu.cn

[✓] Windows Version (Installed version of Windows is version 10 or higher)

[✗] Android toolchain - develop for Android devices
✗ Unable to locate Android SDK.
Install Android Studio from:
On first launch it will assist you in installing the Android SDK components.
(or visit).
If the Android SDK has been installed to a custom location, please use
flutter config --android-sdk to update to that location.

[✓] Chrome - develop for the web
• Chrome at C:\Program Files\Google\Chrome\Application\chrome.exe

[✗] Visual Studio - develop for Windows
✗ Visual Studio not installed; this is necessary for Windows development.
Download at .
Please install the "Desktop development with C++" workload, including all of its default components

[!] Android Studio (not installed)
• Android Studio not found; download from for detailed instructions).

[✓] VS Code (version 1.74.2)
• VS Code at C:\Users\andre\AppData\Local\Programs\Microsoft VS Code
• Flutter extension version 3.56.0

[✓] Connected device (3 available)
• Windows (desktop) • windows • windows-x64    • Microsoft Windows [版本 10.0.22621.963]
• Chrome (web)      • chrome  • web-javascript • Google Chrome 108.0.5359.125
• Edge (web)        • edge    • web-javascript • Microsoft Edge 108.0.1462.54

[✓] HTTP Host Availability
• All required HTTP hosts are available

I hope that someone would tell me how to solve with those Syntax Error problems and demonstrate how did it occurred.


问:
LinearLayout does not respond to child height change in RecyclerView
I'm trying to achieve a expandable textview which allow user to expand our collapse text longer than specified lines.

However, when the text is expanded, requestLayout of the TextView was called, but LinearLayout instead of expanding itself, it cut the TextView and the other child inside LinearLayout becomes 0dp. (Measured in Layout Insepctor)

The code I use to achieve ExpandableTextView is down below:

ExpandTextView.kt

```<code>class ExpandTextView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : AppCompatTextView(context, attrs, defStyleAttr) {

    /**
     * true：展开，false：收起
     */
    private var mExpanded = false

    private var mCallback: ExpandTextViewCallback? = null

    /**
     * 源文字内容
     */
    private var mText = ""
    private var maxLineCount = 3
    private var ellipsizeText = "..."

    fun setMaxLineCount(maxLineCount: Int) {
        this.maxLineCount = maxLineCount
    }

    fun setEllipsizeText(ellipsizeText: String) {
        this.ellipsizeText = ellipsizeText
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)

        val staticLayout = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            StaticLayout(mText, paint, measuredWidth - paddingLeft - paddingRight, Layout.Alignment.ALIGN_CENTER, 1f, 0f, true)
        } else {
            val builder = StaticLayout.Builder.obtain(mText, 0, text.length, paint, measuredWidth - paddingLeft - paddingRight)
                .setAlignment(Layout.Alignment.ALIGN_CENTER)
                .setLineSpacing(0f, 1f)
                .setIncludePad(true)

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                builder.setUseLineSpacingFromFallbacks(true)
            }

            builder.build()
        }

        /**
         * 总计行数
         */
        var lineCount = staticLayout.lineCount
        if (lineCount > maxLineCount) {
            when (mExpanded) {
                true -> {
                    mCallback?.onExpand()
                    text = mText
                }
                false -> {
                    mCallback?.onCollapse()

                    lineCount = maxLineCount

                    val dotWidth = paint.measureText(ellipsizeText)

                    val start = staticLayout.getLineStart(lineCount - 1)
                    val end = staticLayout.getLineEnd(lineCount - 1)
                    val lineText = mText.substring(start, end)

                    var endIndex = 0
                    for (i in lineText.length - 1 downTo 0) {
                        val str = lineText.substring(i, lineText.length)
                        if (paint.measureText(str) >= dotWidth) {
                            endIndex = i
                            break
                        }
                    }

                    val newEndLineText = lineText.substring(0, endIndex) + ellipsizeText
                    text = mText.substring(0, start) + newEndLineText
                }
            }
        } else {
            //mCallback?.onLoss()
            text = mText
        }

        var lineHeight = 0
        for (i in 0 until lineCount) {
            val lienBound = Rect()
            staticLayout.getLineBounds(i, lienBound)
            lineHeight += lienBound.height()
        }

        lineHeight += paddingTop + paddingBottom
        setMeasuredDimension(measuredWidth, lineHeight)
    }

    fun toggleExpand() {
        mExpanded = !mExpanded
        requestLayout()
    }

    fun setText(text: String, callback: ExpandTextViewCallback) {
        mText = text
        mCallback = callback

        setText(text)
    }
}
</code>```

ExpandLayout.kt

```<code>class ExpandLayout @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : LinearLayout(context, attrs, defStyleAttr) {

    private var binding: LayoutExpandViewBinding

    private var maxCollapsedLines = 3
    private var contentTextSize = 18f
    private var contentTextColor = 0
    private var expandText = ""
    private var collapseText = ""
    private var expandCollapseTextSize = 18f
    private var expandCollapseTextColor = 0
    private var expandCollapseTextGravity = 0
    private var ellipsizeText = "..."
    private var middlePadding = 0f

    init {
        initAttrs(context, attrs, defStyleAttr)
        orientation = VERTICAL
        binding = LayoutExpandViewBinding.inflate(LayoutInflater.from(context), this, true)
        binding.etvContent.setMaxLineCount(maxCollapsedLines)
        binding.etvContent.textSize = DensityUtil.px2sp(context, contentTextSize)
        binding.etvContent.setTextColor(contentTextColor)
        binding.etvContent.setEllipsizeText(ellipsizeText)

        val layoutParams = binding.tvTip.layoutParams as LayoutParams
        layoutParams.topMargin = middlePadding.toInt()
        binding.tvTip.layoutParams = layoutParams

        binding.tvTip.textSize = DensityUtil.px2sp(context, expandCollapseTextSize)
        binding.tvTip.setTextColor(expandCollapseTextColor)
        binding.tvTip.gravity = when (expandCollapseTextGravity) {
            0 -> Gravity.LEFT
            1 -> Gravity.CENTER
            2 -> Gravity.RIGHT
            else -> Gravity.LEFT
        }

        binding.etvContent.requestLayout()
        binding.tvTip.requestLayout()
    }

    private fun initAttrs(context: Context, attrs: AttributeSet?, defStyleAttr: Int) {
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.ExpandLayout)
        maxCollapsedLines = typedArray.getInt(R.styleable.ExpandLayout_maxCollapsedLines, 3)
        contentTextSize = typedArray.getDimension(R.styleable.ExpandLayout_contentTextSize, DensityUtil.sp2px(context, 18f).toFloat())
        contentTextColor = typedArray.getColor(R.styleable.ExpandLayout_contentTextColor, resources.getColor(R.color.text_black))
        expandText = if (typedArray.getString(R.styleable.ExpandLayout_expandText).isNullOrEmpty()) "全文" else typedArray.getString(R.styleable.ExpandLayout_expandText).toString()
        collapseText = if (typedArray.getString(R.styleable.ExpandLayout_collapseText).isNullOrEmpty()) "收起" else typedArray.getString(R.styleable.ExpandLayout_collapseText).toString()
        expandCollapseTextSize = typedArray.getDimension(R.styleable.ExpandLayout_expandCollapseTextSize, DensityUtil.sp2px(context, 18f).toFloat())
        expandCollapseTextColor = typedArray.getColor(R.styleable.ExpandLayout_expandCollapseTextColor, resources.getColor(R.color.text_blue))
        expandCollapseTextGravity = typedArray.getColor(R.styleable.ExpandLayout_expandCollapseTextGravity, 0)
        ellipsizeText = if (typedArray.getString(R.styleable.ExpandLayout_ellipsizeText).isNullOrEmpty()) "..." else typedArray.getString(R.styleable.ExpandLayout_ellipsizeText).toString()
        middlePadding = typedArray.getDimension(R.styleable.ExpandLayout_middlePadding, 0f)
        typedArray.recycle()
    }

    fun setContent(text: String) {
        binding.tvTip.setOnClickListener {
            binding.etvContent.toggleExpand()
        }
        binding.etvContent.setText(text, object : ExpandTextViewCallback {
            override fun onExpand() {
                binding.tvTip.visibility = View.VISIBLE
                binding.tvTip.text = collapseText
            }

            override fun onCollapse() {
                binding.tvTip.visibility = View.VISIBLE
                binding.tvTip.text = expandText
            }

            override fun onLoss() {
                binding.tvTip.visibility = View.GONE
            }
        })
    }
}
</code>```

The ExpandLayout layout xml code:

layout_expand_view.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ll_expand_view"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <com.zld.expandlayout.ExpandTextView
        android:id="@+id/etv_content"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/tv_tip"
        android:gravity="left"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="查看全文"
        android:textColor="#39a4d2" />

</LinearLayout>
</code>```

RecyclerView Item Xml:

```<code><androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="14dp"
    app:cardBackgroundColor="@color/white"
    app:cardCornerRadius="8dp"
    app:cardElevation="0dp">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <!-- Many other views here -->

        <com.zld.expandlayout.ExpandLayout
            android:id="@+id/message_content"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="12dp"
            android:layout_marginLeft="12dp"
            android:layout_marginRight="12dp"
            app:contentTextColor="#313131"
            app:contentTextSize="12sp"
            app:expandText="@string/forum_text_expand"
            app:collapseText="@string/forum_text_collapse"
            app:maxCollapsedLines="5"
            app:expandCollapseTextColor="@color/theme_color"
            app:expandCollapseTextGravity="left"
            app:expandCollapseTextSize="12sp" />

    </LinearLayout>

</androidx.cardview.widget.CardView>
</code>```

As you can here, when I click the expand or collapse button, the content did expand, but the LinearLayout cut the content, while the expand or collapse button (the other textview) height becomes 0dp.

Body:
I'm trying to achieve a expandable textview which allow user to expand our collapse text longer than specified lines.

However, when the text is expanded, requestLayout of the TextView was called, but LinearLayout instead of expanding itself, it cut the TextView and the other child inside LinearLayout becomes 0dp. (Measured in Layout Insepctor)

The code I use to achieve ExpandableTextView is down below:

ExpandTextView.kt

class ExpandTextView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : AppCompatTextView(context, attrs, defStyleAttr) {

    /**
     * true：展开，false：收起
     */
    private var mExpanded = false

    private var mCallback: ExpandTextViewCallback? = null

    /**
     * 源文字内容
     */
    private var mText = ""
    private var maxLineCount = 3
    private var ellipsizeText = "..."

    fun setMaxLineCount(maxLineCount: Int) {
        this.maxLineCount = maxLineCount
    }

    fun setEllipsizeText(ellipsizeText: String) {
        this.ellipsizeText = ellipsizeText
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)

        val staticLayout = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            StaticLayout(mText, paint, measuredWidth - paddingLeft - paddingRight, Layout.Alignment.ALIGN_CENTER, 1f, 0f, true)
        } else {
            val builder = StaticLayout.Builder.obtain(mText, 0, text.length, paint, measuredWidth - paddingLeft - paddingRight)
                .setAlignment(Layout.Alignment.ALIGN_CENTER)
                .setLineSpacing(0f, 1f)
                .setIncludePad(true)

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                builder.setUseLineSpacingFromFallbacks(true)
            }

            builder.build()
        }

        /**
         * 总计行数
         */
        var lineCount = staticLayout.lineCount
        if (lineCount > maxLineCount) {
            when (mExpanded) {
                true -> {
                    mCallback?.onExpand()
                    text = mText
                }
                false -> {
                    mCallback?.onCollapse()

                    lineCount = maxLineCount

                    val dotWidth = paint.measureText(ellipsizeText)

                    val start = staticLayout.getLineStart(lineCount - 1)
                    val end = staticLayout.getLineEnd(lineCount - 1)
                    val lineText = mText.substring(start, end)

                    var endIndex = 0
                    for (i in lineText.length - 1 downTo 0) {
                        val str = lineText.substring(i, lineText.length)
                        if (paint.measureText(str) >= dotWidth) {
                            endIndex = i
                            break
                        }
                    }

                    val newEndLineText = lineText.substring(0, endIndex) + ellipsizeText
                    text = mText.substring(0, start) + newEndLineText
                }
            }
        } else {
            //mCallback?.onLoss()
            text = mText
        }

        var lineHeight = 0
        for (i in 0 until lineCount) {
            val lienBound = Rect()
            staticLayout.getLineBounds(i, lienBound)
            lineHeight += lienBound.height()
        }

        lineHeight += paddingTop + paddingBottom
        setMeasuredDimension(measuredWidth, lineHeight)
    }

    fun toggleExpand() {
        mExpanded = !mExpanded
        requestLayout()
    }

    fun setText(text: String, callback: ExpandTextViewCallback) {
        mText = text
        mCallback = callback

        setText(text)
    }
}

ExpandLayout.kt

class ExpandLayout @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : LinearLayout(context, attrs, defStyleAttr) {

    private var binding: LayoutExpandViewBinding

    private var maxCollapsedLines = 3
    private var contentTextSize = 18f
    private var contentTextColor = 0
    private var expandText = ""
    private var collapseText = ""
    private var expandCollapseTextSize = 18f
    private var expandCollapseTextColor = 0
    private var expandCollapseTextGravity = 0
    private var ellipsizeText = "..."
    private var middlePadding = 0f

    init {
        initAttrs(context, attrs, defStyleAttr)
        orientation = VERTICAL
        binding = LayoutExpandViewBinding.inflate(LayoutInflater.from(context), this, true)
        binding.etvContent.setMaxLineCount(maxCollapsedLines)
        binding.etvContent.textSize = DensityUtil.px2sp(context, contentTextSize)
        binding.etvContent.setTextColor(contentTextColor)
        binding.etvContent.setEllipsizeText(ellipsizeText)

        val layoutParams = binding.tvTip.layoutParams as LayoutParams
        layoutParams.topMargin = middlePadding.toInt()
        binding.tvTip.layoutParams = layoutParams

        binding.tvTip.textSize = DensityUtil.px2sp(context, expandCollapseTextSize)
        binding.tvTip.setTextColor(expandCollapseTextColor)
        binding.tvTip.gravity = when (expandCollapseTextGravity) {
            0 -> Gravity.LEFT
            1 -> Gravity.CENTER
            2 -> Gravity.RIGHT
            else -> Gravity.LEFT
        }

        binding.etvContent.requestLayout()
        binding.tvTip.requestLayout()
    }

    private fun initAttrs(context: Context, attrs: AttributeSet?, defStyleAttr: Int) {
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.ExpandLayout)
        maxCollapsedLines = typedArray.getInt(R.styleable.ExpandLayout_maxCollapsedLines, 3)
        contentTextSize = typedArray.getDimension(R.styleable.ExpandLayout_contentTextSize, DensityUtil.sp2px(context, 18f).toFloat())
        contentTextColor = typedArray.getColor(R.styleable.ExpandLayout_contentTextColor, resources.getColor(R.color.text_black))
        expandText = if (typedArray.getString(R.styleable.ExpandLayout_expandText).isNullOrEmpty()) "全文" else typedArray.getString(R.styleable.ExpandLayout_expandText).toString()
        collapseText = if (typedArray.getString(R.styleable.ExpandLayout_collapseText).isNullOrEmpty()) "收起" else typedArray.getString(R.styleable.ExpandLayout_collapseText).toString()
        expandCollapseTextSize = typedArray.getDimension(R.styleable.ExpandLayout_expandCollapseTextSize, DensityUtil.sp2px(context, 18f).toFloat())
        expandCollapseTextColor = typedArray.getColor(R.styleable.ExpandLayout_expandCollapseTextColor, resources.getColor(R.color.text_blue))
        expandCollapseTextGravity = typedArray.getColor(R.styleable.ExpandLayout_expandCollapseTextGravity, 0)
        ellipsizeText = if (typedArray.getString(R.styleable.ExpandLayout_ellipsizeText).isNullOrEmpty()) "..." else typedArray.getString(R.styleable.ExpandLayout_ellipsizeText).toString()
        middlePadding = typedArray.getDimension(R.styleable.ExpandLayout_middlePadding, 0f)
        typedArray.recycle()
    }

    fun setContent(text: String) {
        binding.tvTip.setOnClickListener {
            binding.etvContent.toggleExpand()
        }
        binding.etvContent.setText(text, object : ExpandTextViewCallback {
            override fun onExpand() {
                binding.tvTip.visibility = View.VISIBLE
                binding.tvTip.text = collapseText
            }

            override fun onCollapse() {
                binding.tvTip.visibility = View.VISIBLE
                binding.tvTip.text = expandText
            }

            override fun onLoss() {
                binding.tvTip.visibility = View.GONE
            }
        })
    }
}

The ExpandLayout layout xml code:

layout_expand_view.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ll_expand_view"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <com.zld.expandlayout.ExpandTextView
        android:id="@+id/etv_content"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/tv_tip"
        android:gravity="left"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="查看全文"
        android:textColor="#39a4d2" />

</LinearLayout>

RecyclerView Item Xml:

<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="14dp"
    app:cardBackgroundColor="@color/white"
    app:cardCornerRadius="8dp"
    app:cardElevation="0dp">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <com.zld.expandlayout.ExpandLayout
            android:id="@+id/message_content"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="12dp"
            android:layout_marginLeft="12dp"
            android:layout_marginRight="12dp"
            app:contentTextColor="#313131"
            app:contentTextSize="12sp"
            app:expandText="@string/forum_text_expand"
            app:collapseText="@string/forum_text_collapse"
            app:maxCollapsedLines="5"
            app:expandCollapseTextColor="@color/theme_color"
            app:expandCollapseTextGravity="left"
            app:expandCollapseTextSize="12sp" />

    </LinearLayout>

</androidx.cardview.widget.CardView>

As you can here, when I click the expand or collapse button, the content did expand, but the LinearLayout cut the content, while the expand or collapse button (the other textview) height becomes 0dp.


问:
I need to convert all my images to WEBP in my drf project, how to do this? For images I'm using imagekit library
I need to convert all my images to WEBP in my drf project, how to do this? For images I'm using imagekit library

Is it possible to do this?


问:
How to add file in laravel through dropify data-default-file
Hello i am trying to show the image in the dropify field by fetching the image from database.But i am unable to do so .Kindly check my code.

`

```<code><input type="file" class="dropify" name="profile_pic" data-default-file="{{ url('/uploads/driving/'.$user->profile_pic) }}"/>
</code>```

THE CONTROLLER IS

```<code>public function editUserForm($id)
{
    $user = User::find($id);
    return view('admin.users.edit-users',compact('user'));
}
public function updateUser(Request $request,$id)
{
    $r1 = $request->validate([
        'profile_pic' => 'required|image|mimes:jpg,png,jpeg,gif,svg|max:2048|',
        'name' => 'required',
        'email' => 'required|email',
        'city' => 'required',
        'phone_no' => 'required',
    ]);
    if ($request->hasFile('profile_pic')) {
        $imgName = uniqid() . '.' . $request->profile_pic->getClientOriginalExtension();
    }
    $user = User::find($id);

    $user->name = $request->name;
    $user->email = $request->email;
    $user->phone_no = $request->phone_no;
    $user->profile_pic =$imgName;
    $user->city = $request->city;
    $user->update();
    $path = public_path('uploads/driving');
        if ($request->hasFile('profile_pic')) {
            $request->profile_pic->move($path, $imgName);
        }

    return redirect()->route('users')->with('message', 'User info updated successfully!');
}
</code>```

i created a url data-default-file="{{ url('/uploads/driving/'.$user->profile_pic) }}" but unable to show the image.

Body:
Hello i am trying to show the image in the dropify field by fetching the image from database.But i am unable to do so .Kindly check my code.

`

<input type="file" class="dropify" name="profile_pic" data-default-file="{{ url('/uploads/driving/'.$user->profile_pic) }}"/>

THE CONTROLLER IS

public function editUserForm($id)
{
    $user = User::find($id);
    return view('admin.users.edit-users',compact('user'));
}
public function updateUser(Request $request,$id)
{
    $r1 = $request->validate([
        'profile_pic' => 'required|image|mimes:jpg,png,jpeg,gif,svg|max:2048|',
        'name' => 'required',
        'email' => 'required|email',
        'city' => 'required',
        'phone_no' => 'required',
    ]);
    if ($request->hasFile('profile_pic')) {
        $imgName = uniqid() . '.' . $request->profile_pic->getClientOriginalExtension();
    }
    $user = User::find($id);

    $user->name = $request->name;
    $user->email = $request->email;
    $user->phone_no = $request->phone_no;
    $user->profile_pic =$imgName;
    $user->city = $request->city;
    $user->update();
    $path = public_path('uploads/driving');
        if ($request->hasFile('profile_pic')) {
            $request->profile_pic->move($path, $imgName);
        }

    return redirect()->route('users')->with('message', 'User info updated successfully!');
}

i created a url data-default-file="{{ url('/uploads/driving/'.$user->profile_pic) }}" but unable to show the image.


问:
PHP TCPDF Font Size in MM
in this moment i spend many hours to find a solution to scale a Text in TCPDF in mm.

Is it possible to scale a Text to 190mm width and automatic high?

I need only one Word that is every time scaled to 190mm width.

I dont found something that solve my problem. Maybe you have a idea?

Thank you and have a nice holiday :)

I test several things that i found in google

Maybe i am searching for the wrong things, or maybe i dont have the right keywords?

```<code>$pdf->setPageUnit('mm');
$document_width = $pdf->pixelsToUnits('100');
$document_height = $pdf->pixelsToUnits('100');
$x = $pdf->pixelsToUnits('190');
$y = $pdf->pixelsToUnits('190');
$font_size = $pdf->pixelsToUnits('190');
$txt = 'AAAg';

$pdf->SetFont ('helvetica', '', $font_size , '', 'default', true );
$pdf->Text  ( $x, $y, $txt, false, false, true, 0, 0, '', false, '', 0, false, 'T', 'M', false );
</code>```

Title: PHP TCPDF Font Size in MM

Body:
in this moment i spend many hours to find a solution to scale a Text in TCPDF in mm.

Is it possible to scale a Text to 190mm width and automatic high?

I need only one Word that is every time scaled to 190mm width.

I dont found something that solve my problem. Maybe you have a idea?

Thank you and have a nice holiday :)

I test several things that i found in google

Maybe i am searching for the wrong things, or maybe i dont have the right keywords?

$pdf->setPageUnit('mm');
$document_width = $pdf->pixelsToUnits('100');
$document_height = $pdf->pixelsToUnits('100');
$x = $pdf->pixelsToUnits('190');
$y = $pdf->pixelsToUnits('190');
$font_size = $pdf->pixelsToUnits('190');
$txt = 'AAAg';

$pdf->SetFont ('helvetica', '', $font_size , '', 'default', true );
$pdf->Text  ( $x, $y, $txt, false, false, true, 0, 0, '', false, '', 0, false, 'T', 'M', false );


问:
why is my phpmyadmin panel is working through https://ip/phpmyadmin only?
Have a VPS. I am using hestia CP, node (express), nginx. When i'm trying to connect to myphpadmin in code (via localhost) or in url (https://mydomain/phpmyadmin) it doesn't work. Works via ip/phpadmin only.</p>


问:
Error: Emit attempted before Angular Webpack plugin initialization
My project is based on the old version of Angular,
after updating it shows me this error when running the project.

```<code>./apps/main-app/src/main.ts - Error: Module build failed (from ./node_modules/@ngtools/webpack/src/ivy/index.js):
Error: Emit attempted before Angular Webpack plugin initialization.

./apps/main-app/src/polyfills.ts - Error: Module build failed (from ./node_modules/@ngtools/webpack/src/ivy/index.js):
Error: Emit attempted before Angular Webpack plugin initialization.

Error: Failed to initialize Angular compilation - The Angular Compiler requires TypeScript >=4.6.2 and <4.9.0 but 4.9.4 was found instead.
</code>```

I used npm i and then ng serve and expected it to run but I ran into a problem.

Body:
My project is based on the old version of Angular,
after updating it shows me this error when running the project.

./apps/main-app/src/main.ts - Error: Module build failed (from ./node_modules/@ngtools/webpack/src/ivy/index.js):
Error: Emit attempted before Angular Webpack plugin initialization.

./apps/main-app/src/polyfills.ts - Error: Module build failed (from ./node_modules/@ngtools/webpack/src/ivy/index.js):
Error: Emit attempted before Angular Webpack plugin initialization.

Error: Failed to initialize Angular compilation - The Angular Compiler requires TypeScript >=4.6.2 and <4.9.0 but 4.9.4 was found instead.

I used npm i and then ng serve and expected it to run but I ran into a problem.


问:
npm install stucks in the terminal
I have cloned an angular project and used npm install --force to install the packages but it stucks in the terminal as shown in the pic

and here are my env versions

node: v18.12.1

npm: 8.19.2

and here are the dependecies in the project

```<code>"dependencies": {
    "@angular/animations": "^15.0.0",
    "@angular/common": "^15.0.0",
    "@angular/compiler": "^15.0.0",
    "@angular/core": "^15.0.0",
    "@angular/forms": "^15.0.0",
    "@angular/platform-browser": "^15.0.0",
    "@angular/platform-browser-dynamic": "^15.0.0",
    "@angular/pwa": "^15.0.1",
    "@angular/router": "^15.0.0",
    "@asymmetrik/ngx-leaflet": "^14.0.1",
    "@fortawesome/fontawesome-free": "^6.2.0",
    "@fortawesome/fontawesome-svg-core": "^6.2.0",
    "@mirei/leaflet-semicircle-ts": "^1.0.6",
    "@types/leaflet.fullscreen": "^1.6.1",
    "bootstrap": "^5.2.2",
    "chart.js": "^2.9.3",
    "http-server-pwa": "^2.1.0",
    "jquery": "^3.6.1",
    "leaflet": "^1.8.0",
    "leaflet.fullscreen": "^2.4.0",
    "ng2-charts": "^2.2.3",
    "numeral": "^2.0.6",
    "rxjs": "~7.5.0",
    "tslib": "^2.3.0",
    "zone.js": "~0.11.4"
  },

</code>```

Title: npm install stucks in the terminal

Body:
I have cloned an angular project and used npm install --force to install the packages but it stucks in the terminal as shown in the pic

and here are my env versions

node: v18.12.1

npm: 8.19.2

and here are the dependecies in the project

"dependencies": {
    "@angular/animations": "^15.0.0",
    "@angular/common": "^15.0.0",
    "@angular/compiler": "^15.0.0",
    "@angular/core": "^15.0.0",
    "@angular/forms": "^15.0.0",
    "@angular/platform-browser": "^15.0.0",
    "@angular/platform-browser-dynamic": "^15.0.0",
    "@angular/pwa": "^15.0.1",
    "@angular/router": "^15.0.0",
    "@asymmetrik/ngx-leaflet": "^14.0.1",
    "@fortawesome/fontawesome-free": "^6.2.0",
    "@fortawesome/fontawesome-svg-core": "^6.2.0",
    "@mirei/leaflet-semicircle-ts": "^1.0.6",
    "@types/leaflet.fullscreen": "^1.6.1",
    "bootstrap": "^5.2.2",
    "chart.js": "^2.9.3",
    "http-server-pwa": "^2.1.0",
    "jquery": "^3.6.1",
    "leaflet": "^1.8.0",
    "leaflet.fullscreen": "^2.4.0",
    "ng2-charts": "^2.2.3",
    "numeral": "^2.0.6",
    "rxjs": "~7.5.0",
    "tslib": "^2.3.0",
    "zone.js": "~0.11.4"
  },


问:
Am trying to increase the amount of items in my cart but this codes is not working for me. Any solution?
```<code>case 'INCREASE':
            let tempCart = state.cart.map((cartItem)=>{
                if(cartItem.id === action.payload){
                  return{...cartItem, amount: cartItem.amount + 1}
                }
                 return cartItem;
            })
            return{
                ...state,
                 card:tempCart
            }
</code>```

Am trying to increase the number of items in the cart in React using useReduce hook but the codes is not working and there is no error to.

```<code>case 'INCREASE':
            let tempCart = state.cart.map((cartItem)=>{
                if(cartItem.id === action.payload){
                  return{...cartItem, amount: cartItem.amount + 1}
                }
                 return cartItem;
            })
            return{
                ...state,
                 card:tempCart
            }
</code>```

Body:
case 'INCREASE':
            let tempCart = state.cart.map((cartItem)=>{
                if(cartItem.id === action.payload){
                  return{...cartItem, amount: cartItem.amount + 1}
                }
                 return cartItem;
            })
            return{
                ...state,
                 card:tempCart
            }

Am trying to increase the number of items in the cart in React using useReduce hook but the codes is not working and there is no error to.

case 'INCREASE':
            let tempCart = state.cart.map((cartItem)=>{
                if(cartItem.id === action.payload){
                  return{...cartItem, amount: cartItem.amount + 1}
                }
                 return cartItem;
            })
            return{
                ...state,
                 card:tempCart
            }


问:
Merge 2 GitHub Repositories from GitHub site or VS
I was working on a Project but at that time I didn't knew how to push from Visual Studio to GitHub repositories, so I was manually uploading code to repository (say Repo1). Then I learned how to use GitHub properly. But was unable to push/fetch from Repo1 (maybe I deleted GitHub core files) (has 10 commits). So, I then created Repo2 and then used it to push changes from Visual Studio (which now has 29 commits).

Now I want to merge these two repositories but didn't find any option on GitHub website. I don't use Git scripting for GitHub but use Git control from Visual Studio.

How can I merge Repo1(old one) into Repo2(I want Repo2 as main) without losing commits. Since Repo1 is older, its commits appear in the last. and no change is made latest commit of Repo2.

Kindly guide (without git scripting).


问:
Gracefull termination of multiprocessing.Pool.map function using KeyboardInterrupt
I'm trying to terminate gracefully Pool.map() function using KeyboardInterrupt.

import multiprocessing
import time

def func(num):
    try:
        while True:
            print(f'Process num {num}')
            time.sleep(30)
    except KeyboardInterrupt:
        print(f'Process {num} was interrupted')
    finally:
        print('Cleaning up the thread')

def main():
    pool = multiprocessing.Pool()

    try:
        pool.map(func, range(9))
    except KeyboardInterrupt:
        print('Main process was interrupted)
        pool. Close()

    finally:
        print('Cleaning up main')

if __name__ == '__main__':
    main()
```
<p>While it works fine with <code>range(8)</code> (cuz I have 8 logical cores and only 8 processes running simultaneously). After pressing <kbd>Ctrl</kbd>+<kbd>C</kbd>, I receive the following output:</p>
```python experiment.py

Process num 0
Process num 1
Process num 2
Process num 3
Process num 4
Process num 5
Process num 6
Process num 7
Process 7 was interrupted
Process 6 was interrupted
Cleaning up the thread
Process 4 was interrupted
Cleaning up the thread
Process 5 was interrupted
Process 3 was interrupted
Process 2 was interrupted
Cleaning up the thread
Process 0 was interrupted
Process 1 was interrupted
Cleaning up the thread
Cleaning up the thread
Cleaning up the thread
Cleaning up the thread
Cleaning up the thread
Main process was interrupted
Cleaning up main
```
<p>However, when I use <code>range(9)</code>, after pressing <kbd>Ctrl</kbd>+<kbd>C</kbd> it interrupts only 8 processes that are already running, while <code>map</code> function keeps on running generating a new process, and after pressing <kbd>Ctrl</kbd>+<kbd>C</kbd> once again I get the following output:</p>
```Process num 0
Process num 1
Process num 2
Process num 3
Process num 4
Process num 5
Process num 6
Process num 7
Process 6 was interrupted
Process 7 was interrupted
Process 5 was interrupted
Cleaning up the thread
Cleaning up the thread
Process 2 was interrupted
Cleaning up the thread
Process 3 was interrupted
Process 1 was interrupted
Cleaning up the thread
Process 0 was interrupted
Process num 8
Cleaning up the thread
Cleaning up the thread
Process 4 was interrupted
Cleaning up the thread
Cleaning up the thread
Process 8 was interrupted
Process SpawnPoolWorker-7:
Process SpawnPoolWorker-6:
Process SpawnPoolWorker-4:
Process SpawnPoolWorker-5:
Cleaning up the thread
Process SpawnPoolWorker-3:
Process SpawnPoolWorker-2:
Process SpawnPoolWorker-1:
Main process was interrupted
Cleaning up main
Traceback (most recent call last):
Traceback (most recent call last):
Traceback (most recent call last):
  File "C:\Users\Zamotory\AppData\Local\Programs\Python\Python310\lib\multiprocessing\process.py", line 314, in _bootstrap
    self. Run()
```

Is there any way to stop Pool.map() after the single press of Ctrl+C?

Body:
I'm trying to terminate gracefully Pool.map() function using KeyboardInterrupt.

import multiprocessing
import time

def func(num):
    try:
        while True:
            print(f'Process num {num}')
            time.sleep(30)
    except KeyboardInterrupt:
        print(f'Process {num} was interrupted')
    finally:
        print('Cleaning up the thread')

def main():
    pool = multiprocessing.Pool()

    try:
        pool.map(func, range(9))
    except KeyboardInterrupt:
        print('Main process was interrupted)
        pool. Close()

    finally:
        print('Cleaning up main')

if __name__ == '__main__':
    main()

While it works fine with range(8) (cuz I have 8 logical cores and only 8 processes running simultaneously). After pressing Ctrl+C, I receive the following output:

python experiment.py

Process num 0
Process num 1
Process num 2
Process num 3
Process num 4
Process num 5
Process num 6
Process num 7
Process 7 was interrupted
Process 6 was interrupted
Cleaning up the thread
Process 4 was interrupted
Cleaning up the thread
Process 5 was interrupted
Process 3 was interrupted
Process 2 was interrupted
Cleaning up the thread
Process 0 was interrupted
Process 1 was interrupted
Cleaning up the thread
Cleaning up the thread
Cleaning up the thread
Cleaning up the thread
Cleaning up the thread
Main process was interrupted
Cleaning up main

However, when I use range(9), after pressing Ctrl+C it interrupts only 8 processes that are already running, while map function keeps on running generating a new process, and after pressing Ctrl+C once again I get the following output:

Process num 0
Process num 1
Process num 2
Process num 3
Process num 4
Process num 5
Process num 6
Process num 7
Process 6 was interrupted
Process 7 was interrupted
Process 5 was interrupted
Cleaning up the thread
Cleaning up the thread
Process 2 was interrupted
Cleaning up the thread
Process 3 was interrupted
Process 1 was interrupted
Cleaning up the thread
Process 0 was interrupted
Process num 8
Cleaning up the thread
Cleaning up the thread
Process 4 was interrupted
Cleaning up the thread
Cleaning up the thread
Process 8 was interrupted
Process SpawnPoolWorker-7:
Process SpawnPoolWorker-6:
Process SpawnPoolWorker-4:
Process SpawnPoolWorker-5:
Cleaning up the thread
Process SpawnPoolWorker-3:
Process SpawnPoolWorker-2:
Process SpawnPoolWorker-1:
Main process was interrupted
Cleaning up main
Traceback (most recent call last):
Traceback (most recent call last):
Traceback (most recent call last):
  File "C:\Users\Zamotory\AppData\Local\Programs\Python\Python310\lib\multiprocessing\process.py", line 314, in _bootstrap
    self. Run()

Is there any way to stop Pool.map() after the single press of Ctrl+C?


问:
I want to check how much of my stack memory is getting consumed while performing recursion in java?
I want to calculate stack memory consumed by this function in java. so is there any function to check out stack memory consumed in this code.</p>
```<code>static void insertNodeRecursion(int element, Node parentNode) {
        if (rootOne == null) {
            //System.out.println("Inside root\n");
            rootOne = createNode(element);
        }

    else {

        if (element > parentNode.data) {
            if (parentNode.right == null) {
                //System.out.println("Inside right\n");
                parentNode.right = createNode(element);
            } else {
               // System.out.println("right\n");
                insertNodeRecursion(element, parentNode.right);
            }
        } else {
            if (parentNode.left == null) {
               // System.out.println("Inside left");
                parentNode.left = createNode(element);
            } else {
              //  System.out.println("left");
                insertNodeRecursion(element, parentNode.left);
            }
        }
    }
}
</code>```

Body:
I want to calculate stack memory consumed by this function in java. so is there any function to check out stack memory consumed in this code.

static void insertNodeRecursion(int element, Node parentNode) {
        if (rootOne == null) {
            //System.out.println("Inside root\n");
            rootOne = createNode(element);
        }

    else {

        if (element > parentNode.data) {
            if (parentNode.right == null) {
                //System.out.println("Inside right\n");
                parentNode.right = createNode(element);
            } else {
               // System.out.println("right\n");
                insertNodeRecursion(element, parentNode.right);
            }
        } else {
            if (parentNode.left == null) {
               // System.out.println("Inside left");
                parentNode.left = createNode(element);
            } else {
              //  System.out.println("left");
                insertNodeRecursion(element, parentNode.left);
            }
        }
    }
}


问:
What is the right way to use far direct jmp in emu8086?
I use emu8086 and far indirect jmp in c2_s works ok. But then in c1_s far direct jmp doesn't work. And it goes to begin in c2_s insted p2.

```<code>s_s segment stack "stack"
    dw 2
s_s ends

d_s segment
    aa db 10
    ab db 11
    addr dw p1,0712h
d_s ends

c1_s segment
    assume cs:c1_s

    p1:
    mov bl, ab
    jmp far ptr p2

c1_s ends

c2_s segment
    assume ss:s_s, ds:d_s, cs:c2_s

    begin:
    mov ax, d_s
    mov ds, ax
    mov al, aa

    jmp dword ptr addr

    p2:
    mov ah,4ch
    int 21h

c2_s ends
end begin
</code>```

I tried to use both:

```<code>    jmp far ptr p2
    p2:
</code>```
```<code>    jmp p2
    p2 label far
</code>```

but doesn't work anyway.

Body:
I use emu8086 and far indirect jmp in c2_s works ok. But then in c1_s far direct jmp doesn't work. And it goes to begin in c2_s insted p2.

s_s segment stack "stack"
    dw 2
s_s ends

d_s segment
    aa db 10
    ab db 11
    addr dw p1,0712h
d_s ends

c1_s segment
    assume cs:c1_s

    p1:
    mov bl, ab
    jmp far ptr p2

c1_s ends

c2_s segment
    assume ss:s_s, ds:d_s, cs:c2_s

    begin:
    mov ax, d_s
    mov ds, ax
    mov al, aa

    jmp dword ptr addr

    p2:
    mov ah,4ch
    int 21h

c2_s ends
end begin

I tried to use both:

    jmp far ptr p2
    p2:

    jmp p2
    p2 label far

but doesn't work anyway.


问:
how to enable spring cloud eureka client in exiting spring mvc project which is not springboot application?
I have existing Spring MVC project [Not Spring Boot Application] which is deployed as war in jboss. I want My application to register itself to eureka server.

But I am unable to do so. And On the internet all the answer are giving taking example of springboot.

Spring cloud version specified in Parent Pom

```<code><spring-cloud.version>2022.0.0</spring-cloud.version>
</code>```

Dependency Management Added in parent Pom

```<code><dependencyManagement>
   <dependencies>
       <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
</code>```

Dependency Added in project file

```<code><dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
</code>```

Code added to enable to eureka. Please note package is under package scan.

```<code>@Configuration
public class IntegrationConfiguration {
}
</code>```

After doing all this still project is not registering with eureka server.

Kindly let me know if i am missing something?

Body:
I have existing Spring MVC project [Not Spring Boot Application] which is deployed as war in jboss. I want My application to register itself to eureka server.

But I am unable to do so. And On the internet all the answer are giving taking example of springboot.

Spring cloud version specified in Parent Pom

<spring-cloud.version>2022.0.0</spring-cloud.version>

Dependency Management Added in parent Pom

<dependencyManagement>
   <dependencies>
       <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

Dependency Added in project file

<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>

Code added to enable to eureka. Please note package is under package scan.

@Configuration
public class IntegrationConfiguration {
}

After doing all this still project is not registering with eureka server.

Kindly let me know if i am missing something?


问:
why this code doesn't work?(axios and redux)
In my nextjs appI want to get user date by axios and set theme in initial state in redux.
I want when user enter any page or when refresh the page the get user data function execute.
To do this I put my function into user slice.
but it doesn't work and return a promise or 0.</p>
```<code>import {createSlice} from "@reduxjs/toolkit";
import axios from 'axios'
async function UserData(params) {
    await axios.get('http://localhost:5000/api/auth/getdata',{withCredentials:true})
    .then(res => {
    return res.data
    })
}
const user =  createSlice({
    name: 'user_data',
    initialState:UserData() ,
    reducers: {
//continue of code ....
</code>```

Body:
In my nextjs appI want to get user date by axios and set theme in initial state in redux.
I want when user enter any page or when refresh the page the get user data function execute.
To do this I put my function into user slice.
but it doesn't work and return a promise or 0.

import {createSlice} from "@reduxjs/toolkit";
import axios from 'axios'
async function UserData(params) {
    await axios.get('http://localhost:5000/api/auth/getdata',{withCredentials:true})
    .then(res => {
    return res.data
    })
}
const user =  createSlice({
    name: 'user_data',
    initialState:UserData() ,
    reducers: {
//continue of code ....


问:
How to wait for worker thread to complete in the worker thread itself to do some computations?
I have an existing app which uses worker concept to do audio download from an API. Now I would like to cut the audio once the download is complete in the same worker but the problem is before the full download completes trimming code runs in parellel which leads to empty file creation. Is there any way to wait for the worker to complete its download and do my splitting of audio? I am a complete beginner to node so any help would be appreciated.I am not very familiar with the promise and worker concepts. I am exploring it. Thanks in advance!</p>
```<code>// connect to api
async function connectAPI() {
  await forLogin();
}

// after fetching data creating workers
async function startWorkers() {
  return new Promise((resolve, reject) => {
    // create array for storing data

    threads.add(new Worker("worker.js", { workerData: { worker: id, data: dataperWorker[id] } }));

    for (let worker of threads) {
      worker.on("error", () => {
        //handle error
      });

      worker.on("exit", () => {
        threads.delete(worker);

        return resolve;
      });
      worker.on("message", (message) => {
        //receive messages from worker
        switch (message.type) {
          case "log":
            break;
        }
      });
    }
  });
}
// worker.js

async function downloadAudio(workerId, data, storagePath) {
  await forGetRecordings();

  const file = fs.createWriteStream(`${storagePath}/fileName.mp3`);
  https.get(recordingsURL, async (response) => {
    response.pipe(file);
  });
}

// this is the one I have added to the existing app

function splitAudio(data, storagePath) {
  return new Promise((resolve, reject) => {
    for (const value of data.values) {
      // added some conditions on what basis to split

      ffmpeg(`${storagePath}/fileName.mp3`)
        .inputOptions([`-ss 40`, `-to 150`])

        .output(`${storagePath}/fileName_id.mp3`)
        .on("end", function () {
          logger.info(`Trimming records completed!`);
          return resolve();
        })

        .on("error", function (err) {
          logger.error(`Error occured ${err.message}`);
          return reject();
        })
        .run();
    }
  });
}

async function init(workerId, data) {
  //connect to api
  await forLogin();
  //create folders in local to download audio
  for (const i = 0; i < data.length; i++) {
    await downloadAudio(workerId, data[i], storagePath); // download full audio
    await splitAudio(data[i], storagePath); // I have added a function here
  }
}

init(workerData.worker, workerData.data);
</code>```

Body:
I have an existing app which uses worker concept to do audio download from an API. Now I would like to cut the audio once the download is complete in the same worker but the problem is before the full download completes trimming code runs in parellel which leads to empty file creation. Is there any way to wait for the worker to complete its download and do my splitting of audio? I am a complete beginner to node so any help would be appreciated.I am not very familiar with the promise and worker concepts. I am exploring it. Thanks in advance!

// connect to api
async function connectAPI() {
  await forLogin();
}

// after fetching data creating workers
async function startWorkers() {
  return new Promise((resolve, reject) => {
    // create array for storing data

    threads.add(new Worker("worker.js", { workerData: { worker: id, data: dataperWorker[id] } }));

    for (let worker of threads) {
      worker.on("error", () => {
        //handle error
      });

      worker.on("exit", () => {
        threads.delete(worker);

        return resolve;
      });
      worker.on("message", (message) => {
        //receive messages from worker
        switch (message.type) {
          case "log":
            break;
        }
      });
    }
  });
}
// worker.js

async function downloadAudio(workerId, data, storagePath) {
  await forGetRecordings();

  const file = fs.createWriteStream(`${storagePath}/fileName.mp3`);
  https.get(recordingsURL, async (response) => {
    response.pipe(file);
  });
}

// this is the one I have added to the existing app

function splitAudio(data, storagePath) {
  return new Promise((resolve, reject) => {
    for (const value of data.values) {
      // added some conditions on what basis to split

      ffmpeg(`${storagePath}/fileName.mp3`)
        .inputOptions([`-ss 40`, `-to 150`])

        .output(`${storagePath}/fileName_id.mp3`)
        .on("end", function () {
          logger.info(`Trimming records completed!`);
          return resolve();
        })

        .on("error", function (err) {
          logger.error(`Error occured ${err.message}`);
          return reject();
        })
        .run();
    }
  });
}

async function init(workerId, data) {
  //connect to api
  await forLogin();
  //create folders in local to download audio
  for (const i = 0; i < data.length; i++) {
    await downloadAudio(workerId, data[i], storagePath); // download full audio
    await splitAudio(data[i], storagePath); // I have added a function here
  }
}

init(workerData.worker, workerData.data);


问:
Export intrinsic camera parameters in Blender via .gltf file
I am working on a .gltf data loader in python for the quite popular multi-NeRF framework.

I exported the 3D model in Blender as a .gltf file with the appropriate export settings which means that I also ticked the blender camera in the settings to have the extrinsic camera parameters in the .gltf file.

For the data loader in multi-NeRF there already exists a base class which someone can use for creating custom data loaders. This base class has some minimum aquirements regarding data to work with like for example the extrinsic/intrinsic camera parameters and distortion coefficients etc.

So, my question is how to get the intrinsic camera parameters/distortion coefficients from the Blender camera in order to export them via the .gltf file like the extrinsic camera parameters? Thanks for any help!


问:
Cloud Run, is the default url permanent?
I'm currently experiencing an error with handshaking when communicating with the Cloud Run server in the Flutter Client.

```<code>Unhandled Exception: HandshakeException: Connection terminated during handshake
</code>```

I saw almost 100 answers, and they all about allowed the bad request of flutter http, and also included attributes related to allowing insecure http in the info.plist in ios. And I did every single one and it doesn't work. I just want to give up Cloud Run's custom domain.

So anyway! my question is ..

If the default url is permanent, is it okay to just use the rest api here?

```<code>https://<cloud-run-service-default-url>/v1/api..
</code>```

Body:
I'm currently experiencing an error with handshaking when communicating with the Cloud Run server in the Flutter Client.

Unhandled Exception: HandshakeException: Connection terminated during handshake

I saw almost 100 answers, and they all about allowed the bad request of flutter http, and also included attributes related to allowing insecure http in the info.plist in ios. And I did every single one and it doesn't work. I just want to give up Cloud Run's custom domain.

So anyway! my question is ..

If the default url is permanent, is it okay to just use the rest api here?

https://<cloud-run-service-default-url>/v1/api..


问:
Unit test in Go for function which used chrono scheduling
`

```<code>func (s *svc) MaintainLog() {
      taskScheduler := chrono.NewDefaultTaskScheduler()
      task, err := taskScheduler.ScheduleAtFixedRate(func(ctx context.Context) {
         s.logger.Info("cleaning logs exceeded ttl")
         err := s.dao.MaintainTtlLogs(ctx)
         if err != nil {
            s.logger.Error("error in maintaining logs in db  : ", err)
         }
      }, 24*time.Hour)

      if err == nil {
         log.Print("Task has been scheduled successfully.")
      } else {
         task.Cancel()
      }

}
</code>```

`

This is function for which i have to write unit test.
how this can be done

I tried by channel thing but not getting actually what to do and how

Body:
`

func (s *svc) MaintainLog() {
      taskScheduler := chrono.NewDefaultTaskScheduler()
      task, err := taskScheduler.ScheduleAtFixedRate(func(ctx context.Context) {
         s.logger.Info("cleaning logs exceeded ttl")
         err := s.dao.MaintainTtlLogs(ctx)
         if err != nil {
            s.logger.Error("error in maintaining logs in db  : ", err)
         }
      }, 24*time.Hour)

      if err == nil {
         log.Print("Task has been scheduled successfully.")
      } else {
         task.Cancel()
      }

}

`

This is function for which i have to write unit test.
how this can be done

I tried by channel thing but not getting actually what to do and how


问:
Error in .checkXYnames(colnames(x)) : vectlongitude/latitude in the wrong order
I have a vector and a raster loaded. the points all lie within the raster. However, I get a en error when I run the Hiking function.

enter image description here

enter image description here

enter image description here

enter image description here

Output when i run

```<code> lang_coord_sp_200000 <- lcsa_subr(dem, lang_coord_sp, 400000, 24)
</code>```

I tried to change the order of Longitude and Latitude (then I got an error, that the points are now out of the raster extent). I also tried to rename Longitude and Latitude with no success.

Body:
I have a vector and a raster loaded. the points all lie within the raster. However, I get a en error when I run the Hiking function.

enter image description here

enter image description here

enter image description here

enter image description here

Output when i run

 lang_coord_sp_200000 <- lcsa_subr(dem, lang_coord_sp, 400000, 24)

I tried to change the order of Longitude and Latitude (then I got an error, that the points are now out of the raster extent). I also tried to rename Longitude and Latitude with no success.


问:
SwiftUI change the color of image and text inside a TabView tabItem based on selection state
I have a View and inside the view i have a TabView in SwiftUI. Inside the TabView exist more than one NavigationView. I searched stackoverflow on how to change the color of the tabbar items (image/icon and text) when they are selected by the user and when they are not selected but what i have found does not work. The only thing i have found that works is the .accentColor i am adding to the TabView but this changes the accent color in all the items in the TabView.

I tried also UITabBar.appearance().unselectedItemTintColor = UIColor.white at then init but does not seem to work. So is there any way to change the selected/nonselected color of the items (image/icon and text) in a tabbar item with this specific implementation? Below is my code. Any help or suggestion appreciated.

```<code>import Foundation
import SwiftUI
import ApplicationCore

public struct TabViewTest: View {
    public init() {
          //UITabBar.appearance().unselectedItemTintColor = UIColor.white
    }
    @State var selectedTab: Int = 0

    public static let backgroundColor = Color(red: 52 / 255, green: 12 / 255, blue: 4 / 255)
    public static let backgroundButtonColor = Color(red: 235 / 255, green: 220 / 255, blue: 180 / 255)
    public var body: some View {

        TabView (selection: $selectedTab) {
            NavigationView {
                NavigationLink(destination: Text("destination"))
                {
                    FeedView(selectedTab: $selectedTab)
                        .navigationBarTitle("Feed", displayMode: .inline)

                }
            }
            .tabItem {
                    Image(systemName :"pencil.line")
                    Text("Feed")
            }

            .toolbar(.visible, for: .tabBar)
            .toolbarBackground(
                TabViewTest.backgroundColor,
                for: .tabBar)
            .toolbarBackground(
                .visible,
                for: .tabBar)
            .tag(0)

            NavigationView {
                Text("Read")
                    .navigationBarTitle("Read", displayMode: .inline)
            }
            .tabItem {
                Image(systemName :"books.vertical")
                Text("Read")
            }
            .toolbar(.visible, for: .tabBar)
            .toolbarBackground(
                TabViewTest.backgroundColor,
                for: .tabBar)
            .toolbarBackground(
                .visible,
                for: .tabBar)
            .tag(1)
}
//.accentColor(TabViewTest.backgroundButtonColor)
}

struct FeedView: View {
    @Binding var selectedTab: Int

    var body: some View {
        ZStack {
              TabViewTest.backgroundButtonColor.ignoresSafeArea()
            VStack {
                Text("Nav link test")
                    .font(.largeTitle)

                    .foregroundColor(.white)
                Button (action: {
                    selectedTab = 1
                }, label: {
                    Text("go to read tab")
                        .font(.headline)
                        .padding()
                        .padding(.horizontal)
                        .background(Color.white)
                })
            }
        }
    }
}
</code>```

Body:
I have a View and inside the view i have a TabView in SwiftUI. Inside the TabView exist more than one NavigationView. I searched stackoverflow on how to change the color of the tabbar items (image/icon and text) when they are selected by the user and when they are not selected but what i have found does not work. The only thing i have found that works is the .accentColor i am adding to the TabView but this changes the accent color in all the items in the TabView.

I tried also UITabBar.appearance().unselectedItemTintColor = UIColor.white at then init but does not seem to work. So is there any way to change the selected/nonselected color of the items (image/icon and text) in a tabbar item with this specific implementation? Below is my code. Any help or suggestion appreciated.

import Foundation
import SwiftUI
import ApplicationCore

public struct TabViewTest: View {
    public init() {
          //UITabBar.appearance().unselectedItemTintColor = UIColor.white
    }
    @State var selectedTab: Int = 0

    public static let backgroundColor = Color(red: 52 / 255, green: 12 / 255, blue: 4 / 255)
    public static let backgroundButtonColor = Color(red: 235 / 255, green: 220 / 255, blue: 180 / 255)
    public var body: some View {

        TabView (selection: $selectedTab) {
            NavigationView {
                NavigationLink(destination: Text("destination"))
                {
                    FeedView(selectedTab: $selectedTab)
                        .navigationBarTitle("Feed", displayMode: .inline)

                }
            }
            .tabItem {
                    Image(systemName :"pencil.line")
                    Text("Feed")
            }

            .toolbar(.visible, for: .tabBar)
            .toolbarBackground(
                TabViewTest.backgroundColor,
                for: .tabBar)
            .toolbarBackground(
                .visible,
                for: .tabBar)
            .tag(0)

            NavigationView {
                Text("Read")
                    .navigationBarTitle("Read", displayMode: .inline)
            }
            .tabItem {
                Image(systemName :"books.vertical")
                Text("Read")
            }
            .toolbar(.visible, for: .tabBar)
            .toolbarBackground(
                TabViewTest.backgroundColor,
                for: .tabBar)
            .toolbarBackground(
                .visible,
                for: .tabBar)
            .tag(1)
}
//.accentColor(TabViewTest.backgroundButtonColor)
}

struct FeedView: View {
    @Binding var selectedTab: Int

    var body: some View {
        ZStack {
              TabViewTest.backgroundButtonColor.ignoresSafeArea()
            VStack {
                Text("Nav link test")
                    .font(.largeTitle)

                    .foregroundColor(.white)
                Button (action: {
                    selectedTab = 1
                }, label: {
                    Text("go to read tab")
                        .font(.headline)
                        .padding()
                        .padding(.horizontal)
                        .background(Color.white)
                })
            }
        }
    }
}


问:
enable cache for all criteria queries in throughout the project
I enabled second level cache in hibernate.

```<code><prop key="hibernate.cache.use_second_level_cache">true</prop>
<prop key="hibernate.cache.use_query_cache">true</prop>
<prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop>
<prop key="hibernate.cache.provider_class">org.hibernate.cache.HashtableCacheProvider</prop>
</code>```

when get entity with id, this cache work correctly, but when use of criteria query not work.

After searching, I realized that the cache is activated by adding a setCacheable method to the query.

But I have a big problem

There are a lot of criteria queries throughout the project, and on the other hand, the criteria queries are derived from another class in another project, and I don't have access to that external class.

Is there a way to apply this setting to all criteria queries in the entire project by setting it once ?

Body:
I enabled second level cache in hibernate.

<prop key="hibernate.cache.use_second_level_cache">true</prop>
<prop key="hibernate.cache.use_query_cache">true</prop>
<prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop>
<prop key="hibernate.cache.provider_class">org.hibernate.cache.HashtableCacheProvider</prop>

when get entity with id, this cache work correctly, but when use of criteria query not work.

After searching, I realized that the cache is activated by adding a setCacheable method to the query.

But I have a big problem

There are a lot of criteria queries throughout the project, and on the other hand, the criteria queries are derived from another class in another project, and I don't have access to that external class.

Is there a way to apply this setting to all criteria queries in the entire project by setting it once ?