问:
require is not defined error in es6 export
I am learning to react and right now I am using React and React DOM from CDN instead of the node package.

This is my HTML File:

```<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 rel="preconnect" href="https://fonts.googleapis.com" />
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
    <link
      href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap"
      rel="stylesheet"
    />
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
    <script
      crossorigin
      src="https://unpkg.com/react@18/umd/react.development.js"
    ></script>
    <script
      crossorigin
      src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"
    ></script>
    <link rel="stylesheet" href="index.css" />
  </head>
  <div id="root"></div>
  <body>
    <script type="text/babel" src="index.js"></script>
  </body>
</html>
</code>```

in my index.js I have this code;

import Header from "./Header.js";
import MainComponent from "./MainComponent.js";
import Footer from "./Footer.js";

```<code>function Page() {
  return (
    <>
      <Header />
    </>
  );
}

ReactDOM.render(<Page />, document.getElementById("root"));
</code>```

and in my Header.js I have this as a code:

```<code>function Header() {
  return (
    <header>
      <nav className="nav">
        <img src="./images/logo.png" className="logo"></img>
        <ul className="nav-items">
          <li>Pricing</li>
          <li>About</li>
          <li>Contact</li>
        </ul>
      </nav>
    </header>
  );
}

export default Header;
</code>```

Both Header.js, index.html, and index.js are inside the same folder.

On running the index.html in server, i get this error:

```<code>Uncaught ReferenceError: require is not defined
    at <anonymous>:3:15
    at ive (transformScriptTags.ts:99:10)
    at n (transformScriptTags.ts:173:9)
    at s (transformScriptTags.ts:204:11)
    at t.forEach.e.src.o.onreadystatechange (transformScriptTags.ts:121:9)
</code>```

Can anyone help me, please !!

If anyone is curious, as to why I am doing this in CDN or not in a package or not in npx create react app, I am learning to react and want to learn thoroughly !!

Thank you in advance

Body:
I am learning to react and right now I am using React and React DOM from CDN instead of the node package.

This is my HTML File:

<!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 rel="preconnect" href="https://fonts.googleapis.com" />
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
    <link
      href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap"
      rel="stylesheet"
    />

    <link rel="stylesheet" href="index.css" />

in my index.js I have this code;

import Header from "./Header.js";
import MainComponent from "./MainComponent.js";
import Footer from "./Footer.js";

function Page() {
  return (
    <>

    </>
  );
}

ReactDOM.render(<Page />, document.getElementById("root"));

and in my Header.js I have this as a code:

function Header() {
  return (

Pricing

About

Contact

  );
}

export default Header;

Both Header.js, index.html, and index.js are inside the same folder.

On running the index.html in server, i get this error:

Uncaught ReferenceError: require is not defined
    at <anonymous>:3:15
    at ive (transformScriptTags.ts:99:10)
    at n (transformScriptTags.ts:173:9)
    at s (transformScriptTags.ts:204:11)
    at t.forEach.e.src.o.onreadystatechange (transformScriptTags.ts:121:9)

Can anyone help me, please !!

If anyone is curious, as to why I am doing this in CDN or not in a package or not in npx create react app, I am learning to react and want to learn thoroughly !!

Thank you in advance


来源: stackexchange

问:
How to use mongodbadapteroptions in nextauth
I have found that mongodbadapter in nextauth takes another argument as options like below

```<code>  adapter: MongoDBAdapter(connectDB,{
    collections:{
      Users:""
    }
  })
</code>```

as you can see first one is database connection function and second is options inside it it has collections and inside that it has users and other tables created by nextauth I wanted to know how to use this this is not specified in the nextauth docs. I wanted to know if it can used to define mongodb user schema or model.

and if anyone know how to add custom schema for the user in mongodb please provide the solution i want to add more custom fields in user model thank you

enter image description hereI got to know about this mongodbadapter options from vs code i hovered over the mongodb adapter

ContentLicense: CC BY-SA 4.0

Body:
I have found that mongodbadapter in nextauth takes another argument as options like below

  adapter: MongoDBAdapter(connectDB,{
    collections:{
      Users:""
    }
  })

as you can see first one is database connection function and second is options inside it it has collections and inside that it has users and other tables created by nextauth I wanted to know how to use this this is not specified in the nextauth docs. I wanted to know if it can used to define mongodb user schema or model.

and if anyone know how to add custom schema for the user in mongodb please provide the solution i want to add more custom fields in user model thank you

enter image description hereI got to know about this mongodbadapter options from vs code i hovered over the mongodb adapter


问:
how to convert mongodb Decimal128 to json in rust
i got some data in mongodb like this

```<code>[{"versions": {"version1": {"app": Decimal128(1.1)}}}]
</code>```

i want to convert it to json string in rust,but output like this.

```<code>[{"versions": {"version1": {"app": "$numberDecimalBytes": [10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 62, 48]}}}]
</code>```

how to convert $numberDecimalBytes to a string or float in json output?

this is my code.

```<code>pub fn get_all_versions(db_name: String) -> Result<Json<Vec<Document>>, Status> {
    let db = MongoCLient::init(db_name);
    let version = db.get_all_version();
    let val = version.unwrap();
    Ok(Json(val))
}

pub fn get_all_version(&self) -> Result<Vec<Document>, Error> {
    let cursors = self
        .version_model
        .find(None, None)
        .ok()
        .expect("Error getting list of users");
    let versions = cursors.map(|doc| doc.unwrap()).collect();
    Ok(versions)
}

</code>```

i try to used Decimal128.to_string() to convert a float string, but just output "Decimal128(...)"

Body:
i got some data in mongodb like this

[{"versions": {"version1": {"app": Decimal128(1.1)}}}]

i want to convert it to json string in rust,but output like this.

[{"versions": {"version1": {"app": "$numberDecimalBytes": [10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 62, 48]}}}]

how to convert $numberDecimalBytes to a string or float in json output?

this is my code.

pub fn get_all_versions(db_name: String) -> Result<Json<Vec<Document>>, Status> {
    let db = MongoCLient::init(db_name);
    let version = db.get_all_version();
    let val = version.unwrap();
    Ok(Json(val))
}

pub fn get_all_version(&self) -> Result<Vec<Document>, Error> {
    let cursors = self
        .version_model
        .find(None, None)
        .ok()
        .expect("Error getting list of users");
    let versions = cursors.map(|doc| doc.unwrap()).collect();
    Ok(versions)
}

i try to used Decimal128.to_string() to convert a float string, but just output "Decimal128(...)"


问:
Anyone still using Cocos2dx 3.17.2 in Javascript for Android?
I have an old project in cocos2dx 3.16 javascript version, I needed to upgrade the targetSdkVersion to 31. So I created a new project with cocos2dx 3.17.2 in Javascript, I tried to run the blank project on an android device but it’s showing black screen.
I got these logs:</p>
```<code>cocos2d: fullPathForFilename: No file found at main.js. Possible missing file.
cocos2d: fullPathForFilename: No file found at main.jsc. Possible missing file.
cocos2d: fullPathForFilename: No file found at main.js. Possible missing file.
ScriptingCore:: compileScript fail:main.js
win=Window{b5916f2 u0 Splash Screen com.xx.xxx EXITING} destroySurfaces: appStopped=false cleanupOnResume=false win.mWindowRemovalAllowed=true win.mRemoveOnExit=true win.mViewVisibility=8 caller=com.android.server.wm.WindowState.onExitAnimationDone:5920 com.android.server.wm.ActivityRecord$$ExternalSyntheticLambda11.accept:2 java.util.ArrayList.forEach:1262 com.android.server.wm.ActivityRecord.onAnimationFinished:8436 com.android.server.wm.WindowContainer.doAnimationFinished:3446 com.android.server.wm.WindowContainer.onAnimationFinished:3458 com.android.server.wm.Task.onAnimationFinished:8390
</code>```

Body:
I have an old project in cocos2dx 3.16 javascript version, I needed to upgrade the targetSdkVersion to 31. So I created a new project with cocos2dx 3.17.2 in Javascript, I tried to run the blank project on an android device but it’s showing black screen.
I got these logs:

cocos2d: fullPathForFilename: No file found at main.js. Possible missing file.
cocos2d: fullPathForFilename: No file found at main.jsc. Possible missing file.
cocos2d: fullPathForFilename: No file found at main.js. Possible missing file.
ScriptingCore:: compileScript fail:main.js
win=Window{b5916f2 u0 Splash Screen com.xx.xxx EXITING} destroySurfaces: appStopped=false cleanupOnResume=false win.mWindowRemovalAllowed=true win.mRemoveOnExit=true win.mViewVisibility=8 caller=com.android.server.wm.WindowState.onExitAnimationDone:5920 com.android.server.wm.ActivityRecord$$ExternalSyntheticLambda11.accept:2 java.util.ArrayList.forEach:1262 com.android.server.wm.ActivityRecord.onAnimationFinished:8436 com.android.server.wm.WindowContainer.doAnimationFinished:3446 com.android.server.wm.WindowContainer.onAnimationFinished:3458 com.android.server.wm.Task.onAnimationFinished:8390


问:
dynamically add and remove objects from three.js scene
I would like to generate a 3D matrix of box geometry using Dat GUI slider controls.  I have the forst part working. There are three sliders with range 1-10 in x, y and z directions. I can successfully generate box geometry in all three directions.  Issue is when I want to remove generated boxes using the slider. I can decrease the number in the slider, but the boxes do not remove from the 3D scene.

