问:
Detect headset Call Button press in Android
How do you detect a user pressing the call button on a connected Bluetooth Headset?

While multiple posts address the topic I think I have tried most (if not all) and still have not found a solution which works

The following simplified code connects to the Bluetooth headset in onResume()

It then logs a message if ANY intent is received (which it never does)

```<code>class MainActivity : AppCompatActivity() {

    private lateinit var audioManager : AudioManager
    private var headsetDevice: AudioDeviceInfo? = null // device used for audio input

    private lateinit var mediaSession: MediaSession
    private lateinit var headsetButtonIntentReceiver:  HeadsetButtonIntentReceiver
    private lateinit var headsetButtonIntentFilter: IntentFilter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)

        audioManager = getSystemService(Context.AUDIO_SERVICE) as AudioManager
        mediaSession = MediaSession(this, packageName)

        headsetButtonIntentFilter = IntentFilter(Intent.ACTION_CALL_BUTTON)
        headsetButtonIntentReceiver = HeadsetButtonIntentReceiver()

    }

    class HeadsetButtonIntentReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent) {
            Log.d(TAG, "HeadsetButtonIntentReceiver() !!!!")
            abortBroadcast()
        }
    }

    override fun onResume() {
        super.onResume()
        val devices = audioManager.availableCommunicationDevices
        Log.d(TAG, "audioManager.availableCommunicationDevices found ${devices.size} devices")
        headsetDevice = devices.firstOrNull { it.type == AudioDeviceInfo.TYPE_BLUETOOTH_SCO }
        if (headsetDevice != null) {
            Log.d(TAG, "setCommunicationsDevice ${headsetDevice!!.productName}")
            if (!audioManager.setCommunicationDevice(headsetDevice!!)) Log.d(TAG, "Failed to connect to headset")
        }
        mediaSession.isActive = true
        this.registerReceiver(headsetButtonIntentReceiver, headsetButtonIntentFilter)
    }

    override fun onStop() {
        super.onStop()
        if (headsetDevice != null)
            audioManager.clearCommunicationDevice() // disconnect from the headset
        mediaSession.release()
        mediaSession.isActive = false
        this.unregisterReceiver(headsetButtonIntentReceiver)
    }

    companion object {
        const val TAG = "MediaButton"
    }
}
</code>```

I have tried adding different Button actions to the intent filter - also without success

```<code>headsetButtonIntentFilter = IntentFilter()
headsetButtonIntentFilter.addAction(Intent.ACTION_MEDIA_BUTTON)
headsetButtonIntentFilter.addAction(Intent.ACTION_CALL_BUTTON)
</code>```

I have tried adding the intent into the Manifest (although several posts suggest this is not required)

```<code><intent-filter>
    <action android:name="android.intent.action.CALL_BUTTON" />
</intent-filter>
</code>```

I have tried specifying the receiver in the Manifest - but also nothing

```<code><receiver android:name=".MainActivity$HeadsetButtonIntentReceiver" android:exported="false">
    <intent-filter>
        <action android:name="android.intent.action.CALL_BUTTON"/>
    </intent-filter>
</receiver>
</code>```

For completeness I even tried overriding the onKeyDown() and dispatchKeyEvent() but these are also not being triggered

```<code>override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
    Log.d(TAG, "onKeyDown() KEYCODE $keyCode Event ${event?.action}")
    return super.onKeyDown(keyCode, event)
}

    override fun dispatchKeyEvent(event: KeyEvent?): Boolean {
        Log.d(TAG, "dispatchKeyEvent() KEYCODE ${event?.keyCode} Event ${event?.action}")
        return super.dispatchKeyEvent(event)
    }

</code>```

Frustratingly there are indications the code is close to working. Specifically a double press of the headset call button dials the previous number but when the above code is running that no longer occurs indicating the App is consuming the call button press. Unfortunately the App is not being notified of this action!

Happy to try solutions posted in previous questions I may have missed!

Body:
How do you detect a user pressing the call button on a connected Bluetooth Headset?

While multiple posts address the topic I think I have tried most (if not all) and still have not found a solution which works

The following simplified code connects to the Bluetooth headset in onResume()

It then logs a message if ANY intent is received (which it never does)

class MainActivity : AppCompatActivity() {

    private lateinit var audioManager : AudioManager
    private var headsetDevice: AudioDeviceInfo? = null // device used for audio input

    private lateinit var mediaSession: MediaSession
    private lateinit var headsetButtonIntentReceiver:  HeadsetButtonIntentReceiver
    private lateinit var headsetButtonIntentFilter: IntentFilter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)

        audioManager = getSystemService(Context.AUDIO_SERVICE) as AudioManager
        mediaSession = MediaSession(this, packageName)

        headsetButtonIntentFilter = IntentFilter(Intent.ACTION_CALL_BUTTON)
        headsetButtonIntentReceiver = HeadsetButtonIntentReceiver()

    }

    class HeadsetButtonIntentReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent) {
            Log.d(TAG, "HeadsetButtonIntentReceiver() !!!!")
            abortBroadcast()
        }
    }

    override fun onResume() {
        super.onResume()
        val devices = audioManager.availableCommunicationDevices
        Log.d(TAG, "audioManager.availableCommunicationDevices found ${devices.size} devices")
        headsetDevice = devices.firstOrNull { it.type == AudioDeviceInfo.TYPE_BLUETOOTH_SCO }
        if (headsetDevice != null) {
            Log.d(TAG, "setCommunicationsDevice ${headsetDevice!!.productName}")
            if (!audioManager.setCommunicationDevice(headsetDevice!!)) Log.d(TAG, "Failed to connect to headset")
        }
        mediaSession.isActive = true
        this.registerReceiver(headsetButtonIntentReceiver, headsetButtonIntentFilter)
    }

    override fun onStop() {
        super.onStop()
        if (headsetDevice != null)
            audioManager.clearCommunicationDevice() // disconnect from the headset
        mediaSession.release()
        mediaSession.isActive = false
        this.unregisterReceiver(headsetButtonIntentReceiver)
    }

    companion object {
        const val TAG = "MediaButton"
    }
}

I have tried adding different Button actions to the intent filter - also without success

headsetButtonIntentFilter = IntentFilter()
headsetButtonIntentFilter.addAction(Intent.ACTION_MEDIA_BUTTON)
headsetButtonIntentFilter.addAction(Intent.ACTION_CALL_BUTTON)

I have tried adding the intent into the Manifest (although several posts suggest this is not required)

<intent-filter>
    <action android:name="android.intent.action.CALL_BUTTON" />
</intent-filter>

I have tried specifying the receiver in the Manifest - but also nothing

<receiver android:name=".MainActivity$HeadsetButtonIntentReceiver" android:exported="false">
    <intent-filter>
        <action android:name="android.intent.action.CALL_BUTTON"/>
    </intent-filter>
</receiver>

For completeness I even tried overriding the onKeyDown() and dispatchKeyEvent() but these are also not being triggered

override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
    Log.d(TAG, "onKeyDown() KEYCODE $keyCode Event ${event?.action}")
    return super.onKeyDown(keyCode, event)
}

    override fun dispatchKeyEvent(event: KeyEvent?): Boolean {
        Log.d(TAG, "dispatchKeyEvent() KEYCODE ${event?.keyCode} Event ${event?.action}")
        return super.dispatchKeyEvent(event)
    }

Frustratingly there are indications the code is close to working. Specifically a double press of the headset call button dials the previous number but when the above code is running that no longer occurs indicating the App is consuming the call button press. Unfortunately the App is not being notified of this action!

Happy to try solutions posted in previous questions I may have missed!


来源: stackexchange

问:
Error with Jest and React importing SCSS files
I am writing unit test cases using Jest and my application is running with reactjs. I am trying to test a page component in my React application, but I am receiving errors that are shown in the following screenshot;

enter image description here

● Test suite failed to run

```<code>src/pages/unregistered/pep-login/login/login-layout.tsx:13:31 - error TS2307: Cannot find module '../../landing-new.scss'.

13 import * as stylesLayout from '../../landing-new.scss';
                                 ~~~~~~~~~~~~~~~~~~~~~~~~
</code>```

FAIL  src/pages/adu/dashboard/application-metrics/test/totalFailed.test.tsx
● Test suite failed to run

```<code>src/pages/adu/dashboard/application-metrics/total-failed-api-list.tsx:5:31 - error TS2307: Cannot find
</code>```

module './application-metrics.scss'.

```<code>5 import * as stylesLayout from './application-metrics.scss';
</code>```

Here is my package.json configurations

