问:
Javascript animation not retaining new position after animation ends with fill: "forwards" enabled
I am attempting an animation project that will have words falling on the screen a certain distance per second using SetInterval() with an animation effect; the goal is for the letters to fall to the bottom of the screen before I implement the next step.

I am using an animation for the distance that the words fall on each second using a function that uses an animation and then being fired by SetInterval. I am using 'fill: "forwards"` in the animation options to retain the new position but the letters revert back to the original position after each interval.

I looked up the Mozilla documentation, postings, etc... the only answers I could find is to use fill: "forwards". I also tried to not use setInterval() and use iterations: Infinity in the animation options but the outcome is still the same.

```<code><!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link href="main.css" rel="stylesheet">
    <link rel="icon" href="#" type="image/x-icon" />
</head>

<body>
    <script src="main.js"></script>
</body>

</html>
</code>```
```<code>body {
    background-color: black;
    position: relative;
    min-height: 100vh;
    min-width: 100vw;
}
</code>```
```<code>const array = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l",
"m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O",
"P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "1", "2", "3",
"4", "5", "6", "7", "8", "9", "0"
];

const utilities = {
    //Getting a random number between 0 (inclusive) and 1 (exclusive)
    zero_one: function getRandom() {
        return Math.random();
      },
    //Getting a random number between two values
    two_num: function getRandomArbitrary(min, max) {
        return Math.random() * (max - min) + min;
      },
    //Getting a random integer between two values
    two_int: function getRandomInt(min, max) {
        min = Math.ceil(min);
        max = Math.floor(max);
        return Math.floor(Math.random() * (max - min) + min); // The maximum is exclusive and the minimum is inclusive
      },
    string_break: function string_break(string) {
        const array = Array.from(string)
        if (array.length === 3) {
            let string = array[0]
            let number = Number(string)
            return number
        }else if (array.length === 4) {
            let string = array[0] + array[1]
            let number = Number(string)
            return number
        }else if (array.length === 5) {
            let string = array[0] + array[1] + array[2]
            let number = Number(string)
            return number
        }

    },
    string_animation_001: function string_anim_01(num, posY, posY_plus_one) {

        const parameters = [
            {top: posY + 'vh'},
            {top: posY_plus_one + `vh`}
        ]

        const options = {
            //retain new position
            fill: 'forwards',
            //length of words falling
            duration: num
        }

        let array = [parameters, options];

        return array
    },
    string_position_001: function string_position(current_pos) {
        let new_pos_y = current_pos + 1;
        if (current_pos >= 100) {
            new_pos_y = -25
        }
        return new_pos_y
    }
}

let total = 0;
const glob_array = []
const m_duration = 1000

//#1. create the falling elements and put them into a global array

const createElement = function() {
    const e = document.createElement('div');
        e.className = "elements";
        total += 1;
        e.id = "elements" + total;
        let z_index_num = utilities.two_int(-100, 100)
        e.setAttribute("style", `color: green;
                width: 1vw;
                height: 1vh;
                position: absolute;
                z-index: ${z_index_num}
                `);
        e.textContent = array[utilities.two_int(0, array.length)];
        glob_array.push(e)
}

const loadGlobalArray = function(num) {
    for (let i = 0; i < num; i++) {
        createElement()
    }
}

const loadScreen = function() {
    let a = 20*100;
    let b = 40*100;
    loadGlobalArray(utilities.two_int(a, b));

    for (let i = 0; i < glob_array.length; i++) {
        let element = glob_array[i];
            element.style.top = '0px';
        let posX = utilities.two_int(0, 100);
        let posY = utilities.two_int(0, 100);
            element.style.left = posX + "vw";
            element.style.top = posY + "vh";

        const body = document.querySelector("body");
            body.appendChild(element);
            glob_array.shift();
            i--;
    }
}

const unloadGlobalArray = function() {
    for (let i = 0; i < glob_array.length; i++) {
        let element = glob_array[i];
            element.style.top = '0px';
        let posX = utilities.two_int(0, 100);
            element.style.left = posX + "%";
            console.log(element)
        const body = document.querySelector("body");
            body.appendChild(element);
            glob_array.shift();
    }
}

loadGlobalArray(utilities.two_int(40, 60));
loadScreen()

const runAnimation = function() {
    const elements_array = document.querySelectorAll('.elements');

    for (let i = 0; i < elements_array.length; i++) {
        const id = elements_array[i].id
        const element = document.querySelector('#' + id);

        //with vh
        const current_pos = element.style.top

        //without vh
        const pos_num = utilities.string_break(current_pos);

        //new position
        const new_pos = utilities.string_position_001(pos_num);

        //duration / current pos / future position
        const animation = utilities.string_animation_001(1000, pos_num, new_pos);

        element.animate(animation[0], animation[1]);

    }
}
runAnimation()

setInterval(runAnimation, 1000)
</code>```

Body:
I am attempting an animation project that will have words falling on the screen a certain distance per second using SetInterval() with an animation effect; the goal is for the letters to fall to the bottom of the screen before I implement the next step.

I am using an animation for the distance that the words fall on each second using a function that uses an animation and then being fired by SetInterval. I am using 'fill: "forwards"` in the animation options to retain the new position but the letters revert back to the original position after each interval.

I looked up the Mozilla documentation, postings, etc... the only answers I could find is to use fill: "forwards". I also tried to not use setInterval() and use iterations: Infinity in the animation options but the outcome is still the same.

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link href="main.css" rel="stylesheet">
    <link rel="icon" href="#" type="image/x-icon" />

body {
    background-color: black;
    position: relative;
    min-height: 100vh;
    min-width: 100vw;
}

const array = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l",
"m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O",
"P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "1", "2", "3",
"4", "5", "6", "7", "8", "9", "0"
];

const utilities = {
    //Getting a random number between 0 (inclusive) and 1 (exclusive)
    zero_one: function getRandom() {
        return Math.random();
      },
    //Getting a random number between two values
    two_num: function getRandomArbitrary(min, max) {
        return Math.random() * (max - min) + min;
      },
    //Getting a random integer between two values
    two_int: function getRandomInt(min, max) {
        min = Math.ceil(min);
        max = Math.floor(max);
        return Math.floor(Math.random() * (max - min) + min); // The maximum is exclusive and the minimum is inclusive
      },
    string_break: function string_break(string) {
        const array = Array.from(string)
        if (array.length === 3) {
            let string = array[0]
            let number = Number(string)
            return number
        }else if (array.length === 4) {
            let string = array[0] + array[1]
            let number = Number(string)
            return number
        }else if (array.length === 5) {
            let string = array[0] + array[1] + array[2]
            let number = Number(string)
            return number
        }

    },
    string_animation_001: function string_anim_01(num, posY, posY_plus_one) {

        const parameters = [
            {top: posY + 'vh'},
            {top: posY_plus_one + `vh`}
        ]

        const options = {
            //retain new position
            fill: 'forwards',
            //length of words falling
            duration: num
        }

        let array = [parameters, options];

        return array
    },
    string_position_001: function string_position(current_pos) {
        let new_pos_y = current_pos + 1;
        if (current_pos >= 100) {
            new_pos_y = -25
        }
        return new_pos_y
    }
}

let total = 0;
const glob_array = []
const m_duration = 1000

//#1. create the falling elements and put them into a global array

const createElement = function() {
    const e = document.createElement('div');
        e.className = "elements";
        total += 1;
        e.id = "elements" + total;
        let z_index_num = utilities.two_int(-100, 100)
        e.setAttribute("style", `color: green;
                width: 1vw;
                height: 1vh;
                position: absolute;
                z-index: ${z_index_num}
                `);
        e.textContent = array[utilities.two_int(0, array.length)];
        glob_array.push(e)
}

const loadGlobalArray = function(num) {
    for (let i = 0; i < num; i++) {
        createElement()
    }
}

const loadScreen = function() {
    let a = 20*100;
    let b = 40*100;
    loadGlobalArray(utilities.two_int(a, b));

    for (let i = 0; i < glob_array.length; i++) {
        let element = glob_array[i];
            element.style.top = '0px';
        let posX = utilities.two_int(0, 100);
        let posY = utilities.two_int(0, 100);
            element.style.left = posX + "vw";
            element.style.top = posY + "vh";

        const body = document.querySelector("body");
            body.appendChild(element);
            glob_array.shift();
            i--;
    }
}

const unloadGlobalArray = function() {
    for (let i = 0; i < glob_array.length; i++) {
        let element = glob_array[i];
            element.style.top = '0px';
        let posX = utilities.two_int(0, 100);
            element.style.left = posX + "%";
            console.log(element)
        const body = document.querySelector("body");
            body.appendChild(element);
            glob_array.shift();
    }
}

loadGlobalArray(utilities.two_int(40, 60));
loadScreen()

const runAnimation = function() {
    const elements_array = document.querySelectorAll('.elements');

    for (let i = 0; i < elements_array.length; i++) {
        const id = elements_array[i].id
        const element = document.querySelector('#' + id);

        //with vh
        const current_pos = element.style.top

        //without vh
        const pos_num = utilities.string_break(current_pos);

        //new position
        const new_pos = utilities.string_position_001(pos_num);

        //duration / current pos / future position
        const animation = utilities.string_animation_001(1000, pos_num, new_pos);

        element.animate(animation[0], animation[1]);

    }
}
runAnimation()

setInterval(runAnimation, 1000)


来源: stackexchange

问:
JPA connect to Derby Database with Hibernate-ORM related problem in Quarkus
Currently, I am trying to build an API with JPA and Derby Database, and I've got some problems with Hibernate Reactive/Hibernate ORM.

Particularly, I want to connect to a Derby database server as follows:

QueryService.java:

```<code>@Transactional
@RequestScoped
public class QueryService implements Serializable {
    @PersistenceContext
    EntityManagerFactory emf;
    private final static Logger LOGGER = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
    public QueryService() {}

    @PostConstruct
    public void init() {
        String urlDB = "my-persistence-unit";
        emf = Persistence.createEntityManagerFactory(urlDB);
    }

    @PreDestroy
    public void destroy() {
        emf.close();
    }
</code>```

application.properties:

```<code>quarkus.hibernate-orm.database.generation=none

quarkus.datasource.db-kind=derby
quarkus.datasource.jdbc.url=jdbc:derby://localhost:1527/appDB;create=true
quarkus.datasource.jdbc.driver=org.apache.derby.jdbc.ClientDriver
quarkus.datasource.username=admin
quarkus.datasource.password=admin

quarkus.live-reload.instrumentation=true
</code>```

In the persistence.xml file, I define a persistence unit to be used by the EntityManagerFactory in QueryService.java.