```<code>//--- script.js ---
import './style.css'
import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'
import * as dat from 'dat.gui'

/**
 * Base
 */
// Canvas
const canvas = document.querySelector('canvas.webgl')

// Cursor
const cursor = {
    x: 0,
    y: 0
}

window.addEventListener('mousemove', (event) =>
{
    cursor.x = event.clientX / sizes.width - 0.5
    cursor.y = - (event.clientY / sizes.height - 0.5)
})

// Scene
const scene = new THREE.Scene()

//cube
var geometry = new THREE.BoxGeometry(.875, .25, .25);
var material = new THREE.MeshBasicMaterial({
  color: 0x00ff00,
  wireframe: false,
});

const gui = new dat.GUI()
// Add sliders to number fields by passing min and max
const myObj = {
    iX: 1,
    kY: 1,
    nZ: 1
};

const myObject = {
    StartOver: function() { location.reload(); },
};

//---reload the webpage---//
gui.add( myObject, 'StartOver' ); // Button

//--slider values 1-10 ---
gui.add(myObj, 'iX', 0, 10, 1).onChange( iX => { genBeams( iX ); });
gui.add(myObj, 'kY', 0, 10, 1).onChange( kY => { genBeams( kY ); });
gui.add(myObj, 'nZ', 0, 10, 1).onChange( nZ => { genBeams( nZ ); });

//---generate 3D matrix of box geometry---
function genBeams(iX, kY, nZ) {
    for (let i = 0; i < myObj.iX; i++) {
        for (let k = 0; k < myObj.kY; k++) {
            for (let n = 0; n < myObj.nZ; n++) {
            var cube = new THREE.Mesh(geometry, material);
            cube.name = "cube_"+iX;
            console.log(cube.name);
            cube.position.x = i;
            cube.position.y = k;
            cube.position.z = n;
            scene.add(cube);
            };
        }
    };
}

const sizes = {
    width: window.innerWidth,
    height: window.innerHeight
}

window.addEventListener('resize', () =>
{
    // Update sizes
    sizes.width = window.innerWidth
    sizes.height = window.innerHeight

    // Update camera
    camera.aspect = sizes.width / sizes.height
    camera.updateProjectionMatrix()

    // Update renderer
    renderer.setSize(sizes.width, sizes.height)
    renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))
})

// Camera
const camera = new THREE.PerspectiveCamera(75, sizes.width / sizes.height, 0.1, 100)
camera.position.z = 10
scene.add(camera)

// Controls
const controls = new OrbitControls(camera, canvas)
controls.enableDamping = true

// Renderer
const renderer = new THREE.WebGLRenderer({
    canvas: canvas
})
renderer.setSize(sizes.width, sizes.height)

  renderer.render(scene, camera);

// Animate
const clock = new THREE.Clock()

const tick = () =>
{
    const elapsedTime = clock.getElapsedTime()

    // Update controls
    controls.update()

    // Render
    renderer.render(scene, camera)

    // Call tick again on the next frame
    window.requestAnimationFrame(tick)
}

tick()
</code>```
```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>my Blocks</title>
</head>
<body>
    <canvas class="webgl"></canvas>
</body>
</html>
</code>```

I have investigated dispose and remove, but an not been successful to implement them.

Body:
I would like to generate a 3D matrix of box geometry using Dat GUI slider controls.  I have the forst part working. There are three sliders with range 1-10 in x, y and z directions. I can successfully generate box geometry in all three directions.  Issue is when I want to remove generated boxes using the slider. I can decrease the number in the slider, but the boxes do not remove from the 3D scene.

//--- script.js ---
import './style.css'
import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'
import * as dat from 'dat.gui'

/**
 * Base
 */
// Canvas
const canvas = document.querySelector('canvas.webgl')

// Cursor
const cursor = {
    x: 0,
    y: 0
}

window.addEventListener('mousemove', (event) =>
{
    cursor.x = event.clientX / sizes.width - 0.5
    cursor.y = - (event.clientY / sizes.height - 0.5)
})

// Scene
const scene = new THREE.Scene()

//cube
var geometry = new THREE.BoxGeometry(.875, .25, .25);
var material = new THREE.MeshBasicMaterial({
  color: 0x00ff00,
  wireframe: false,
});

const gui = new dat.GUI()
// Add sliders to number fields by passing min and max
const myObj = {
    iX: 1,
    kY: 1,
    nZ: 1
};

const myObject = {
    StartOver: function() { location.reload(); },
};

//---reload the webpage---//
gui.add( myObject, 'StartOver' ); // Button

//--slider values 1-10 ---
gui.add(myObj, 'iX', 0, 10, 1).onChange( iX => { genBeams( iX ); });
gui.add(myObj, 'kY', 0, 10, 1).onChange( kY => { genBeams( kY ); });
gui.add(myObj, 'nZ', 0, 10, 1).onChange( nZ => { genBeams( nZ ); });

//---generate 3D matrix of box geometry---
function genBeams(iX, kY, nZ) {
    for (let i = 0; i < myObj.iX; i++) {
        for (let k = 0; k < myObj.kY; k++) {
            for (let n = 0; n < myObj.nZ; n++) {
            var cube = new THREE.Mesh(geometry, material);
            cube.name = "cube_"+iX;
            console.log(cube.name);
            cube.position.x = i;
            cube.position.y = k;
            cube.position.z = n;
            scene.add(cube);
            };
        }
    };
}

const sizes = {
    width: window.innerWidth,
    height: window.innerHeight
}

window.addEventListener('resize', () =>
{
    // Update sizes
    sizes.width = window.innerWidth
    sizes.height = window.innerHeight

    // Update camera
    camera.aspect = sizes.width / sizes.height
    camera.updateProjectionMatrix()

    // Update renderer
    renderer.setSize(sizes.width, sizes.height)
    renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))
})

// Camera
const camera = new THREE.PerspectiveCamera(75, sizes.width / sizes.height, 0.1, 100)
camera.position.z = 10
scene.add(camera)

// Controls
const controls = new OrbitControls(camera, canvas)
controls.enableDamping = true

// Renderer
const renderer = new THREE.WebGLRenderer({
    canvas: canvas
})
renderer.setSize(sizes.width, sizes.height)

  renderer.render(scene, camera);

// Animate
const clock = new THREE.Clock()

const tick = () =>
{
    const elapsedTime = clock.getElapsedTime()

    // Update controls
    controls.update()

    // Render
    renderer.render(scene, camera)

    // Call tick again on the next frame
    window.requestAnimationFrame(tick)
}

tick()

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>my Blocks</title>

    <canvas class="webgl"></canvas>

I have investigated dispose and remove, but an not been successful to implement them.


问:
Android: Http request fails in wifi connection
I have an issue with HTTPS requests. I do not know why? But I have been observing that in the same wifi(mobile hotspot) youtube and Instagram loads very well. But in my app, I have tried Picasso, Glide, OkHttp, HttpURLConnection, etc. These all take time to get a response. I have a list of 20 image URLs all are CDN(if I open these URLs in the browser it takes max 40ms or less, if the internet connection is very slow then takes 1-2sec). When I connect to another mobile hotspot Picasso, Glide, OkHttp, and HttpURLConnection take a lot of time, which means more than 20 sec,  after 20 sec the mobile data speed suddenly goes up to Mbps and it loads all the images but at the same time, Instagram & youtube maintain the consistent internet connection and my main issue is, why the first response takes time? but at the same time, Instagram & youtube works very well.

ERROR

```<code> class com.bumptech.glide.load.engine.GlideException: Failed to load resource
    There was 1 root cause:
    com.bumptech.glide.load.HttpException(Failed to connect or obtain data, status code: -1)
     call GlideException#logRootCauses(String) for more detail
      Cause (1 of 1): class com.bumptech.glide.load.engine.GlideException: Fetching data failed, class java.io.InputStream, REMOTE
    There was 1 root cause:
    com.bumptech.glide.load.HttpException(Failed to connect or obtain data, status code: -1)
     call GlideException#logRootCauses(String) for more detail
        Cause (1 of 1): class com.bumptech.glide.load.engine.GlideException: Fetch failed
    There was 1 root cause:
    com.bumptech.glide.load.HttpException(Failed to connect or obtain data, status code: -1)
     call GlideException#logRootCauses(String) for more detail
          Cause (1 of 1): class com.bumptech.glide.load.HttpException: Failed to connect or obtain data, status code: -1
</code>```

Yes I'm getting the issue when I connect to that specific mobile hotspot. When I connect to other hotspots it works well. But I have a doubt How do Instagram & youtube manage to achieve good speed?

Are there any techniques to force hardware or any kind of different code they are using?

Body:
I have an issue with HTTPS requests. I do not know why? But I have been observing that in the same wifi(mobile hotspot) youtube and Instagram loads very well. But in my app, I have tried Picasso, Glide, OkHttp, HttpURLConnection, etc. These all take time to get a response. I have a list of 20 image URLs all are CDN(if I open these URLs in the browser it takes max 40ms or less, if the internet connection is very slow then takes 1-2sec). When I connect to another mobile hotspot Picasso, Glide, OkHttp, and HttpURLConnection take a lot of time, which means more than 20 sec,  after 20 sec the mobile data speed suddenly goes up to Mbps and it loads all the images but at the same time, Instagram & youtube maintain the consistent internet connection and my main issue is, why the first response takes time? but at the same time, Instagram & youtube works very well.

ERROR

 class com.bumptech.glide.load.engine.GlideException: Failed to load resource
    There was 1 root cause:
    com.bumptech.glide.load.HttpException(Failed to connect or obtain data, status code: -1)
     call GlideException#logRootCauses(String) for more detail
      Cause (1 of 1): class com.bumptech.glide.load.engine.GlideException: Fetching data failed, class java.io.InputStream, REMOTE
    There was 1 root cause:
    com.bumptech.glide.load.HttpException(Failed to connect or obtain data, status code: -1)
     call GlideException#logRootCauses(String) for more detail
        Cause (1 of 1): class com.bumptech.glide.load.engine.GlideException: Fetch failed
    There was 1 root cause:
    com.bumptech.glide.load.HttpException(Failed to connect or obtain data, status code: -1)
     call GlideException#logRootCauses(String) for more detail
          Cause (1 of 1): class com.bumptech.glide.load.HttpException: Failed to connect or obtain data, status code: -1

Yes I'm getting the issue when I connect to that specific mobile hotspot. When I connect to other hotspots it works well. But I have a doubt How do Instagram & youtube manage to achieve good speed?

Are there any techniques to force hardware or any kind of different code they are using?


问:
Using cloudprnt with python with mc-print3
Does anyone know how to use cloudprnt with python on a mc-print3 receipt printer? Unfortunately, StarTSP's support wasn't able to help or provide any tutorials.</p>


问:
Will x more future data be used to predict more past data in LightGBM's future projections?
Does more future data in X or y affect more past forecasts when forecasting with LightGBM time series data?

I understand that when the data is divided into windows like LSTM, the future data somehow does not affect the past. However, I am concerned that the future data may have more influence on the past data when inputting a single time series data including moving averages, such as LightGBM.

I am also concerned that the future data may have more influence on the past forecast when making a forecast during testing.

The reason is that when performing real-time forecasting of time-series data, the same preprocessing is performed, but the forecasting accuracy is lower, and the only difference here is that only y[-1] is collected at each real-time time interval, rather than using all of the forecasted y to produce accuracy.

So I thought that more past forecasts would be more accurate when looking at y alone because they are influenced by more future data, and that collecting a lot of y[-1] with no future data and averaging them together would result in less accuracy.

I would like to know the correct way to learn time series data that can be applied to this kind of real-time forecasting.

Also, how long should the time series be for real-time forecasting?

Thank you in advance, experts.

Since it is not reliable to predict by putting X together in predict, we added the time series data one row at a time and evaluated the accuracy by aggregating the results only for y[-1] of the y output after the predictions were made.

The batch prediction yielded an accuracy of 88%, but the one-by-one prediction yielded an accuracy of 49%.

The size of X was tried for all time series data up to that point, 8192, 4096, 1024, etc., but there was no significant difference.