"jest": {
"collectCoverage": true,
"coverageDirectory": "target/testCoverage",
"collectCoverageFrom": [
"src/**/.{ts,tsx}"
],
"setupFiles": [
"/config/polyfills.js"
],
"testPathIgnorePatterns": [
"/\\[/\\]"
],
"testEnvironment": "node",
"testURL": "http://localhost",
"transform": {
".(ts|tsx)": "/node_modules/ts-jest/preprocessor.js",
".+\.(css|styl|less|sass|scss)$": "jest-transform-css"
},
"transformIgnorePatterns": [
"[/\\]node_modules[/\\].+\.(js|jsx)$"
],
"moduleNameMapper": {
"^reac-native$": "react-native-web"
},
"moduleFileExtensions": [
"ts",
"tsx",
"js"
],
"testRegex": "(/tests/.|\.(test|spec))\.(ts|tsx|js)$"
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

enter image description here

ContentLicense: CC BY-SA 4.0

Body:
I am writing unit test cases using Jest and my application is running with reactjs. I am trying to test a page component in my React application, but I am receiving errors that are shown in the following screenshot;

enter image description here

● Test suite failed to run

src/pages/unregistered/pep-login/login/login-layout.tsx:13:31 - error TS2307: Cannot find module '../../landing-new.scss'.

13 import * as stylesLayout from '../../landing-new.scss';
                                 ~~~~~~~~~~~~~~~~~~~~~~~~

FAIL  src/pages/adu/dashboard/application-metrics/test/totalFailed.test.tsx
● Test suite failed to run

src/pages/adu/dashboard/application-metrics/total-failed-api-list.tsx:5:31 - error TS2307: Cannot find

module './application-metrics.scss'.

5 import * as stylesLayout from './application-metrics.scss';

Here is my package.json configurations

"jest": {
"collectCoverage": true,
"coverageDirectory": "target/testCoverage",
"collectCoverageFrom": [
"src/**/.{ts,tsx}"
],
"setupFiles": [
"/config/polyfills.js"
],
"testPathIgnorePatterns": [
"/\\[/\\]"
],
"testEnvironment": "node",
"testURL": "http://localhost",
"transform": {
".(ts|tsx)": "/node_modules/ts-jest/preprocessor.js",
".+\.(css|styl|less|sass|scss)$": "jest-transform-css"
},
"transformIgnorePatterns": [
"[/\\]node_modules[/\\].+\.(js|jsx)$"
],
"moduleNameMapper": {
"^reac-native$": "react-native-web"
},
"moduleFileExtensions": [
"ts",
"tsx",
"js"
],
"testRegex": "(/tests/.|\.(test|spec))\.(ts|tsx|js)$"
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

enter image description here


问:
Multiple Video Playing Simultaneosly PLay only 1 at a time
`I have a video slider in my page all videos are in < video > tag in different .
So if i play 1 video and try to play other video both the video are playing same time i neeed to pause or stop the last video and when i play the second or any other video on the same screen. There should be only 1 video play at a time . Like if video 1 is playing when play video 2 video 1 should be pause/stop

```<code>$('video').on('click', function(e) {
  let vids = $.makeArray($(this).siblings('video'));

  vids.forEach(vid => {
    vid.pause();
    vid.classList.remove('active');
  });

  $(this).toggleClass('active');
  if ($(this).is('.active')) {
    this.play();
  } else {
    this.pause();
  }
});
</code>```

i tried this but when i click 1st video its not playing and acive class toggle working. Its not working like how i expected video not pause or active class not removing if i press other video `

Body:
`I have a video slider in my page all videos are in < video > tag in different .
So if i play 1 video and try to play other video both the video are playing same time i neeed to pause or stop the last video and when i play the second or any other video on the same screen. There should be only 1 video play at a time . Like if video 1 is playing when play video 2 video 1 should be pause/stop

$('video').on('click', function(e) {
  let vids = $.makeArray($(this).siblings('video'));

  vids.forEach(vid => {
    vid.pause();
    vid.classList.remove('active');
  });

  $(this).toggleClass('active');
  if ($(this).is('.active')) {
    this.play();
  } else {
    this.pause();
  }
});

i tried this but when i click 1st video its not playing and acive class toggle working. Its not working like how i expected video not pause or active class not removing if i press other video `


问:
Android Studio is creating debug packages
I have created an Android project. Somehow Android Studio is create weird packages, I wonder why?

I tried to delete them as well, but they recreated themselves.

Android Studio Version:

```<code>Android Studio Flamingo | 2022.2.1 Canary 11
</code>```

Body:
I have created an Android project. Somehow Android Studio is create weird packages, I wonder why?

I tried to delete them as well, but they recreated themselves.

Android Studio Version:

Android Studio Flamingo | 2022.2.1 Canary 11


问:
Salesforce Mobile App Navigation Item Customization
Is it possible to develop a custom aura/lwc component that helps each user to set up his salesforce app main page when he first open the app?

I know that it is possible to do that through the app edit but unfortunately our client need to do it through a custom component so he can select among drop down list one page and when he click save it will shows him the selected page as a main page when he opens the salesforce mobile app.


问:
ERROR importing SQL Database in PHP Admin
Error Screenshot

I am trying to Import database in MyPHPAdmin I'm getting an error message. The same file was successfully imported in Windows Environment but i'm facing this issue in MAC_OS Monterey 12.6.1
Can anyone help me with this ?


问:
Make a text-to-speech dialog in different voices in python gtts
I'm trying to make a conversation between two text-to-speech voices using gtts. I'm trying to make one be english sound french. I'm having trouble layering one voice to talk then another to talk right after it like an actual dialog. I was thinking about splitting up the dialog into two sentences, but they just talk over each other when I do try to merge them unless I somehow know exactly when each is done with a sentence.</p>
```<code>from gtts import gTTS

mytext = "Mary: Can I stay up for tonight? Sarah: No, you have school tomorrow. Mary: But all my friends are staying up! Sarah: No, rules are rules, no staying up on a school day. Mary: What if I do dishes for a week? Sarah: Deal."

language = 'fr'
language2 = 'en'
myobj = gTTS(text=mytext, lang=language, slow=False)
#myobj2 = gTTS(text = mytext2, lang=language2, slow=False) #I split mytext into just Marys talk and they just talked over each other.
myobj.save("testing.mp3")
</code>```

Body:
I'm trying to make a conversation between two text-to-speech voices using gtts. I'm trying to make one be english sound french. I'm having trouble layering one voice to talk then another to talk right after it like an actual dialog. I was thinking about splitting up the dialog into two sentences, but they just talk over each other when I do try to merge them unless I somehow know exactly when each is done with a sentence.

from gtts import gTTS

mytext = "Mary: Can I stay up for tonight? Sarah: No, you have school tomorrow. Mary: But all my friends are staying up! Sarah: No, rules are rules, no staying up on a school day. Mary: What if I do dishes for a week? Sarah: Deal."

language = 'fr'
language2 = 'en'
myobj = gTTS(text=mytext, lang=language, slow=False)
#myobj2 = gTTS(text = mytext2, lang=language2, slow=False) #I split mytext into just Marys talk and they just talked over each other.
myobj.save("testing.mp3")


问:
How to import quip spreadsheet data to s3?
I saw some code on quip to s3 exporter in GitHub but it seems like that page has been taken down.

Basically for any change event (or regular interval sync also works) in the quip, an s3 bucket (table) should be updated. The code I saw in GitHub had used Lambda among other AWS services.


问:
Nakama service gets terminated on aws t2xlrage Ireland
our project run fine after half an hour gets terminated. currently our project alive and we have a problem with the nakama service getting terminated we have checked Nakama catches this error :
Nakama service error

and regarding the infrastructure wise we have hosted on the AWS t2xlarge instance

we have realized that a fatal error occur in the go build in Nakama it seem mutex happed 2 goroutines try to reach the same resource at the same time and race condition happened.

We have checked server log nakam fatal error concurrent map write after that Nakama catch this exception:

```<code>github.com/heroiclabs/nakama/v3/server.NewRuntimeEventQueue.func1()
nakama: github.com/heroiclabs/nakama/v3/server/runtime_event.go:46 +0x92
nakama: created by github.com/heroiclabs/nakama/v3/server.NewRuntimeEventQueue
nakama: github.com/heroiclabs/nakama/v3/server/runtime_event.go:44 +0x117
nakama: goroutine 382027 [IO wait]:
nakama: internal/poll.runtime_pollWait(0x7f0df2b1c9f0, 0x72)
nakama: runtime/netpoll.go:302 +0x89
nakama: internal/poll.(*pollDesc).wait(0xc000df6580?, 0xc00019c000?, 0x0)
nakama: internal/poll/fd_poll_runtime.go:83 +0x32
nakama: internal/poll.(*pollDesc).waitRead(...)
nakama: internal/poll/fd_poll_runtime.go:88
nakama: internal/poll.(*FD).Read(0xc000df6580, {0xc00019c000, 0x1000, 0x1000})

</code>```
```<code>nakama: goroutine 84 [select, 1 minutes]:
nakama: github.com/blugelabs/bluge/index.analysisWorker(0xc0004c04e0, 0xc0004c0540)
nakama: github.com/blugelabs/bluge@v0.1.9/index/writer.go:549 +0x7f
nakama: github.com/blugelabs/bluge/index.OpenWriter.func1()
nakama: github.com/blugelabs/bluge@v0.1.9/index/writer.go:69 +0x2f
nakama: created by github.com/blugelabs/bluge/index.defaultConfig.func2
nakama: github.com/blugelabs/bluge@v0.1.9/index/config.go:205 +0x19
nakama: goroutine 85 [select, 1 minutes]:
nakama: github.com/blugelabs/bluge/index.analysisWorker(0xc0004c04e0, 0xc0004c0540)
nakama: github.com/blugelabs/bluge@v0.1.9/index/writer.go:549 +0x7f
nakama: github.com/blugelabs/bluge/index.OpenWriter.func1()
nakama: github.com/blugelabs/bluge@v0.1.9/index/writer.go:69 +0x2f
nakama: created by github.com/blugelabs/bluge/index.defaultConfig.func2
nakama: github.com/blugelabs/bluge@v0.1.9/index/config.go:205 +0x19
nakama: goroutine 86 [select]:
</code>```

Nakama Fatal error

Body:
our project run fine after half an hour gets terminated. currently our project alive and we have a problem with the nakama service getting terminated we have checked Nakama catches this error :
Nakama service error

and regarding the infrastructure wise we have hosted on the AWS t2xlarge instance

we have realized that a fatal error occur in the go build in Nakama it seem mutex happed 2 goroutines try to reach the same resource at the same time and race condition happened.

We have checked server log nakam fatal error concurrent map write after that Nakama catch this exception:

github.com/heroiclabs/nakama/v3/server.NewRuntimeEventQueue.func1()
nakama: github.com/heroiclabs/nakama/v3/server/runtime_event.go:46 +0x92
nakama: created by github.com/heroiclabs/nakama/v3/server.NewRuntimeEventQueue
nakama: github.com/heroiclabs/nakama/v3/server/runtime_event.go:44 +0x117
nakama: goroutine 382027 [IO wait]:
nakama: internal/poll.runtime_pollWait(0x7f0df2b1c9f0, 0x72)
nakama: runtime/netpoll.go:302 +0x89
nakama: internal/poll.(*pollDesc).wait(0xc000df6580?, 0xc00019c000?, 0x0)
nakama: internal/poll/fd_poll_runtime.go:83 +0x32
nakama: internal/poll.(*pollDesc).waitRead(...)
nakama: internal/poll/fd_poll_runtime.go:88
nakama: internal/poll.(*FD).Read(0xc000df6580, {0xc00019c000, 0x1000, 0x1000})

nakama: goroutine 84 [select, 1 minutes]:
nakama: github.com/blugelabs/bluge/index.analysisWorker(0xc0004c04e0, 0xc0004c0540)
nakama: github.com/blugelabs/bluge@v0.1.9/index/writer.go:549 +0x7f
nakama: github.com/blugelabs/bluge/index.OpenWriter.func1()
nakama: github.com/blugelabs/bluge@v0.1.9/index/writer.go:69 +0x2f
nakama: created by github.com/blugelabs/bluge/index.defaultConfig.func2
nakama: github.com/blugelabs/bluge@v0.1.9/index/config.go:205 +0x19
nakama: goroutine 85 [select, 1 minutes]:
nakama: github.com/blugelabs/bluge/index.analysisWorker(0xc0004c04e0, 0xc0004c0540)
nakama: github.com/blugelabs/bluge@v0.1.9/index/writer.go:549 +0x7f
nakama: github.com/blugelabs/bluge/index.OpenWriter.func1()
nakama: github.com/blugelabs/bluge@v0.1.9/index/writer.go:69 +0x2f
nakama: created by github.com/blugelabs/bluge/index.defaultConfig.func2
nakama: github.com/blugelabs/bluge@v0.1.9/index/config.go:205 +0x19
nakama: goroutine 86 [select]:

Nakama Fatal error


问:
MFi Product Plan ID (PPID)
I have created one application with is working fine using the the ppid for serial communication.

Can we use multiple MFi Product Plan ID (PPID) of the hardware accessory associated with same iOS app?

Title: MFi Product Plan ID (PPID)


问:
Loading spinner not showing up in React JS web app
I'm trying to include a loading spinner in my react web app to show the loading animation when the API is fetching the data. Below is the code:

```<code>import Head from "next/head";
import React, { useState } from "react";
import styles from "./index.module.css";
import Spinner from 'react-bootstrap/Spinner';

export default function Home() {
  const [bookInput, setBookInput] = useState("");
  const [result, setResult] = useState();
  const [isLoading, setIsLoading] = useState(false);

  async function onSubmit(event) {
    setIsLoading(true);
    event.preventDefault();
    try {
      const response = await fetch("/api/generate", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ book: bookInput }),
      });

      const data = await response.json();
      if (response.status !== 200) {
        throw data.error || new Error(`Request failed with status ${response.status}`);
      }
      setResult(data.result);
      setIsLoading(false);
      //setBookInput("");
    } catch(error) {
      // Consider implementing your own error handling logic here
      console.error(error);
      alert(error.message);
      setIsLoading(false);
    }
  }

  return (
    <div>
      <Head>
        <title>Quickread</title>
        <link rel="icon" href="/book.png" />
      </Head>

      <main className={styles.main}>
        <img src="/book.png" className={styles.icon} />
        <h2>QuickRead</h2>
        <form onSubmit={onSubmit}>
          <input
            type="text"
            name="book"
            placeholder="Enter a Book Title"
            value={bookInput}
            onChange={(e) => setBookInput(e.target.value)}
          />
           {isLoading ? <Spinner animation="border" role="status"/> : <input type="submit" value="Summarize" />}
        </form>
        <div className={styles.result}>{result}</div>
      </main>
    </div>
  );
}

</code>```

I am using the react-bootstrap library for the loading spinner but not sure why is it not showing when the API is fetching the data. Appreciate if someone can help me on this.

Body:
I'm trying to include a loading spinner in my react web app to show the loading animation when the API is fetching the data. Below is the code:

import Head from "next/head";
import React, { useState } from "react";
import styles from "./index.module.css";
import Spinner from 'react-bootstrap/Spinner';

export default function Home() {
  const [bookInput, setBookInput] = useState("");
  const [result, setResult] = useState();
  const [isLoading, setIsLoading] = useState(false);

  async function onSubmit(event) {
    setIsLoading(true);
    event.preventDefault();
    try {
      const response = await fetch("/api/generate", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ book: bookInput }),
      });

      const data = await response.json();
      if (response.status !== 200) {
        throw data.error || new Error(`Request failed with status ${response.status}`);
      }
      setResult(data.result);
      setIsLoading(false);
      //setBookInput("");
    } catch(error) {
      // Consider implementing your own error handling logic here
      console.error(error);
      alert(error.message);
      setIsLoading(false);
    }
  }

  return (

        <title>Quickread</title>
        <link rel="icon" href="/book.png" />

QuickRead

        <form onSubmit={onSubmit}>
          <input
            type="text"
            name="book"
            placeholder="Enter a Book Title"
            value={bookInput}
            onChange={(e) => setBookInput(e.target.value)}
          />
           {isLoading ? <Spinner animation="border" role="status"/> : <input type="submit" value="Summarize" />}
        </form>

{result}

  );
}