persistence.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.2"
             xmlns="http://xmlns.jcp.org/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
     http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd">

    <persistence-unit
            name="my-persistence-unit"
            transaction-type="JTA">

        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>

        <properties>
            <property name="hibernate.connection.url" value="jdbc:derby://localhost:1527/appDB;create=true"/>
            <property name="hibernate.connection.username" value="admin"/>
            <property name="hibernate.connection.password" value="admin"/>
            <property name="hibernate.connection.driver_class" value="org.apache.derby.jdbc.ClientDriver"/>
            <property name="hibernate.dialect" value="org.hibernate.dialect.DerbyDialect"/>
            <property name="hibernate.show_sql" value="true"/>
        </properties>
    </persistence-unit>
</persistence>
</code>```

If I run this, I get this error: { "details": "Error id 07333181-bf2e-4640-8497-01de9bf6ccf7-1, java.lang.NullPointerException: Cannot invoke \"io.quarkus.hibernate.orm.runtime.recording.RecordedState.isReactive()\" because \"recordedState\" is null", "stack": "java.lang.NullPointerException: Cannot invoke \"io.quarkus.hibernate.orm.runtime.recording.RecordedState.isReactive()\" because \"recordedState\" is null\r\n\tat io.quarkus.hibernate.orm.runtime.FastBootHibernatePersistenceProvider.getEntityManagerFactoryBuilderOrNull(FastBootHibernatePersistenceProvider.java:172)\r\n\tat io.quarkus.hibernate.orm.runtime.FastBootHibernatePersistenceProvider.createEntityManagerFactory(FastBootHibernatePersistenceProvider.java:66)\r\n\tat javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:80)\r\n\tat javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:55)\r\n\tat app.QueryService.init(QueryService.java:29)\r\n\tat app.QueryService_Bean.create(Unknown Source)\r\n\tat app.QueryService_Bean.create(Unknown Source)\r\n\tat io.quarkus.arc.impl.RequestContext.getIfActive(RequestContext.java:74)\r\n\tat io.quarkus.arc.impl.ClientProxies.getDelegate(ClientProxies.java:30)\r\n\tat app.QueryService_ClientProxy.arc$delegate(Unknown Source)\r\n\tat app.QueryService_ClientProxy.obtainCourseList(Unknown Source)\r\n\tat app.Scolarite.obtainCourseList(Scolarite.java:49)\r\n\tat app.Scolarite_Subclass.obtainCourseList$$superforward1(Unknown Source)\r\n\tat app.Scolarite_Subclass$$function$$2.apply(Unknown Source)\r\n\tat io.quarkus.arc.impl.AroundInvokeInvocationContext.proceed(AroundInvokeInvocationContext.java:54)\r\n\tat io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorBase.invokeInOurTx(TransactionalInterceptorBase.java:133)\r\n\tat io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorBase.invokeInOurTx(TransactionalInterceptorBase.java:104)\r\n\tat io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorRequired.doIntercept(TransactionalInterceptorRequired.java:38)\r\n\tat io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorBase.intercept(TransactionalInterceptorBase.java:58)\r\n\tat io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorRequired.intercept(TransactionalInterceptorRequired.java:32)\r\n\tat io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorRequired_Bean.intercept(Unknown Source)\r\n\tat io.quarkus.arc.impl.InterceptorInvocation.invoke(InterceptorInvocation.java:42)\r\n\tat io.quarkus.arc.impl.AroundInvokeInvocationContext.perform(AroundInvokeInvocationContext.java:41)\r\n\tat io.quarkus.arc.impl.InvocationContexts.performAroundInvoke(InvocationContexts.java:33)\r\n\tat app.Scolarite_Subclass.obtainCourseList(Unknown Source)\r\n\tat app.Scolarite_ClientProxy.obtainCourseList(Unknown Source)\r\n\tat app.ScolariteApplication.getCourseList(ScolariteApplication.java:22)\r\n\tat app.ScolariteApplication$quarkusrestinvoker$getCourseList_9c2e0d4fdac50820476d652c171e60223f72a1d5.invoke(Unknown Source)\r\n\tat org.jboss.resteasy.reactive.server.handlers.InvocationHandler.handle(InvocationHandler.java:29)\r\n\tat io.quarkus.resteasy.reactive.server.runtime.QuarkusResteasyReactiveRequestContext.invokeHandler(QuarkusResteasyReactiveRequestContext.java:114)\r\n\tat org.jboss.resteasy.reactive.common.core.AbstractResteasyReactiveContext.run(AbstractResteasyReactiveContext.java:145)\r\n\tat io.quarkus.vertx.core.runtime.VertxCoreRecorder$14.runWith(VertxCoreRecorder.java:576)\r\n\tat org.jboss.threads.EnhancedQueueExecutor$Task.run(EnhancedQueueExecutor.java:2449)\r\n\tat org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1478)\r\n\tat org.jboss.threads.DelegatingRunnable.run(DelegatingRunnable.java:29)\r\n\tat org.jboss.threads.ThreadLocalResettingRunnable.run(ThreadLocalResettingRunnable.java:29)\r\n\tat io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)\r\n\tat java.base/java.lang.Thread.run(Thread.java:833)" }

I tried to search for this on the internet, and it is said that this was because Hibernate Reactive and Hibernate Orm cannot be used together. But I don't know how to solve it. I am quite new to this. Could you please help me with it?

ContentLicense: CC BY-SA 4.0

Body:
Currently, I am trying to build an API with JPA and Derby Database, and I've got some problems with Hibernate Reactive/Hibernate ORM.

Particularly, I want to connect to a Derby database server as follows:

QueryService.java:

@Transactional
@RequestScoped
public class QueryService implements Serializable {
    @PersistenceContext
    EntityManagerFactory emf;
    private final static Logger LOGGER = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
    public QueryService() {}

    @PostConstruct
    public void init() {
        String urlDB = "my-persistence-unit";
        emf = Persistence.createEntityManagerFactory(urlDB);
    }

    @PreDestroy
    public void destroy() {
        emf.close();
    }

application.properties:

quarkus.hibernate-orm.database.generation=none

quarkus.datasource.db-kind=derby
quarkus.datasource.jdbc.url=jdbc:derby://localhost:1527/appDB;create=true
quarkus.datasource.jdbc.driver=org.apache.derby.jdbc.ClientDriver
quarkus.datasource.username=admin
quarkus.datasource.password=admin

quarkus.live-reload.instrumentation=true

In the persistence.xml file, I define a persistence unit to be used by the EntityManagerFactory in QueryService.java.

persistence.xml:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.2"
             xmlns="http://xmlns.jcp.org/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
     http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd">

    <persistence-unit
            name="my-persistence-unit"
            transaction-type="JTA">

        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>

        <properties>
            <property name="hibernate.connection.url" value="jdbc:derby://localhost:1527/appDB;create=true"/>
            <property name="hibernate.connection.username" value="admin"/>
            <property name="hibernate.connection.password" value="admin"/>
            <property name="hibernate.connection.driver_class" value="org.apache.derby.jdbc.ClientDriver"/>
            <property name="hibernate.dialect" value="org.hibernate.dialect.DerbyDialect"/>
            <property name="hibernate.show_sql" value="true"/>
        </properties>
    </persistence-unit>
</persistence>

If I run this, I get this error: { "details": "Error id 07333181-bf2e-4640-8497-01de9bf6ccf7-1, java.lang.NullPointerException: Cannot invoke \"io.quarkus.hibernate.orm.runtime.recording.RecordedState.isReactive()\" because \"recordedState\" is null", "stack": "java.lang.NullPointerException: Cannot invoke \"io.quarkus.hibernate.orm.runtime.recording.RecordedState.isReactive()\" because \"recordedState\" is null\r\n\tat io.quarkus.hibernate.orm.runtime.FastBootHibernatePersistenceProvider.getEntityManagerFactoryBuilderOrNull(FastBootHibernatePersistenceProvider.java:172)\r\n\tat io.quarkus.hibernate.orm.runtime.FastBootHibernatePersistenceProvider.createEntityManagerFactory(FastBootHibernatePersistenceProvider.java:66)\r\n\tat javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:80)\r\n\tat javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:55)\r\n\tat app.QueryService.init(QueryService.java:29)\r\n\tat app.QueryService_Bean.create(Unknown Source)\r\n\tat app.QueryService_Bean.create(Unknown Source)\r\n\tat io.quarkus.arc.impl.RequestContext.getIfActive(RequestContext.java:74)\r\n\tat io.quarkus.arc.impl.ClientProxies.getDelegate(ClientProxies.java:30)\r\n\tat app.QueryService_ClientProxy.arc$delegate(Unknown Source)\r\n\tat app.QueryService_ClientProxy.obtainCourseList(Unknown Source)\r\n\tat app.Scolarite.obtainCourseList(Scolarite.java:49)\r\n\tat app.Scolarite_Subclass.obtainCourseList$$superforward1(Unknown Source)\r\n\tat app.Scolarite_Subclass$$function$$2.apply(Unknown Source)\r\n\tat io.quarkus.arc.impl.AroundInvokeInvocationContext.proceed(AroundInvokeInvocationContext.java:54)\r\n\tat io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorBase.invokeInOurTx(TransactionalInterceptorBase.java:133)\r\n\tat io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorBase.invokeInOurTx(TransactionalInterceptorBase.java:104)\r\n\tat io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorRequired.doIntercept(TransactionalInterceptorRequired.java:38)\r\n\tat io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorBase.intercept(TransactionalInterceptorBase.java:58)\r\n\tat io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorRequired.intercept(TransactionalInterceptorRequired.java:32)\r\n\tat io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorRequired_Bean.intercept(Unknown Source)\r\n\tat io.quarkus.arc.impl.InterceptorInvocation.invoke(InterceptorInvocation.java:42)\r\n\tat io.quarkus.arc.impl.AroundInvokeInvocationContext.perform(AroundInvokeInvocationContext.java:41)\r\n\tat io.quarkus.arc.impl.InvocationContexts.performAroundInvoke(InvocationContexts.java:33)\r\n\tat app.Scolarite_Subclass.obtainCourseList(Unknown Source)\r\n\tat app.Scolarite_ClientProxy.obtainCourseList(Unknown Source)\r\n\tat app.ScolariteApplication.getCourseList(ScolariteApplication.java:22)\r\n\tat app.ScolariteApplication$quarkusrestinvoker$getCourseList_9c2e0d4fdac50820476d652c171e60223f72a1d5.invoke(Unknown Source)\r\n\tat org.jboss.resteasy.reactive.server.handlers.InvocationHandler.handle(InvocationHandler.java:29)\r\n\tat io.quarkus.resteasy.reactive.server.runtime.QuarkusResteasyReactiveRequestContext.invokeHandler(QuarkusResteasyReactiveRequestContext.java:114)\r\n\tat org.jboss.resteasy.reactive.common.core.AbstractResteasyReactiveContext.run(AbstractResteasyReactiveContext.java:145)\r\n\tat io.quarkus.vertx.core.runtime.VertxCoreRecorder$14.runWith(VertxCoreRecorder.java:576)\r\n\tat org.jboss.threads.EnhancedQueueExecutor$Task.run(EnhancedQueueExecutor.java:2449)\r\n\tat org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1478)\r\n\tat org.jboss.threads.DelegatingRunnable.run(DelegatingRunnable.java:29)\r\n\tat org.jboss.threads.ThreadLocalResettingRunnable.run(ThreadLocalResettingRunnable.java:29)\r\n\tat io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)\r\n\tat java.base/java.lang.Thread.run(Thread.java:833)" }

I tried to search for this on the internet, and it is said that this was because Hibernate Reactive and Hibernate Orm cannot be used together. But I don't know how to solve it. I am quite new to this. Could you please help me with it?


问:
VST3 SDK: moduleinfotool.exe fails when using FFTW functions
I am trying to write a VST3 plugin using the Steinberg VST3 SDK, that uses the FFTW library to perform a Fast Fourier Transform on an incoming audio signal. I have followed all the stepts for including the FFTW library in my project and the linker resolves it correctly.

Whenever I use one of the functions that the library provides, such as fftw_malloc for example, the moduleinfotool.exe fails to generate the moduleinfo.json file, exiting with code 1 and failing the build with a very undescriptive error message.

Here is a part of the process function where I tried using the FFTW functions:

tresult PLUGIN_API kw_SquarifyProcessor::process (Vst::ProcessData& data)
{
    if (data.numInputs == 0 || data.numOutputs == 0)
    {
        return kResultOk;
    }

    fftw_complex* in, * out;

    // This is the code that, when included, makes the build crash.
    // Using any other function provided by the FFTW library also crashes the build.
    in = (fftw_complex*)fftw_malloc (sizeof (fftw_complex) * 1024);
}
```