问:
Mongodb size limit
I'm new to mongo db. I want to use mongo db in my local server. Mongo db documentation says that maximum document size is 16 MB. If i'm going to use mongodb for long term project how i overcome that problem. Is it means total database can only store 16mb or is something else? please explain.
(p.s: I'm using express js with node js for my backend.)

I want to know about limitations of mongodb. and also know about what are the alternatives best for my web projects runs on local server.

Title: Mongodb size limit


问:
Bot won't register user reactions
So I have been trying to add a new command to a discord bot of mine and so far it's all working aside from trying to register when a user has reacted to a message. From what I can tell, the user field in the filter variable is null and undefined which makes it fail all the checks is my guess, but I don't know how I can change or fix that. The time out message I have works every time and messages in the channel

```<code>module.exports = {
    data: new SlashCommandBuilder()
    .setName('chess')
    .setDescription('Starts a game of chess with a specified user')

    .addUserOption(option => option.setName("user")
        .setDescription("User to play")
        .setRequired(true)),

    async execute(interaction)
    {
        interaction.deferReply();
        interaction.deleteReply();

        let username = `${interaction.options.getUser('user')}`
        const message = await interaction.channel.send(`${interaction.user} challenges ` + username)
        message.react('✅').then(() => message.react('❌'))

        const filter = (reaction, user) => {
            return ['✅', '❌'].includes(reaction.emoji.name) && user.id === interaction.options.getUser('user')
        };
        message.awaitReactions({ filter, max: 1, time: 40000, errors: ['time'] })
            .then(collected => {
                const reaction = collected.first()

                if (reaction.emoji.name === '✅')
                    interaction.channel.send(username + ' accepted.')

                else
                    interaction.channel.send(username + ' declined.')

            })
            .catch(() => {
                interaction.channel.send(username + ' has not responded and has timed out.')
            });
    }
}
</code>```

Title: Bot won't register user reactions

Body:
So I have been trying to add a new command to a discord bot of mine and so far it's all working aside from trying to register when a user has reacted to a message. From what I can tell, the user field in the filter variable is null and undefined which makes it fail all the checks is my guess, but I don't know how I can change or fix that. The time out message I have works every time and messages in the channel

module.exports = {
    data: new SlashCommandBuilder()
    .setName('chess')
    .setDescription('Starts a game of chess with a specified user')

    .addUserOption(option => option.setName("user")
        .setDescription("User to play")
        .setRequired(true)),

    async execute(interaction)
    {
        interaction.deferReply();
        interaction.deleteReply();

        let username = `${interaction.options.getUser('user')}`
        const message = await interaction.channel.send(`${interaction.user} challenges ` + username)
        message.react('✅').then(() => message.react('❌'))

        const filter = (reaction, user) => {
            return ['✅', '❌'].includes(reaction.emoji.name) && user.id === interaction.options.getUser('user')
        };
        message.awaitReactions({ filter, max: 1, time: 40000, errors: ['time'] })
            .then(collected => {
                const reaction = collected.first()

                if (reaction.emoji.name === '✅')
                    interaction.channel.send(username + ' accepted.')

                else
                    interaction.channel.send(username + ' declined.')

            })
            .catch(() => {
                interaction.channel.send(username + ' has not responded and has timed out.')
            });
    }
}


问:
error 'SOAP-ERROR: Parsing WSDL: Could not find any usable binding services in WSDL.' connecting to SOAP client with PHP
i am connecting to a service that has no documentation available.  the URL is https://data.tga.gov.au/ARTGSearch/ARTGWebService.svc

i am trying to connect to this service using php 7.4. i have got the SOAP extension installed.

after hunting around SO, my connection code is:

```<code>  public function go()
  {
    $opts = [
      'http' => [
        'user_agent' => 'PHPSoapClient'
      ],
    ];
    $context = stream_context_create($opts);
    $wsdlUrl = 'http://data.tga.gov.au/ARTGSearch/ARTGWebService.svc?wsdl';
    $soapClientOptions = array(
      'stream_context' => $context,
      'cache_wsdl' => WSDL_CACHE_NONE
    );
    $client = new SoapClient($wsdlUrl, $soapClientOptions);
    $params              = [];
    $params['pagestart'] = 1;
    $params['pageend']   = 2;
    $params['entrytype'] = 'medicine';
    $out = $client->ARTGSearchJson($params);
    var_dump($out);
  }

</code>```

looking at the output of http://data.tga.gov.au/ARTGSearch/ARTGWebService.svc?wsdl it does seem legitimate, i can certainly see the method that i want to use.

i am not familiar with SOAP clients - does anyone have any ideas how i can use the service to use the ARTGSearchJson method?
(the vendors are not able to provide any documentation)

Body:
i am connecting to a service that has no documentation available.  the URL is https://data.tga.gov.au/ARTGSearch/ARTGWebService.svc

i am trying to connect to this service using php 7.4. i have got the SOAP extension installed.

after hunting around SO, my connection code is:

  public function go()
  {
    $opts = [
      'http' => [
        'user_agent' => 'PHPSoapClient'
      ],
    ];
    $context = stream_context_create($opts);
    $wsdlUrl = 'http://data.tga.gov.au/ARTGSearch/ARTGWebService.svc?wsdl';
    $soapClientOptions = array(
      'stream_context' => $context,
      'cache_wsdl' => WSDL_CACHE_NONE
    );
    $client = new SoapClient($wsdlUrl, $soapClientOptions);
    $params              = [];
    $params['pagestart'] = 1;
    $params['pageend']   = 2;
    $params['entrytype'] = 'medicine';
    $out = $client->ARTGSearchJson($params);
    var_dump($out);
  }

looking at the output of http://data.tga.gov.au/ARTGSearch/ARTGWebService.svc?wsdl it does seem legitimate, i can certainly see the method that i want to use.

i am not familiar with SOAP clients - does anyone have any ideas how i can use the service to use the ARTGSearchJson method?
(the vendors are not able to provide any documentation)


问:
How to use gestureListener kotlin
i am trying to create a video player app using kotlin , now in player activity i am trying to use gesture listner but problem is i use a java class to use gesture listener , but in java onTouchListerner function
gesture listener class work somthly but in kotlin i dont know how to imple ment this class please help me

OnSwifelistener.java

```<code>import android.content.Context;
import android.graphics.Rect;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;

import androidx.core.view.GestureDetectorCompat;

public abstract class OnSwipeTouchListener implements View.OnTouchListener {

    private final GestureDetectorCompat gestureDetector;
    private final GestureListener gestureListener;

    protected OnSwipeTouchListener(Context context){
        gestureListener = new GestureListener();
        gestureDetector = new GestureDetectorCompat(context, gestureListener);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        gestureListener.onTouchEvent(event);
        return true;
    }
    public boolean onSwipeRight() {
        return false;
    }
    public boolean onSwipeLeft() {
        return false;
    }

    public boolean onSwipeTop() {
        return false;
    }

    public boolean onSwipeBottom() {
        return false;
    }

    public boolean onDoubleTap() {
        return false;
    }

    public boolean onSingleTap() {
        return true;
    }
    public abstract void onGestureDone();
    public abstract void adjustBrightness(double adjustPercent);
    public abstract void adjustVolumeLevel(double adjustPercent);
    public abstract void adjustVideoPosition(double adjustPercent, boolean forwardDirection);
    public abstract Rect viewRect();

    private enum SwipeEventType {
        NONE,
        BRIGHTNESS,
        VOLUME,
        SEEK,
        COMMENTS,
        DESCRIPTION
    }

    private final class GestureListener extends GestureDetector.SimpleOnGestureListener {

        private static final int SWIPE_THRESHOLD = 50;
        private SwipeEventType swipeEventType = SwipeEventType.NONE;
        private MotionEvent startEvent;

        @Override
        public boolean onDoubleTap(MotionEvent e) {
            return OnSwipeTouchListener.this.onDoubleTap();
        }

        @Override
        public boolean onSingleTapConfirmed(MotionEvent e) {
            return onSingleTap();
        }

        @Override
        public boolean onScroll(MotionEvent start, MotionEvent end,
                                float distanceX, float distanceY) {
            // function depends on start position. (volume or brightness or play position.)
            double yDistance = end.getY() - start.getY();
            double xDistance = end.getX() - start.getX();

            if (swipeEventType == SwipeEventType.COMMENTS) {
                return onSwipeLeft();
            } else if (swipeEventType == SwipeEventType.DESCRIPTION) {
                return onSwipeTop();
            } else if (swipeEventType == SwipeEventType.BRIGHTNESS) {
                // use half of BrightnessRect's height to calculate percent.
                double percent = yDistance / (getBrightnessRect().height() / 2.0f) * -1.0f;
                adjustBrightness(percent);
            } else if (swipeEventType == SwipeEventType.VOLUME) {
                // use half of volumeRect's height to calculate percent.
                double percent = yDistance / (getVolumeRect().height() / 2.0f) * -1.0f;
                adjustVolumeLevel(percent);
            } else if (swipeEventType == SwipeEventType.SEEK) {
                double percent = xDistance / viewRect().width();
                adjustVideoPosition(percent, distanceX < 0);
            }

            return true;
        }

        private boolean isEventValid(MotionEvent event) {
            // this gesture just worked on single pointer.
            return event.getPointerCount() == 1;
        }

        private void onTouchEvent(MotionEvent event) {
            if (isEventValid(event)) {
                // decide which process is needed.
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        startEvent = MotionEvent.obtain(event);
                        break;
                    case MotionEvent.ACTION_MOVE:
                        if (swipeEventType == SwipeEventType.NONE && startEvent != null) {
                            swipeEventType = whatTypeIsIt(startEvent, event);
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                        onGestureDone();
                        swipeEventType = SwipeEventType.NONE;
                        startEvent = null;
                        break;
                    default:
                        break;
                }
            }

            gestureDetector.onTouchEvent(event);
        }

        /**
         * Ok, swipe detected. What did user want? Let's find out
         */
        private SwipeEventType whatTypeIsIt(MotionEvent startEvent, MotionEvent currentEvent) {
            float startX = startEvent.getX();
            float startY = startEvent.getY();
            float currentX = currentEvent.getX();
            float currentY = currentEvent.getY();
            float diffY = startY - currentY;
            float diffX = startX - currentX;

            if (Math.abs(currentX - startX) >= SWIPE_THRESHOLD && Math.abs(currentX - startX) > Math.abs(currentY - startY)) {
                if (getCommentsRect().contains((int) startX, (int) startY) && diffX > 0)
                    return SwipeEventType.COMMENTS;

                return SwipeEventType.SEEK;
            } else if (Math.abs(currentY - startY) >= SWIPE_THRESHOLD) {
                if (getDescriptionRect().contains((int) startX, (int) startY) && diffY > 0) {
                    return SwipeEventType.DESCRIPTION;
                } else if (getBrightnessRect().contains((int) startX, (int) startY)) {
                    return SwipeEventType.BRIGHTNESS;
                } else if (getVolumeRect().contains((int) startX, (int) startY)) {
                    return SwipeEventType.VOLUME;
                }
            }
            return SwipeEventType.NONE;
        }

        /**
         * Here we decide in what place of the screen user should swipe to get a new brightness value.
         */
        private Rect getBrightnessRect() {
            return new Rect(viewRect().right / 2, 0, viewRect().right, viewRect().bottom);
        }

        /**
         * Here we decide in what place of the screen user should swipe to get a new volume value.
         */
        private Rect getVolumeRect() {
            return new Rect(0, 0, viewRect().right / 2, viewRect().bottom);
        }

        /**
         * Here we choose a rect for swipe which then will be used to open the comments view.
         */
        private Rect getCommentsRect() {
            // 20% from right side will trigger comments view
            return new Rect((int)(viewRect().right - Math.min(viewRect().bottom, viewRect().right) * 0.2), 0, viewRect().right, viewRect().bottom);
        }

        /**
         * Here we choose a rect for swipe which then will be used to open the description view.
         */
        private Rect getDescriptionRect() {
            // 20% from bottom side will trigger description view
            return new Rect(0, (int)(viewRect().bottom - Math.min(viewRect().bottom, viewRect().right) * 0.2), viewRect().right, viewRect().bottom);
        }

    }

}
</code>```

and this is my kotlin relative layout ontouchlistener code

```<code>binding.playerView.setOnTouchListener(OnSwifeListener)
</code>```

How to implement above java class in kotlin touch listener?

Title: How to use gestureListener kotlin

Body:
i am trying to create a video player app using kotlin , now in player activity i am trying to use gesture listner but problem is i use a java class to use gesture listener , but in java onTouchListerner function
gesture listener class work somthly but in kotlin i dont know how to imple ment this class please help me

OnSwifelistener.java

import android.content.Context;
import android.graphics.Rect;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;

import androidx.core.view.GestureDetectorCompat;

public abstract class OnSwipeTouchListener implements View.OnTouchListener {

    private final GestureDetectorCompat gestureDetector;
    private final GestureListener gestureListener;

    protected OnSwipeTouchListener(Context context){
        gestureListener = new GestureListener();
        gestureDetector = new GestureDetectorCompat(context, gestureListener);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        gestureListener.onTouchEvent(event);
        return true;
    }
    public boolean onSwipeRight() {
        return false;
    }
    public boolean onSwipeLeft() {
        return false;
    }

    public boolean onSwipeTop() {
        return false;
    }

    public boolean onSwipeBottom() {
        return false;
    }

    public boolean onDoubleTap() {
        return false;
    }

    public boolean onSingleTap() {
        return true;
    }
    public abstract void onGestureDone();
    public abstract void adjustBrightness(double adjustPercent);
    public abstract void adjustVolumeLevel(double adjustPercent);
    public abstract void adjustVideoPosition(double adjustPercent, boolean forwardDirection);
    public abstract Rect viewRect();

    private enum SwipeEventType {
        NONE,
        BRIGHTNESS,
        VOLUME,
        SEEK,
        COMMENTS,
        DESCRIPTION
    }

    private final class GestureListener extends GestureDetector.SimpleOnGestureListener {

        private static final int SWIPE_THRESHOLD = 50;
        private SwipeEventType swipeEventType = SwipeEventType.NONE;
        private MotionEvent startEvent;

        @Override
        public boolean onDoubleTap(MotionEvent e) {
            return OnSwipeTouchListener.this.onDoubleTap();
        }

        @Override
        public boolean onSingleTapConfirmed(MotionEvent e) {
            return onSingleTap();
        }

        @Override
        public boolean onScroll(MotionEvent start, MotionEvent end,
                                float distanceX, float distanceY) {
            // function depends on start position. (volume or brightness or play position.)
            double yDistance = end.getY() - start.getY();
            double xDistance = end.getX() - start.getX();

            if (swipeEventType == SwipeEventType.COMMENTS) {
                return onSwipeLeft();
            } else if (swipeEventType == SwipeEventType.DESCRIPTION) {
                return onSwipeTop();
            } else if (swipeEventType == SwipeEventType.BRIGHTNESS) {
                // use half of BrightnessRect's height to calculate percent.
                double percent = yDistance / (getBrightnessRect().height() / 2.0f) * -1.0f;
                adjustBrightness(percent);
            } else if (swipeEventType == SwipeEventType.VOLUME) {
                // use half of volumeRect's height to calculate percent.
                double percent = yDistance / (getVolumeRect().height() / 2.0f) * -1.0f;
                adjustVolumeLevel(percent);
            } else if (swipeEventType == SwipeEventType.SEEK) {
                double percent = xDistance / viewRect().width();
                adjustVideoPosition(percent, distanceX < 0);
            }

            return true;
        }

        private boolean isEventValid(MotionEvent event) {
            // this gesture just worked on single pointer.
            return event.getPointerCount() == 1;
        }

        private void onTouchEvent(MotionEvent event) {
            if (isEventValid(event)) {
                // decide which process is needed.
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        startEvent = MotionEvent.obtain(event);
                        break;
                    case MotionEvent.ACTION_MOVE:
                        if (swipeEventType == SwipeEventType.NONE && startEvent != null) {
                            swipeEventType = whatTypeIsIt(startEvent, event);
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                        onGestureDone();
                        swipeEventType = SwipeEventType.NONE;
                        startEvent = null;
                        break;
                    default:
                        break;
                }
            }

            gestureDetector.onTouchEvent(event);
        }

        /**
         * Ok, swipe detected. What did user want? Let's find out
         */
        private SwipeEventType whatTypeIsIt(MotionEvent startEvent, MotionEvent currentEvent) {
            float startX = startEvent.getX();
            float startY = startEvent.getY();
            float currentX = currentEvent.getX();
            float currentY = currentEvent.getY();
            float diffY = startY - currentY;
            float diffX = startX - currentX;

            if (Math.abs(currentX - startX) >= SWIPE_THRESHOLD && Math.abs(currentX - startX) > Math.abs(currentY - startY)) {
                if (getCommentsRect().contains((int) startX, (int) startY) && diffX > 0)
                    return SwipeEventType.COMMENTS;

                return SwipeEventType.SEEK;
            } else if (Math.abs(currentY - startY) >= SWIPE_THRESHOLD) {
                if (getDescriptionRect().contains((int) startX, (int) startY) && diffY > 0) {
                    return SwipeEventType.DESCRIPTION;
                } else if (getBrightnessRect().contains((int) startX, (int) startY)) {
                    return SwipeEventType.BRIGHTNESS;
                } else if (getVolumeRect().contains((int) startX, (int) startY)) {
                    return SwipeEventType.VOLUME;
                }
            }
            return SwipeEventType.NONE;
        }

        /**
         * Here we decide in what place of the screen user should swipe to get a new brightness value.
         */
        private Rect getBrightnessRect() {
            return new Rect(viewRect().right / 2, 0, viewRect().right, viewRect().bottom);
        }

        /**
         * Here we decide in what place of the screen user should swipe to get a new volume value.
         */
        private Rect getVolumeRect() {
            return new Rect(0, 0, viewRect().right / 2, viewRect().bottom);
        }

        /**
         * Here we choose a rect for swipe which then will be used to open the comments view.
         */
        private Rect getCommentsRect() {
            // 20% from right side will trigger comments view
            return new Rect((int)(viewRect().right - Math.min(viewRect().bottom, viewRect().right) * 0.2), 0, viewRect().right, viewRect().bottom);
        }

        /**
         * Here we choose a rect for swipe which then will be used to open the description view.
         */
        private Rect getDescriptionRect() {
            // 20% from bottom side will trigger description view
            return new Rect(0, (int)(viewRect().bottom - Math.min(viewRect().bottom, viewRect().right) * 0.2), viewRect().right, viewRect().bottom);
        }

    }

}

and this is my kotlin relative layout ontouchlistener code

binding.playerView.setOnTouchListener(OnSwifeListener)

How to implement above java class in kotlin touch listener?


问:
Why does Pandas export incomplete real-time data to CSV file when converted to dataframe?
I'm working with a dynamic system whose velocity data is stored in a matrix as such:

Vd = [v_min, v_max, yaw_rate_min, yaw_rate_max]

and the output is as follows when printed:

-0.02        0.02       -1.83728716  1.83728716

 0.02        0.06       -0.36745743  3.30711689

 0.04        0.08       -1.1023723   2.57220202

 0.06        0.1        -1.46982973  2.20474459

...

I want to export this data (specifically, maximum and minimum velocity data) to a CSV file. However, I'm unable to extract the full data as I'm only able to output a CSV file with only one row of the velocity matrix.

I have tried converting the matrix to an array, and then converting the array to a dataframe. With Pandas' df.to_csv syntax, I expected the full velocity matrix to be exported to a CSV file, but as mentioned before, I can only obtain one row of data. Below is the code I have written. If it makes a difference, the data is collected in real-time as the code runs. Any advice is appreciated.

`

```<code>Vs = [config.min_speed+config.U1, config.max_speed+config.U1,
      -config.max_yaw_rate, config.max_yaw_rate]

Vd = [x[3] - config.max_accel * config.dt,
      x[3] + config.max_accel * config.dt,
      x[4] - config.max_delta_yaw_rate * config.dt,
      x[4] + config.max_delta_yaw_rate * config.dt]

#  [v_min, v_max, yaw_rate_min, yaw_rate_max]
dw = [max(Vs[0], Vd[0]), min(Vs[1], Vd[1]),
      max(Vs[2], Vd[2]), min(Vs[3], Vd[3])] **# n x 4 matrix**
dw_arr = np.array(dw)
vMin = dw_arr[:,0] #Minimum velocity data column
vMax = dw_arr[:,1] #Maximum velocity data column
print(dw_arr)

df = pd.DataFrame([vMin, vMax])
df.to_csv('Velocity Data.csv') **# This only saves one row of data from dw_arr array**
</code>```

`

Body:
I'm working with a dynamic system whose velocity data is stored in a matrix as such:

Vd = [v_min, v_max, yaw_rate_min, yaw_rate_max]

and the output is as follows when printed:

-0.02        0.02       -1.83728716  1.83728716

 0.02        0.06       -0.36745743  3.30711689

 0.04        0.08       -1.1023723   2.57220202

 0.06        0.1        -1.46982973  2.20474459

...

I want to export this data (specifically, maximum and minimum velocity data) to a CSV file. However, I'm unable to extract the full data as I'm only able to output a CSV file with only one row of the velocity matrix.

I have tried converting the matrix to an array, and then converting the array to a dataframe. With Pandas' df.to_csv syntax, I expected the full velocity matrix to be exported to a CSV file, but as mentioned before, I can only obtain one row of data. Below is the code I have written. If it makes a difference, the data is collected in real-time as the code runs. Any advice is appreciated.

`

Vs = [config.min_speed+config.U1, config.max_speed+config.U1,
      -config.max_yaw_rate, config.max_yaw_rate]

Vd = [x[3] - config.max_accel * config.dt,
      x[3] + config.max_accel * config.dt,
      x[4] - config.max_delta_yaw_rate * config.dt,
      x[4] + config.max_delta_yaw_rate * config.dt]

#  [v_min, v_max, yaw_rate_min, yaw_rate_max]
dw = [max(Vs[0], Vd[0]), min(Vs[1], Vd[1]),
      max(Vs[2], Vd[2]), min(Vs[3], Vd[3])] **# n x 4 matrix**
dw_arr = np.array(dw)
vMin = dw_arr[:,0] #Minimum velocity data column
vMax = dw_arr[:,1] #Maximum velocity data column
print(dw_arr)

df = pd.DataFrame([vMin, vMax])
df.to_csv('Velocity Data.csv') **# This only saves one row of data from dw_arr array**

`


问:
create 3d sound in scene ursina
Making 3d game in Ursina. How can one create a sound in a 3d environment where you parent it to an object so the further away the player is, the less sound is emitted?

Like something like:

```<code>a = Audio("file.mp3", range = 1, parent = "some entity")
</code>```

Title: create 3d sound in scene ursina

Body:
Making 3d game in Ursina. How can one create a sound in a 3d environment where you parent it to an object so the further away the player is, the less sound is emitted?

Like something like:

a = Audio("file.mp3", range = 1, parent = "some entity")


问:
Multiplication in LC3 without knowing which registers are full
How would I write assembly code to multiply two registers if I don't know which registers are full?

I am writing a C program that expands a mult macro or pseudo-instruction in LC3 code to multiply two registers.  So I do not have access to the assembly code to know which are full.

But the mult "instruction" is specified to only write the destination, without modifying any other registers.  There's no general way to figure out which registers might be unused or ok to modify at a certain point in an asm file, so how can I use any temporaries for a loop?

For example:
Let's say this is the ASM file, input to my program.  The output would be another asm file, using a sequence of other instructions to replace the mult.

```<code>LD      R1, THREE
LD      R2, TWO

MULT R2, R3, R4  ; (This multiplies Register three and four and loads the result into R2).
</code>```

I am converting the MULT code into code LC3 knows and can execute

If I do not have access to this original file, then I wouldn't know that Register 2 has something in it in order to not choose it as a counter when I am writing the code to multiply registers 2 and 3. The easiest way to multiply is to use a counter and then keep adding over and over.

How would I multiply if I am unable to choose a register to use as a counter?

I have tried using a counter, however this does not work without knowing which register is free.

Body:
How would I write assembly code to multiply two registers if I don't know which registers are full?

I am writing a C program that expands a mult macro or pseudo-instruction in LC3 code to multiply two registers.  So I do not have access to the assembly code to know which are full.

But the mult "instruction" is specified to only write the destination, without modifying any other registers.  There's no general way to figure out which registers might be unused or ok to modify at a certain point in an asm file, so how can I use any temporaries for a loop?

For example:
Let's say this is the ASM file, input to my program.  The output would be another asm file, using a sequence of other instructions to replace the mult.

LD      R1, THREE
LD      R2, TWO

MULT R2, R3, R4  ; (This multiplies Register three and four and loads the result into R2).

I am converting the MULT code into code LC3 knows and can execute

If I do not have access to this original file, then I wouldn't know that Register 2 has something in it in order to not choose it as a counter when I am writing the code to multiply registers 2 and 3. The easiest way to multiply is to use a counter and then keep adding over and over.

How would I multiply if I am unable to choose a register to use as a counter?

I have tried using a counter, however this does not work without knowing which register is free.


问:
How to implement wall sliding for player in pygame?
I'm making my very first pygame and I've got walking, jumping, falling and now I want to add wall sliding. I tried to go into collision detection and change the falling image to wall sliding image if: player is on air, player is falling, player is colliding with a wall on x-axis and the key of that direction is pressed.
But I'm lost when I'm typing codes. Would be great if anyone can tell if my theory is going to work. Here's my code for player, there's no wall sliding code because all my attempts have failed and caused other animations to shake or fly.

class Player():
    def __init__(self,x,y):
        self.img_stand = pygame.image.load('D:\ThingThing\inthething\H stand.png')
        self.img_standL = pygame.image.load('D:\ThingThing\inthething\H standL.png')
        self.img_asc = pygame.image.load('D:\ThingThing\inthething\H asc.png')
        self.img_dsc = pygame.image.load('D:\ThingThing\inthething\H dsc.png')
        self.img_ascL = pygame.transform.flip(self.img_asc, True, False)
        self.img_dscL = pygame.transform.flip(self.img_dsc, True, False)
        self.img_slide = pygame.image.load('D:\ThingThing\inthething\H slide.png')
        self.img_slideL = pygame.transform.flip(self.img_slide,True,False)
        #walk animation
        self.images_right = []
        self.images_left = []
        self.index = 0
        self.counter = 0
        self.direction = 1
        self.onair = False
        self.jump_counter = 0

        for num in range(1,17):
            img_right = pygame.image.load(f'D:\ThingThing\inthething\H walk{num}.png')
            self.images_right.append(img_right)

        for num in range(1,17):
            img_left = pygame.image.load(f'D:\ThingThing\inthething\H walkL{num}.png')
            self.images_left.append(img_left)

        self.image = self.img_stand
        self.width = self.image.get_width()
        self.height = self.image.get_height()
        self.rect = self.image.get_rect(topleft = (x,y))
        self.hit_box = self.rect.copy()

        self.rect.x = x
        self.rect.y = y
        self.width = self.image.get_width()
        self.height = self.image.get_height()

        self.vel_y = 0
        self.jumped = False
        self.slidey = 0
    def update(self):
        dx = 0
        dy = 0
        walk_cooldown = 8

        #get key
        key = pygame.key.get_pressed()

        if key[pygame.K_RIGHT]:
            dx += 1
            self.image = self.images_right[self.index]
            self.counter += 1
            # change size of self.rect
            self.rect = self.image.get_rect(midbottom=self.rect.midbottom)
            self.direction = 1

        elif key[pygame.K_LEFT]:
            dx -= 1
            self.image = self.images_left[self.index]
            self.counter += 1
            # change size of self.rect
            self.rect = self.image.get_rect(midbottom=self.rect.midbottom)
            self.direction = -1

        if (key[pygame.K_LEFT] == False and key[pygame.K_RIGHT] == False) or (key[pygame.K_LEFT] == True and key[pygame.K_RIGHT] == True):
            self.counter = 0
            self.index = 0
            if self.direction == 1:
                self.image = self.img_stand

            elif self.direction == -1:
                self.image = self.img_standL
            dx = 0

            self.tempx = self.rect.centerx
            self.tempy = self.rect.bottom
            self.rect = self.image.get_rect()
            self.rect.centerx = self.tempx
            self.rect.bottom = self.tempy

        if self.counter > walk_cooldown:
            self.counter = 0
            self.index += 1
            if self.direction == 1:
                if self.index >= len(self.images_right):
                    self.index = 0
                self.image = self.images_right[self.index]
            if self.direction == -1:
                if self.index >= len(self.images_left):
                    self.index = 0
                self.image = self.images_left[self.index]

        if key[pygame.K_SPACE] and self.jumped == False:
            self.vel_y = -8
            self.jumped = True
            self.onair = True

        #jump + gravity
        self.vel_y += 0.3
        if self.vel_y > 10:
            self.vel_y = 10
        dy += self.vel_y

        #collide
        for tile in world.tile_list:
            if tile[1].colliderect(self.hit_box.x, self.hit_box.y + dy,self.width,self.height):

                if self.vel_y < 0:
                    dy = tile[1].bottom - self.hit_box.top
                    self.vel_y = 0
                elif self.vel_y > 0:
                    dy = tile[1].top - self.hit_box.bottom
                    self.vel_y = 0
                    self.jumped = False
                    self.onair = False

            if tile[1].colliderect(self.hit_box.x + dx, self.hit_box.y, self.width, self.height):
                if self.vel_y == 0:
                    if self.direction == -1:
                        self.image = self.img_standL
                    if self.direction == 1:
                        self.image = self.img_stand

                self.tempx = self.rect.centerx
                self.tempy = self.rect.bottom
                dx = 0
                self.rect = self.image.get_rect()
                self.rect.centerx = self.tempx
                self.rect.bottom = self.tempy

        if self.onair == True:
            if self.vel_y < 0:
                if self.direction == 1:
                    self.image = self.img_asc

                if self.direction == -1:
                    self.image = self.img_ascL

            elif self.vel_y > 0:
                if self.direction == 1:
                    self.image = self.img_dsc

                if self.direction == -1:
                    self.image = self.img_dscL

            self.tempx = self.rect.centerx
            self.tempy = self.rect.bottom
            self.rect = self.image.get_rect()
            self.rect.centerx = self.tempx
            self.rect.bottom = self.tempy

        #move

        self.rect.centerx += dx
        self.rect.bottom += dy
        self.hit_box.midbottom = self.rect.midbottom

        #onto screen
        screen.blit(self.image,self.rect)
        print(self.rect)
        pygame.draw.rect(screen,(255,255,255),self.rect,2)
        pygame.draw.rect(screen,(255,255,255),self.hit_box,3)
```


问:
docker-compose cannot update and refresh the file after error (express mongodb)
I try to use the docker-compose for mongodb and express which i know that there are some error on the mongodb part which remain unfix for the connection.But the there are error on server.js after when running docker-compose up.When i update the file , docker cannot detect the update which remain unchange with the same error message.

error message:

```<code> expressnew | ff
    expressnew | /usr/src/app/server.js:8
    expressnew | app.use(cors());
    expressnew |     ^
    expressnew |
    expressnew | ReferenceError: cors is not defined
    expressnew |     at Object.<anonymous> (/usr/src/app/server.js:8:5)
    expressnew |     at Module._compile (node:internal/modules/cjs/loader:1165:14)
    expressnew |     at Object.Module._extensions..js (node:internal/modules/cjs/loader:1219:10)
    expressnew |     at Module.load (node:internal/modules/cjs/loader:1043:32)
    expressnew |     at Function.Module._load (node:internal/modules/cjs/loader:878:12)
    expressnew |     at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    expressnew |     at node:internal/main/run_main_module:22:47
</code>```

my docker-compose.yml:

```<code>version: "3.8"

services:
  mongodb:
    container_name: mongo_ex
    image: mongo
    env_file: ./.env
    environment:
      - MONGO_INITDB_ROOT_USERNAME=Alexso0121
      - MONGO_INITDB_ROOT_PASSWORD=LR4135alex
    ports:
      - '27017:27017'
    volumes:
      - db:/data/db
  app:
    container_name: expressnew
    depends_on:
      - mongodb
    build: .
    env_file: ./.env
    ports:
      - '80:3000'
    environment:
      - DB_HOST=mongodb
      - DB_USER=alexso0121
      - DB_PASSWORD=LR4135alex
      - DB_NAME=
      - DB_PORT=$MONGODB_DOCKER_PORT
    stdin_open: true
    tty: true

volumes:
  db:
</code>```

server.js (after update):

```<code>const bodyParser = require('body-parser')
const express = require('express')
const app = express()
console.log("ff")
const mongoose=require('mongoose')
mongoose.set('strictQuery',false)
require('dotenv/config')

app.use(bodyParser.json());

const db=mongoose.connection
db.on('error',(error)=>console.error(error))
db.once('open',()=> console.log('connect to db'))

mongoose.connect(
    process.env.DB_CONNECTION
    ,{ useNewUrlParser:true })
app.use(logger)

//app.use(bodyParser.urlencoded({ extended: false }));

app.get('/',logger,(req,res)=>{
    console.log("ddd")
    //res.status(500)
    res.json({ username : "alex"})

})

const userRouter = require('./routes/users')

function logger(req,res,next){
    console.log(req.originalUrl)
    next()
}
app.use('/users',userRouter)
app.listen(3000)
</code>```

Body:
I try to use the docker-compose for mongodb and express which i know that there are some error on the mongodb part which remain unfix for the connection.But the there are error on server.js after when running docker-compose up.When i update the file , docker cannot detect the update which remain unchange with the same error message.

error message:

 expressnew | ff
    expressnew | /usr/src/app/server.js:8
    expressnew | app.use(cors());
    expressnew |     ^
    expressnew |
    expressnew | ReferenceError: cors is not defined
    expressnew |     at Object.<anonymous> (/usr/src/app/server.js:8:5)
    expressnew |     at Module._compile (node:internal/modules/cjs/loader:1165:14)
    expressnew |     at Object.Module._extensions..js (node:internal/modules/cjs/loader:1219:10)
    expressnew |     at Module.load (node:internal/modules/cjs/loader:1043:32)
    expressnew |     at Function.Module._load (node:internal/modules/cjs/loader:878:12)
    expressnew |     at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    expressnew |     at node:internal/main/run_main_module:22:47

my docker-compose.yml:

version: "3.8"

services:
  mongodb:
    container_name: mongo_ex
    image: mongo
    env_file: ./.env
    environment:
      - MONGO_INITDB_ROOT_USERNAME=Alexso0121
      - MONGO_INITDB_ROOT_PASSWORD=LR4135alex
    ports:
      - '27017:27017'
    volumes:
      - db:/data/db
  app:
    container_name: expressnew
    depends_on:
      - mongodb
    build: .
    env_file: ./.env
    ports:
      - '80:3000'
    environment:
      - DB_HOST=mongodb
      - DB_USER=alexso0121
      - DB_PASSWORD=LR4135alex
      - DB_NAME=
      - DB_PORT=$MONGODB_DOCKER_PORT
    stdin_open: true
    tty: true

volumes:
  db:

server.js (after update):

const bodyParser = require('body-parser')
const express = require('express')
const app = express()
console.log("ff")
const mongoose=require('mongoose')
mongoose.set('strictQuery',false)
require('dotenv/config')

app.use(bodyParser.json());

const db=mongoose.connection
db.on('error',(error)=>console.error(error))
db.once('open',()=> console.log('connect to db'))

mongoose.connect(
    process.env.DB_CONNECTION
    ,{ useNewUrlParser:true })
app.use(logger)

//app.use(bodyParser.urlencoded({ extended: false }));

app.get('/',logger,(req,res)=>{
    console.log("ddd")
    //res.status(500)
    res.json({ username : "alex"})

})

const userRouter = require('./routes/users')

function logger(req,res,next){
    console.log(req.originalUrl)
    next()
}
app.use('/users',userRouter)
app.listen(3000)


问:
Flutter Firebase delete user account
I'm attempting to delete a Firebase user account that has data in several other collections. Because Firebase requires a recent login in order to delete accounts or change passwords, I'm asking the user to sign in again in the following code. The code below deletes the user account, but the application automatically shuts after pressing the delete button. Lost connection to the device. The user is still signed in with their data when I restart the app (perhaps because it is persistent), so I have to manually log them out.

The code is as follows-

This Function runs when delete account button is pressed.

```<code>  /// Function to delete user account
  void deleteUserAccountEmail(
      {required String password, required BuildContext context}) async {
    //
    try {
      await _auth
          .signInWithEmailAndPassword(
              email: currentUser!.email!, password: password)
          .then(
        (_) async {
          //
          currentUser = _auth.currentUser;

          //
          _rankController.deleteRank();

          // Deleting user
          currentUser!.delete().then(
                (value) => signOut(),
              );
        },
      );
    } catch (error) {
      final e = error.toString().replaceRange(0, 14, '').split(']')[1];
      _uniWidgets.errorSnackBarFN(
        errorTitle: 'Error',
        errorMessage: e,
      );
    }
  }
</code>```

StreamBuilder in the HomeScreen Body

```<code>return StreamBuilder(
                stream: FirebaseAuth.instance.authStateChanges(),
                builder: (context, snapshot) {
                  if (snapshot.connectionState == ConnectionState.waiting) {
                    return Center(child: CircularProgressIndicator());
                  } else if (snapshot.hasData) {
                    return _authController.currentUser!.emailVerified
                        ? HomeScreen()
                        : AuthScreen();
                  } else if (snapshot.hasError) {
                    return Text(snapshot.error.toString());
                  } else {
                    return AuthScreen();
                  }
                },
              );
            } else {
              return NoConnectionScreen();
            }