I am using the react-bootstrap library for the loading spinner but not sure why is it not showing when the API is fetching the data. Appreciate if someone can help me on this.


问:
Type error: function() got multiple values for argument
Below python 3 code gives an type error

```<code>def print_lst(lst, *list2):
    print(lst)
    print(*list2)

list1 = [1,2,3]
list2 = [4,5,6]
print_lst(lst=list1, *list2)  # Keywords included
</code>```

TypeError: print_lst() got multiple values for argument 'list1'

But this does not

```<code>def print_lst(lst, *list2):
    print(lst)
    print(*list2)

list1 = [1,2,3]
list2 = [4,5,6]
print_lst(list1, *list2)  # No keywords included
</code>```

The only thing that separates the two pieces of code is in one I included a keyword and in other I did not.
The outcome should be the same, right?

Body:
Below python 3 code gives an type error

def print_lst(lst, *list2):
    print(lst)
    print(*list2)

list1 = [1,2,3]
list2 = [4,5,6]
print_lst(lst=list1, *list2)  # Keywords included

TypeError: print_lst() got multiple values for argument 'list1'

But this does not

def print_lst(lst, *list2):
    print(lst)
    print(*list2)

list1 = [1,2,3]
list2 = [4,5,6]
print_lst(list1, *list2)  # No keywords included

The only thing that separates the two pieces of code is in one I included a keyword and in other I did not.
The outcome should be the same, right?


问:
Reportlab balanced cols control split of flowables
I am using BalancedColumns to generate multiple column layout.
I am not sure, how to resolve an issue of the split happening of the Flowables across the column frames.

I have a heading and it's content. I don't want BalancedColumns to split the flowables in such a way that heading is part of one column and its content is part of another.

The content of the paragraph can split.

The basic python code:

from reportlab.platypus.flowables import BalancedColumns, CondPageBreak
from reportlab.platypus import BaseDocTemplate, Paragraph, Spacer, Frame, PageTemplate, PageBreak
from reportlab.lib.units import mm
from reportlab.lib.pagesizes import A4, LETTER
import os
from reportlab.lib.colors import HexColor

framewidth = A4[0] - 10*mm
frameheight = A4[1] - 20*mm
portrait_frame = Frame(5*mm, 10*mm, framewidth, frameheight,
                                    leftPadding=0,
                                    bottomPadding=0,
                                    rightPadding=0,
                                    topPadding=0,
                                    id=0,
                                    showBoundary=False )
pTemplate = PageTemplate(id=0,frames=[portrait_frame])
templates = [pTemplate]

pdfPath = os.path.abspath(os.path.join(os.path.dirname(__file__), 'balancedColTest.pdf'))

doc = BaseDocTemplate(pdfPath, pagesize=A4, rightMargin=2*mm, leftMargin=2*mm,topMargin=5*mm,bottomMargin=5*mm,showBoundary=0)
doc.addPageTemplates(templates)

# generate stories for balanced columns
story = []
minPadding = 2
for i in range(3):
    fs = []
    numOfFlowables = random.choice([2, 5, 6, 1, 3])
    padding = minPadding + 5*i

    for ii in range(numOfFlowables):
        text = '  Heading
'
        heading = Paragraph(text)
        heading.keepWithNext = True
        fs.append(heading)
        fs.append(Paragraph("This is another text in new Para flowable."))

    # numCols = 2 if i%2 == 0 else 3
    numCols = 2
    bCols = BalancedColumns(fs, nCols=numCols, spaceAfter=5*mm, vLinesStrokeColor=HexColor('#77D179'), vLinesStrokeWidth=0.5)
    story.append(bCols)

doc.build(story)
```
<p><img src="https://i.stack.imgur.com/9NmCH.png" alt="Issue demo" /></p>
<p>Even if I try to use <code>keepWithNext=True</code> the flowables are not part of same frame.</p>
<p>If I use <code>KeepTogether</code>, the BalanceColumns takes the entire space of the page.</p>
<pre class="lang-py prettyprint-override"><code>        heading = Paragraph(text)
        content = Paragraph("This is another text in the paragraph")
        f= KeepTogether([heading, content])
        fs.append(f)
</code>```

Can anyone suggest a solution so that the heading and its underlying paragraph can remain in the same frame?

Body:
I am using BalancedColumns to generate multiple column layout.
I am not sure, how to resolve an issue of the split happening of the Flowables across the column frames.

I have a heading and it's content. I don't want BalancedColumns to split the flowables in such a way that heading is part of one column and its content is part of another.

The content of the paragraph can split.

The basic python code:

from reportlab.platypus.flowables import BalancedColumns, CondPageBreak
from reportlab.platypus import BaseDocTemplate, Paragraph, Spacer, Frame, PageTemplate, PageBreak
from reportlab.lib.units import mm
from reportlab.lib.pagesizes import A4, LETTER
import os
from reportlab.lib.colors import HexColor

framewidth = A4[0] - 10*mm
frameheight = A4[1] - 20*mm
portrait_frame = Frame(5*mm, 10*mm, framewidth, frameheight,
                                    leftPadding=0,
                                    bottomPadding=0,
                                    rightPadding=0,
                                    topPadding=0,
                                    id=0,
                                    showBoundary=False )
pTemplate = PageTemplate(id=0,frames=[portrait_frame])
templates = [pTemplate]

pdfPath = os.path.abspath(os.path.join(os.path.dirname(__file__), 'balancedColTest.pdf'))

doc = BaseDocTemplate(pdfPath, pagesize=A4, rightMargin=2*mm, leftMargin=2*mm,topMargin=5*mm,bottomMargin=5*mm,showBoundary=0)
doc.addPageTemplates(templates)

# generate stories for balanced columns
story = []
minPadding = 2
for i in range(3):
    fs = []
    numOfFlowables = random.choice([2, 5, 6, 1, 3])
    padding = minPadding + 5*i

    for ii in range(numOfFlowables):
        text = '  Heading
'
        heading = Paragraph(text)
        heading.keepWithNext = True
        fs.append(heading)
        fs.append(Paragraph("This is another text in new Para flowable."))

    # numCols = 2 if i%2 == 0 else 3
    numCols = 2
    bCols = BalancedColumns(fs, nCols=numCols, spaceAfter=5*mm, vLinesStrokeColor=HexColor('#77D179'), vLinesStrokeWidth=0.5)
    story.append(bCols)

doc.build(story)

Even if I try to use keepWithNext=True the flowables are not part of same frame.

If I use KeepTogether, the BalanceColumns takes the entire space of the page.

        heading = Paragraph(text)
        content = Paragraph("This is another text in the paragraph")
        f= KeepTogether([heading, content])
        fs.append(f)

Can anyone suggest a solution so that the heading and its underlying paragraph can remain in the same frame?


问:
How to handle textView, which can be expandable according to the text inside UITableViewCell
This is the textView, I want it to be expandable according the text which is inside UITableViewCell.

I have tried to give tableView height, but I am unable to expand UITextView.


问:
How to set width for rect element in a bar chart using d3
I'm trying to plot a simple bar chart with date as x axis and temperature value as y axis. I'm using d3 library.

Created the xScale ans yScale as

```<code>const xScale = d3
    .scaleTime()
    .domain(d3.extent(dataset, xAccessor))
    .range([0, dimensions.boundWidth]);

const yScale = d3
    .scaleLinear()
    .domain([0, d3.max(dataset, yAccessor)])
    .range([dimensions.boundHeight, 0]);
</code>```

Set the accessor functions as

```<code>const dateParse = d3.timeParse("%Y-%m-%d");
const xAccessor = (d) => dateParse(d["date"]);
const yAccessor = (d) => d["temperatureMax"];
</code>```

And drew the rectangles using

```<code>const barsGroup = bounds.append("g");
const barGroups = barsGroup
    .selectAll("mybars")
    .data(dataset.slice(0, 10))
    .join("g");

const barRects = barGroups
    .append("rect")
    .attr("x", (d) => xScale(xAccessor(d)))
    .attr("y", (d) => yScale(yAccessor(d)))
    .attr("width", "10")
    .attr("height", (d) => dimensions.boundHeight - yScale(yAccessor(d)))
    .attr("fill", "darkgray");
</code>```

I'm trying to find out how to set the width attribute. Here I set it as a constant "10" just to see something on screen. Also trying to find out how to set proper spacing between each bars. I have a set up a codesandbox.io with the above set up. Any suggestions would be really helpful.

Body:
I'm trying to plot a simple bar chart with date as x axis and temperature value as y axis. I'm using d3 library.

Created the xScale ans yScale as

const xScale = d3
    .scaleTime()
    .domain(d3.extent(dataset, xAccessor))
    .range([0, dimensions.boundWidth]);

const yScale = d3
    .scaleLinear()
    .domain([0, d3.max(dataset, yAccessor)])
    .range([dimensions.boundHeight, 0]);