I have no idea what to do right now, and am amazed there are virtually zero resources about the VST3 SDK (apart from the documentation which does not seem to cover cryptic errors like these), so if anyone could point me to some of those/some guide on how to perform FFTs in the VST3 SDK that would be much appreciated as well!

Body:
I am trying to write a VST3 plugin using the Steinberg VST3 SDK, that uses the FFTW library to perform a Fast Fourier Transform on an incoming audio signal. I have followed all the stepts for including the FFTW library in my project and the linker resolves it correctly.

Whenever I use one of the functions that the library provides, such as fftw_malloc for example, the moduleinfotool.exe fails to generate the moduleinfo.json file, exiting with code 1 and failing the build with a very undescriptive error message.

Here is a part of the process function where I tried using the FFTW functions:

tresult PLUGIN_API kw_SquarifyProcessor::process (Vst::ProcessData& data)
{
    if (data.numInputs == 0 || data.numOutputs == 0)
    {
        return kResultOk;
    }

    fftw_complex* in, * out;

    // This is the code that, when included, makes the build crash.
    // Using any other function provided by the FFTW library also crashes the build.
    in = (fftw_complex*)fftw_malloc (sizeof (fftw_complex) * 1024);
}

I have no idea what to do right now, and am amazed there are virtually zero resources about the VST3 SDK (apart from the documentation which does not seem to cover cryptic errors like these), so if anyone could point me to some of those/some guide on how to perform FFTs in the VST3 SDK that would be much appreciated as well!


问:
GORM - uniqueIndex with soft delete
I'm using Gorm's unique index to enforce a certain ordering of elements

```<code>type Element struct {
  gorm.Model
  ID         int            `gorm:"primary_key"`
  Index      int            `gorm:"uniqueIndex:unique_order"`
  ParentID   int            `gorm:"uniqueIndex:unique_order"`
}
</code>```

The problem I'm running into is when I create and delete multiple elements I start to get an error like

```<code>ERROR: duplicate key value violates unique constraint "unique_order" (SQLSTATE 23505)
</code>```

This is happening because Gorm soft deletes elements by setting deleted_at, but the rows still exist in the database and the unique index is still enforced.

I know I can get around this using a partial index in Postgres SQL, but I'm wondering if there's a way I can handle this with Gorm?

Title: GORM - uniqueIndex with soft delete

Body:
I'm using Gorm's unique index to enforce a certain ordering of elements

type Element struct {
  gorm.Model
  ID         int            `gorm:"primary_key"`
  Index      int            `gorm:"uniqueIndex:unique_order"`
  ParentID   int            `gorm:"uniqueIndex:unique_order"`
}

The problem I'm running into is when I create and delete multiple elements I start to get an error like

ERROR: duplicate key value violates unique constraint "unique_order" (SQLSTATE 23505)

This is happening because Gorm soft deletes elements by setting deleted_at, but the rows still exist in the database and the unique index is still enforced.

I know I can get around this using a partial index in Postgres SQL, but I'm wondering if there's a way I can handle this with Gorm?


问:
Animation on elements only applies on the first render for flastlist component
I want to animate newly elements that are added to my messages array with my  translateYChatBubble``` animation. However, whenever I add an element to the array, the element doesn't animate, it only applies on the first render.</p>
<p>Here is my flatlist component render item:</p>
```  const renderItem = ({ item, index }) => {
    return (
      <ChatBubble
        key={index}
        message={item.message.trim()}
        index={index}
        animate={true}
      />
    );
  };
```
<p>Here's a portion of my <code>ChatBubble</code> component:</p>
```const translateYChatBubble = useRef(new Animated.Value(20)).current;

  useEffect(() => {
    Animated.timing(translateYChatBubble, {
      toValue: 0,
      duration: 500,
      useNativeDriver: true,
    }).start();
  }, []);