</code>```

Title: Flutter Firebase delete user account

Body:
I'm attempting to delete a Firebase user account that has data in several other collections. Because Firebase requires a recent login in order to delete accounts or change passwords, I'm asking the user to sign in again in the following code. The code below deletes the user account, but the application automatically shuts after pressing the delete button. Lost connection to the device. The user is still signed in with their data when I restart the app (perhaps because it is persistent), so I have to manually log them out.

The code is as follows-

This Function runs when delete account button is pressed.

  /// Function to delete user account
  void deleteUserAccountEmail(
      {required String password, required BuildContext context}) async {
    //
    try {
      await _auth
          .signInWithEmailAndPassword(
              email: currentUser!.email!, password: password)
          .then(
        (_) async {
          //
          currentUser = _auth.currentUser;

          //
          _rankController.deleteRank();

          // Deleting user
          currentUser!.delete().then(
                (value) => signOut(),
              );
        },
      );
    } catch (error) {
      final e = error.toString().replaceRange(0, 14, '').split(']')[1];
      _uniWidgets.errorSnackBarFN(
        errorTitle: 'Error',
        errorMessage: e,
      );
    }
  }

StreamBuilder in the HomeScreen Body

return StreamBuilder(
                stream: FirebaseAuth.instance.authStateChanges(),
                builder: (context, snapshot) {
                  if (snapshot.connectionState == ConnectionState.waiting) {
                    return Center(child: CircularProgressIndicator());
                  } else if (snapshot.hasData) {
                    return _authController.currentUser!.emailVerified
                        ? HomeScreen()
                        : AuthScreen();
                  } else if (snapshot.hasError) {
                    return Text(snapshot.error.toString());
                  } else {
                    return AuthScreen();
                  }
                },
              );
            } else {
              return NoConnectionScreen();
            }


问:
How to expire user token if particular field value is updated in User model in Django?
I'm trying to make a signal to expire the user token if a field value is updated in the User model.

This is the signal I've written. But for some reason, instance.is_corporate_profile_admin is giving older data and not the data which is recently saved or sent from the request when the API was hit.

apps.py

```<code>class UserConfig(AppConfig):
    name = 'user'
    def ready(self):
        from . import signals
        request_finished.connect(signals.task_token_expire)