Set the accessor functions as

const dateParse = d3.timeParse("%Y-%m-%d");
const xAccessor = (d) => dateParse(d["date"]);
const yAccessor = (d) => d["temperatureMax"];

And drew the rectangles using

const barsGroup = bounds.append("g");
const barGroups = barsGroup
    .selectAll("mybars")
    .data(dataset.slice(0, 10))
    .join("g");

const barRects = barGroups
    .append("rect")
    .attr("x", (d) => xScale(xAccessor(d)))
    .attr("y", (d) => yScale(yAccessor(d)))
    .attr("width", "10")
    .attr("height", (d) => dimensions.boundHeight - yScale(yAccessor(d)))
    .attr("fill", "darkgray");

I'm trying to find out how to set the width attribute. Here I set it as a constant "10" just to see something on screen. Also trying to find out how to set proper spacing between each bars. I have a set up a codesandbox.io with the above set up. Any suggestions would be really helpful.


问:
Can we distribute incoming traffic based on the resource utilization of a webserver using NGINX?
I'm doing Nginx POC for a project and want to know if diverting the incoming traffic based on the resource utilization of the webservers. For example, if a webserver has the CPU utilization over 80% Nginx should not send any request to that particular. It has to send requests to the servers which has the CPU utilization lower than 80%. Thanks in advance.

We have least connections load balancing method for Nginx which diverts the traffic to the webserver which has the least connections, but is it possible to divert the traffic as per the resource utilization on a webserver?


问:
Flutter Reorder-able Widgets Size
I am trying to create a Flutter page with reorder-able widgets of different sizes. The closest analogy is like Android/iOS home screens with widgets.

Both of these OS' can be have apps (1x1 size), small widgets (4x1), and even large widgets (4x4) on the same page. More so, when a large app takes up the full width of a page, it re-orders the widgets below/above it as to not interfere with the UI.

I am trying to do the same with Flutter, and hopefully make is so that user's can move widgets within my application the same way they do with their mobile operating systems.

The most similar StackOverFlow question to this one can be found here -- but its quite different.

Prerequisite packages:

reorderable_widgets.dart

custom_sizes.dart

The closest I got so far is with these two packages. But, I can't seem to figure the next steps after making this:

// imported packages
import 'package:flutter/material.dart';

import 'custom_sizes.dart';
import 'reorderable_widgets.dart';

class Demo extends StatelessWidget {
  const Demo({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const Scaffold(
      backgroundColor: Colors.grey,
      body: CustomWidgetGrid(),
    );
  }
}

class CustomWidgetGrid extends StatefulWidget {
  const CustomWidgetGrid({Key? key,}) : super(key: key);

  @override
  State<CustomWidgetGrid> createState() => _CustomWidgetGridState();
}

class _CustomWidgetGridState extends State<CustomWidgetGrid> {
  final items1 = fillWithCustomWidgets1();
  final items2 = fillWithCustomWidgets2();
  final items3 = fillWithCustomWidgets2();

  @override
  Widget build(BuildContext context) {
    return CustomScrollView(
          clipBehavior: Clip.hardEdge,
          slivers: <Widget>[
            CustomSliverReorderableGrid(maxExtent: MediaQuery.of(context).size.width/(items2.length), children: items2,),
            CustomSliverReorderableGrid(maxExtent: MediaQuery.of(context).size.width/items1.length, children: items1,),
          ],
        );
  }
}
```

This has already solved:

Having responsive, moveable widgets that save their end state

Providing padding around each widget

But the problem that I'm running at is that all widgets are the same size. Messing with the source code for the package has been a bit of pain, and I think that there is any easy solution that I missed (or don't know about).

Any thoughts would be greatly appreciated!

Title: Flutter Reorder-able Widgets Size

Body:
I am trying to create a Flutter page with reorder-able widgets of different sizes. The closest analogy is like Android/iOS home screens with widgets.

Both of these OS' can be have apps (1x1 size), small widgets (4x1), and even large widgets (4x4) on the same page. More so, when a large app takes up the full width of a page, it re-orders the widgets below/above it as to not interfere with the UI.

I am trying to do the same with Flutter, and hopefully make is so that user's can move widgets within my application the same way they do with their mobile operating systems.

The most similar StackOverFlow question to this one can be found here -- but its quite different.

Prerequisite packages:

reorderable_widgets.dart

custom_sizes.dart

The closest I got so far is with these two packages. But, I can't seem to figure the next steps after making this:

// imported packages
import 'package:flutter/material.dart';

import 'custom_sizes.dart';
import 'reorderable_widgets.dart';

class Demo extends StatelessWidget {
  const Demo({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const Scaffold(
      backgroundColor: Colors.grey,
      body: CustomWidgetGrid(),
    );
  }
}

class CustomWidgetGrid extends StatefulWidget {
  const CustomWidgetGrid({Key? key,}) : super(key: key);

  @override
  State<CustomWidgetGrid> createState() => _CustomWidgetGridState();
}

class _CustomWidgetGridState extends State<CustomWidgetGrid> {
  final items1 = fillWithCustomWidgets1();
  final items2 = fillWithCustomWidgets2();
  final items3 = fillWithCustomWidgets2();

  @override
  Widget build(BuildContext context) {
    return CustomScrollView(
          clipBehavior: Clip.hardEdge,
          slivers: <Widget>[
            CustomSliverReorderableGrid(maxExtent: MediaQuery.of(context).size.width/(items2.length), children: items2,),
            CustomSliverReorderableGrid(maxExtent: MediaQuery.of(context).size.width/items1.length, children: items1,),
          ],
        );
  }
}

This has already solved:

Having responsive, moveable widgets that save their end state

Providing padding around each widget

But the problem that I'm running at is that all widgets are the same size. Messing with the source code for the package has been a bit of pain, and I think that there is any easy solution that I missed (or don't know about).

Any thoughts would be greatly appreciated!


问:
Angular SwUpdate Jest test
I have a PWA and i would like to test, that dialog shown when there are updates reloads the location if user agreed to update.

Here is my test:

```<code>describe('AppUpdateDialog', () => {
    let component: AppUpdateDialog;
    let fixture: ComponentFixture<AppUpdateDialog>;

    const dialogMock = {
        close: () => {
            // Empty method for testing
        },
    };

    const swUpdateMock = {
        activateUpdate: () => {
            return Promise.resolve();
        },
    };

    beforeEach(async () => {
        TestBed.configureTestingModule({
            declarations: [AppUpdateDialog],
            imports: [
                MatIconModule,
                RouterTestingModule,
                MatDialogModule,
                ServiceWorkerModule.register('ngsw-worker.js', {
                    enabled: environment.production,
                    registrationStrategy: 'registerImmediately',
                }),
            ],
            providers: [
                {
                    provide: MatDialogRef,
                    useValue: dialogMock,
                },
                { provide: SwUpdate, useValue: swUpdateMock },
            ],
        }).compileComponents();

        fixture = TestBed.createComponent(AppUpdateDialog);
        component = fixture.componentInstance;
        fixture.detectChanges();
    });

    it('should create', () => {
        expect(component).toBeTruthy();
    });

    it('should render correctly', () => {
        expect(fixture).toMatchSnapshot();
    });

    it('should close the dialog', () => {
        jest.spyOn(component.dialogRef, 'close');
        component.onNoClick();
        expect(component.dialogRef.close).toHaveBeenCalled();
    });

    it('should activate update and reload on yes click', async () => {
        const mockReload = jest.fn();
        const mockLocation = { reload: mockReload };
        Object.defineProperty(window, 'location', { value: mockLocation });
        component.onYesClick();
        expect(mockReload).toHaveBeenCalled();
    });
});
</code>```

So my tests fails on the last line with:

Expected number of calls: >= 1
Received number of calls:    0

How to correctly fix this test case?

Title: Angular SwUpdate Jest test

Body:
I have a PWA and i would like to test, that dialog shown when there are updates reloads the location if user agreed to update.

Here is my test:

describe('AppUpdateDialog', () => {
    let component: AppUpdateDialog;
    let fixture: ComponentFixture<AppUpdateDialog>;

    const dialogMock = {
        close: () => {
            // Empty method for testing
        },
    };

    const swUpdateMock = {
        activateUpdate: () => {
            return Promise.resolve();
        },
    };

    beforeEach(async () => {
        TestBed.configureTestingModule({
            declarations: [AppUpdateDialog],
            imports: [
                MatIconModule,
                RouterTestingModule,
                MatDialogModule,
                ServiceWorkerModule.register('ngsw-worker.js', {
                    enabled: environment.production,
                    registrationStrategy: 'registerImmediately',
                }),
            ],
            providers: [
                {
                    provide: MatDialogRef,
                    useValue: dialogMock,
                },
                { provide: SwUpdate, useValue: swUpdateMock },
            ],
        }).compileComponents();

        fixture = TestBed.createComponent(AppUpdateDialog);
        component = fixture.componentInstance;
        fixture.detectChanges();
    });

    it('should create', () => {
        expect(component).toBeTruthy();
    });

    it('should render correctly', () => {
        expect(fixture).toMatchSnapshot();
    });

    it('should close the dialog', () => {
        jest.spyOn(component.dialogRef, 'close');
        component.onNoClick();
        expect(component.dialogRef.close).toHaveBeenCalled();
    });

    it('should activate update and reload on yes click', async () => {
        const mockReload = jest.fn();
        const mockLocation = { reload: mockReload };
        Object.defineProperty(window, 'location', { value: mockLocation });
        component.onYesClick();
        expect(mockReload).toHaveBeenCalled();
    });
});

So my tests fails on the last line with:

Expected number of calls: >= 1
Received number of calls:    0

How to correctly fix this test case?


问:
i try to implement zoomDrawer but faced this issue
Exception has occurred.
_CastError (Null check operator used on a null value)

Null check operator used on a null valueenter image description here


问:
Unable to start mqtt image with password file
I have created a docker image of mqtt broker along with a config file. When I am trying to launch the image I am getting error saying: Error: Invalid password hash for user user.

Dockerfile:

```<code>FROM eclipse-mosquitto:1.4.12
RUN mkdir -p /mosquitto/data/
COPY mosquitto.conf /mosquitto/config/mosquitto.conf
COPY password.txt /mosquitto/config/password.txt
VOLUME /mosquitto/data/
EXPOSE 80
</code>```

mosquitto config file:

```<code>## Logging

log_dest stdout
log_type error
log_type warning
log_type notice
log_type information

# per_listener_settings true
allow_anonymous false
password_file /mosquitto/config/password.txt
## MQTT Listener

listener 1883
protocol mqtt

## WebSockets Listener

listener 80
protocol websockets

## Persistence

persistence false
</code>```

Password File:

Error:

I am trying to build an mqtt image with password file and websocket protocol

Body:
I have created a docker image of mqtt broker along with a config file. When I am trying to launch the image I am getting error saying: Error: Invalid password hash for user user.

Dockerfile:

FROM eclipse-mosquitto:1.4.12
RUN mkdir -p /mosquitto/data/
COPY mosquitto.conf /mosquitto/config/mosquitto.conf
COPY password.txt /mosquitto/config/password.txt
VOLUME /mosquitto/data/
EXPOSE 80

mosquitto config file:

## Logging

log_dest stdout
log_type error
log_type warning
log_type notice
log_type information

# per_listener_settings true
allow_anonymous false
password_file /mosquitto/config/password.txt
## MQTT Listener

listener 1883
protocol mqtt

## WebSockets Listener

listener 80
protocol websockets

## Persistence

persistence false

Password File:

Error:

I am trying to build an mqtt image with password file and websocket protocol


问:
OpenSSL package issue in python 3.10
Am trying to run a following command which was perfectly running in Ubuntu 20 with python version 3.8.

```<code>comm = 'openssl pkcs12 -in %s -out %s -nodes -passin pass:%s -clcerts -nokeys' % (pkl_path,certif_path, password)
os.system(comm)
</code>```

It is working in ubuntu 20 with python 3.8 and while we print os.system(comm) am getting output as zero, the same in ubuntu 22 with python 3.8 gives me output 256.

Thanks in advance

Am expecting while we print os.system(comm), in should get the output 0.

Title: OpenSSL package issue in python 3.10

Body:
Am trying to run a following command which was perfectly running in Ubuntu 20 with python version 3.8.

comm = 'openssl pkcs12 -in %s -out %s -nodes -passin pass:%s -clcerts -nokeys' % (pkl_path,certif_path, password)
os.system(comm)

It is working in ubuntu 20 with python 3.8 and while we print os.system(comm) am getting output as zero, the same in ubuntu 22 with python 3.8 gives me output 256.

Thanks in advance

Am expecting while we print os.system(comm), in should get the output 0.


问:
rewrites in next js working fine in local, but not working after deployment in vercel
```<code>this is how my next.config.js looks like =>
{
async rewrites() {
    return [
      {
        source: '/:path*',
        destination: `/:path*`,
      },
        {
          source: '/sell',
          destination: `${NEXT_PUBLIC_APP_URL}/sell`,
        },
        {
          source: '/sell/:path*',
          destination: `${NEXT_PUBLIC_APP_URL}/sell/:path*`,
        },
      ]
  }
}
</code>```

for /sell => i am using another website www.anotherWebsite.com/sell to show.
it is working perfectly in local, but not working after deployment in vercel.

for /sell => it should show website www.anotherWebsite.com/sell.
as it is working in my local.

Body:
this is how my next.config.js looks like =>
{
async rewrites() {
    return [
      {
        source: '/:path*',
        destination: `/:path*`,
      },
        {
          source: '/sell',
          destination: `${NEXT_PUBLIC_APP_URL}/sell`,
        },
        {
          source: '/sell/:path*',
          destination: `${NEXT_PUBLIC_APP_URL}/sell/:path*`,
        },
      ]
  }
}

for /sell => i am using another website www.anotherWebsite.com/sell to show.
it is working perfectly in local, but not working after deployment in vercel.

for /sell => it should show website www.anotherWebsite.com/sell.
as it is working in my local.


问:
how to use python assert to determine if a html element has loaded
I am trying to use python's assert construct to determine if a string has appeared in html to confirm a given page has loaded.

(noting selenium is installed but I want to instead use python's assert while I am learning about asserts..)

When I attempt to run this, expecting a negative result, I receive the standard NoSuchElement type exception, while the actual 'assert' construct itself seems to do nothing.

Should I instead be using python's try except on its own or use selenium assertions instead?

Following is example of what I am trying to do and its result:

constants definition py file..

SEARCH_RESULTS_PAGE_STRING = "Search results"   <- I expect this to pass and it seems to run without error..

SEARCH_RESULTS_PAGE_STRING = "Search duh results"   <- I expect this to fail and it does, but mentions nothing about an AssertionError in the runtime output.. It just says:

```<code>selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//span[text()='Search duh results']"}
</code>```

in my class / method definition py file..

try:

assert const.SEARCH_RESULTS_PAGE_STRING == self.find_element(By.XPATH, f"//span[text()='{const.SEARCH_RESULTS_PAGE_STRING}']").text, f"'{const.SEARCH_RESULTS_PAGE_STRING}' has not been found on the Search Results page."

except AssertionError as assertErrorMsg:
print(assertErrorMsg)

Body:
I am trying to use python's assert construct to determine if a string has appeared in html to confirm a given page has loaded.

(noting selenium is installed but I want to instead use python's assert while I am learning about asserts..)

When I attempt to run this, expecting a negative result, I receive the standard NoSuchElement type exception, while the actual 'assert' construct itself seems to do nothing.

Should I instead be using python's try except on its own or use selenium assertions instead?

Following is example of what I am trying to do and its result:

constants definition py file..

SEARCH_RESULTS_PAGE_STRING = "Search results"   <- I expect this to pass and it seems to run without error..

SEARCH_RESULTS_PAGE_STRING = "Search duh results"   <- I expect this to fail and it does, but mentions nothing about an AssertionError in the runtime output.. It just says:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//span[text()='Search duh results']"}

in my class / method definition py file..

try:

assert const.SEARCH_RESULTS_PAGE_STRING == self.find_element(By.XPATH, f"//span[text()='{const.SEARCH_RESULTS_PAGE_STRING}']").text, f"'{const.SEARCH_RESULTS_PAGE_STRING}' has not been found on the Search Results page."

except AssertionError as assertErrorMsg:
print(assertErrorMsg)


问:
How do I override a block in a nested template in Twig 2.x
I'm trying to override a block in a nested template, but I can't figure out how it's done.

See my problem at TwigFiddle.

The myblockis correctly overridden to show custom myblock, but the nestedblock won't be overridden, and I can't figure out how to do it.

Can anybody give some good pointers? :)

Actual output:

```<code>Hi