return (
 <Container
      style={{
        alignItems: isMe ? "flex-end" : "flex-start",
        marginTop: addMargin ? 25 : 0,
        transform: [{ translateY: translateYChatBubble }],
      }}
    >
      {children}

    </Container>
```

My goal is to have the function animate elements whenever they are added to the array, but they're only animating on the first render.

Body:
I want to animate newly elements that are added to my messages array with my  translateYChatBubble``` animation. However, whenever I add an element to the array, the element doesn't animate, it only applies on the first render.

Here is my flatlist component render item:

  const renderItem = ({ item, index }) => {
    return (
      <ChatBubble
        key={index}
        message={item.message.trim()}
        index={index}
        animate={true}
      />
    );
  };

Here's a portion of my ChatBubble component:

const translateYChatBubble = useRef(new Animated.Value(20)).current;

  useEffect(() => {
    Animated.timing(translateYChatBubble, {
      toValue: 0,
      duration: 500,
      useNativeDriver: true,
    }).start();
  }, []);

return (
 <Container
      style={{
        alignItems: isMe ? "flex-end" : "flex-start",
        marginTop: addMargin ? 25 : 0,
        transform: [{ translateY: translateYChatBubble }],
      }}
    >
      {children}

    </Container>

My goal is to have the function animate elements whenever they are added to the array, but they're only animating on the first render.


问:
How to remove whitespace caused by sticky navbar?(Nextjs + tailwind)
I'm trying to make a sticky navbar component but the problem is it creates a whitespace/gap between other elements

The code in my index.tsx file

```<code>import Nav from '../components/Nav

<main>  /*Yes, this "main" element isn't styled. */
    <section>
    </section>

    <Nav/>

    <section>
    </section>
</main>

</code>```

In my global.css

```<code>*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

*, html{
    scroll-behavior: smooth !important;
    -webkit-tap-highlight-color:  rgba(255, 255, 255, 0);
}
</code>```

in Nav.tsx

```<code><nav className='flex flex-col items-center w-[45px] bg-gradient-to-b from-blue-500 to-pink-500 py-[20px] px-[10px] rounded-full gap-4 z-[5] translate-y-[-50%] lg:flex-row lg:w-full lg:ml-0 sticky left-0 top-[50%] m-0'>

</nav>

/*note - i am using tailwind css here*/
</code>```

I've read some past questions here and they mostly point out the margin, but when i tried to set it using "  * " in the global.css file it still didn't work, tried setting margin to 0 manually on navbar and its parent elements.

Body:
I'm trying to make a sticky navbar component but the problem is it creates a whitespace/gap between other elements

The code in my index.tsx file

import Nav from '../components/Nav

  /*Yes, this "main" element isn't styled. */

In my global.css

*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

*, html{
    scroll-behavior: smooth !important;
    -webkit-tap-highlight-color:  rgba(255, 255, 255, 0);
}

in Nav.tsx

/*note - i am using tailwind css here*/

I've read some past questions here and they mostly point out the margin, but when i tried to set it using "  * " in the global.css file it still didn't work, tried setting margin to 0 manually on navbar and its parent elements.


问:
Using GitHub Actions with a React/NodeJS + shared code monorepo
I'm writing an application split (at least for this repo) between a React frontend and an Express/NodeJS server.
Some of the code that I needed was used by both, so I split it into a third folder and used npm link to locally install it into the frontend and server folders.

```<code>shared-code/
├─ dist/             // output of npm build (tsc)
├─ src/
│  ├─ index.ts       // export const sharedFn = () => {}
├─ tsconfig.json
├─ package.json
├─ package-lock.json
server/
├─ dist/             // output of npm build
├─ src/
│  ├─ index.ts       // import { sharedFn } from 'shared-code'
├─ tsconfig.json
├─ package.json
├─ package-lock.json
frontend/
├─ dist/             // output of npm build
├─ src/
│  ├─ index.ts       // import { sharedFn } from 'shared-code'
├─ tsconfig.json
├─ package.json
├─ package-lock.json
</code>```
```<code>// in shared-code directory
npm run build
// in server directory
npm link ../shared-code
// produces in server/package.json
 "dependencies": {
    "express": "^4.18.2",
    "shared-code": "file:../shared-code",
    "ws": "^8.11.0"
  },
</code>```

The dist folders are generated by tsc (or npm run build, which for the frontend uses a CRA script) but are not stored in the repo. This seems to complicate the use of a GitHub action, since the shared-code/dist doesn't exist in a clean checkout, breaking naïve approaches to a separate script for each portion, and my attempts to use needs and a single yaml file.

I haven't been able to work out how to do this in a GitHub action, or how to approach this. I don't want to publish an npm package publicly, and my desired outcome would be to produce GitHub releases in a form that I can download them onto a remote device (by curl, wget, whatever) and then run them with node some/path/to/dist/index.js, chromium /some/path/to/dist/index.html. (But I'd say that all of deployment is not in the scope of this question - only writing in case it changes the suitable method.)

Body:
I'm writing an application split (at least for this repo) between a React frontend and an Express/NodeJS server.
Some of the code that I needed was used by both, so I split it into a third folder and used npm link to locally install it into the frontend and server folders.

shared-code/
├─ dist/             // output of npm build (tsc)
├─ src/
│  ├─ index.ts       // export const sharedFn = () => {}
├─ tsconfig.json
├─ package.json
├─ package-lock.json
server/
├─ dist/             // output of npm build
├─ src/
│  ├─ index.ts       // import { sharedFn } from 'shared-code'
├─ tsconfig.json
├─ package.json
├─ package-lock.json
frontend/
├─ dist/             // output of npm build
├─ src/
│  ├─ index.ts       // import { sharedFn } from 'shared-code'
├─ tsconfig.json
├─ package.json
├─ package-lock.json

// in shared-code directory
npm run build
// in server directory
npm link ../shared-code
// produces in server/package.json
 "dependencies": {
    "express": "^4.18.2",
    "shared-code": "file:../shared-code",
    "ws": "^8.11.0"
  },

The dist folders are generated by tsc (or npm run build, which for the frontend uses a CRA script) but are not stored in the repo. This seems to complicate the use of a GitHub action, since the shared-code/dist doesn't exist in a clean checkout, breaking naïve approaches to a separate script for each portion, and my attempts to use needs and a single yaml file.

I haven't been able to work out how to do this in a GitHub action, or how to approach this. I don't want to publish an npm package publicly, and my desired outcome would be to produce GitHub releases in a form that I can download them onto a remote device (by curl, wget, whatever) and then run them with node some/path/to/dist/index.js, chromium /some/path/to/dist/index.html. (But I'd say that all of deployment is not in the scope of this question - only writing in case it changes the suitable method.)


问:
Remove the center line in data_bars() in reactablefmtr package in R
I am using reactablefmtr package in R and apply data_bars() for the plot. I couldn't find any parameter to remove the center line between positive and negative number. I did check css, but I don't know how to apply to the chart. Any help will be great.

```<code>library(reactablefmtr)
library(htmltools)
library(tidyverse)
cars <- mtcars %>%
  rownames_to_column(var = 'model') %>%
  select(c(model,wt,mpg,hp)) %>%
  mutate(wt = wt-mean(wt),
         mpg = mpg-mean(mpg),
         hp = hp-mean(hp))

reactable(cars,
  theme = nytimes(centered = TRUE),
  compact = TRUE,
  defaultSortOrder = 'desc',
  defaultSorted = 'mpg',
  pagination = FALSE,
  columns = list(
    wt = colDef(
      name = 'WT VS AVG',
      minWidth = 150,
      align = 'center',
      cell = data_bars(
        data = cars,
        text_position = 'outside-end',
        fill_color = viridis::mako(5),
        number_fmt = scales::number_format(accuracy = 0.01)
      )
    ),
    hp = colDef(
      name = 'HP VS AVG',
      minWidth = 150,
      align = 'center',
      cell = data_bars(
        data = cars,
        text_position = 'outside-end',
        fill_color = c('#C40233','#127852'),
        number_fmt = scales::comma
      )
    ),
    mpg = colDef(
      name = 'MPG VS AVG',
      minWidth = 150,
      align = 'center',
      cell = data_bars(
        data = cars,
        text_position = 'none',
        box_shadow = TRUE,
        fill_color = MetBrewer::met.brewer('VanGogh3'),
        number_fmt = scales::comma
      )
    )
  )
)
</code>```

Body:
I am using reactablefmtr package in R and apply data_bars() for the plot. I couldn't find any parameter to remove the center line between positive and negative number. I did check css, but I don't know how to apply to the chart. Any help will be great.

library(reactablefmtr)
library(htmltools)
library(tidyverse)
cars <- mtcars %>%
  rownames_to_column(var = 'model') %>%
  select(c(model,wt,mpg,hp)) %>%
  mutate(wt = wt-mean(wt),
         mpg = mpg-mean(mpg),
         hp = hp-mean(hp))

reactable(cars,
  theme = nytimes(centered = TRUE),
  compact = TRUE,
  defaultSortOrder = 'desc',
  defaultSorted = 'mpg',
  pagination = FALSE,
  columns = list(
    wt = colDef(
      name = 'WT VS AVG',
      minWidth = 150,
      align = 'center',
      cell = data_bars(
        data = cars,
        text_position = 'outside-end',
        fill_color = viridis::mako(5),
        number_fmt = scales::number_format(accuracy = 0.01)
      )
    ),
    hp = colDef(
      name = 'HP VS AVG',
      minWidth = 150,
      align = 'center',
      cell = data_bars(
        data = cars,
        text_position = 'outside-end',
        fill_color = c('#C40233','#127852'),
        number_fmt = scales::comma
      )
    ),
    mpg = colDef(
      name = 'MPG VS AVG',
      minWidth = 150,
      align = 'center',
      cell = data_bars(
        data = cars,
        text_position = 'none',
        box_shadow = TRUE,
        fill_color = MetBrewer::met.brewer('VanGogh3'),
        number_fmt = scales::comma
      )
    )
  )
)


问:
Telegram bot written using Telebot stucks when is used by 2+ people
I wrote a simple TicTacToe game: user sends cell's index and bot places character('X' or 'O') into that cell and plays back. It works fine as long as it's being used by one person. However, when a few are concurrently playing, bot refuses to process requests and sometimes sends the similar board(which I store in dict for each player individually)

I think that I messed up with async function 'MakeMove'. I haven't used python much and a bit of advise would be highly appreciated. Thank you!

```<code>import telebot
import asyncio

#Consists of objects of class Player
players = {}

class Player:
    def __init__(self, userName):
        self.userName = userName
        self.winsAmount = 0
        self.loses = 0
        self.pickedChar = 'X'
        self.isGameRunning = False
        self.isTurn = True
        self.currentBoard = Board(self.pickedChar)
...

@bot.message_handler(commands=['game'])
def StartGame(message):
    chatId = message.chat.id

    if chatId not in players:
        players[chatId] = Player(message.from_user.username)
    if not isGameRunning(chatId):
        player = players[chatId]
        player.isGameRunning = True
        bot.send_message(chatId, f'Hello, *{player.userName}*!\nYour wins amount is _{player.winsAmount}_\nYou\'ve lost _{player.loses}_ times', parse_mode='Markdown')

        keyboard = telebot.types.InlineKeyboardMarkup()
        keyboard.row(telebot.types.InlineKeyboardButton('X', callback_data='charX'),
                    telebot.types.InlineKeyboardButton('O', callback_data='charO'))
        bot.send_message(chatId, 'Choose your side: X | O', reply_markup=keyboard)
    else:
        keyboard = telebot.types.InlineKeyboardMarkup()
        keyboard.row(telebot.types.InlineKeyboardButton('End the current game', callback_data='endGame'))
        bot.send_message(chatId, 'The game is still running!', reply_markup=keyboard)

@bot.message_handler(content_types=['text'])
def HandleMoves(message):
    player = players[message.chat.id]
    board = player.currentBoard
    for i in range(9):
        if message.text == (str)(i + 1) and player.isGameRunning and player.isTurn:
            if board.desk[i] == '_':
                board.desk[i] = board.playerChar
                player.isTurn = False
            else:
                bot.send_message(message.chat.id, 'The cell is already occupied')
.........................................................
# I suppouse these two functions cause the problem

async def CheckForTurn(chatId):
    while True:
        if not players[chatId].isTurn:
            return
        await asyncio.sleep(0.2)

async def MakeMove(chatId):
    board = players[chatId].currentBoard
    player = players[chatId]
    while True:
        DrawBoard(chatId)
        if board.GetState() != States.IN_GAME:
            EndGame(chatId, board.GetState())
            break
        if player.isTurn:
            bot.send_message(chatId, 'Make a move (from 1 to 9)')
            await CheckForTurn(chatId)
        if not player.isTurn:
            index = GetBestMove(board)
            char = ' '
            if player.pickedChar == 'O':
                char = 'X'
            else:
                char = 'O'
            board.desk[index] = char
            player.isTurn = True
</code>```

Body:
I wrote a simple TicTacToe game: user sends cell's index and bot places character('X' or 'O') into that cell and plays back. It works fine as long as it's being used by one person. However, when a few are concurrently playing, bot refuses to process requests and sometimes sends the similar board(which I store in dict for each player individually)

I think that I messed up with async function 'MakeMove'. I haven't used python much and a bit of advise would be highly appreciated. Thank you!

import telebot
import asyncio

#Consists of objects of class Player
players = {}

class Player:
    def __init__(self, userName):
        self.userName = userName
        self.winsAmount = 0
        self.loses = 0
        self.pickedChar = 'X'
        self.isGameRunning = False
        self.isTurn = True
        self.currentBoard = Board(self.pickedChar)
...

@bot.message_handler(commands=['game'])
def StartGame(message):
    chatId = message.chat.id

    if chatId not in players:
        players[chatId] = Player(message.from_user.username)
    if not isGameRunning(chatId):
        player = players[chatId]
        player.isGameRunning = True
        bot.send_message(chatId, f'Hello, *{player.userName}*!\nYour wins amount is _{player.winsAmount}_\nYou\'ve lost _{player.loses}_ times', parse_mode='Markdown')

        keyboard = telebot.types.InlineKeyboardMarkup()
        keyboard.row(telebot.types.InlineKeyboardButton('X', callback_data='charX'),
                    telebot.types.InlineKeyboardButton('O', callback_data='charO'))
        bot.send_message(chatId, 'Choose your side: X | O', reply_markup=keyboard)
    else:
        keyboard = telebot.types.InlineKeyboardMarkup()
        keyboard.row(telebot.types.InlineKeyboardButton('End the current game', callback_data='endGame'))
        bot.send_message(chatId, 'The game is still running!', reply_markup=keyboard)

@bot.message_handler(content_types=['text'])
def HandleMoves(message):
    player = players[message.chat.id]
    board = player.currentBoard
    for i in range(9):
        if message.text == (str)(i + 1) and player.isGameRunning and player.isTurn:
            if board.desk[i] == '_':
                board.desk[i] = board.playerChar
                player.isTurn = False
            else:
                bot.send_message(message.chat.id, 'The cell is already occupied')
.........................................................
# I suppouse these two functions cause the problem

async def CheckForTurn(chatId):
    while True:
        if not players[chatId].isTurn:
            return
        await asyncio.sleep(0.2)

async def MakeMove(chatId):
    board = players[chatId].currentBoard
    player = players[chatId]
    while True:
        DrawBoard(chatId)
        if board.GetState() != States.IN_GAME:
            EndGame(chatId, board.GetState())
            break
        if player.isTurn:
            bot.send_message(chatId, 'Make a move (from 1 to 9)')
            await CheckForTurn(chatId)
        if not player.isTurn:
            index = GetBestMove(board)
            char = ' '
            if player.pickedChar == 'O':
                char = 'X'
            else:
                char = 'O'
            board.desk[index] = char
            player.isTurn = True


问:
Register MulterModule multiple times in the same module in nest.js
I want to register MulterModule twice in the same module because I have two types of uploads: a video and a thumbnail. I tried this implementation it did not work. Is it even possible?

video.module.ts

```<code>import { Module } from '@nestjs/common';
import { VideoController } from './video.controller';
import { MulterModule } from '@nestjs/platform-express';
import VideoDiskStorage from './multer/storage/video-disk-storage.service';
import ThumbnailDiskStorage from './multer/storage/thumbnail-disk-storage';

@Module({
  imports: [
    MulterModule.registerAsync({
      useClass: VideoDiskStorage,
    }),
    MulterModule.registerAsync({
      useClass: ThumbnailDiskStorage,
    }),
  ],
  controllers: [VideoController],
})
export class VideoModule {}
</code>```

video-disk-storage.ts

```<code>import multer, { StorageEngine } from 'multer';
import { nanoid } from 'nanoid';
import path from 'node:path';
import { BadRequestException, Injectable } from '@nestjs/common';
import { ensureDir } from 'fs-extra';
import {
  MulterModuleOptions,
  MulterOptionsFactory,
} from '@nestjs/platform-express';

@Injectable()
class VideoDiskStorage implements MulterOptionsFactory {
  private dir: string;
  createMulterOptions(): Promise<MulterModuleOptions> | MulterModuleOptions {
    return {
      storage: this.diskStorage(),

      limits: {
        fileSize: 1024 * 1024 * 1024 * 10,
      },
    };
  }
  private diskStorage(): StorageEngine {
    return multer.diskStorage({
      filename: async (req, file, cb) => {
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-ignore
        const userId = req.session?.getUserId();
        if (!userId) {
          return cb(new BadRequestException('Invalid user'), null);
        }

        const mimeType = file.mimetype.split('/')[0];
        if (mimeType !== 'video') {
          return cb(
            new BadRequestException('only video files are allowed'),
            null,
          );
        }

        const fileName = nanoid() + path.extname(file.originalname);

        const dir = path.join(
          process.cwd(),
          'tmp',
          'uploads',
          'videos',
          'original',
          userId,
        );
        await ensureDir(dir);
        this.dir = dir;

        cb(null, fileName);
      },
      destination: this.dir,
    });
  }
}
export default VideoDiskStorage;
</code>```

thumbnail-disk-storage.ts

```<code>import multer, { StorageEngine } from 'multer';
import { nanoid } from 'nanoid';
import path from 'node:path';
import { BadRequestException, Injectable } from '@nestjs/common';
import { ensureDir } from 'fs-extra';
import {
  MulterModuleOptions,
  MulterOptionsFactory,
} from '@nestjs/platform-express';

@Injectable()
class ThumbnailDiskStorage implements MulterOptionsFactory {
  private dir: string;
  createMulterOptions(): Promise<MulterModuleOptions> | MulterModuleOptions {
    return {
      storage: this.diskStorage(),
      limits: {
        fileSize: 1024 * 2,
      },
    };
  }
  private diskStorage(): StorageEngine {
    return multer.diskStorage({
      filename: async (req, file, cb) => {
        console.log('file', file);
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-ignore
        const userId = req.session?.getUserId();
        if (!userId) {
          return cb(new BadRequestException('Invalid user'), null);
        }

        const mimeType = file.mimetype.split('/')[0];
        console.log('mimeType', mimeType);
        if (mimeType !== 'img') {
          return cb(
            new BadRequestException('only images files are allowed'),
            null,
          );
        }

        const thumbnailName = nanoid() + path.extname(file.originalname);

        const dir = path.join(
          process.cwd(),
          'tmp',
          'thumbnails',
          'original',
          userId,
        );
        await ensureDir(dir);
        this.dir = dir;

        cb(null, thumbnailName);
      },
      destination: this.dir,
    });
  }
}
export default ThumbnailDiskStorage;
</code>```

The problem with this implementation is first registered MulterModule is overwritten by the second. So how can I use both of them?

Body:
I want to register MulterModule twice in the same module because I have two types of uploads: a video and a thumbnail. I tried this implementation it did not work. Is it even possible?

video.module.ts

import { Module } from '@nestjs/common';
import { VideoController } from './video.controller';
import { MulterModule } from '@nestjs/platform-express';
import VideoDiskStorage from './multer/storage/video-disk-storage.service';
import ThumbnailDiskStorage from './multer/storage/thumbnail-disk-storage';

@Module({
  imports: [
    MulterModule.registerAsync({
      useClass: VideoDiskStorage,
    }),
    MulterModule.registerAsync({
      useClass: ThumbnailDiskStorage,
    }),
  ],
  controllers: [VideoController],
})
export class VideoModule {}

video-disk-storage.ts

import multer, { StorageEngine } from 'multer';
import { nanoid } from 'nanoid';
import path from 'node:path';
import { BadRequestException, Injectable } from '@nestjs/common';
import { ensureDir } from 'fs-extra';
import {
  MulterModuleOptions,
  MulterOptionsFactory,
} from '@nestjs/platform-express';

@Injectable()
class VideoDiskStorage implements MulterOptionsFactory {
  private dir: string;
  createMulterOptions(): Promise<MulterModuleOptions> | MulterModuleOptions {
    return {
      storage: this.diskStorage(),

      limits: {
        fileSize: 1024 * 1024 * 1024 * 10,
      },
    };
  }
  private diskStorage(): StorageEngine {
    return multer.diskStorage({
      filename: async (req, file, cb) => {
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-ignore
        const userId = req.session?.getUserId();
        if (!userId) {
          return cb(new BadRequestException('Invalid user'), null);
        }

        const mimeType = file.mimetype.split('/')[0];
        if (mimeType !== 'video') {
          return cb(
            new BadRequestException('only video files are allowed'),
            null,
          );
        }

        const fileName = nanoid() + path.extname(file.originalname);

        const dir = path.join(
          process.cwd(),
          'tmp',
          'uploads',
          'videos',
          'original',
          userId,
        );
        await ensureDir(dir);
        this.dir = dir;

        cb(null, fileName);
      },
      destination: this.dir,
    });
  }
}
export default VideoDiskStorage;

thumbnail-disk-storage.ts

import multer, { StorageEngine } from 'multer';
import { nanoid } from 'nanoid';
import path from 'node:path';
import { BadRequestException, Injectable } from '@nestjs/common';
import { ensureDir } from 'fs-extra';
import {
  MulterModuleOptions,
  MulterOptionsFactory,
} from '@nestjs/platform-express';

@Injectable()
class ThumbnailDiskStorage implements MulterOptionsFactory {
  private dir: string;
  createMulterOptions(): Promise<MulterModuleOptions> | MulterModuleOptions {
    return {
      storage: this.diskStorage(),
      limits: {
        fileSize: 1024 * 2,
      },
    };
  }
  private diskStorage(): StorageEngine {
    return multer.diskStorage({
      filename: async (req, file, cb) => {
        console.log('file', file);
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-ignore
        const userId = req.session?.getUserId();
        if (!userId) {
          return cb(new BadRequestException('Invalid user'), null);
        }

        const mimeType = file.mimetype.split('/')[0];
        console.log('mimeType', mimeType);
        if (mimeType !== 'img') {
          return cb(
            new BadRequestException('only images files are allowed'),
            null,
          );
        }

        const thumbnailName = nanoid() + path.extname(file.originalname);

        const dir = path.join(
          process.cwd(),
          'tmp',
          'thumbnails',
          'original',
          userId,
        );
        await ensureDir(dir);
        this.dir = dir;

        cb(null, thumbnailName);
      },
      destination: this.dir,
    });
  }
}
export default ThumbnailDiskStorage;

The problem with this implementation is first registered MulterModule is overwritten by the second. So how can I use both of them?


问:
How to make Google Chrome Developer tools JavaScript console Variable persistent?
Is it possible to make a JavaScript variable persistent in chrome developer tools so that it remains available in next page also. For example I want to preserve the List variable

```<code>List = fetchDetails(element)
</code>```

I am working on a simple script which extracts data from a page to the List variable. What I need to do is to somehow save this variable so that when I load the next page, and extract information from that page, I am able to append the details to the previously filled list.

```<code>List2 = fetchDetails(element)
List.push(...List2)
</code>```

In Summary, I need to access the List across many pages.

Body:
Is it possible to make a JavaScript variable persistent in chrome developer tools so that it remains available in next page also. For example I want to preserve the List variable

List = fetchDetails(element)

I am working on a simple script which extracts data from a page to the List variable. What I need to do is to somehow save this variable so that when I load the next page, and extract information from that page, I am able to append the details to the previously filled list.

List2 = fetchDetails(element)
List.push(...List2)

In Summary, I need to access the List across many pages.


问:
Append a data in javascript
In javaScript i try to append a data it work but in data url id and close button not working

success: function(response)
{
    $.each(response, function () {
        $.each(this, function (index, value) {
            $('#List').append('' +
                '

'+ value.item +
                '<button data-id='+value.id+' data-token="{{ csrf_token() }}" data-url="{{ route("list.delete", '+value.id+') }}" type="button" class="close cls-btn" data-dismiss="alert">times;</button>'+
                '
'+
                '
'
            );
        });
    });
},
```

the above code data-url="{{ route("list.delete", '+value.id+') }}" show data-url="http://127.0.0.1:8000/delete/+value.id+" and times;</button>show times;
how to add value in data-url and close button in appending time?

Title: Append a data in javascript

Body:
In javaScript i try to append a data it work but in data url id and close button not working

success: function(response)
{
    $.each(response, function () {
        $.each(this, function (index, value) {
            $('#List').append('' +
                '

'+ value.item +
                '<button data-id='+value.id+' data-token="{{ csrf_token() }}" data-url="{{ route("list.delete", '+value.id+') }}" type="button" class="close cls-btn" data-dismiss="alert">times;</button>'+
                '
'+
                '
'
            );
        });
    });
},

the above code data-url="{{ route("list.delete", '+value.id+') }}" show data-url="http://127.0.0.1:8000/delete/+value.id+" and times;</button>show times;
how to add value in data-url and close button in appending time?


问:
OpenGL client—server model, synchronization and 'deferred' loading in OpenGL 3.3
I heard of PBOs in OpenGL, they are pretty neat in texture loading / uploading. Using PBO involves using synchronisation fences, like they are used in this PBO tutorial. I've tried this technique and it's a great replacement of glTexImage and glGetTexImage in case of big images. Now I want to apply the same approach to other loading / uploading routines (and possibly some other).

If I understand OpenGL client—server model correctly, it works as follows:

(Italics are the things I am not sure of)

Client (my program) 'asks' OGL context to place new commands into OGL command queue. It is done by simply calling the gl* functions in the order that client wants them to execute;

If command flushing is enabled (it is by default), commands are immidiately flushed to the GPU (e. g. via PCI). Otherwise they are placed in some buffer and flushed afterwards when needed (call to glFlush does this);

GPU (server) receives commands from OGL context and executes them in desired order and changes object / context state;

GPU sends back a reply that context (client) asked for;

Context replies to client with the data received from server.

Fences may be used to indicate whether GPU is done executing previous commands.

(2) implies that command execution is not necessarily done instantly. One can, for example, block command flushing by calling glWaitSync, place new commands into queue and then call glFlush. Commands will be flushed to GPU and executed asynchronously (independently from client). When GPU is busy executing given commands, CPU can focus on doing other stuff (e. g. sending info to a remote TCP server, or receiving input from user, or pretty much anything else). When CPU needs to perform something with OGL context again, it can wait until GPU is done with previous job by calling glClientWaitSync and place new commands in the queue, and the cycle repeats.

Based on all of the above, in case of that PBO tutorial, OGL context receives data from the program, buffers it and then sends it to GPU. Sending large amounts of data takes time, hence fence is used to know when sending is complete.

However, Khronos wiki says that only rendering functions are asynchronous. I understand it: rendering also takes time. But then why does the PBO example above work? And it's not like the image upload to GPU is instant, fence is not signaled instantly. Surely, the time it takes to finish uploading depends on how big is the image (I tested it with different image sizes).

Another example: I send a source code for a shader with glShaderSource and then do glCompileShader. Then I instantly check the GL_COMPILE_STATUS with glGetShaderiv. If the shader is not yet compiled when I do glGetShaderiv (it simply did not have enough time to compile), is it possible that GL_COMPILE_STATUS will state that shader is not compiled? Or is it guaranteed that the GL_COMPILE_STATUS is only returned after the compilation? Or is the compilation performed on CPU and does not need to communicate with GPU? (i. e. compilation does not place any commands in GPU queue). It has never really happened to me that shader compilation failed due to time limits, it failed only because of bad shader code.

The questions are:

Is my understanding of OGL client—server model correct or does it need some adjustments?

If not all functions can be executed asynchronously, what are those functions exactly?

Why does wiki say that only render actions may be performed asynchronously?

If command execution may indeed be 'deferred' (not really the right word for it...) with glWaitSync for example, how can I upload and compile shaders the same way images are uploaded in PBO example? Or how can I perform VBO / EBO upload the same way? Or UBO? Or TBO? Non-buffer objects? Is it just uploading and then waiting for fence to be signaled?

In case it matters, I use OGL with latest GLFW github release, latest GLAD (configuration) and C++ (MinGWx64 11.2.0).

UPD: I found this answer that touches the subject of my question. However, I must specify that my question is not about where and how OGL functions are executed, it's about how to control the flow of them, i. e. control when they are executed, to perform asynchronous work of GPU and CPU if it is even possible (it seems to be, if I understand wiki page right).


问:
What causes error: "Warning, too much iteration done before the next frame. Check your code, or increase the Clock.max_iteration attribute" in Kivy?
I'm still learning and I'm getting an error *Warning, too much iteration done before the next frame. Check your code, or increase the Clock.max_iteration attribute. *

```<code>BoxLayout:
        size_hint: None, None
        size: area_img.size
        pos_hint: {'center_x': .5, 'center_y': .5}
        Court:
            id: area_img
            source: 'half-court.png'
            size: self.texture_size

        MDBottomNavigation:
            MDBottomNavigationItem:
                name: "btnSave"
                text: "Save"
                icon: "images/save.png"
                selected_color_background: 147/255,84/255,48/255
                on_tab_release: root.show_save()

            MDBottomNavigationItem:
                name: "btnClear"
                text: "Clear Screen"
                icon: "images/clear.png"
                selected_color_background: 147/255,84/255,48/255
                on_tab_release: root.clear_drawing()

            MDBottomNavigationItem:
                name: "btnBack"
                text: "Home"
                icon: "images/home.png"
                selected_color_background: 147/255,84/255,48/255
                # on_tab_release: app.root.current = 'main'
</code>```

I'm trying to include the MDBottomNavigation to the screen so I can save, clear the output of the data and can easily go back to home screen. This is my kv file. Without the MDBottomNavigation it's working well, but when I include it, that's the error being said.

How it looks like with MDBottomNavigation
Without

Body:
I'm still learning and I'm getting an error *Warning, too much iteration done before the next frame. Check your code, or increase the Clock.max_iteration attribute. *

BoxLayout:
        size_hint: None, None
        size: area_img.size
        pos_hint: {'center_x': .5, 'center_y': .5}
        Court:
            id: area_img
            source: 'half-court.png'
            size: self.texture_size

        MDBottomNavigation:
            MDBottomNavigationItem:
                name: "btnSave"
                text: "Save"
                icon: "images/save.png"
                selected_color_background: 147/255,84/255,48/255
                on_tab_release: root.show_save()

            MDBottomNavigationItem:
                name: "btnClear"
                text: "Clear Screen"
                icon: "images/clear.png"
                selected_color_background: 147/255,84/255,48/255
                on_tab_release: root.clear_drawing()

            MDBottomNavigationItem:
                name: "btnBack"
                text: "Home"
                icon: "images/home.png"
                selected_color_background: 147/255,84/255,48/255
                # on_tab_release: app.root.current = 'main'

I'm trying to include the MDBottomNavigation to the screen so I can save, clear the output of the data and can easily go back to home screen. This is my kv file. Without the MDBottomNavigation it's working well, but when I include it, that's the error being said.

How it looks like with MDBottomNavigation
Without


问:
I am trying to install opencv-python through visual studio 2017 and getting connection error but pip install working through cmd, pip is updated
WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x000001E3E664D518>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed',))': /simple/opencv-python/
WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x000001E3E664DB70>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed',))': /simple/opencv-python/
WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x000001E3E664DB00>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed',))': /simple/opencv-python/
WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x000001E3E664DBE0>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed',))': /simple/opencv-python/
WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ProxyError('Cannot connect to proxy.', NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x000001E3E664DC50>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed',))': /simple/opencv-python/

I tried changing proxy settings, disabling proxy, reinstalling python, firewall is OFF.


问:
How to use granular synthesis on mic input?
I've been trying to get a good pitch shifting setup working for a while now. I've found some that work, but are pretty heavy on the computational end. I've recently been reading about granular synthesis and how it is a lighter weight setup for pitch shifting. Is there a way to utilize granular synthesis on a live mic input?</p>


问:
How to add a link to redirect to LinkedIn chat in html [Web development]
Is there any way i can add a link to redirect user to chat with me on linkedin like we do for whatsapp

```<code><a href="https://api.whatsapp.com/send?phone=number">Click me</a>
</code>```

something like this but for linkedin

Body:
Is there any way i can add a link to redirect user to chat with me on linkedin like we do for whatsapp

Click me

something like this but for linkedin


问:
How can I give blur effect in android studio?
How can I do to give the lighting effect to the edges of the letter in android studio? The card I use is an image and I want to give it the border and lighting

I tried to put in an image but it is too complicated for me


问:
How to fix "Unable to create javax script engine for javascript" in netbeans?
Im trying to do a project using Javafx and Netbeans IDE and I can not run my project because this message below "Unable to create javax script engine for javascript". Please can someone tell me how can I fix this please.. Below you can see what the link can open in my IDE . Please help


问:
Is there a way to extract the calculation metadata from a pyspark dataframe?
I don't know if I'm using the right key terms in my question. My use-case here is as follows: I'm creating DataFrames in pyspark, and I'd love to be able to automate the documentation on how fields are calculated.

For Example:

from pyspark.sql import functions as f

df = spark.createDataFrame(
    [
        (1, "foo"),
        (2, "bar"),
    ],
    ["id", "label"]
)

df = df.withColumn('calc', f.col("id") + f.lit(1))
df = df.withColumn('calc', f.when(f.col('calc') > 1, 1).otherwise(0))

```

I've created a super simple DataFrame here with columns "id" and "label", and added the calculated field "calc" based on a condition on the "id" field.

My understanding of Spark is that the calculations of the new field "calc" are cached and will be translated into a Spark SQL statement at time of execution when a function like show() or collect() are performed. I know this because when encountering errors using pyspark, the error message will show a SQL statement representing the field of issue, even if it was generated using pyspark syntax.

Is there a way for me to extract this underlying translated SQL statement showing the aggregate transformations performed on calculated fields?

I've been trying to search for this using the key term "calculation metadata" but have found no results. Either I'm using the incorrect term to search for the information I want, or what I'm looking to do is not feasible.

Body:
I don't know if I'm using the right key terms in my question. My use-case here is as follows: I'm creating DataFrames in pyspark, and I'd love to be able to automate the documentation on how fields are calculated.

For Example:

from pyspark.sql import functions as f

df = spark.createDataFrame(
    [
        (1, "foo"),
        (2, "bar"),
    ],
    ["id", "label"]
)

df = df.withColumn('calc', f.col("id") + f.lit(1))
df = df.withColumn('calc', f.when(f.col('calc') > 1, 1).otherwise(0))

I've created a super simple DataFrame here with columns "id" and "label", and added the calculated field "calc" based on a condition on the "id" field.

My understanding of Spark is that the calculations of the new field "calc" are cached and will be translated into a Spark SQL statement at time of execution when a function like show() or collect() are performed. I know this because when encountering errors using pyspark, the error message will show a SQL statement representing the field of issue, even if it was generated using pyspark syntax.

Is there a way for me to extract this underlying translated SQL statement showing the aggregate transformations performed on calculated fields?

I've been trying to search for this using the key term "calculation metadata" but have found no results. Either I'm using the incorrect term to search for the information I want, or what I'm looking to do is not feasible.


问:
** File 'ae.sty' not found** error when compiling PDF for sweave (.rnw) file on RStudio - docker image amoselb/rstudio-m1 running on Mac-M1-Silicon

Problem Statement

Am learning LaTex by running it on RStudio created from a Docker Image (amoselb/rstudio-m1)on my Macbook M1-Silicon

Is this a new issue:

I have seen a couple similar issues on stackoverflow and have tried the solutions -- they did not work

Is this unique to Mac-M1-Silicon?:

I believe this is the case and the reason why I am using the image: amoselb/rstudio-m1

Sweave Settings on RStudio:

Weave Rnew files using 'Sweave'
Typeset LaTex into PDF using: pdfLaTex

System

```<code>Macbook M1 Pro
macOS: Ventura
</code>```

Sample file

```<code>\documentclass{article}

\begin{document}
\usepackage{ae}

\SweaveOpts{concordance=TRUE}

First document. This is a simple example, with no
extra parameters or packages included.
\end{document
</code>```

Action

Compile

Error

Line 30 LaTex Error: File 'ae.sty' not found

Current Status

Tried installing package 'ae' with

```<code>install.packages('ae')
</code>```

also tried

```<code>packages <- function(pkg){
  new.pkg <- pkg[!(pkg %in% installed.packages()[, "Package"])]
  if (length(new.pkg))
    install.packages(new.pkg, dependencies = TRUE, repos='https://cran.rstudio.com/')
  sapply(pkg, require, character.only = TRUE)
}

packages(c("ae"))

</code>```

Error (when installing package 'ae')

```<code>Installing package into '/home/rstudio/R/aarch64-unknown-linux-gnu-library/4.0'
(as 'lib' is unspecified)
Warning in install.packages :
  package 'ae' is not available for this version of R

</code>```

Body:
Problem Statement

Am learning LaTex by running it on RStudio created from a Docker Image (amoselb/rstudio-m1)on my Macbook M1-Silicon

Is this a new issue:

I have seen a couple similar issues on stackoverflow and have tried the solutions -- they did not work

Is this unique to Mac-M1-Silicon?:

I believe this is the case and the reason why I am using the image: amoselb/rstudio-m1

Sweave Settings on RStudio:

Weave Rnew files using 'Sweave'
Typeset LaTex into PDF using: pdfLaTex

System

Macbook M1 Pro
macOS: Ventura

Sample file

\documentclass{article}

\begin{document}
\usepackage{ae}

\SweaveOpts{concordance=TRUE}

First document. This is a simple example, with no
extra parameters or packages included.
\end{document

Action

Compile

Error

Line 30 LaTex Error: File 'ae.sty' not found

Current Status

Tried installing package 'ae' with

install.packages('ae')

also tried

packages <- function(pkg){
  new.pkg <- pkg[!(pkg %in% installed.packages()[, "Package"])]
  if (length(new.pkg))
    install.packages(new.pkg, dependencies = TRUE, repos='https://cran.rstudio.com/')
  sapply(pkg, require, character.only = TRUE)
}

packages(c("ae"))

Error (when installing package 'ae')

Installing package into '/home/rstudio/R/aarch64-unknown-linux-gnu-library/4.0'
(as 'lib' is unspecified)
Warning in install.packages :
  package 'ae' is not available for this version of R


问:
How can I output ONLY the code from one open tab in VS Code?
I'm very new to VS Code and since I'm learning coding (Python), I use it to test code when trying to solve challenges/puzzles from various websites.
So for that, I like to have several tabs open to try out different things rather than constantly comment in/out code on a single tab.
However, the annoying this is, when I run the code, VS Code will output the code from ALL those open tabs which can be really confusing and messy.
Is there a way to have it ONLY output code from the current open tab I'm working on?
Thx!

As an alternative, I know I can just hit 'Run Python File' (since that's what each tab is in effect) and only that then gets sent to the terminal but I prefer and was hoping to have it sent to 'Output' as that's the I have it set it up so the code comes out looking 'clean' that way.


问:
Convert htaccess to nginx.conf
Hi i have to convert this into nginx.conf directives, but something doesn't work:

```<code><IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
    Options -MultiViews -Indexes
</IfModule>

RewriteEngine On

# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]

# Send Requests To Front Controller...
RewriteCond %{REQUEST_URI} !(\.css|\.js|\.png|\.jpg|\.jpeg|\.gif|robots\.txt|\.ico|\.woff|\.woff2|.ttf|\.svg)$ [NC]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !^/public/
RewriteRule ^(css|assets|landing|storage|installer|js|custom)/(.*)$ public/$1/$2 [L,NC]
</code>```

This is my last try (nginx.conf translated):

```<code>autoindex off;

location ~*
(\.css|\.js|\.png|\.jpg|\.jpeg|\.gif|robots\.txt|\.ico|\.woff|\.woff2|.ttf|\.svg)$ {
}

location ~ /public/ {
}

location / {
    if (!-e $request_filename){
        rewrite ^(.*)$ /%1 redirect;
    }
    if (!-e $request_filename){
        rewrite ^(.*)$ /index.php break;
    }
    if (!-e $request_filename){
        rewrite ^/(css|assets|landing|storage|installer|js|custom)/(.*)$ /public/$1/$2 break;
    }
}
</code>```

But this way i get a loop error on my website..

I have also another .htaccess file placed in another folder and it is this:

```<code><IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
    Options -MultiViews -Indexes
</IfModule>

RewriteEngine On

# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]

# Send Requests To Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>
</code>```

But the problem is still there

Title: Convert htaccess to nginx.conf

Body:
Hi i have to convert this into nginx.conf directives, but something doesn't work:

<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
    Options -MultiViews -Indexes
</IfModule>

RewriteEngine On

# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]

# Send Requests To Front Controller...
RewriteCond %{REQUEST_URI} !(\.css|\.js|\.png|\.jpg|\.jpeg|\.gif|robots\.txt|\.ico|\.woff|\.woff2|.ttf|\.svg)$ [NC]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !^/public/
RewriteRule ^(css|assets|landing|storage|installer|js|custom)/(.*)$ public/$1/$2 [L,NC]

This is my last try (nginx.conf translated):

autoindex off;

location ~*
(\.css|\.js|\.png|\.jpg|\.jpeg|\.gif|robots\.txt|\.ico|\.woff|\.woff2|.ttf|\.svg)$ {
}

location ~ /public/ {
}

location / {
    if (!-e $request_filename){
        rewrite ^(.*)$ /%1 redirect;
    }
    if (!-e $request_filename){
        rewrite ^(.*)$ /index.php break;
    }
    if (!-e $request_filename){
        rewrite ^/(css|assets|landing|storage|installer|js|custom)/(.*)$ /public/$1/$2 break;
    }
}

But this way i get a loop error on my website..

I have also another .htaccess file placed in another folder and it is this:

<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
    Options -MultiViews -Indexes
</IfModule>

RewriteEngine On

# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]

# Send Requests To Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>

But the problem is still there


问:
how to get EditText cursor pos x and y in the screen ? in Android
i'm searching a way to get the x and y locations of Cursor position of EditText in the whole Screen. so i can show PopupWindow at that location

to get the x and y in the layout of EditText i'm using the bellow code, But when i call show window at this location x and y, the window apears to far in another side, i want to understand what i'm missing and thanks in advance

```<code>Layout layout = editText.getLayout();

            int start = editText.getSelectionStart();

            int line = layout.getLineForOffset(start);

            float y = layout.getLineTop(line) + editText.getPaddingTop();

            float x = layout.getPrimaryHorizontal(start) + editText.getPaddingLeft();

            PopupWindow window = new PopupWindow(this);

            LayoutInflater inflater = (LayoutInflater) getApplicationContext()
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            View view = inflater.inflate(R.layout.test, null);

            window.setContentView(view);

            window.showAtLocation(editText, Gravity.TOP | Gravity.LEFT, (int) x, (int) y);
</code>```

Body:
i'm searching a way to get the x and y locations of Cursor position of EditText in the whole Screen. so i can show PopupWindow at that location

to get the x and y in the layout of EditText i'm using the bellow code, But when i call show window at this location x and y, the window apears to far in another side, i want to understand what i'm missing and thanks in advance

Layout layout = editText.getLayout();

            int start = editText.getSelectionStart();

            int line = layout.getLineForOffset(start);

            float y = layout.getLineTop(line) + editText.getPaddingTop();

            float x = layout.getPrimaryHorizontal(start) + editText.getPaddingLeft();

            PopupWindow window = new PopupWindow(this);

            LayoutInflater inflater = (LayoutInflater) getApplicationContext()
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            View view = inflater.inflate(R.layout.test, null);

            window.setContentView(view);

            window.showAtLocation(editText, Gravity.TOP | Gravity.LEFT, (int) x, (int) y);


问:
WebdriverIO javascript not java : Neither ANDROID_HOME nor ANDROID_SDK_ROOT environment variable was exported
I'm trying to automate app in android emulator but I'm always getting this WebDriverio , I don't know how to handle it ,

I know how to control this error in java using hash map and passing that env to appium service builder but I'm relatively new to javascript.

could some one please help me on how to resolve the below error :

[0-0] 2023-01-07T17:52:20.007Z WARN webdriver: Request failed with status 500 due to An unknown server-side error occurred while processing the command. Original error: Neither ANDROID_HOME nor ANDROID_SDK_ROOT environment variable was exported.

automate app in android emulator using appium javascript/webdriverio


问:
there is no option of Team Explorer menu in my visual code studio how can I get that option
actually happened that I select all my file in source control by mistake and then I am not able to deselect
it was showing your file are pending to edit, or something like that. Then I come back to desktop page.
and again I open VS code and my all files are disappear. and also disappear from my machine also. Now I want my all files back. what can I do next??

I tried to find my file but I not able to found. and I also try to find team explorer but also it is
not showing and I am expecting that your team will help me and I will get my files back..


问:
RShiny deployed app not showing updated data
I have deployed a R Shiny app on R studio connect server. In the app, I am picking up 6 files from Azure BLOB, and then convert it into respective RDS file. I then convert it into dataframes for accessing values from that file.

The file coming from BLOB gets updated when user changes it, I have scheduled a cron job(which runs every minute) for detecting the updated file.

Problem is although the cron job is working totally fine and the data in the backend's RDS file is getting updated the moment the BLOB file gets updated, but the R Shiny dashboard takes almost a day(roughly 10 hours) to update to current updated values.

This is a problem and it should refresh/update in a minute or so.

I tried storing the RDS into a database rather than locally but that didn't help too.


问:
How to block a request in an asynchrounous way inside a Firefox add-on?
I'm working on a minimal dyi ad-blocker in a form of a firefox add-on.
This is a project for my courses, so I need to be quite specific on a solution.
The solution goes like this:

Catch every request

Stop it for a while

Do analysis of the URL (simply checking some aspects of the URL using regex)

Do analysis of the response (fetch the response, and again using regex, find certain aspects in the URL's response)

Console.log everything

Block the request

The issue I'm having is that the browser.webRequest.filterResponseData I'm using to check the URL's response data is asynchronous. I've been playing around with everything, but nothing worked.

This is the current code I have:

Manifest.json file:

```<code>{
    "description": "Adblock by Morty",
    "manifest_version": 2,
    "name": "MJ Custom Adblock",
    "version": "1.0",
    "icons": {
        "48": "pen.svg"
    },
    "permissions":[
        "webRequest", "webRequestBlocking", "<all_urls>"
    ],
    "background":{
        "scripts": ["blocked_domains.js", "background.js"]
    },
    "browser_specific_settings": {
        "gecko": {
          "strict_min_version": "57.0a1"
        }
    }
}
</code>```

background.js

```<code>let cancelRequest = false;

function listener(details) {
  //console.log(details.requestId);
  let filter = browser.webRequest.filterResponseData(details.requestId);
  filter.onstart = (event) => {
    console.log("started");
  };
  filter.ondata = (event) => {
    console.log("hi");
    console.log(event.data);
    filter.write(event.data);
  };
  filter.onstop = (event) => {
    console.log("stopped");
    cancelRequest = true;
    filter.disconnect();
  };
  filter.onerror = (event) => {
    console.log("some error happened");
  };
  return new Promise((resolve) => {
    const interval = setInterval(() => {
      if (cancelRequest) {
        clearInterval(interval);
        resolve({cancel: true});
      }
    }, 500);
  });
}

browser.webRequest.onBeforeRequest.addListener(
  listener,
  {urls: blocked_domains},
  ["blocking"]
</code>```

The blocked domain array is held inside "blocked_domains.js" as it has around 57000 urls.

I've just started so I haven't implemented the analysis yet, what I'm trying to do now is to only return the cancel after the filter's events have finished.

background.js you're seeing there is the latest iteration of it where I tried to implement a promise that waits for a value to be set to true before returning anything. I chose this solution as I don't care about the speed, all I need is the results, I can wait for 30 minutes if I need to.

The issue with the solution provided above is that if I have that return Promise there, none of the filter's functions work (none of the console logs are logged). If the promise is not there and I don't block the request I get all the needed console logs.

I can clearly see that this is purely the async things happening that are breaking everything, yet I can't find a proper solution to solve this. I've tried returning the {cancel:true} inside filter.onstop, Postponing the returning for a while, runnning the whole
webRequest.onBeforeRequest listener as an async function, nothing worked.

Any ideas or solutions?

Edit: I found out the the filterResponseData never gets initialized.

Body:
I'm working on a minimal dyi ad-blocker in a form of a firefox add-on.
This is a project for my courses, so I need to be quite specific on a solution.
The solution goes like this:

Catch every request

Stop it for a while

Do analysis of the URL (simply checking some aspects of the URL using regex)

Do analysis of the response (fetch the response, and again using regex, find certain aspects in the URL's response)

Console.log everything

Block the request

The issue I'm having is that the browser.webRequest.filterResponseData I'm using to check the URL's response data is asynchronous. I've been playing around with everything, but nothing worked.

This is the current code I have:

Manifest.json file:

{
    "description": "Adblock by Morty",
    "manifest_version": 2,
    "name": "MJ Custom Adblock",
    "version": "1.0",
    "icons": {
        "48": "pen.svg"
    },
    "permissions":[
        "webRequest", "webRequestBlocking", "<all_urls>"
    ],
    "background":{
        "scripts": ["blocked_domains.js", "background.js"]
    },
    "browser_specific_settings": {
        "gecko": {
          "strict_min_version": "57.0a1"
        }
    }
}

background.js

let cancelRequest = false;

function listener(details) {
  //console.log(details.requestId);
  let filter = browser.webRequest.filterResponseData(details.requestId);
  filter.onstart = (event) => {
    console.log("started");
  };
  filter.ondata = (event) => {
    console.log("hi");
    console.log(event.data);
    filter.write(event.data);
  };
  filter.onstop = (event) => {
    console.log("stopped");
    cancelRequest = true;
    filter.disconnect();
  };
  filter.onerror = (event) => {
    console.log("some error happened");
  };
  return new Promise((resolve) => {
    const interval = setInterval(() => {
      if (cancelRequest) {
        clearInterval(interval);
        resolve({cancel: true});
      }
    }, 500);
  });
}

browser.webRequest.onBeforeRequest.addListener(
  listener,
  {urls: blocked_domains},
  ["blocking"]

The blocked domain array is held inside "blocked_domains.js" as it has around 57000 urls.

I've just started so I haven't implemented the analysis yet, what I'm trying to do now is to only return the cancel after the filter's events have finished.

background.js you're seeing there is the latest iteration of it where I tried to implement a promise that waits for a value to be set to true before returning anything. I chose this solution as I don't care about the speed, all I need is the results, I can wait for 30 minutes if I need to.

The issue with the solution provided above is that if I have that return Promise there, none of the filter's functions work (none of the console logs are logged). If the promise is not there and I don't block the request I get all the needed console logs.

I can clearly see that this is purely the async things happening that are breaking everything, yet I can't find a proper solution to solve this. I've tried returning the {cancel:true} inside filter.onstop, Postponing the returning for a while, runnning the whole
webRequest.onBeforeRequest listener as an async function, nothing worked.

Any ideas or solutions?

Edit: I found out the the filterResponseData never gets initialized.


问:
Getting 401 Unauthorized when using browser
I am creating SPA with Nest.js and React.js and wanted to use passport JWT authentication but run into a problem.
After successful login in browser, 401 Error occurs while trying to access routes protected by JwtAuthGuard, like adding new article or logging out.
When trying to add new article or log out after successful login using Insomnia, everything works as intended.
Why authentication only works when using Insomnia?
Do I need to authorize React using cors and provide credentials?

jwt.strategy.ts:

```<code>import { ExtractJwt, Strategy } from "passport-jwt";
import { PassportStrategy } from "@nestjs/passport";
import { Injectable, UnauthorizedException } from "@nestjs/common";
import { UserEntity } from "src/user/entities/user.entity";

export interface JwtPayload {
  id: string;
}

function cookieExtractor(req: any): null | string {
  return (req && req.cookies) ? (req.cookies?.jwt ?? null) : null
}

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor() {
    super({
      jwtFromRequest: cookieExtractor,
      secretOrKey: process.env.SECRET_OR_KEY,
    });
  }

  async validate(payload: JwtPayload, done: (error: Error, user: UserEntity | boolean) => void) {
    if (!payload || !payload.id) {
      return done(new UnauthorizedException(), false);
    }
    const user = await UserEntity.findOne({where: {
      currentTokenId: payload.id,
    }});
    if (!user) {
      return done(new UnauthorizedException(), false)
    }
    done(null, user);
  }
}
</code>```

I've tried changing jwtFromRequest from cookieExtractor to ExtractJwt.fromAuthHeaderAsBearerToken(), but no results.

Body:
I am creating SPA with Nest.js and React.js and wanted to use passport JWT authentication but run into a problem.
After successful login in browser, 401 Error occurs while trying to access routes protected by JwtAuthGuard, like adding new article or logging out.
When trying to add new article or log out after successful login using Insomnia, everything works as intended.
Why authentication only works when using Insomnia?
Do I need to authorize React using cors and provide credentials?

jwt.strategy.ts:

import { ExtractJwt, Strategy } from "passport-jwt";
import { PassportStrategy } from "@nestjs/passport";
import { Injectable, UnauthorizedException } from "@nestjs/common";
import { UserEntity } from "src/user/entities/user.entity";

export interface JwtPayload {
  id: string;
}

function cookieExtractor(req: any): null | string {
  return (req && req.cookies) ? (req.cookies?.jwt ?? null) : null
}

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor() {
    super({
      jwtFromRequest: cookieExtractor,
      secretOrKey: process.env.SECRET_OR_KEY,
    });
  }

  async validate(payload: JwtPayload, done: (error: Error, user: UserEntity | boolean) => void) {
    if (!payload || !payload.id) {
      return done(new UnauthorizedException(), false);
    }
    const user = await UserEntity.findOne({where: {
      currentTokenId: payload.id,
    }});
    if (!user) {
      return done(new UnauthorizedException(), false)
    }
    done(null, user);
  }
}

I've tried changing jwtFromRequest from cookieExtractor to ExtractJwt.fromAuthHeaderAsBearerToken(), but no results.


问:
How to capture page links with Selenium?
my code is not capturing all group links

I participate in 120 groups but the code returns only 60

```<code>driver.get("")
driver.maximize_window()
sleep(5)

botao_entrar = driver.find_element(By.LINK_TEXT, "Entrar").click()
sleep(2)
campo_email = driver.find_element(By.XPATH, "//input[@id='m_login_email']").send_keys(email)
sleep(2)
campo_senha = driver.find_element(By.XPATH, "//input[@id='m_login_password']").send_keys(senha, Keys.ENTER)
sleep(50)
###################################################################################################

links = []

for i in range(8):
        print("Rolar Pagina")
        driver.execute_script("window.scrollBy(0, 400)")
        sleep(1)

#grupos = driver.find_elements(By.XPATH, "//*[@id='root']/table/tbody/tr/td/div[2]/ul/li/table/tbody/tr/td/a")
grupos = driver.find_elements(By.CLASS_NAME, "_7hkg")
for elm in grupos:
        link = elm.get_attribute("href")
        #link = elm.get_attribute("href").replace("m.","")
        print(link)
        links.append(link)
        data = {'URL': links}
        df = pd.DataFrame(data)
        df.to_excel(r"C:\__Imagens e Planilhas Python\Facebook\LinksGrupo.xlsx", engine='xlsxwriter')
        print(df)
</code>```

I tried to use AbsXpath
CSSLECTOR

and I didn't get all the links on the page

Body:
my code is not capturing all group links

I participate in 120 groups but the code returns only 60

driver.get("")
driver.maximize_window()
sleep(5)

botao_entrar = driver.find_element(By.LINK_TEXT, "Entrar").click()
sleep(2)
campo_email = driver.find_element(By.XPATH, "//input[@id='m_login_email']").send_keys(email)
sleep(2)
campo_senha = driver.find_element(By.XPATH, "//input[@id='m_login_password']").send_keys(senha, Keys.ENTER)
sleep(50)
###################################################################################################

links = []

for i in range(8):
        print("Rolar Pagina")
        driver.execute_script("window.scrollBy(0, 400)")
        sleep(1)

#grupos = driver.find_elements(By.XPATH, "//*[@id='root']/table/tbody/tr/td/div[2]/ul/li/table/tbody/tr/td/a")
grupos = driver.find_elements(By.CLASS_NAME, "_7hkg")
for elm in grupos:
        link = elm.get_attribute("href")
        #link = elm.get_attribute("href").replace("m.","")
        print(link)
        links.append(link)
        data = {'URL': links}
        df = pd.DataFrame(data)
        df.to_excel(r"C:\__Imagens e Planilhas Python\Facebook\LinksGrupo.xlsx", engine='xlsxwriter')
        print(df)

I tried to use AbsXpath
CSSLECTOR

and I didn't get all the links on the page