</code>```

signals.py

```<code>def expire_user_knox_token(user_id : int, time : object) -> bool:
    from knox.models import AuthToken
    try:
        _ = AuthToken.objects.filter(user_id=user_id).update(expiry=time)
        return True
    except:
        return False

@receiver(post_save, sender=UserDetail)
def task_token_expire(sender, instance, **kwargs):
    if instance and instance.id:
        from django.db import transaction
        with transaction.atomic():
            from datetime import datetime
            logout_time = datetime.now()
            # If is_cp_admin value changed or if no user entry in UserDetailOlderValues then only token expire.
            try:
                older_is_cp_admin_value = UserDetailOlderValues.objects.filter(user=instance).order_by('-id').first().is_corporate_profile_admin
                print('older_is_cp_admin_value------------->', older_is_cp_admin_value)
                print('new value------------->', instance.is_corporate_profile_admin)    # ! THIS VALUE IS NOT THE LATEST VALUE WHICH IS SENT IN THE REQUEST
                if instance.is_corporate_profile_admin != older_is_cp_admin_value:
                    expire_user_knox_token(user_id=instance.id, time=logout_time)
                    _updated= UserDetailOlderValues.objects.filter(user=instance).update(is_corporate_profile_admin=instance.is_corporate_profile_admin, last_token_expired_at=logout_time)

            except:
                expire_user_knox_token(user_id=instance.id, time=logout_time)
                _obj, _created = UserDetailOlderValues.objects.update_or_create(user=instance, is_corporate_profile_admin=instance.is_corporate_profile_admin, last_token_expired_at=logout_time)