    custom myblock

    nestedblock
</code>```

Expected output:

```<code>Hi

    custom myblock

    custom nestedblock
</code>```

Body:
I'm trying to override a block in a nested template, but I can't figure out how it's done.

See my problem at TwigFiddle.

The myblockis correctly overridden to show custom myblock, but the nestedblock won't be overridden, and I can't figure out how to do it.

Can anybody give some good pointers? :)

Actual output:

Hi

    custom myblock

    nestedblock

Expected output:

Hi

    custom myblock

    custom nestedblock


问:
Blind Call Transfer in Asterisk | ari-client (Node.js)
Precise overview about the flow:

I am calling my initial extension(100) using Zoiper through Twilio sip domain using Zoiper as soft phone which actually direct the call to my asterisk server.

Now when my call is in asterisk server I'm trying to forward it to another extension using Zoiper. I have already configured it according to documentation provided by asterisk will also be attaching the reference links.

I just want to forward the current call to a particular extension. So please can anyone guide me that how it can be possibly done?

ari-client

```<code>  bridge.once(‘BridgeAttendedTransfer’, event => {
      var transferee = new ari.Channel(event.transferee.id);
      transferee.continueInDialplan({
            context: event.context,
            extension: event.exten,
            priority: 1
      });
  });
</code>```

extension.conf

```<code>  exten => 201,1,Dial(SIP/201,20,tT)
</code>```

features.conf

```<code>  blindxfer = #2 ("#2" or "##" instead of "#1")
  atxfer = *2

  transferdigittimeout = 1; Number of seconds to wait between digits when transferring a call
  xfersound = beep ; to indicate an attended transfer is complete
  xferfailsound = beeperr ; to indicate a failed transfer
  transferdialattempts = 3 ; Number of times that a transferer may attempt to dial an extension before
  being kicked back to the original call.
  transferretrysound = "beep" ; Sound to play when a transferer fails to dial a valid extension.
  transferinvalidsound = "beeperr" ; Sound to play when a transferer fails to dial a valid extension
</code>```

Using Zoiper to make a transfer

References:

https://wiki.asterisk.org/wiki/display/AST/Feature+Code+Call+Transfers

https://www.aska-ltd.jp/en/blog/185

https://community.asterisk.org/t/call-transfer-not-working-on-softphones/33817

https://asteriskfaqs.org/2020/12/22/uncategorized/handling-transfers-with-ari.html

Trying to implement blind call transfer.

Body:
Precise overview about the flow:

I am calling my initial extension(100) using Zoiper through Twilio sip domain using Zoiper as soft phone which actually direct the call to my asterisk server.

Now when my call is in asterisk server I'm trying to forward it to another extension using Zoiper. I have already configured it according to documentation provided by asterisk will also be attaching the reference links.

I just want to forward the current call to a particular extension. So please can anyone guide me that how it can be possibly done?

ari-client

  bridge.once(‘BridgeAttendedTransfer’, event => {
      var transferee = new ari.Channel(event.transferee.id);
      transferee.continueInDialplan({
            context: event.context,
            extension: event.exten,
            priority: 1
      });
  });

extension.conf

  exten => 201,1,Dial(SIP/201,20,tT)

features.conf

  blindxfer = #2 ("#2" or "##" instead of "#1")
  atxfer = *2

  transferdigittimeout = 1; Number of seconds to wait between digits when transferring a call
  xfersound = beep ; to indicate an attended transfer is complete
  xferfailsound = beeperr ; to indicate a failed transfer
  transferdialattempts = 3 ; Number of times that a transferer may attempt to dial an extension before
  being kicked back to the original call.
  transferretrysound = "beep" ; Sound to play when a transferer fails to dial a valid extension.
  transferinvalidsound = "beeperr" ; Sound to play when a transferer fails to dial a valid extension

Using Zoiper to make a transfer

References:

https://wiki.asterisk.org/wiki/display/AST/Feature+Code+Call+Transfers

https://www.aska-ltd.jp/en/blog/185

https://community.asterisk.org/t/call-transfer-not-working-on-softphones/33817

https://asteriskfaqs.org/2020/12/22/uncategorized/handling-transfers-with-ari.html

Trying to implement blind call transfer.


问:
When single order is having tax,discount,sales then in report all the three are displaying seperate colum w.r.to that plan. Sample planname: SALESPLAN

Please help me to get three records in a single column. Please find the query below and help me. Thanks in advance

```<code>SELECT
    salereg.currency_symbol        AS currency_symbol_1,
    salereg.company_name           AS company_name_2,
    salereg.customer_type_descr    AS customer_type_descr_3,
    salereg.product_name           AS product_name_4,
    salereg.priceline_descr        AS priceline_descr_5,
    salereg.charge_amount          AS charge_amount_6,
    salereg.discount_amount        AS discount_amount_7,
    salereg.adjustment_amount      AS adjustment_amount_8,
    salereg.tax_amount             AS tax_amount_9
FROM
    sales_register_summary_vw  salereg,
    customer_details           ci,
    user_entities              ue
WHERE
    trunc(salereg.invoice_date) BETWEEN to_date(:p_frminvoice_date, 'dd/MM/yyyy') AND to_date(:p_toinvoice_date, 'dd/MM/yyyy')
    AND salereg.opentity = :p_opentity
    AND salereg.customer_type = :p_customer_type
    AND salereg.customer_id = ci.customer_id
    AND ci.opentity_id = ue.entity_id
    AND ue.is_deleted = 0
    AND ue.user_id = :p_userid
GROUP BY
    salereg.currency_symbol,
    salereg.company_name,
    salereg.customer_type_descr,
    salereg.product_name,
    salereg.priceline_descr,
    salereg.charge_amount,
    salereg.discount_amount,
    salereg.adjustment_amount,
    salereg.tax_amount;
</code>```

Body:
Please help me to get three records in a single column. Please find the query below and help me. Thanks in advance

SELECT
    salereg.currency_symbol        AS currency_symbol_1,
    salereg.company_name           AS company_name_2,
    salereg.customer_type_descr    AS customer_type_descr_3,
    salereg.product_name           AS product_name_4,
    salereg.priceline_descr        AS priceline_descr_5,
    salereg.charge_amount          AS charge_amount_6,
    salereg.discount_amount        AS discount_amount_7,
    salereg.adjustment_amount      AS adjustment_amount_8,
    salereg.tax_amount             AS tax_amount_9
FROM
    sales_register_summary_vw  salereg,
    customer_details           ci,
    user_entities              ue
WHERE
    trunc(salereg.invoice_date) BETWEEN to_date(:p_frminvoice_date, 'dd/MM/yyyy') AND to_date(:p_toinvoice_date, 'dd/MM/yyyy')
    AND salereg.opentity = :p_opentity
    AND salereg.customer_type = :p_customer_type
    AND salereg.customer_id = ci.customer_id
    AND ci.opentity_id = ue.entity_id
    AND ue.is_deleted = 0
    AND ue.user_id = :p_userid
GROUP BY
    salereg.currency_symbol,
    salereg.company_name,
    salereg.customer_type_descr,
    salereg.product_name,
    salereg.priceline_descr,
    salereg.charge_amount,
    salereg.discount_amount,
    salereg.adjustment_amount,
    salereg.tax_amount;


问:
Set position of the checkbox on ExpandableListView
In my Android application, I have an ExpandableListView with each group having some childs, which contains a checkbox. I'm having trouble in setting the position of the checkboxes.
Curent, my checkbox on the right of the Childs When run on phone, even though it's on the left in Childs.XML, now I want to move the checkbox to the left of the Childs.
Guide me. plsss.. Thanks all so much.

My main XML:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    tools:context=".discover.DiscoverFilterFragment">
    <ProgressBar
        android:id="@+id/filter_progressBar"
        style="?android:attr/progressBarStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:visibility="gone" />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="666dp"
        android:orientation="vertical"
        android:padding="0dp"
        android:id="@+id/expLayout">
        <ExpandableListView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/expFilter"
            android:groupIndicator="@drawable/expand_icon"
            android:layoutDirection="rtl"
            android:layout_marginStart="10dp"
            android:layout_marginEnd="10dp"
            android:indicatorLeft="?android:attr/expandableListPreferredItemIndicatorLeft"
            />

    </LinearLayout>

    <androidx.appcompat.widget.LinearLayoutCompat
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="6dp"
        android:background="@drawable/btn_view_attachments">

        <Button
            android:id="@+id/btnApply"
            android:layout_width="328dp"
            android:layout_height="wrap_content"
            android:background="#00FFFFFF"
            android:backgroundTint="#00FFFFFF"
            android:text="Apply"
            android:textColor="#FFFFFF"
            android:textSize="16sp" />
    </androidx.appcompat.widget.LinearLayoutCompat>

</RelativeLayout>
</code>```

My Parent XML:

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

    <TextView
        android:id="@+id/listTitle"
        android:text="@string/title"
        android:textSize="22sp"
        android:textAppearance="@style/TextAppearance.AppCompat.Medium.Inverse"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="10dp"
        android:layout_marginStart="25dp"
        android:paddingTop="10dp"
        android:textColor="@android:color/black"/>

</LinearLayout>
</code>```

My Child XML:

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

    <CheckBox
        android:id="@+id/itemsCheckbox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="0dp"
        android:focusable="false"
        android:clickable="false"
        style="@android:style/Widget.CompoundButton.RadioButton"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingTop="16dp"
        android:id="@+id/listItem"
        android:layoutDirection="ltr"
        android:textAppearance="@style/TextAppearance.AppCompat.Small"
        tools:text="Item 0" />
</LinearLayout>
</code>```

Body:
In my Android application, I have an ExpandableListView with each group having some childs, which contains a checkbox. I'm having trouble in setting the position of the checkboxes.
Curent, my checkbox on the right of the Childs When run on phone, even though it's on the left in Childs.XML, now I want to move the checkbox to the left of the Childs.
Guide me. plsss.. Thanks all so much.

My main XML:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    tools:context=".discover.DiscoverFilterFragment">
    <ProgressBar
        android:id="@+id/filter_progressBar"
        style="?android:attr/progressBarStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:visibility="gone" />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="666dp"
        android:orientation="vertical"
        android:padding="0dp"
        android:id="@+id/expLayout">
        <ExpandableListView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/expFilter"
            android:groupIndicator="@drawable/expand_icon"
            android:layoutDirection="rtl"
            android:layout_marginStart="10dp"
            android:layout_marginEnd="10dp"
            android:indicatorLeft="?android:attr/expandableListPreferredItemIndicatorLeft"
            />

    </LinearLayout>

    <androidx.appcompat.widget.LinearLayoutCompat
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="6dp"
        android:background="@drawable/btn_view_attachments">

        <Button
            android:id="@+id/btnApply"
            android:layout_width="328dp"
            android:layout_height="wrap_content"
            android:background="#00FFFFFF"
            android:backgroundTint="#00FFFFFF"
            android:text="Apply"
            android:textColor="#FFFFFF"
            android:textSize="16sp" />
    </androidx.appcompat.widget.LinearLayoutCompat>

</RelativeLayout>

My Parent XML:

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

    <TextView
        android:id="@+id/listTitle"
        android:text="@string/title"
        android:textSize="22sp"
        android:textAppearance="@style/TextAppearance.AppCompat.Medium.Inverse"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="10dp"
        android:layout_marginStart="25dp"
        android:paddingTop="10dp"
        android:textColor="@android:color/black"/>

</LinearLayout>

My Child XML:

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

    <CheckBox
        android:id="@+id/itemsCheckbox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="0dp"
        android:focusable="false"
        android:clickable="false"
        style="@android:style/Widget.CompoundButton.RadioButton"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingTop="16dp"
        android:id="@+id/listItem"
        android:layoutDirection="ltr"
        android:textAppearance="@style/TextAppearance.AppCompat.Small"
        tools:text="Item 0" />
</LinearLayout>


问:
Click on a duet link and open in a new tab angular 15
I am trying to open a page in a new tab in angular 15. Here is my code,

```<code><duet-link url='./info/${id}' external>Info</duet-link>
</code>```

Here when I click , control+ click or right click-> open in a new tab options,page is opening in a new tab but getting error page 403. I am reading values from cacheManager in that page.

But simply clicking the link opens correctly in same tab.

How can I get the local storage values so that it can be opened in a new tab.

Body:
I am trying to open a page in a new tab in angular 15. Here is my code,

<duet-link url='./info/${id}' external>Info</duet-link>

Here when I click , control+ click or right click-> open in a new tab options,page is opening in a new tab but getting error page 403. I am reading values from cacheManager in that page.

But simply clicking the link opens correctly in same tab.

How can I get the local storage values so that it can be opened in a new tab.


问:
how do i create multiple nesting levels with ngx-datatable and ngx-datatable-row-detail
so that when you click on the value in the first column of the main table, an additional one opens, which would also have an additional table.

I'm trying to do something like this in general

```<code><ngx-datatable>
    <ngx-datatable-row-detail>
        <ngx-datatable>
            <ngx-datatable-row-detail>
            </ngx-datatable-row-detail>
        </ngx-datatable>
    </ngx-datatable-row-detail>
</ngx-datatable>
</code>```

but I have not been able to make a working version. I would like to see an example
perhaps it will be easier to solve this problem using a simple

Body:
so that when you click on the value in the first column of the main table, an additional one opens, which would also have an additional table.

I'm trying to do something like this in general

<ngx-datatable>
    <ngx-datatable-row-detail>
        <ngx-datatable>
            <ngx-datatable-row-detail>
            </ngx-datatable-row-detail>
        </ngx-datatable>
    </ngx-datatable-row-detail>
</ngx-datatable>

but I have not been able to make a working version. I would like to see an example
perhaps it will be easier to solve this problem using a simple


问:
How to ensure the result from for idm in range (0,n): is correct for R3_temp?
With the same for loop (for idm in range (0,n):), I would like to get the np.shape(R3_temp) = np.shape(WL_PS_storage) = (3,).

However, from the following codes, the result of R3_temp is different.
In this case, could anyone let me know what is missed for the code here, please?

Thank you in advance.

```<code>import numpy as np
import pandas as pd

w = 5
v = 3

m = np.array([2,3,2]) #parallel chambers
n = len(m)
steps = np.arange(1,n+1)
q = np.remainder(steps,2)

p_one = 30
c_one = 50

p_three = 40
c_three = 40

start_p_two = 20
start_c_two = 20

total_p_two = 21
total_c_two = 21

Total_combination = total_p_two*total_c_two

Z_comb = [np.arange(0,m[0]),np.arange(0,m[1]),np.arange(0,m[2])]
Z_comb
</code>```

Z_comb = [array([0, 1]), array([0, 1, 2]), array([0, 1])]

```<code>storage_R1_R2_max = []
for p_two in range(start_p_two,total_p_two):
    p = np.array([p_one, p_two, p_three])
    for c_two in range(start_c_two,total_c_two):
        c = np.array([c_one, c_two, c_three])

        #calculate workload
        WL_PS_storage = []

        for idm in range (0,n):
            WL_PS = (1/m[idm])*(p[idm] + c[idm] + 2*w)
            WL_PS_storage.append(WL_PS) #in the loop of idm, len WL_PS_storage = 3
        WL_PS_max = max(WL_PS_storage) #same column with for idm

        WL_robot = 2*(n+1)*(v+w)
        workload = max(WL_PS_max,WL_robot)

        R2_storage = []
        for idm in range (0,n):

        #calculate R2
            R2 = (1/m[idm])*(p[idm] + c[idm] + 2*w)
            R2_storage.append(R2)
            R2_max = max(R2_storage)

        #calculate R1
        R1 = (n+1)*(2*v + 2*w)
        max_R1_R2 = max(R1, R2_max)
        storage_R1_R2_max.append(max_R1_R2)

print('shape WL_PS_storage', np.shape(WL_PS_storage))
print('WL_PS_storage', WL_PS_storage)
print('R2 storage', R2_storage)
</code>```

shape WL_PS_storage (3,)

WL_PS_storage [45.0, 16.666666666666664, 45.0]

R2 storage [45.0, 16.666666666666664, 45.0]

```<code>for p_two in range(start_p_two,total_p_two):
    p = np.array([p_one, p_two, p_three])
    for c_two in range(start_c_two,total_c_two):
        c = np.array([c_one, c_two, c_three])

        for z_one in Z_comb[0]:
            for z_two in Z_comb[1]:
                for z_three in Z_comb[2]:

                    R3_temp = []
                    for idm in range(0,n):
                        #calculate R3

                        if idm <= (n-1):
                            R3 = (q[idm]*c[idm]+ (1-q[idm])*p[idm] + (1+n)*w + n*v)* ((q[idm]/(m[idm]-z)) + ((1-q[idm])/(m[idm]-z)))
                        if idm == (n-1):
                            R3 = (q[idm]*p[idm] + (1-q[idm])*c[idm] + (1+n)*w + n*v)* (q[idm]/(m[idm]-z) + (1-q[idm])/(m[idm]-z))
                            R3_temp.append(R3)

print('np shape R3_temp', np.shape(R3_temp))
print('R3_temp', R3_temp)
</code>```

np shape R3_temp (1, 2)

R3_temp [array([34.5, 69. ])]

Body:
With the same for loop (for idm in range (0,n):), I would like to get the np.shape(R3_temp) = np.shape(WL_PS_storage) = (3,).

However, from the following codes, the result of R3_temp is different.
In this case, could anyone let me know what is missed for the code here, please?

Thank you in advance.

import numpy as np
import pandas as pd

w = 5
v = 3

m = np.array([2,3,2]) #parallel chambers
n = len(m)
steps = np.arange(1,n+1)
q = np.remainder(steps,2)

p_one = 30
c_one = 50

p_three = 40
c_three = 40

start_p_two = 20
start_c_two = 20

total_p_two = 21
total_c_two = 21

Total_combination = total_p_two*total_c_two

Z_comb = [np.arange(0,m[0]),np.arange(0,m[1]),np.arange(0,m[2])]
Z_comb

Z_comb = [array([0, 1]), array([0, 1, 2]), array([0, 1])]

storage_R1_R2_max = []
for p_two in range(start_p_two,total_p_two):
    p = np.array([p_one, p_two, p_three])
    for c_two in range(start_c_two,total_c_two):
        c = np.array([c_one, c_two, c_three])