</code>```

I tried using pre_save before post_save, to hold previous data but both pre_save and post_save are fetching same older data. So, I created another model to save older data of is_corporate_profile_admin. But in post_save instance.is_corporate_profile_admin still reflects older data.

Here is my UserDetailOlderValues model:

```<code>class UserDetailOlderValues(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='udov', blank=True, null=True)
    is_corporate_profile_admin = models.BooleanField(default=False)
    last_token_expired_at = models.DateTimeField(blank=True, null=True)

    def __str__(self):
        return str(self.id)
    class Meta:
        db_table = 'user_detail_older_values'
</code>```

Along with that, I'm getting this as well: TypeError: task_token_expire() missing 1 required positional argument: 'instance'.

Body:
I'm trying to make a signal to expire the user token if a field value is updated in the User model.

This is the signal I've written. But for some reason, instance.is_corporate_profile_admin is giving older data and not the data which is recently saved or sent from the request when the API was hit.

apps.py

class UserConfig(AppConfig):
    name = 'user'
    def ready(self):
        from . import signals
        request_finished.connect(signals.task_token_expire)

signals.py

def expire_user_knox_token(user_id : int, time : object) -> bool:
    from knox.models import AuthToken
    try:
        _ = AuthToken.objects.filter(user_id=user_id).update(expiry=time)
        return True
    except:
        return False

@receiver(post_save, sender=UserDetail)
def task_token_expire(sender, instance, **kwargs):
    if instance and instance.id:
        from django.db import transaction
        with transaction.atomic():
            from datetime import datetime
            logout_time = datetime.now()
            # If is_cp_admin value changed or if no user entry in UserDetailOlderValues then only token expire.
            try:
                older_is_cp_admin_value = UserDetailOlderValues.objects.filter(user=instance).order_by('-id').first().is_corporate_profile_admin
                print('older_is_cp_admin_value------------->', older_is_cp_admin_value)
                print('new value------------->', instance.is_corporate_profile_admin)    # ! THIS VALUE IS NOT THE LATEST VALUE WHICH IS SENT IN THE REQUEST
                if instance.is_corporate_profile_admin != older_is_cp_admin_value:
                    expire_user_knox_token(user_id=instance.id, time=logout_time)
                    _updated= UserDetailOlderValues.objects.filter(user=instance).update(is_corporate_profile_admin=instance.is_corporate_profile_admin, last_token_expired_at=logout_time)

            except:
                expire_user_knox_token(user_id=instance.id, time=logout_time)
                _obj, _created = UserDetailOlderValues.objects.update_or_create(user=instance, is_corporate_profile_admin=instance.is_corporate_profile_admin, last_token_expired_at=logout_time)

I tried using pre_save before post_save, to hold previous data but both pre_save and post_save are fetching same older data. So, I created another model to save older data of is_corporate_profile_admin. But in post_save instance.is_corporate_profile_admin still reflects older data.

Here is my UserDetailOlderValues model:

class UserDetailOlderValues(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='udov', blank=True, null=True)
    is_corporate_profile_admin = models.BooleanField(default=False)
    last_token_expired_at = models.DateTimeField(blank=True, null=True)

    def __str__(self):
        return str(self.id)
    class Meta:
        db_table = 'user_detail_older_values'

Along with that, I'm getting this as well: TypeError: task_token_expire() missing 1 required positional argument: 'instance'.


问:
How to align text to left in Medium Widget Extension in Swift
I am trying to add widgets to my app and I am very new to this, I am showing 3 links in the medium Widget extension and the problem is all 3 links are in the centre and I want them to align on left side, I have tried many things which are available online but still not working,
this is my code :

```<code>var body: some View {
    ZStack {
        GeometryReader { geo in
            Image("background")
                .resizable()
                .aspectRatio(contentMode: .fill)
                .frame(width: geo.size.width,
                       height: geo.size.height,
                       alignment: .center)
            }

        switch family{
        case .systemSmall:
            Text(entry.date, style: .time)
                        .widgetURL(URL(string: "fcv://open_activity"))
        case .systemMedium:
            VStack (alignment: .leading){
                               Link(destination: URL(string: "game:///link1")!, label: {
                                   Text("Link1")
                                       .multilineTextAlignment(.leading)

                               })
                               Spacer()
                               Link(destination: URL(string: "game1:///link2")!, label: {
                                   Text("Link2")
                                       .multilineTextAlignment(.trailing)

                               })
                               Spacer()
                               Link(destination: URL(string: "game2:///link3")!, label: {
                                   Text("Link3")
                                       .multilineTextAlignment(.center)

                               })
                           }
                           .padding()
        default:
            Link(destination: URL(string: "fcv2://open_activity")!) {
                Text("Link 4")
            }
</code>```

I have tried this:

```<code>.font(.body)
.fontWeight(.bold)
.lineLimit(1)
.allowsTightening(true)
</code>```

and also this:

```<code> .zIndex(2)
 .shadow(radius: 5)
</code>```

but neither of them work.

Body:
I am trying to add widgets to my app and I am very new to this, I am showing 3 links in the medium Widget extension and the problem is all 3 links are in the centre and I want them to align on left side, I have tried many things which are available online but still not working,
this is my code :

var body: some View {
    ZStack {
        GeometryReader { geo in
            Image("background")
                .resizable()
                .aspectRatio(contentMode: .fill)
                .frame(width: geo.size.width,
                       height: geo.size.height,
                       alignment: .center)
            }

        switch family{
        case .systemSmall:
            Text(entry.date, style: .time)
                        .widgetURL(URL(string: "fcv://open_activity"))
        case .systemMedium:
            VStack (alignment: .leading){
                               Link(destination: URL(string: "game:///link1")!, label: {
                                   Text("Link1")
                                       .multilineTextAlignment(.leading)

                               })
                               Spacer()
                               Link(destination: URL(string: "game1:///link2")!, label: {
                                   Text("Link2")
                                       .multilineTextAlignment(.trailing)

                               })
                               Spacer()
                               Link(destination: URL(string: "game2:///link3")!, label: {
                                   Text("Link3")
                                       .multilineTextAlignment(.center)

                               })
                           }
                           .padding()
        default:
            Link(destination: URL(string: "fcv2://open_activity")!) {
                Text("Link 4")
            }

I have tried this:

.font(.body)
.fontWeight(.bold)
.lineLimit(1)
.allowsTightening(true)

and also this:

 .zIndex(2)
 .shadow(radius: 5)

but neither of them work.


问:
Java LinkedList rotation
I'm trying to implement a custom class that extends the java.util.LinkedList class and adds a new method called rotate(). The rotate() method should rotate the elements in the list by a specified number of positions, similar to the way the Unix rotate command works.

For example:

RotatingList<Integer> list = new RotatingList<>(1, 2, 3, 4, 5);
list.rotate(2);
System.out.println(list);  // Outputs: [4, 5, 1, 2, 3]
```

I have the basic structure of the RotatingList class set up, but I'm having trouble with the implementation of the rotate() method. How can I efficiently rotate the elements in the list by a specified number of positions?"

Title: Java LinkedList rotation

Body:
I'm trying to implement a custom class that extends the java.util.LinkedList class and adds a new method called rotate(). The rotate() method should rotate the elements in the list by a specified number of positions, similar to the way the Unix rotate command works.

For example:

RotatingList<Integer> list = new RotatingList<>(1, 2, 3, 4, 5);
list.rotate(2);
System.out.println(list);  // Outputs: [4, 5, 1, 2, 3]

I have the basic structure of the RotatingList class set up, but I'm having trouble with the implementation of the rotate() method. How can I efficiently rotate the elements in the list by a specified number of positions?"


问:
how to delay elements entering the DOM using TransitionGroup?
The problem I am running into is that all the elements are rendered first before the animation starts. The effect that I want to achieve is that the element is animated while entering the DOM and it happens one after another. What's wrong with my code?

```<code><template>
  <TransitionGroup appear name="stagger" tag="ul">
    <li v-for="(num, index) in list" :style="{ '--order': index }" :key="num">
      {{ num }}
    </li>
  </TransitionGroup>
</template>

<script setup>
const list = Array.from({ length: 5 }, (_, index) => index + 1);
</script>

<style scoped>
.stagger-enter-active {
  animation-name: stagger;
  animation-duration: 0.5s;
  animation-delay: calc(var(--order) * 0.15s);
}

@keyframes stagger {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>
</code>```

After reading the official doc one more time, I realized that the same animation effect can be made with just transition and it works, which got me wondering what's the main difference between these two approaches?

.stagger-enter-from {
  opacity: 0;
  transform: translateX(-1em);
}
.stagger-enter-active {
  transition: opacity 0.5s linear, transform 0.5s ease;
  transition-delay: calc(var(--order) * 0.15s);
}
```

Body:
The problem I am running into is that all the elements are rendered first before the animation starts. The effect that I want to achieve is that the element is animated while entering the DOM and it happens one after another. What's wrong with my code?

<template>
  <TransitionGroup appear name="stagger" tag="ul">

      {{ num }}

  </TransitionGroup>
</template>

After reading the official doc one more time, I realized that the same animation effect can be made with just transition and it works, which got me wondering what's the main difference between these two approaches?

.stagger-enter-from {
  opacity: 0;
  transform: translateX(-1em);
}
.stagger-enter-active {
  transition: opacity 0.5s linear, transform 0.5s ease;
  transition-delay: calc(var(--order) * 0.15s);
}


问:
Convert a list to String in kotlinx.serialization
I want to convert a list of a model that I've defined to String for saving it in Database I know how to do that in Gson but I want to do the same in kotlinx.serialization

Convert a list of a model to String In Gson:

```<code>val gson = Gson()
return gson.toJson(data)
</code>```

Convert the String to the model in Gson:

```<code>val listType = object : TypeToken<ArrayList<String>>() {}.type
return Gson().fromJson(string, listType)
</code>```

How can I do that in kotlinx.serialization?

Body:
I want to convert a list of a model that I've defined to String for saving it in Database I know how to do that in Gson but I want to do the same in kotlinx.serialization

Convert a list of a model to String In Gson:

val gson = Gson()
return gson.toJson(data)

Convert the String to the model in Gson:

val listType = object : TypeToken<ArrayList<String>>() {}.type
return Gson().fromJson(string, listType)

How can I do that in kotlinx.serialization?


问:
accessing the selected value from filter_select or sharedData object crosstalk R
I want to be able to use the selected value from a crosstalk::filter_select in the title of a plot that is based on the sharedData.  Here is a minimal example of what I am after (except instead of "x" in the title it is the filtered value).</p>
```<code>library(crosstalk)
library(ggplot2)
library(plotly)

shared_mtcars <- SharedData$new(mtcars)

plt <- ggplot(shared_mtcars, aes(wt, mpg))+
  geom_point()+
  labs(title=paste("Weight vs. MPG for", "x", "cylinder cars."))

bscols(widths = c(3,NA),
       list(
         crosstalk::filter_select("cyl", "Cylinders", shared_mtcars, ~cyl, multiple = FALSE)
       ),
      ggplotly(plt)
)
</code>```

Body:
I want to be able to use the selected value from a crosstalk::filter_select in the title of a plot that is based on the sharedData.  Here is a minimal example of what I am after (except instead of "x" in the title it is the filtered value).

library(crosstalk)
library(ggplot2)
library(plotly)

shared_mtcars <- SharedData$new(mtcars)

plt <- ggplot(shared_mtcars, aes(wt, mpg))+
  geom_point()+
  labs(title=paste("Weight vs. MPG for", "x", "cylinder cars."))

bscols(widths = c(3,NA),
       list(
         crosstalk::filter_select("cyl", "Cylinders", shared_mtcars, ~cyl, multiple = FALSE)
       ),
      ggplotly(plt)
)


问:
Installing Github .zip files on Chromebook via Linux
I'm using a Linux Debian terminal, trying to install a Github .zip file by following a walkthrough (from Chromebook). They're using a Windows terminal and access the zip file from a G: drive. They run the following:

```<code>C:\Users\zasur>G:

G:\>cd filename.zip

G:\filename>npm install
</code>```

Which installs the Github zip. I've looked all over online and tried a few different solutions but can't get past the second command they run.

I was able to open /mnt/chromeos/MyFiles/Downloads from Linux by sharing the Downloads folder with it.

I'm not sure how to change the directory from here to the filename.zip and/or run commands from it. Whenever I try to run cd filename.zip or cd /mnt/chromeos/MyFiles/Downloads/filename.zip it always fails. Is this even possible on a Chromebook?

Body:
I'm using a Linux Debian terminal, trying to install a Github .zip file by following a walkthrough (from Chromebook). They're using a Windows terminal and access the zip file from a G: drive. They run the following:

C:\Users\zasur>G:

G:\>cd filename.zip

G:\filename>npm install

Which installs the Github zip. I've looked all over online and tried a few different solutions but can't get past the second command they run.

I was able to open /mnt/chromeos/MyFiles/Downloads from Linux by sharing the Downloads folder with it.

I'm not sure how to change the directory from here to the filename.zip and/or run commands from it. Whenever I try to run cd filename.zip or cd /mnt/chromeos/MyFiles/Downloads/filename.zip it always fails. Is this even possible on a Chromebook?


问:
Access Service layer property in Controller
I'm trying to learn SpEL to inject a property in controller which is inside service layer. The output is however always null.

This is my controller class.

```<code>@RestController
@Validated
 public class RestApp1 implements CONSTANTS, ApplicationContextAware {

@Value("dummy String 3")
String value3;

@Value("#{@dummyServiceLayer.dbProperty}")
String value4;

@Autowired
DummyServiceLayer dummyLayer;

public ApplicationContext context;

@Autowired
RestTemplate restTemplate;

@GetMapping("/dummyGet")
public ResponseEntity<?> getMethodDummy() throws Exception {

    System.out.println("value 3 is : " + value3);
    System.out.println("value 4 is : " + dummyLayer.dbProperty);
        dummyLayer.doingDBstuff();

    return new ResponseEntity("Api Completed", HttpStatus.OK);
}
}
</code>```

This is service layer class

```<code>@Service
 public class DummyServiceLayer {

@Autowired
JdbcTemplate jdbcTemplate;

@Autowired
NamedParameterJdbcTemplate namedJdbcTemplateMaster;

@Value("#{dummyLayer2.getDbProperty('dummyString')}")
public String dbProperty;

@Value("some value")
public String dbProperty1;

@Transactional(propagation = Propagation.REQUIRES_NEW)
@Async("asyncTaskWorkerPool")
public void doingDBstuff() throws Exception {

    System.out.println("object hash : "+this);
        System.out.println("DB property fetched using spring expression library        +"+dbProperty);

}
}
</code>```

The output is like this:
value 3 is : dummy String 3
value 4 is : null

When i debugged the application it seems like when the service layer is called then some proxy object is substituted which contains the correct values.

Can anyone explain why value4 is always null in controller. Tried everything didn't help.

Body:
I'm trying to learn SpEL to inject a property in controller which is inside service layer. The output is however always null.

This is my controller class.

@RestController
@Validated
 public class RestApp1 implements CONSTANTS, ApplicationContextAware {

@Value("dummy String 3")
String value3;

@Value("#{@dummyServiceLayer.dbProperty}")
String value4;

@Autowired
DummyServiceLayer dummyLayer;

public ApplicationContext context;

@Autowired
RestTemplate restTemplate;

@GetMapping("/dummyGet")
public ResponseEntity<?> getMethodDummy() throws Exception {

    System.out.println("value 3 is : " + value3);
    System.out.println("value 4 is : " + dummyLayer.dbProperty);
        dummyLayer.doingDBstuff();

    return new ResponseEntity("Api Completed", HttpStatus.OK);
}
}

This is service layer class

@Service
 public class DummyServiceLayer {

@Autowired
JdbcTemplate jdbcTemplate;

@Autowired
NamedParameterJdbcTemplate namedJdbcTemplateMaster;

@Value("#{dummyLayer2.getDbProperty('dummyString')}")
public String dbProperty;

@Value("some value")
public String dbProperty1;

@Transactional(propagation = Propagation.REQUIRES_NEW)
@Async("asyncTaskWorkerPool")
public void doingDBstuff() throws Exception {

    System.out.println("object hash : "+this);
        System.out.println("DB property fetched using spring expression library        +"+dbProperty);

}
}

The output is like this:
value 3 is : dummy String 3
value 4 is : null

When i debugged the application it seems like when the service layer is called then some proxy object is substituted which contains the correct values.

Can anyone explain why value4 is always null in controller. Tried everything didn't help.


问:
How to start %index% with 1 in OS::Heat::ResourceGroup
I use %index% in OS::Heat::ResourceGroup and it starts with a 0 value.
I want it to start with the value of 1. How to do it?

```<code>resources:
  server_group:
     type: OS::Heat::ResourceGroup
     properties:
        count: 3
        resource_def:
           type: OS::Nova::Server
           name: { get_param: [ server_names, '%index%' ] }
</code>```

I tried with '%index% + 1' but it did not work:

Error return: invalid literal for int() with base 10: '0 + 1'

Body:
I use %index% in OS::Heat::ResourceGroup and it starts with a 0 value.
I want it to start with the value of 1. How to do it?

resources:
  server_group:
     type: OS::Heat::ResourceGroup
     properties:
        count: 3
        resource_def:
           type: OS::Nova::Server
           name: { get_param: [ server_names, '%index%' ] }

I tried with '%index% + 1' but it did not work:

Error return: invalid literal for int() with base 10: '0 + 1'


问:
Firebase events
I have a Flutter mobile with Firebase in the backend. I would like to offer profile boosts to the clients where each user can purchase one or more boosts.  When the user activates a boost, my system should boost user profile for exactly one hour.

My question is how do I trigger events after one hour from the time the boost has started. So if the boost started at 10:31, then an event should be triggered at 11:31 to stop the boost.

There will be lots of users and lots of boosts and those boosts need to be terminated at the correct time.

Title: Firebase events


问:
How to Read Dom Elements From Chrome IAccessible? Is there any way to get interop or any example will be appreciated?
How to read content from google chrome like Likes and Comments ? Is there any way to get attach to chrome access to Chrome ? I do not know how to get chrome from marshal or ROT Table.</p>
```<code>var guid = new Guid("618736E0-3C3D-11CF-810C-00AA00389B71");
            var handle = _desktopEventManager.Process.MainWindowHandle; // Chrome Handle

            var window = NativeWindow.FromHandle(handle);

            var procbook = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(Guid)));
            var procbookp = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(IntPtr)));
            uint u = 0x00000000;
            AccessibleObjectFromWindow(handle, u, guid.ToByteArray(), out procbookp);
            procbook = Marshal.ReadIntPtr(procbookp);
            var iAccessiblePtr = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(Guid)));
            var iAccessibleGuid = new Guid("6d5140c1-7436-11ce-8034-00aa006009fa");
            Marshal.QueryInterface(procbookp, ref iAccessibleGuid, out iAccessiblePtr);
            _iAccessible = (IAccessible)Marshal.GetTypedObjectForIUnknown(iAccessiblePtr, typeof(IAccessible));

            Debug.WriteLine("IAccessible Role is : " + _iAccessible.get_accRole());
            Debug.WriteLine("IAccessible Type: " + _iAccessible.GetType());
            Debug.WriteLine("IAccessible Focus is: " + _iAccessible.accFocus);
            Debug.WriteLine("IAccessible Selection is: " + _iAccessible.accSelection);
            Debug.WriteLine("IAccessible Selection is " + _iAccessible.get_accState());
</code>```

Body:
How to read content from google chrome like Likes and Comments ? Is there any way to get attach to chrome access to Chrome ? I do not know how to get chrome from marshal or ROT Table.

var guid = new Guid("618736E0-3C3D-11CF-810C-00AA00389B71");
            var handle = _desktopEventManager.Process.MainWindowHandle; // Chrome Handle

            var window = NativeWindow.FromHandle(handle);

            var procbook = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(Guid)));
            var procbookp = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(IntPtr)));
            uint u = 0x00000000;
            AccessibleObjectFromWindow(handle, u, guid.ToByteArray(), out procbookp);
            procbook = Marshal.ReadIntPtr(procbookp);
            var iAccessiblePtr = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(Guid)));
            var iAccessibleGuid = new Guid("6d5140c1-7436-11ce-8034-00aa006009fa");
            Marshal.QueryInterface(procbookp, ref iAccessibleGuid, out iAccessiblePtr);
            _iAccessible = (IAccessible)Marshal.GetTypedObjectForIUnknown(iAccessiblePtr, typeof(IAccessible));

            Debug.WriteLine("IAccessible Role is : " + _iAccessible.get_accRole());
            Debug.WriteLine("IAccessible Type: " + _iAccessible.GetType());
            Debug.WriteLine("IAccessible Focus is: " + _iAccessible.accFocus);
            Debug.WriteLine("IAccessible Selection is: " + _iAccessible.accSelection);
            Debug.WriteLine("IAccessible Selection is " + _iAccessible.get_accState());


问:
Parsing conflict in Lemon grammar
I am writing a parser for LaTeX mathematical formulas to convert them into MathML. So I wrote this grammar for Lemon.

```<code>%token BEGIN_GROUP END_GROUP MATH_SHIFT ALIGNMENT_TAB.
%token END_OF_LINE PARAMETER SUPERSCRIPT SUBSCRIPT.
%token SPACE LETTER DIGIT SYMBOL.
%token COMMAND COMMAND_LEFT COMMAND_RIGHT.
%token COMMAND_LIMITS COMMAND_NOLIMITS.
%token BEGIN_ENV END_ENV.
%token NBSP.