        #calculate workload
        WL_PS_storage = []

        for idm in range (0,n):
            WL_PS = (1/m[idm])*(p[idm] + c[idm] + 2*w)
            WL_PS_storage.append(WL_PS) #in the loop of idm, len WL_PS_storage = 3
        WL_PS_max = max(WL_PS_storage) #same column with for idm

        WL_robot = 2*(n+1)*(v+w)
        workload = max(WL_PS_max,WL_robot)

        R2_storage = []
        for idm in range (0,n):

        #calculate R2
            R2 = (1/m[idm])*(p[idm] + c[idm] + 2*w)
            R2_storage.append(R2)
            R2_max = max(R2_storage)

        #calculate R1
        R1 = (n+1)*(2*v + 2*w)
        max_R1_R2 = max(R1, R2_max)
        storage_R1_R2_max.append(max_R1_R2)

print('shape WL_PS_storage', np.shape(WL_PS_storage))
print('WL_PS_storage', WL_PS_storage)
print('R2 storage', R2_storage)

shape WL_PS_storage (3,)

WL_PS_storage [45.0, 16.666666666666664, 45.0]

R2 storage [45.0, 16.666666666666664, 45.0]

for p_two in range(start_p_two,total_p_two):
    p = np.array([p_one, p_two, p_three])
    for c_two in range(start_c_two,total_c_two):
        c = np.array([c_one, c_two, c_three])

        for z_one in Z_comb[0]:
            for z_two in Z_comb[1]:
                for z_three in Z_comb[2]:

                    R3_temp = []
                    for idm in range(0,n):
                        #calculate R3

                        if idm <= (n-1):
                            R3 = (q[idm]*c[idm]+ (1-q[idm])*p[idm] + (1+n)*w + n*v)* ((q[idm]/(m[idm]-z)) + ((1-q[idm])/(m[idm]-z)))
                        if idm == (n-1):
                            R3 = (q[idm]*p[idm] + (1-q[idm])*c[idm] + (1+n)*w + n*v)* (q[idm]/(m[idm]-z) + (1-q[idm])/(m[idm]-z))
                            R3_temp.append(R3)

print('np shape R3_temp', np.shape(R3_temp))
print('R3_temp', R3_temp)

np shape R3_temp (1, 2)

R3_temp [array([34.5, 69. ])]


问:
Get Speed of Vehicle using Expo Location in React native
I'm doing the mobile application in Expo React Native that can track the vehicle speed.
Currently I am using Expo Location API to track the vehicle location for every 5 seconds.

```<code>import * as Location from 'expo-location';

  const startLocationTracking = async () => {
  await Location.startLocationUpdatesAsync(LOCATION_TRACKING, {
      accuracy: Location.Accuracy.Highest,
      timeInterval: 5000,
      distanceInterval: 0,
  });
  const hasStarted = await Location.hasStartedLocationUpdatesAsync(
      LOCATION_TRACKING
  );
  setLocationStarted(hasStarted);
  console.log('tracking started?', hasStarted);
};

TaskManager.defineTask(LOCATION_TRACKING, async ({ data, error }) => {
 if (error) {
  console.log('LOCATION_TRACKING task ERROR:', error);
  return;
 }
 if (data) {
  Location.g
  const { locations } = data;
  let lat = locations[0].coords.latitude;
  let long = locations[0].coords.longitude;

  l1 = lat;
  l2 = long;
  origin = lat+','+long;

 }
 });
</code>```

In Expo Location Document Document there is a option to get speed.

Can anyone let me know how to track speed using this option. Or any other alternatives to track speed using coordinate movement change.

Body:
I'm doing the mobile application in Expo React Native that can track the vehicle speed.
Currently I am using Expo Location API to track the vehicle location for every 5 seconds.

import * as Location from 'expo-location';

  const startLocationTracking = async () => {
  await Location.startLocationUpdatesAsync(LOCATION_TRACKING, {
      accuracy: Location.Accuracy.Highest,
      timeInterval: 5000,
      distanceInterval: 0,
  });
  const hasStarted = await Location.hasStartedLocationUpdatesAsync(
      LOCATION_TRACKING
  );
  setLocationStarted(hasStarted);
  console.log('tracking started?', hasStarted);
};

TaskManager.defineTask(LOCATION_TRACKING, async ({ data, error }) => {
 if (error) {
  console.log('LOCATION_TRACKING task ERROR:', error);
  return;
 }
 if (data) {
  Location.g
  const { locations } = data;
  let lat = locations[0].coords.latitude;
  let long = locations[0].coords.longitude;

  l1 = lat;
  l2 = long;
  origin = lat+','+long;

 }
 });

In Expo Location Document Document there is a option to get speed.

Can anyone let me know how to track speed using this option. Or any other alternatives to track speed using coordinate movement change.


问:
theGraph: create subgraph loading but not working
subgraph

Recently I have been having problem with the graph. Any time I try to create a subgraph. It shows the loading spinner but nothing shows up. I tried this for hours but still nothing. I changed networks, used vpn and nothing worked.

I thought the problem was my network, but it turned out it wasn't, I tried using vpn and nothing worked.


问:
Why does filebeat docker container exit without error and doing anything?
Im sure its a very simple question but I cant figure it out.
Im using the following setup:

filebeat.yml

```<code>filebeat.config:
  modules:
    path: ${path.config}/modules.d/*.yml
    reload.enabled: false

filebeat.inputs:
- type: log
  paths:
    - /usr/share/filebeat/applogs/*.log
-type:
filebeat.autodiscover:
  providers:
    - type: docker
      hints.enabled: true
</code>```

Dockerfile

```<code>FROM docker.elastic.co/beats/filebeat:6.8.23
COPY filebeatconfig/filebeat.yml /usr/share/filebeat/filebeat.yml
USER root
RUN chown root:filebeat /usr/share/filebeat/filebeat.yml
RUN chmod go-w /usr/share/filebeat/filebeat.yml
USER filebeat
</code>```

cmd

```<code>docker build -f filebeatconfig/ -t myfilebeat .
docker run --name myfb --network host \
-v $PWD/logs/:/usr/share/filebeat/applogs/ \
myfilebeat setup -E output.elasticsearch.hosts=["localhost:9200"]
</code>```

The connections to the local kibana and elastic search container are fine and I have a stub file that is constantly receiving more inputs.

Why does filebeat not do shit and exits after like 10 seconds after the following output?

```<code>Loaded index template
Loading dashboards (Kibana must be running and reachable)
Loaded dashboards
Loaded machine learning job configurations
</code>```

The structure of the directory is below:

```<code>.
├── fakelogger.py
├── filebeatconfig
│   ├── Dockerfile
│   └── filebeat.yml
├── kb.yml
├── logs
    └── fake.log
</code>```

Body:
Im sure its a very simple question but I cant figure it out.
Im using the following setup:

filebeat.yml

filebeat.config:
  modules:
    path: ${path.config}/modules.d/*.yml
    reload.enabled: false

filebeat.inputs:
- type: log
  paths:
    - /usr/share/filebeat/applogs/*.log
-type:
filebeat.autodiscover:
  providers:
    - type: docker
      hints.enabled: true

Dockerfile

FROM docker.elastic.co/beats/filebeat:6.8.23
COPY filebeatconfig/filebeat.yml /usr/share/filebeat/filebeat.yml
USER root
RUN chown root:filebeat /usr/share/filebeat/filebeat.yml
RUN chmod go-w /usr/share/filebeat/filebeat.yml
USER filebeat

cmd

docker build -f filebeatconfig/ -t myfilebeat .
docker run --name myfb --network host \
-v $PWD/logs/:/usr/share/filebeat/applogs/ \
myfilebeat setup -E output.elasticsearch.hosts=["localhost:9200"]

The connections to the local kibana and elastic search container are fine and I have a stub file that is constantly receiving more inputs.

Why does filebeat not do shit and exits after like 10 seconds after the following output?

Loaded index template
Loading dashboards (Kibana must be running and reachable)
Loaded dashboards
Loaded machine learning job configurations

The structure of the directory is below:

.
├── fakelogger.py
├── filebeatconfig
│   ├── Dockerfile
│   └── filebeat.yml
├── kb.yml
├── logs
    └── fake.log


问:
Problem with creating an table with hibernate
I'm learning how to make ORM databases in Java. But after I created the table model, it gives me an error.

I want to combine minecraft api with orm database for easily store data of the players(his modified items data) and now i creating my 'magical storage' where players can store his items.

Models:

```<code>@Entity
@Table(name = "users")
public class User {

    @Id
    @Column(name = "uuid")
    @JdbcTypeCode(SqlTypes.UUID)
    private UUID uuid;

    @Column(name = "username")
    private String username;

    @Column(name = "storage_id")
    @JdbcTypeCode(SqlTypes.UUID)
    private UUID storageId;

    @OneToOne(orphanRemoval = true)
    private UserStorage userStorage;

    public UserStorage getUserStorage() {
        return userStorage;
    }

    public void setUserStorage(UserStorage userStorage) {
        this.userStorage = userStorage;
    }

    public User() {
    }

    public User(UUID uuid, String username, UUID storageId) {
        this.uuid = uuid;
        this.username = username;
        this.storageId = storageId;
    }

    public UUID getUUID() {
        return this.uuid;
    }

    public void setUUID(UUID uuid) {
        this.uuid = uuid;
    }

    public UUID getStorageId() {
        return storageId;
    }

    public void setStorageId(UUID storageId) {
        this.storageId = storageId;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @Override
    public String toString() {
        return "User " +
                "[uuid = \"" +
                this.uuid.toString() +
                "\", username = \"" +
                this.username +
                "\", storageId = " +
                this.storageId +
                "]";
    }
}
</code>```
```<code>@Entity
@Table(name = "items")
public class RawItem {
    @Id
    @Column(name = "storage_id", nullable = false)
    @JdbcTypeCode(SqlTypes.UUID)
    private UUID storageId;

    @ManyToOne
    private UserStorage userStorage;

    @Column(name = "type")
    private String type;

    @Column(name = "data", length = 4096)
    private String data;

    @Column(name = "name")
    private String name;

    public JSONObject getData() throws ParseException {
        return (JSONObject) new JSONParser().parse(this.data);
    }

    public void setData(JSONObject data) {
        this.data = data.toJSONString();
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public UserStorage getUserStorage() {
        return userStorage;
    }

    public void setUserStorage(UserStorage userStorage) {
        this.userStorage = userStorage;
    }

    public UUID getStorageId() {
        return storageId;
    }

    public void setStorageId(UUID storageId) {
        this.storageId = storageId;
    }
}
</code>```
```<code>@Entity
@Table(name = "user_storage")
public class UserStorage {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false)
    @JdbcTypeCode(SqlTypes.UUID)
    private UUID id;

    @Column(name = "slots_count")
    @JdbcTypeCode(SqlTypes.BIGINT)
    private Integer slotsCount;

    @OneToOne(mappedBy = "userStorage", orphanRemoval = true)
    private User user;

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public Integer getSlotsCount() {
        return slotsCount;
    }

    public void setSlotsCount(Integer slotsCount) {
        this.slotsCount = slotsCount;
    }

    public UUID getId() {
        return id;
    }

    public void setId(UUID id) {
        this.id = id;
    }

    @OneToMany(mappedBy = "userStorage", orphanRemoval = true)
    private List<RawItem> rawItems = new ArrayList<>();

    public List<RawItem> getRawItems() {
        return rawItems;
    }

    public void setRawItems(List<RawItem> rawItems) {
        this.rawItems = rawItems;
    }

    public UserStorage() {}

    public UserStorage(Integer slotsCount) {
        this.slotsCount = slotsCount;
    }
}
</code>```

Error:

```<code>org.hibernate.MappingException: Error creating SQL create commands for table : user_storage
        at org.hibernate.tool.schema.internal.StandardTableExporter.getSqlCreateStrings(StandardTableExporter.java:174) ~[?:?]
        at org.hibernate.tool.schema.internal.StandardTableExporter.getSqlCreateStrings(StandardTableExporter.java:33) ~[?:?]
        at org.hibernate.tool.schema.internal.SchemaCreatorImpl.createFromMetadata(SchemaCreatorImpl.java:364) ~[?:?]
        at org.hibernate.tool.schema.internal.SchemaCreatorImpl.performCreation(SchemaCreatorImpl.java:176) ~[?:?]
        at org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImpl.java:144) ~[?:?]
        at org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImpl.java:128) ~[?:?]
        at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:254) ~[?:?]
        at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.lambda$process$5(SchemaManagementToolCoordinator.java:143) ~[?:?]
        at java.util.HashMap.forEach(HashMap.java:1421) ~[?:?]
        at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:140) ~[?:?]
        at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:336) ~[?:?]
        at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:415) ~[?:?]
        at org.hibernate.boot.internal.MetadataImpl.buildSessionFactory(MetadataImpl.java:186) ~[?:?]
</code>```

Body:
I'm learning how to make ORM databases in Java. But after I created the table model, it gives me an error.

I want to combine minecraft api with orm database for easily store data of the players(his modified items data) and now i creating my 'magical storage' where players can store his items.

Models:

@Entity
@Table(name = "users")
public class User {

    @Id
    @Column(name = "uuid")
    @JdbcTypeCode(SqlTypes.UUID)
    private UUID uuid;

    @Column(name = "username")
    private String username;

    @Column(name = "storage_id")
    @JdbcTypeCode(SqlTypes.UUID)
    private UUID storageId;

    @OneToOne(orphanRemoval = true)
    private UserStorage userStorage;

    public UserStorage getUserStorage() {
        return userStorage;
    }

    public void setUserStorage(UserStorage userStorage) {
        this.userStorage = userStorage;
    }

    public User() {
    }

    public User(UUID uuid, String username, UUID storageId) {
        this.uuid = uuid;
        this.username = username;
        this.storageId = storageId;
    }

    public UUID getUUID() {
        return this.uuid;
    }

    public void setUUID(UUID uuid) {
        this.uuid = uuid;
    }

    public UUID getStorageId() {
        return storageId;
    }

    public void setStorageId(UUID storageId) {
        this.storageId = storageId;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @Override
    public String toString() {
        return "User " +
                "[uuid = \"" +
                this.uuid.toString() +
                "\", username = \"" +
                this.username +
                "\", storageId = " +
                this.storageId +
                "]";
    }
}

@Entity
@Table(name = "items")
public class RawItem {
    @Id
    @Column(name = "storage_id", nullable = false)
    @JdbcTypeCode(SqlTypes.UUID)
    private UUID storageId;

    @ManyToOne
    private UserStorage userStorage;

    @Column(name = "type")
    private String type;

    @Column(name = "data", length = 4096)
    private String data;

    @Column(name = "name")
    private String name;

    public JSONObject getData() throws ParseException {
        return (JSONObject) new JSONParser().parse(this.data);
    }

    public void setData(JSONObject data) {
        this.data = data.toJSONString();
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public UserStorage getUserStorage() {
        return userStorage;
    }

    public void setUserStorage(UserStorage userStorage) {
        this.userStorage = userStorage;
    }

    public UUID getStorageId() {
        return storageId;
    }

    public void setStorageId(UUID storageId) {
        this.storageId = storageId;
    }
}

@Entity
@Table(name = "user_storage")
public class UserStorage {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false)
    @JdbcTypeCode(SqlTypes.UUID)
    private UUID id;

    @Column(name = "slots_count")
    @JdbcTypeCode(SqlTypes.BIGINT)
    private Integer slotsCount;

    @OneToOne(mappedBy = "userStorage", orphanRemoval = true)
    private User user;

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public Integer getSlotsCount() {
        return slotsCount;
    }

    public void setSlotsCount(Integer slotsCount) {
        this.slotsCount = slotsCount;
    }

    public UUID getId() {
        return id;
    }

    public void setId(UUID id) {
        this.id = id;
    }

    @OneToMany(mappedBy = "userStorage", orphanRemoval = true)
    private List<RawItem> rawItems = new ArrayList<>();

    public List<RawItem> getRawItems() {
        return rawItems;
    }

    public void setRawItems(List<RawItem> rawItems) {
        this.rawItems = rawItems;
    }

    public UserStorage() {}

    public UserStorage(Integer slotsCount) {
        this.slotsCount = slotsCount;
    }
}

Error:

org.hibernate.MappingException: Error creating SQL create commands for table : user_storage
        at org.hibernate.tool.schema.internal.StandardTableExporter.getSqlCreateStrings(StandardTableExporter.java:174) ~[?:?]
        at org.hibernate.tool.schema.internal.StandardTableExporter.getSqlCreateStrings(StandardTableExporter.java:33) ~[?:?]
        at org.hibernate.tool.schema.internal.SchemaCreatorImpl.createFromMetadata(SchemaCreatorImpl.java:364) ~[?:?]
        at org.hibernate.tool.schema.internal.SchemaCreatorImpl.performCreation(SchemaCreatorImpl.java:176) ~[?:?]
        at org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImpl.java:144) ~[?:?]
        at org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImpl.java:128) ~[?:?]
        at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:254) ~[?:?]
        at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.lambda$process$5(SchemaManagementToolCoordinator.java:143) ~[?:?]
        at java.util.HashMap.forEach(HashMap.java:1421) ~[?:?]
        at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:140) ~[?:?]
        at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:336) ~[?:?]
        at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:415) ~[?:?]
        at org.hibernate.boot.internal.MetadataImpl.buildSessionFactory(MetadataImpl.java:186) ~[?:?]


问:
Why doesn't sanitize-html remove blacklisted tags from my NestJS output DTO?
How do I use the sanitize-HTML node module to remove some tags from my output? I have made sure that my service is referencing my output DTO. The DTO does not double as a database model file. I used sanitize-HTML as the transform function in a @Transform() decorator, like this:

Output DTO:

```<code>import * as sanitizeHtml from 'sanitize-html';

@ObjectType()
export class Output {
  @Transform((value) =>
    sanitizeHtml(value, {
      allowedTags: ['p', 'a', 'br'],
      allowedAttributes: {
        '*': {
          multiple: true,
          values: [
            'href',
            'name',
            'align',
            'center',
            'text-align',
            'font-size',
          ],
        },
      },
    }),
  )
  @Field()
  description: string;
}

</code>```

Removing the allowedAttributes property and using the disallowedTagsMode: 'recursiveEscape; option did not fix the problem. I made sure to allow transforms in my main.ts file but it did not work either. Finally, I enabled implicit transformation, but that did not change the result.

main.ts:

```<code>new ValidationPipe({
      transform: true,
      transformOptions: { enableImplicitConversion: true },
    }),
</code>```

How do I sanitize HTML from the output DTO? I want to avoid having to sanitize every input DTO. I cannot use a universal or generalized input DTO either since many different inputs and routes use this same output DTO.

Body:
How do I use the sanitize-HTML node module to remove some tags from my output? I have made sure that my service is referencing my output DTO. The DTO does not double as a database model file. I used sanitize-HTML as the transform function in a @Transform() decorator, like this:

Output DTO:

import * as sanitizeHtml from 'sanitize-html';

@ObjectType()
export class Output {
  @Transform((value) =>
    sanitizeHtml(value, {
      allowedTags: ['p', 'a', 'br'],
      allowedAttributes: {
        '*': {
          multiple: true,
          values: [
            'href',
            'name',
            'align',
            'center',
            'text-align',
            'font-size',
          ],
        },
      },
    }),
  )
  @Field()
  description: string;
}

Removing the allowedAttributes property and using the disallowedTagsMode: 'recursiveEscape; option did not fix the problem. I made sure to allow transforms in my main.ts file but it did not work either. Finally, I enabled implicit transformation, but that did not change the result.

main.ts:

new ValidationPipe({
      transform: true,
      transformOptions: { enableImplicitConversion: true },
    }),

How do I sanitize HTML from the output DTO? I want to avoid having to sanitize every input DTO. I cannot use a universal or generalized input DTO either since many different inputs and routes use this same output DTO.


问:
vs code runs separate test from ide with environment variable set
For debug test following configuration is working:

```<code>    {
        "name": "Python: Debug Tests",
        "type": "python",
        "request": "launch",
        "program": "${file}",
        "purpose": [
            "debug-test"
        ],
        "console": "integratedTerminal",
        "justMyCode": true,
        "env": {
            "TEST_OUT": "AaA"
        }
</code>```

when I run separate test debug from ide ( from pytest explorer or directly from editor) env variable is available.

How can I achieve the same behavior for test execution?

Body:
For debug test following configuration is working:

    {
        "name": "Python: Debug Tests",
        "type": "python",
        "request": "launch",
        "program": "${file}",
        "purpose": [
            "debug-test"
        ],
        "console": "integratedTerminal",
        "justMyCode": true,
        "env": {
            "TEST_OUT": "AaA"
        }

when I run separate test debug from ide ( from pytest explorer or directly from editor) env variable is available.

How can I achieve the same behavior for test execution?