/* Some API */

document ::= list.

list ::= list element.
list ::= .

element ::= identifier(Id).
element ::= symbol(O).
element ::= number(Num).

identifier ::= LETTER.

symbol ::= SYMBOL.

number(N) ::= number DIGIT(D). /* Append digit */
number(N) ::= DIGIT(D). /* Init digits */

/* Lexer code */
</code>```

This grammar is incomplete, it doesn't contains main program code. This is an output from Lemon parser:

```<code>State 2:
      (2) element ::= number *
          number ::= number * DIGIT

                         DIGIT shift-reduce 3      number ::= number DIGIT
                         DIGIT reduce       2       ** Parsing conflict **
                     {default} reduce       2      element ::= number
</code>```

This grammar produces one parsing conflict. How can I resolve this conflict?

I am writing my parser for the first time so I don't have enough experience to solve this problem.

Title: Parsing conflict in Lemon grammar

Body:
I am writing a parser for LaTeX mathematical formulas to convert them into MathML. So I wrote this grammar for Lemon.

%token BEGIN_GROUP END_GROUP MATH_SHIFT ALIGNMENT_TAB.
%token END_OF_LINE PARAMETER SUPERSCRIPT SUBSCRIPT.
%token SPACE LETTER DIGIT SYMBOL.
%token COMMAND COMMAND_LEFT COMMAND_RIGHT.
%token COMMAND_LIMITS COMMAND_NOLIMITS.
%token BEGIN_ENV END_ENV.
%token NBSP.

/* Some API */

document ::= list.

list ::= list element.
list ::= .

element ::= identifier(Id).
element ::= symbol(O).
element ::= number(Num).

identifier ::= LETTER.

symbol ::= SYMBOL.

number(N) ::= number DIGIT(D). /* Append digit */
number(N) ::= DIGIT(D). /* Init digits */

/* Lexer code */

This grammar is incomplete, it doesn't contains main program code. This is an output from Lemon parser:

State 2:
      (2) element ::= number *
          number ::= number * DIGIT

                         DIGIT shift-reduce 3      number ::= number DIGIT
                         DIGIT reduce       2       ** Parsing conflict **
                     {default} reduce       2      element ::= number

This grammar produces one parsing conflict. How can I resolve this conflict?

I am writing my parser for the first time so I don't have enough experience to solve this problem.