问:
Change GlobalScope on Ktor client Websocket [Android]
I'm implement Ktor client websocket using GlobalScope coroutine (yes, I know that's not recommended option), but I need to keep alive the socket connection while the app is open because the main functionallity depends of the data from socket.
Sometimes when the network is saturated, the socket retrieves the new data with 5 or 10 minutes of delay :(, exists any way to prevent this delays? I think that GlobalScope provoke some leak when the network is slow and data delays ocurrs.

That's my code in Application class:

```<code>@DelicateCoroutinesApi
    fun initCommandSocket(commandData: Map<String, Any>) {
        this.ctx?.let {ctx ->
            if (!RetrofitConfig.checkKtorConfig(ctx)) {
                Utils.showAlertMessage(
                    ctx,
                    "Error",
                    "No se encuentra configurado el servicio de Ktor.",
                    MODERATE_ERROR) {}
            } else {
                GlobalScope.launch(Dispatchers.IO) {
                    try {
                        if (httpClientSocket == null) {
                            httpClientSocket = HttpClient(OkHttp.create()) {
                                install(Logging) {
                                    logger = Logger.ANDROID
                                    level = LogLevel.ALL
                                    developmentMode = true
                                }
                                install(WebSockets)
                            }
                        }
                        if (defaultClientWebSocketSession == null) {
                            val webService = "//" + SharedPreferenceManager.getKtorWebService(ctx)
                            val port = SharedPreferenceManager.getKtorPort(ctx)
                            httpClientSocket?.webSocket(
                                method = HttpMethod.Get,
                                host = webService,
                                port = port?.toInt()!!,
                                path = ApiConstants.COMMAND_SOCKET_URL
                            ) {
                                defaultClientWebSocketSession = this
                                if (commandData.isNotEmpty()) {
                                    defaultClientWebSocketSession?.send(Frame.Text(JSONObject(commandData).toString()))
                                    socketIgnited = true
                                }

                                while (true) {
                                    when (val income = incoming.receive()) {
                                        is Frame.Text -> {
                                            when (ctx) {
                                                is KDSActivity ->  {
                                                   updateCommandInfo(income.readText())
                                                }
                                            }
                                        } else -> Log.d(Tags.COMMAND_TAG, "INCOME NO ES TEXT :/ QUE ES?:::: $income")
                                    }
                                }
                            }
                        } else {
                            defaultClientWebSocketSession?.send(Frame.Text(JSONObject(commandData).toString()))
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()

                        (ctx as KDSActivity).apply {
                            runOnUiThread {
                                showMessage("Reintentando conexión...")
                            }
                        }
                        if (reconnectionAttempts < 6) {
                            Handler(Looper.getMainLooper()).postDelayed({
                                httpClientSocket = null
                                defaultClientWebSocketSession = null
                                initCommandSocket (
                                    mapOf(
                                        "action" to "handShake",
                                        "id" to 0,
                                        "status" to "A",
                                        "sell" to 0,
                                        "people" to 0
                                    )
                                )
                                reconnectionAttempts ++
                            }, 1000)
                        } else {
                            httpClientSocket = null
                            defaultClientWebSocketSession = null
                            reconnectionAttempts = 0
                            ctx.runOnUiThread {
                                socketCallback.onError(
                                    "Ocurrió un error al intentar establecer conexión con el socket del servidor remoto, causa: ${e.message}"
                                )
                            }
                        }
                    } finally {
                        httpClientSocket?.close()
                    }
                }
            }
        }
    }
</code>```

Body:
I'm implement Ktor client websocket using GlobalScope coroutine (yes, I know that's not recommended option), but I need to keep alive the socket connection while the app is open because the main functionallity depends of the data from socket.
Sometimes when the network is saturated, the socket retrieves the new data with 5 or 10 minutes of delay :(, exists any way to prevent this delays? I think that GlobalScope provoke some leak when the network is slow and data delays ocurrs.

That's my code in Application class:

@DelicateCoroutinesApi
    fun initCommandSocket(commandData: Map<String, Any>) {
        this.ctx?.let {ctx ->
            if (!RetrofitConfig.checkKtorConfig(ctx)) {
                Utils.showAlertMessage(
                    ctx,
                    "Error",
                    "No se encuentra configurado el servicio de Ktor.",
                    MODERATE_ERROR) {}
            } else {
                GlobalScope.launch(Dispatchers.IO) {
                    try {
                        if (httpClientSocket == null) {
                            httpClientSocket = HttpClient(OkHttp.create()) {
                                install(Logging) {
                                    logger = Logger.ANDROID
                                    level = LogLevel.ALL
                                    developmentMode = true
                                }
                                install(WebSockets)
                            }
                        }
                        if (defaultClientWebSocketSession == null) {
                            val webService = "//" + SharedPreferenceManager.getKtorWebService(ctx)
                            val port = SharedPreferenceManager.getKtorPort(ctx)
                            httpClientSocket?.webSocket(
                                method = HttpMethod.Get,
                                host = webService,
                                port = port?.toInt()!!,
                                path = ApiConstants.COMMAND_SOCKET_URL
                            ) {
                                defaultClientWebSocketSession = this
                                if (commandData.isNotEmpty()) {
                                    defaultClientWebSocketSession?.send(Frame.Text(JSONObject(commandData).toString()))
                                    socketIgnited = true
                                }

                                while (true) {
                                    when (val income = incoming.receive()) {
                                        is Frame.Text -> {
                                            when (ctx) {
                                                is KDSActivity ->  {
                                                   updateCommandInfo(income.readText())
                                                }
                                            }
                                        } else -> Log.d(Tags.COMMAND_TAG, "INCOME NO ES TEXT :/ QUE ES?:::: $income")
                                    }
                                }
                            }
                        } else {
                            defaultClientWebSocketSession?.send(Frame.Text(JSONObject(commandData).toString()))
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()

                        (ctx as KDSActivity).apply {
                            runOnUiThread {
                                showMessage("Reintentando conexión...")
                            }
                        }
                        if (reconnectionAttempts < 6) {
                            Handler(Looper.getMainLooper()).postDelayed({
                                httpClientSocket = null
                                defaultClientWebSocketSession = null
                                initCommandSocket (
                                    mapOf(
                                        "action" to "handShake",
                                        "id" to 0,
                                        "status" to "A",
                                        "sell" to 0,
                                        "people" to 0
                                    )
                                )
                                reconnectionAttempts ++
                            }, 1000)
                        } else {
                            httpClientSocket = null
                            defaultClientWebSocketSession = null
                            reconnectionAttempts = 0
                            ctx.runOnUiThread {
                                socketCallback.onError(
                                    "Ocurrió un error al intentar establecer conexión con el socket del servidor remoto, causa: ${e.message}"
                                )
                            }
                        }
                    } finally {
                        httpClientSocket?.close()
                    }
                }
            }
        }
    }


来源: stackexchange

问:
There was a problem loading the project on an Android Emulator
After creating a development build with the command :

> eas build --profile development --platform android

I’m facing a problem loading the project on an android emulator after lunching it with the command :

> npx expo start --dev-client

Also when running the command :

> expo run:android

Loading stops at 77% with no feedback on return

enter image description here

I was expecting the lunch of my app on Adroid Emulator from the vscode with the command npx expo start --dev-client

ContentLicense: CC BY-SA 4.0


问:
How to make my protobuf objects pickle-able?
I have this protobuf file called HistogramBins.proto like this:

syntax = "proto3";

message HistogramBins {
  string field_name = 1;
  repeated float bins = 2;
}
```
<p>which I compile it this way:</p>
```protoc --python_out=. ./HistogramBins.proto
```
<p>And this will generate a file called <code>HistogramBins_pb2.py</code> for me. Then I'll try to serialize an Apache Beam stream using this class:</p>
<pre class="lang-py prettyprint-override"><code>import apache_beam as beam
from components.HistogramBins_pb2 import HistogramBins
from apache_beam.options.pipeline_options import PipelineOptions

class ToProtoFn(beam.DoFn):
  def process(self, t):
    hBin = HistogramBins()
    hBin.field_name = t[0]
    hBin.bins.extend(t[1])
    print(hBin)
    yield hBin

with beam.Pipeline(options=PipelineOptions()) as p:
    input_collection = (
        p
        | 'Read input data' >> beam.Create([("f1", [1.0, 2.0]), ("f2", [3.0, 4.0])])
        | 'record to HistogramBins' >> beam.ParDo(ToProtoFn())
        | beam.io.WriteToText('data/test2.pbtxt',
                              coder=beam.coders.ProtoCoder(HistogramBins().__class__))
    )
</code>```

But fails with the following error message (this is the final line):

```<code>_pickle.PicklingError: Can't pickle <class 'HistogramBins_pb2.HistogramBins'>: it's not found as HistogramBins_pb2.HistogramBins
</code>```

This is while the following example works just fine. This time, I'm using a protobuf from Google package:

import apache_beam as beam
from google.protobuf.timestamp_pb2 import Timestamp
from apache_beam.options.pipeline_options import PipelineOptions

class ToProtoFn(beam.DoFn):
  def process(self, element):
    timestamp = Timestamp()
    timestamp.seconds, timestamp.nanos = [int(x) for x in element.strip().split(',')]
    print(timestamp)
    yield timestamp

with beam.Pipeline(options=PipelineOptions()) as p:
  lines = (p
      | beam.Create(["1586753000,222333000", "1586754000,222333000"])
      | beam.ParDo(ToProtoFn())
      | beam.io.WriteToText('time-pb',
                            coder=beam.coders.ProtoCoder(Timestamp().__class__)))
```
<p>What is the difference between my protobuf and theirs?</p>
<p>This is Google's protobuf file:</p>
<pre class="lang-protobuf prettyprint-override"><code>syntax = "proto3";

package google.protobuf;

option csharp_namespace = "Google.Protobuf.WellKnownTypes";
option cc_enable_arenas = true;
option go_package = "github.com/golang/protobuf/ptypes/timestamp";
option java_package = "com.google.protobuf";
option java_outer_classname = "TimestampProto";
option java_multiple_files = true;
option objc_class_prefix = "GPB";

message Timestamp {
  int64 seconds = 1;
  int32 nanos = 2;
}
</code>```

Body:
I have this protobuf file called HistogramBins.proto like this:

syntax = "proto3";

message HistogramBins {
  string field_name = 1;
  repeated float bins = 2;
}

which I compile it this way:

protoc --python_out=. ./HistogramBins.proto

And this will generate a file called HistogramBins_pb2.py for me. Then I'll try to serialize an Apache Beam stream using this class:

import apache_beam as beam
from components.HistogramBins_pb2 import HistogramBins
from apache_beam.options.pipeline_options import PipelineOptions

class ToProtoFn(beam.DoFn):
  def process(self, t):
    hBin = HistogramBins()
    hBin.field_name = t[0]
    hBin.bins.extend(t[1])
    print(hBin)
    yield hBin

with beam.Pipeline(options=PipelineOptions()) as p:
    input_collection = (
        p
        | 'Read input data' >> beam.Create([("f1", [1.0, 2.0]), ("f2", [3.0, 4.0])])
        | 'record to HistogramBins' >> beam.ParDo(ToProtoFn())
        | beam.io.WriteToText('data/test2.pbtxt',
                              coder=beam.coders.ProtoCoder(HistogramBins().__class__))
    )

But fails with the following error message (this is the final line):

_pickle.PicklingError: Can't pickle <class 'HistogramBins_pb2.HistogramBins'>: it's not found as HistogramBins_pb2.HistogramBins

This is while the following example works just fine. This time, I'm using a protobuf from Google package:

import apache_beam as beam
from google.protobuf.timestamp_pb2 import Timestamp
from apache_beam.options.pipeline_options import PipelineOptions

class ToProtoFn(beam.DoFn):
  def process(self, element):
    timestamp = Timestamp()
    timestamp.seconds, timestamp.nanos = [int(x) for x in element.strip().split(',')]
    print(timestamp)
    yield timestamp

with beam.Pipeline(options=PipelineOptions()) as p:
  lines = (p
      | beam.Create(["1586753000,222333000", "1586754000,222333000"])
      | beam.ParDo(ToProtoFn())
      | beam.io.WriteToText('time-pb',
                            coder=beam.coders.ProtoCoder(Timestamp().__class__)))

What is the difference between my protobuf and theirs?

This is Google's protobuf file:

syntax = "proto3";

package google.protobuf;

option csharp_namespace = "Google.Protobuf.WellKnownTypes";
option cc_enable_arenas = true;
option go_package = "github.com/golang/protobuf/ptypes/timestamp";
option java_package = "com.google.protobuf";
option java_outer_classname = "TimestampProto";
option java_multiple_files = true;
option objc_class_prefix = "GPB";

message Timestamp {
  int64 seconds = 1;
  int32 nanos = 2;
}


问:
How can I correct System.Runtime.WindowsRuntime version too low?
I have a method that loads a PDF document and creates .png files for each page of the document (has worked in the past).  Now I am getting an exception indicating that the file was not found or one or more dependencies could not be loaded.  The file exists, the path is correct, the data being passed is all correct but when the method is called the following appears:

enter image description here

I have System.Runtime.WindowsRuntime version 4.7.0.0 installed as a reference.  Shouldn't the system accept newer versions?  How can I correct this?

Here is the method. ```</p>
```         public static async Task ReadPdfDocAsync(string FormName, string FName)
        {
            // Load the pdf file from specified path then convert the pdf pages into a list of images.
            if (!string.IsNullOrEmpty(FormName))
            {
                var file = await StorageFile.GetFileFromPathAsync(FormName).AsTask();
                var pdfdoc = await PdfDocument.LoadFromFileAsync(file);
                await PdfToImagesAsync(pdfdoc, FName);
            }
        }
```
``````

Body:
I have a method that loads a PDF document and creates .png files for each page of the document (has worked in the past).  Now I am getting an exception indicating that the file was not found or one or more dependencies could not be loaded.  The file exists, the path is correct, the data being passed is all correct but when the method is called the following appears:

enter image description here

I have System.Runtime.WindowsRuntime version 4.7.0.0 installed as a reference.  Shouldn't the system accept newer versions?  How can I correct this?

Here is the method. ```

         public static async Task ReadPdfDocAsync(string FormName, string FName)
        {
            // Load the pdf file from specified path then convert the pdf pages into a list of images.
            if (!string.IsNullOrEmpty(FormName))
            {
                var file = await StorageFile.GetFileFromPathAsync(FormName).AsTask();
                var pdfdoc = await PdfDocument.LoadFromFileAsync(file);
                await PdfToImagesAsync(pdfdoc, FName);
            }
        }


问:
Default arguments in __init__ of class inheriting from int
I feel like I'm losing my mind. I was working on a simple project involving a subclass of int, which may not be the best idea, but I need to inherit many of int's magic methods for integer operations.

I added a default argument wraps=True to the class' __init__ method but started getting an unexpected TypeError, where my default argument was being assumed as a keyword argument for int.

The section of the code could be simplified to this:

class MyClass(int):

    def __init__(self, a, *args, b=False, **kwargs):
        super().__init__(*args, **kwargs)
        self.a = a
        self.b = b
```

and for some reason b (or in my case, wraps) was being passed as a keyword argument to int, which of course, didn't work.

After some testing I found that the same problem occurred with str but not with most other classes, which means that, (I'm guessing) the problem arises from inheriting from an immutable class. Am I correct and is there a way around this problem?

Thanks in advance.

Body:
I feel like I'm losing my mind. I was working on a simple project involving a subclass of int, which may not be the best idea, but I need to inherit many of int's magic methods for integer operations.

I added a default argument wraps=True to the class' __init__ method but started getting an unexpected TypeError, where my default argument was being assumed as a keyword argument for int.

The section of the code could be simplified to this:

class MyClass(int):

    def __init__(self, a, *args, b=False, **kwargs):
        super().__init__(*args, **kwargs)
        self.a = a
        self.b = b

and for some reason b (or in my case, wraps) was being passed as a keyword argument to int, which of course, didn't work.

After some testing I found that the same problem occurred with str but not with most other classes, which means that, (I'm guessing) the problem arises from inheriting from an immutable class. Am I correct and is there a way around this problem?

Thanks in advance.


问:
Does ngx-uploader support binary responses?
I am employing the ngx-uploader npm module in my angular single page application.

In an angular component, I am using the ngx-uploader module to upload a file to my server endpoint. The server processes the data and returns binary data -- zip file content.

The below typescript code is executed when the http response is received from the server -- the 'done' case.

The output object contains response data in the 'output.file.response' property.

But when I save the data to a zip file, the zip file contains data that is CORRUPTED.

Has the 'output.file.response' been altered in some way (e.g. converted binary to string)?

What do I need to do to properly create a Blob object from the response?

```<code>    case 'done':

         this.inProgress = false;

         const zipData = output.file?.response;

         const blobOptions: BlobPropertyBag = {
             type: 'application/zip'
         };

         const zipFileContent = new Blob(
             [ zipData ],
             blobOptions
         );

        const zipFileName = 'zip-file.zip';

        FileSaver.saveAs(
             zipFileContent,
             zipFileName
        );

        break;

</code>```

2023-01-02 Follow up:

I see that at:

https://github.com/bleenco/ngx-uploader/blob/master/projects/ngx-uploader/src/lib/ngx-uploader.class.ts

This code is being used:

```<code>    try {
         file.response = JSON.parse(xhr.response);
    } catch (e) {
         file.response = xhr.response;
    }

</code>```

It appears that the catch block is not applied and the binary response is being corrupted. I don't see any way to workaround. Looks like I will have to find another module.

Body:
I am employing the ngx-uploader npm module in my angular single page application.

In an angular component, I am using the ngx-uploader module to upload a file to my server endpoint. The server processes the data and returns binary data -- zip file content.

The below typescript code is executed when the http response is received from the server -- the 'done' case.

The output object contains response data in the 'output.file.response' property.

But when I save the data to a zip file, the zip file contains data that is CORRUPTED.

Has the 'output.file.response' been altered in some way (e.g. converted binary to string)?

What do I need to do to properly create a Blob object from the response?

    case 'done':

         this.inProgress = false;

         const zipData = output.file?.response;

         const blobOptions: BlobPropertyBag = {
             type: 'application/zip'
         };

         const zipFileContent = new Blob(
             [ zipData ],
             blobOptions
         );

        const zipFileName = 'zip-file.zip';

        FileSaver.saveAs(
             zipFileContent,
             zipFileName
        );

        break;

2023-01-02 Follow up:

I see that at:

https://github.com/bleenco/ngx-uploader/blob/master/projects/ngx-uploader/src/lib/ngx-uploader.class.ts

This code is being used:

    try {
         file.response = JSON.parse(xhr.response);
    } catch (e) {
         file.response = xhr.response;
    }

It appears that the catch block is not applied and the binary response is being corrupted. I don't see any way to workaround. Looks like I will have to find another module.


问:
Incremental model without updating changed records
I want to build a dbt model that returns the minimum timestamp for each user_id.

My source table is a versioning table with several billion rows. Hence, I want to build it as an incremental model.

In source data, version_id is unique and each user_id can have several records. Here is what it looks like:

```<code>with t1 (version_id, user_id, updated_at, is_activated) as (
        select * from values
        (1, 'a', '2022-12-01'::timestamp, true)
      , (2, 'b', '2022-12-02'::timestamp, true)
      , (2, 'b', '2022-12-03'::timestamp, false)
   --   , (1, 'a', '2022-12-03'::timestamp, true)
)
select * from t1
</code>```

When a user_id gets another row (e.g. 4th row) with a newer time, I don't want dbt to update the old row as the first row has the minimum timestamp.
How to ensure the new rows do not update all the old ones based on the min timestamp per user_id?

```<code>{{
    config(
        materialized='incremental',
        unique_key='version_id'
    )
}}
    WITH filtered AS (

        SELECT
            version_id
            , user_id
            , updated_at
        FROM {{ ref('versions') }}

        WHERE is_activated = TRUE
            {% if is_incremental() %}
                AND updated_at > (SELECT MAX(this.updated_at) FROM {{ this }} AS this)
            {% endif %}

        QUALIFY ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY updated_at) = 1
    )

    SELECT * FROM filtered
</code>```

Body:
I want to build a dbt model that returns the minimum timestamp for each user_id.

My source table is a versioning table with several billion rows. Hence, I want to build it as an incremental model.

In source data, version_id is unique and each user_id can have several records. Here is what it looks like:

with t1 (version_id, user_id, updated_at, is_activated) as (
        select * from values
        (1, 'a', '2022-12-01'::timestamp, true)
      , (2, 'b', '2022-12-02'::timestamp, true)
      , (2, 'b', '2022-12-03'::timestamp, false)
   --   , (1, 'a', '2022-12-03'::timestamp, true)
)
select * from t1

When a user_id gets another row (e.g. 4th row) with a newer time, I don't want dbt to update the old row as the first row has the minimum timestamp.
How to ensure the new rows do not update all the old ones based on the min timestamp per user_id?

{{
    config(
        materialized='incremental',
        unique_key='version_id'
    )
}}
    WITH filtered AS (

        SELECT
            version_id
            , user_id
            , updated_at
        FROM {{ ref('versions') }}

        WHERE is_activated = TRUE
            {% if is_incremental() %}
                AND updated_at > (SELECT MAX(this.updated_at) FROM {{ this }} AS this)
            {% endif %}

        QUALIFY ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY updated_at) = 1
    )

    SELECT * FROM filtered


问:
How to store arbitrary metadata in a photo saved using the Photos library?
The app takes pictures. Then is meant to save those pictures using the below code in the delegate method:

```<code>public func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {

    // Abort if an error was faced.
    guard error.isNone else {
        print("Error capturing photo: \(error!).")
        return
    }

    // Get the image data from the photo.
    guard let imageData=photo.fileDataRepresentation() else {
        print("Error converting photo to data.")
        return
    }

    // Create a `UIImage` from the image data.
    guard let image: UIImage = .init(data: imageData) else {
        print("Error converting data to a `UIImage`.")
        return
    }

    // Edit image.
    let result: UIImage=UIGraphicsImageRenderer(size: image.size).image(actions: { _ in
        ...
    })

    // Save edited image to photo library.
    PHPhotoLibrary.shared().performChanges {
        let creationRequest: PHAssetChangeRequest = .creationRequestForAsset(from: result)

        // Add metadata to the photo.
        creationRequest.creationDate = Date()
        if let location=self.location {
            creationRequest.location = .init(latitude: location.latitude, longitude: location.longitude)
        }
    }
}
</code>```

However, I need to save some metadata with the photo. The metadata is two strings. One is a description and the other is a category. How can I include these strings in the saved photo's metadata?

Body:
The app takes pictures. Then is meant to save those pictures using the below code in the delegate method:

public func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {

    // Abort if an error was faced.
    guard error.isNone else {
        print("Error capturing photo: \(error!).")
        return
    }

    // Get the image data from the photo.
    guard let imageData=photo.fileDataRepresentation() else {
        print("Error converting photo to data.")
        return
    }

    // Create a `UIImage` from the image data.
    guard let image: UIImage = .init(data: imageData) else {
        print("Error converting data to a `UIImage`.")
        return
    }

    // Edit image.
    let result: UIImage=UIGraphicsImageRenderer(size: image.size).image(actions: { _ in
        ...
    })

    // Save edited image to photo library.
    PHPhotoLibrary.shared().performChanges {
        let creationRequest: PHAssetChangeRequest = .creationRequestForAsset(from: result)

        // Add metadata to the photo.
        creationRequest.creationDate = Date()
        if let location=self.location {
            creationRequest.location = .init(latitude: location.latitude, longitude: location.longitude)
        }
    }
}

However, I need to save some metadata with the photo. The metadata is two strings. One is a description and the other is a category. How can I include these strings in the saved photo's metadata?


问:
Python AudioPlayer on Chromebook fails to play file
I have this python program:

```<code>from gtts import gTTS
from audioplayer import AudioPlayer

speech = gTTS('Hello, world!')
speech.save('test.mp3')
AudioPlayer('test.mp3').play(block=True)
</code>```

This runs fine on my Macbook. When I try to run it on my chromebook I get this error:

```<code>Traceback (most recent call last):
  File "/home/me/test.py", line 6, in <module>
    AudioPlayer('test.mp3').play(block=True)
  File "/home/me/.local/lib/python3.9/site-packages/audioplayer/abstractaudioplayer.py", line 114, in play
    self._doplay(loop, block)
  File "/home/me/.local/lib/python3.9/site-packages/audioplayer/audioplayer_linux.py", line 45, in _doplay
    raise AudioPlayerError(
audioplayer.abstractaudioplayer.AudioPlayerError: Failed to play "/home/me/test.mp3"
</code>```

The AudioPlayer pypi page (https://pypi.org/project/audioplayer/) lists packages to install. The very first one I try, python-gst-1.0 isn't found.

```<code>sudo apt-get install python-gst-1.0
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
E: Unable to locate package python-gst-1.0
E: Couldn't find any package by glob 'python-gst-1.0'
E: Couldn't find any package by regex 'python-gst-1.0'
</code>```

Not sure what to do next.

Body:
I have this python program:

from gtts import gTTS
from audioplayer import AudioPlayer

speech = gTTS('Hello, world!')
speech.save('test.mp3')
AudioPlayer('test.mp3').play(block=True)

This runs fine on my Macbook. When I try to run it on my chromebook I get this error:

Traceback (most recent call last):
  File "/home/me/test.py", line 6, in <module>
    AudioPlayer('test.mp3').play(block=True)
  File "/home/me/.local/lib/python3.9/site-packages/audioplayer/abstractaudioplayer.py", line 114, in play
    self._doplay(loop, block)
  File "/home/me/.local/lib/python3.9/site-packages/audioplayer/audioplayer_linux.py", line 45, in _doplay
    raise AudioPlayerError(
audioplayer.abstractaudioplayer.AudioPlayerError: Failed to play "/home/me/test.mp3"

The AudioPlayer pypi page (https://pypi.org/project/audioplayer/) lists packages to install. The very first one I try, python-gst-1.0 isn't found.

sudo apt-get install python-gst-1.0
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
E: Unable to locate package python-gst-1.0
E: Couldn't find any package by glob 'python-gst-1.0'
E: Couldn't find any package by regex 'python-gst-1.0'

Not sure what to do next.


问:
Connecting a dictionary and datalist
I am trying to make a stock trading webapp using ASP.Net Core MVC One of the things I am trying to implement is auto-complete search box where you can type the name of a stock and it would be suggested to the user. I tried to use a datalist. I want to use a dictionary where the name of the stock is the key and the value would be the symbol. example key- Apple value-AAPL. When the name is selected, I am trying to use the symbol to call other data from an API elsewhere in the app.

The 2 things I am trying to figure out is

A. Can I implement a dictionary with a datalist to accomplish this?

B. Is there a way to use a database to accomplish this? There are several thousand Stocks and Stock symbols and hard coding them would be very cumbersome and time consuming and would be easier to copy and paste stock names and corresponding symbols into a database.

Thanks in advance. This is my first time posting.

Here is what I have so far. Not sure how to proceed or if this is possible.

```<code><form>
  <label for="stock">Choose a Stock:</label>
  <input list="stock" name="stock" id="stock">
  <datalist id="stock">
    <option value="Tesla"/>
    <option value="IBM"/>
    <option value="Microsoft"/>
    <option value="Apple"/>
    <option value="Amazon"/>
  </datalist>
  <input type="submit">
</form>
</code>```

Title: Connecting a dictionary and datalist

Body:
I am trying to make a stock trading webapp using ASP.Net Core MVC One of the things I am trying to implement is auto-complete search box where you can type the name of a stock and it would be suggested to the user. I tried to use a datalist. I want to use a dictionary where the name of the stock is the key and the value would be the symbol. example key- Apple value-AAPL. When the name is selected, I am trying to use the symbol to call other data from an API elsewhere in the app.

The 2 things I am trying to figure out is

A. Can I implement a dictionary with a datalist to accomplish this?

B. Is there a way to use a database to accomplish this? There are several thousand Stocks and Stock symbols and hard coding them would be very cumbersome and time consuming and would be easier to copy and paste stock names and corresponding symbols into a database.

Thanks in advance. This is my first time posting.

Here is what I have so far. Not sure how to proceed or if this is possible.

<form>
  Choose a Stock:
  <input list="stock" name="stock" id="stock">
  <datalist id="stock">
    <option value="Tesla"/>
    <option value="IBM"/>
    <option value="Microsoft"/>
    <option value="Apple"/>
    <option value="Amazon"/>
  </datalist>
  <input type="submit">
</form>


问:
android:breakStrategy delimeters change
How to edit the delimeters used by android breakStrategy or switch it off all together

I dont't want a new line even if that means that alphabets of same word end up in different lines

I am making a password generator
Open for example

Title: android:breakStrategy delimeters change


问:
Importhtml google sheet not showing the table
I'm trying to import the table from this website
https://diegebetszeiten.de/erlangen-de-diyanet-methode/

to google sheet using

```<code>=IMPORTHTML("https://diegebetszeiten.de/erlangen-de-diyanet-methode/";"table";1)

=IMPORTHTML("https://diegebetszeiten.de/wp-json/oembed/1.0/embed?url=https%3A%2F%2Fdiegebetszeiten.de%2Ferlangen-de-diyanet-methode%2F";"table";1)
</code>```

Answer:
#N/A
#N/A

how can I find the correct code of the table shown on the website?

I tried different sites I foun din the source code of the website.

Body:
I'm trying to import the table from this website
https://diegebetszeiten.de/erlangen-de-diyanet-methode/

to google sheet using

=IMPORTHTML("https://diegebetszeiten.de/erlangen-de-diyanet-methode/";"table";1)

=IMPORTHTML("https://diegebetszeiten.de/wp-json/oembed/1.0/embed?url=https%3A%2F%2Fdiegebetszeiten.de%2Ferlangen-de-diyanet-methode%2F";"table";1)

Answer:
#N/A
#N/A

how can I find the correct code of the table shown on the website?

I tried different sites I foun din the source code of the website.


问:
Error with Firebase Authentication with react native expo
I get this error: TypeError: (0, _firebase.auth) is not a function. (In '(0, _firebase.auth)()', '(0, _firebase.auth)' is an instance of AuthImpl)

My code is:

`

```<code>// Import the functions you need from the SDKs you need
import firebase from 'firebase/compat/app';
import { getAuth } from "firebase/auth";
import AsyncStorage from '@react-native-async-storage/async-storage';
import { initializeAuth, getReactNativePersistence} from 'firebase/auth/react-native';

const firebaseConfig = {

};

// Initialize Firebase
const app = firebase.initializeApp(firebaseConfig);
const auth = initializeAuth(app, {
  persistence: getReactNativePersistence(AsyncStorage)
  });

export { auth };
</code>```

`

I tried many variations of imports and different ways for the const auth.

Body:
I get this error: TypeError: (0, _firebase.auth) is not a function. (In '(0, _firebase.auth)()', '(0, _firebase.auth)' is an instance of AuthImpl)

My code is:

`

// Import the functions you need from the SDKs you need
import firebase from 'firebase/compat/app';
import { getAuth } from "firebase/auth";
import AsyncStorage from '@react-native-async-storage/async-storage';
import { initializeAuth, getReactNativePersistence} from 'firebase/auth/react-native';

const firebaseConfig = {

};

// Initialize Firebase
const app = firebase.initializeApp(firebaseConfig);
const auth = initializeAuth(app, {
  persistence: getReactNativePersistence(AsyncStorage)
  });

export { auth };

`

I tried many variations of imports and different ways for the const auth.


问:
Is there any way to change FK naming convention while using doctrine migration?
Currently, while using doctrine migration, FK names are dechex(crc32()) encoded column names.
This is a problem when, I want to start using Doctrine migration for my existing Symfony + Doctrine application, which has really huge DB.

And Index names are also HEX-encoded names.

The problem is, we really don't want to rename all our current ones to hex'y names, because tables are huge.

Need suggestions.


问:
Infinite Loop at Checkout Woocommerce [woocommerce_package_rates]
I have written the following script to automatically apply a $350 credit to the shipping rates if the shipping rate is over $350. When removing this script from my functions.php there are no issues at Checkout, the shipping methods will populate. When leaving this script in functions.php, the Checkout page requires multiple refreshes to populate and does not end the spinning loading loop.

Is there something I am missing here?

```<code>add_filter('woocommerce_package_rates', 'custom_shipping_rate_label_based_on_cost', 100, 2);
function custom_shipping_rate_label_based_on_cost( $rates, $package ){

    // Declare Variables
    $subtotal = $package['cart_subtotal'];
    $counter = 0;
    $first = 0;
    $category = 0;
    $discount = 350;

     // Set Category True if Walk In Tub
     foreach ($package['contents'] as $product) {
        $product_cats = wp_get_post_terms( $product['product_id'], 'product_cat', array('fields' => 'names') );

      if( in_array('Walk In Tubs', $product_cats) ) {
            $category = 1;
        }
    }

    // Set First Shipping Rate Cost and Counter
    foreach ( $rates as $key => $rate ) {
            $rate_cost = $rate->cost;

            if( $counter == 0 ) {
                $firstcost = $rate_cost;
            }

             if( $counter == 1 ) {
                $secondcost = $rate_cost;
            }

            $counter = $counter + 1;
    }

  if ($firstcost == 0) {
      $firstcost = $secondcost;
  }

    // Over or Equal to 350
     if ( $firstcost >= 350 && $subtotal >= 4500 && $category = 1 && is_checkout()) {
           $rates[$key]->cost = $rates[$key]->cost - ( $discount );
            wc_print_notice( __( '<div class="shippingdiscount">$350 Discount Applied to Total Shipping Cost</div>', 'woocommerce' ), 'notice' );
            }

              // Under 350
     else if ( $firstcost < 350 && $firstcost != 0 && $subtotal >= 4500 && $category = 1 && is_checkout()) {
          foreach ( $rates as $key => $rate ) {
            $rates[$key]->cost = $rates[$key]->cost - ( $firstcost );
          }
            wc_print_notice( __( '<div class="shippingdiscount">Your order is eligible for Free Shipping</div>', 'woocommerce' ), 'notice' );
            }

            else {
                return;
            }

    return $rates;
}
</code>```

It seems the issue is stemming from: wc_print_notice

Body:
I have written the following script to automatically apply a $350 credit to the shipping rates if the shipping rate is over $350. When removing this script from my functions.php there are no issues at Checkout, the shipping methods will populate. When leaving this script in functions.php, the Checkout page requires multiple refreshes to populate and does not end the spinning loading loop.

Is there something I am missing here?

add_filter('woocommerce_package_rates', 'custom_shipping_rate_label_based_on_cost', 100, 2);
function custom_shipping_rate_label_based_on_cost( $rates, $package ){

    // Declare Variables
    $subtotal = $package['cart_subtotal'];
    $counter = 0;
    $first = 0;
    $category = 0;
    $discount = 350;

     // Set Category True if Walk In Tub
     foreach ($package['contents'] as $product) {
        $product_cats = wp_get_post_terms( $product['product_id'], 'product_cat', array('fields' => 'names') );

      if( in_array('Walk In Tubs', $product_cats) ) {
            $category = 1;
        }
    }

    // Set First Shipping Rate Cost and Counter
    foreach ( $rates as $key => $rate ) {
            $rate_cost = $rate->cost;

            if( $counter == 0 ) {
                $firstcost = $rate_cost;
            }

             if( $counter == 1 ) {
                $secondcost = $rate_cost;
            }

            $counter = $counter + 1;
    }

  if ($firstcost == 0) {
      $firstcost = $secondcost;
  }

    // Over or Equal to 350
     if ( $firstcost >= 350 && $subtotal >= 4500 && $category = 1 && is_checkout()) {
           $rates[$key]->cost = $rates[$key]->cost - ( $discount );
            wc_print_notice( __( '
$350 Discount Applied to Total Shipping Cost
', 'woocommerce' ), 'notice' );
            }

              // Under 350
     else if ( $firstcost < 350 && $firstcost != 0 && $subtotal >= 4500 && $category = 1 && is_checkout()) {
          foreach ( $rates as $key => $rate ) {
            $rates[$key]->cost = $rates[$key]->cost - ( $firstcost );
          }
            wc_print_notice( __( '
Your order is eligible for Free Shipping
', 'woocommerce' ), 'notice' );
            }

            else {
                return;
            }

    return $rates;
}

It seems the issue is stemming from: wc_print_notice


问:
Unable to build Hibernate SessionFactory
in a jakarta - wildfly project when i try to run the project this error message appears.

```<code>Deploying on WildFly Application Server
    profile mode: false
    debug mode: false
    force redeploy: true
Undeploying ...
Initial deploying EutopeanDynamics-shop-2022 to C:\Program Files\wildfly-27.0.1.Final\standalone\deployments\WebEshop.war
Completed initial distribution of EutopeanDynamics-shop-2022
Deploying C:\Program Files\wildfly-27.0.1.Final\standalone\deployments\WebEshop.war
"{\"WFLYCTL0080: Failed services\" => {\"jboss.persistenceunit.\\\"WebEshop.war#Persistence\\\"\" => \"jakarta.persistence.PersistenceException: [PersistenceUnit: Persistence] Unable to build Hibernate SessionFactory
    Caused by: jakarta.persistence.PersistenceException: [PersistenceUnit: Persistence] Unable to build Hibernate SessionFactory
    Caused by: org.hibernate.exception.GenericJDBCException: Unable to open JDBC Connection for DDL execution
    Caused by: java.sql.SQLException: jakarta.resource.ResourceException: IJ000453: Unable to get managed connection for java:/MySqlDS
    Caused by: jakarta.resource.ResourceException: IJ000453: Unable to get managed connection for java:/MySqlDS
    Caused by: jakarta.resource.ResourceException: IJ031084: Unable to create connection
    Caused by: java.sql.SQLException: Access denied for user 'admin'@'localhost' (using password: YES)\"}}"

</code>```

Here is my persistence class

```<code><?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
             version="2.1">
    <persistence-unit name="Persistence" transaction-type="JTA">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
        <jta-data-source>java:/MySqlDS</jta-data-source>
        <properties>
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
            <property name="hibernate.hbm2ddl.auto" value="validate"/>
            <property name="hibernate.show_sql" value="true"/>
            <property name="hibernate.format_sql" value="true"/>
            <property name="hibernate.globally_quoted_identifiers" value="true"/>
            <property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
        </properties>
    </persistence-unit>
</persistence>
</code>```

I am using wildfly application server. The server is running and from localhost:9990 i created a datasource pointing in an empty database called 'eshop" as shown in the image above
enter image description here

Body:
in a jakarta - wildfly project when i try to run the project this error message appears.

Deploying on WildFly Application Server
    profile mode: false
    debug mode: false
    force redeploy: true
Undeploying ...
Initial deploying EutopeanDynamics-shop-2022 to C:\Program Files\wildfly-27.0.1.Final\standalone\deployments\WebEshop.war
Completed initial distribution of EutopeanDynamics-shop-2022
Deploying C:\Program Files\wildfly-27.0.1.Final\standalone\deployments\WebEshop.war
"{\"WFLYCTL0080: Failed services\" => {\"jboss.persistenceunit.\\\"WebEshop.war#Persistence\\\"\" => \"jakarta.persistence.PersistenceException: [PersistenceUnit: Persistence] Unable to build Hibernate SessionFactory
    Caused by: jakarta.persistence.PersistenceException: [PersistenceUnit: Persistence] Unable to build Hibernate SessionFactory
    Caused by: org.hibernate.exception.GenericJDBCException: Unable to open JDBC Connection for DDL execution
    Caused by: java.sql.SQLException: jakarta.resource.ResourceException: IJ000453: Unable to get managed connection for java:/MySqlDS
    Caused by: jakarta.resource.ResourceException: IJ000453: Unable to get managed connection for java:/MySqlDS
    Caused by: jakarta.resource.ResourceException: IJ031084: Unable to create connection
    Caused by: java.sql.SQLException: Access denied for user 'admin'@'localhost' (using password: YES)\"}}"

Here is my persistence class

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
             version="2.1">
    <persistence-unit name="Persistence" transaction-type="JTA">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
        <jta-data-source>java:/MySqlDS</jta-data-source>
        <properties>
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
            <property name="hibernate.hbm2ddl.auto" value="validate"/>
            <property name="hibernate.show_sql" value="true"/>
            <property name="hibernate.format_sql" value="true"/>
            <property name="hibernate.globally_quoted_identifiers" value="true"/>
            <property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
        </properties>
    </persistence-unit>
</persistence>

I am using wildfly application server. The server is running and from localhost:9990 i created a datasource pointing in an empty database called 'eshop" as shown in the image above
enter image description here


问:
Camera/Scene Jumps When Replacing OrthographicCamera in CameraControl
When I finish playing an animation with camera movement, I want the cameraContols to pick up where the clamped animation left off. But everything I have tried so results in the camera jumping to a different location. (The lookAt position seems to be OK.)

I have tried capturing the animeCamera’s attributes and resetting them after replacing the controls’ .camera - but no success.

Any suggestions or examples to look at?

```<code>AnimationMixer = new THREE.AnimationMixer(gltf.scene);
var that = this;
AnimationMixer.addEventListener('finished', function(e){
    // replace default camera with animation camera
    that.controls.camera = animeCamera;
    that.controls.update();
    that.controls.enabled = true;
});
</code>```

Body:
When I finish playing an animation with camera movement, I want the cameraContols to pick up where the clamped animation left off. But everything I have tried so results in the camera jumping to a different location. (The lookAt position seems to be OK.)

I have tried capturing the animeCamera’s attributes and resetting them after replacing the controls’ .camera - but no success.

Any suggestions or examples to look at?

AnimationMixer = new THREE.AnimationMixer(gltf.scene);
var that = this;
AnimationMixer.addEventListener('finished', function(e){
    // replace default camera with animation camera
    that.controls.camera = animeCamera;
    that.controls.update();
    that.controls.enabled = true;
});


问:
Whenever i load a localhost using the firebase serve command it loads older code?
Whenever i load a localhost using the firebase serve command it loads older code. I dont know how to fix this issue, my new code is in the public folder and still does not function as i wanted it to.

What im trying to: That my new code would be used instead of my older code this is especially with css as it has trouble with loading that.


问:
State Machine addCatch error handler of a parallel state drops step event fields
I'm using AWS cdk. I have a few lambdas running in a parallel state of a state machine and if one of them fails I am currently:

Adding a custom object to the step function event in the lambda wrapper

Have a failure lambda that then reads that custom object to see what the error was and alert about it.

The problem is that in the logs I can see that the step function event that moves between the step function steps has got populated with the custom object during shutdown, but the failure lambda catch does not have that in its input. It successfully gets the shortened error in the resultPath prop I provide, but that's unfortunately not enough.

```<code>const parallel = new sfn.Parallel(this, 'WithdrawEventParallelState')
      .branch(happyPath)
      .addCatch(failure.next(rollback), { resultPath: '$.Error' });

</code>```

Am I missing some prop to carry on into the error catch lambda with the latest step function event?

Tried removing the resultPath, then I get no error at all

Body:
I'm using AWS cdk. I have a few lambdas running in a parallel state of a state machine and if one of them fails I am currently:

Adding a custom object to the step function event in the lambda wrapper

Have a failure lambda that then reads that custom object to see what the error was and alert about it.

The problem is that in the logs I can see that the step function event that moves between the step function steps has got populated with the custom object during shutdown, but the failure lambda catch does not have that in its input. It successfully gets the shortened error in the resultPath prop I provide, but that's unfortunately not enough.

const parallel = new sfn.Parallel(this, 'WithdrawEventParallelState')
      .branch(happyPath)
      .addCatch(failure.next(rollback), { resultPath: '$.Error' });

Am I missing some prop to carry on into the error catch lambda with the latest step function event?

Tried removing the resultPath, then I get no error at all


问:
document not defined error in a client component in beta version
I have the following component in NextJs version 13 (Beta).

I have marked it to be a client component. Yet I get the following error.

Uncaught Error: document is not defined

I can call something like document.location inside useEffect, no issues.

The issue comes when I call document inside the return block.

I am not the one doing it. It is the external dependency component that calls document.

Thus not within my control. How can I address this?

It is throwing the document is not defined error due to the ReactQuill component.

This component is at /app/editor/page.tsx

```<code>'use client'
import React, { useState } from 'react';
import ReactQuill from 'react-quill';

const Editor = ({ placeholder }) => {
  // no issues with using hooks
  const [editorHtml, setEditorHtml] = useState('');
  const [theme, setTheme] = useState('snow');

  useEffect(() => {
    // no issues here
    console.log(document.location.href)
  })

  return (
    <div>
    {/* somewhere inside this component there is a call to document causing issue */}
    {/* issue is with the quill dependency that has a call to document */}
    {/* even adding checks like document !== 'undefined' results in same error*/}
      <ReactQuill
        theme={theme}
        value={editorHtml}
        modules={Editor.modules}
        formats={Editor.formats}
        bounds={'.app'}
        placeholder={placeholder}
      />
    </div>
  );
};

export default Editor;
</code>```

Body:
I have the following component in NextJs version 13 (Beta).

I have marked it to be a client component. Yet I get the following error.

Uncaught Error: document is not defined

I can call something like document.location inside useEffect, no issues.

The issue comes when I call document inside the return block.

I am not the one doing it. It is the external dependency component that calls document.

Thus not within my control. How can I address this?

It is throwing the document is not defined error due to the ReactQuill component.

This component is at /app/editor/page.tsx

'use client'
import React, { useState } from 'react';
import ReactQuill from 'react-quill';

const Editor = ({ placeholder }) => {
  // no issues with using hooks
  const [editorHtml, setEditorHtml] = useState('');
  const [theme, setTheme] = useState('snow');

  useEffect(() => {
    // no issues here
    console.log(document.location.href)
  })

  return (

    {/* somewhere inside this component there is a call to document causing issue */}
    {/* issue is with the quill dependency that has a call to document */}
    {/* even adding checks like document !== 'undefined' results in same error*/}
      <ReactQuill
        theme={theme}
        value={editorHtml}
        modules={Editor.modules}
        formats={Editor.formats}
        bounds={'.app'}
        placeholder={placeholder}
      />

  );
};

export default Editor;


问:
How to parse XAML from Xamarin as a string with C#?
I'm trying to parse a string that contains XAML from Xamarin but I get an error that I don't know how to get rid of. Here is the string I'm trying to parse:

```<code>string xaml = "<ContentPage xmlns=\"http://xamarin.com/schemas/2014/forms\"\r\n" +
            "xmlns:x=\"http://schemas.microsoft.com/winfx/2009/xaml\"\r\n" +
            "x:Class=\"MyMauiApp.MyPage\"\r\n" +
            "Title=\"MyPage\"\r\n" +
            "BackgroundColor=\"White\">\r\n" +
            "<StackLayout>\r\n" +
            "<Label Text=\"Welcome\"\r\n" +
            " VerticalOptions=\"Center\"\r\n" +
            "HorizontalOptions=\"Center\"/>\r\n" +
            "<!-- Other views go here -->\r\n" +
            "</StackLayout></ContentPage>\r\n";
</code>```

I successfully parsed the string with a XML parser:

```<code>XDocument xml = XDocument.Parse(xaml);
</code>```

However, I get an error trying the conversion with a XAML parser:

```<code>System.Xaml.XamlServices.Parse(xaml);
</code>```

Here is the error:

Error

It says unable to create unknown type '{http://xamarin.com/schemas/2014/forms}ContentPage' number of line 2 position 2.

What is wrong with the string? If the string is OK, what do I need to change to parse without error?

Thanks

Body:
I'm trying to parse a string that contains XAML from Xamarin but I get an error that I don't know how to get rid of. Here is the string I'm trying to parse:

string xaml = "<ContentPage xmlns=\"http://xamarin.com/schemas/2014/forms\"\r\n" +
            "xmlns:x=\"http://schemas.microsoft.com/winfx/2009/xaml\"\r\n" +
            "x:Class=\"MyMauiApp.MyPage\"\r\n" +
            "Title=\"MyPage\"\r\n" +
            "BackgroundColor=\"White\">\r\n" +
            "<StackLayout>\r\n" +
            "\r\n" +
            "\r\n" +
            "</StackLayout></ContentPage>\r\n";

I successfully parsed the string with a XML parser:

XDocument xml = XDocument.Parse(xaml);

However, I get an error trying the conversion with a XAML parser:

System.Xaml.XamlServices.Parse(xaml);

Here is the error:

Error

It says unable to create unknown type '{http://xamarin.com/schemas/2014/forms}ContentPage' number of line 2 position 2.

What is wrong with the string? If the string is OK, what do I need to change to parse without error?

Thanks


问:
websocket automatically trying to decode broken string into utf8 and failing. Could not decode a text frame as UTF-8
```<code>var ip = 'wss://173-255-221-28.devast.io/';

websocket = new window.WebSocket(ip);

websocket.binaryType = "arraybuffer";

websocket.onmessage = function(event) {

    console.log("aa");
};

websocket.onopen = function(event) {
    websocket.send('[30,"3056nick85j2ktlkH54a","40555", -1, 0, "JOCKO WILLINKS", 0, 0, 0]');
};
</code>```

I'm receiving a broken string that cannot be decoded with utf8 because it has unsupported characters.

I have zero access to the server.

I heard browsers automatically close websocket connections if non utf8 encoded characters are found.

The problem is from the server which I don't have access to, from this code, I should get a message with array of player nicknames in the server, and some people glitched unsupported nicknames and now onmessage doesn't even work

Similar thing happens to web chatrooms where some user sends a complicated unsupported message and all the chatroom will disconnect

That's how the bytes look in raw in python, 120 items of nicknames.

"\\u000b \\r\\t\\n\\f" is probably the culprit

Using arraybuffer to get raw binary in JS won't work still, because it will automatically convert to string.

How can I ignore this error, or get the data without error and from there manually fix it? I need websockets for low input delay.

Body:
var ip = 'wss://173-255-221-28.devast.io/';

websocket = new window.WebSocket(ip);

websocket.binaryType = "arraybuffer";

websocket.onmessage = function(event) {

    console.log("aa");
};

websocket.onopen = function(event) {
    websocket.send('[30,"3056nick85j2ktlkH54a","40555", -1, 0, "JOCKO WILLINKS", 0, 0, 0]');
};

I'm receiving a broken string that cannot be decoded with utf8 because it has unsupported characters.

I have zero access to the server.

I heard browsers automatically close websocket connections if non utf8 encoded characters are found.

The problem is from the server which I don't have access to, from this code, I should get a message with array of player nicknames in the server, and some people glitched unsupported nicknames and now onmessage doesn't even work

Similar thing happens to web chatrooms where some user sends a complicated unsupported message and all the chatroom will disconnect

That's how the bytes look in raw in python, 120 items of nicknames.

"\\u000b \\r\\t\\n\\f" is probably the culprit

Using arraybuffer to get raw binary in JS won't work still, because it will automatically convert to string.

How can I ignore this error, or get the data without error and from there manually fix it? I need websockets for low input delay.


问:
Uncaught ReflectionException: Class App\Http\Kernel does not exist laravel 8
composer.json >>>>

```<code>{
    "name": "laravel/laravel",
    "type": "project",
    "description": "The Laravel Framework.",
    "keywords": [
        "framework",
        "laravel"
    ],
    "license": "MIT",
    "require": {
        "php": "^7.3",
        "fideloper/proxy": "^4.2",
        "fruitcake/laravel-cors": "^2.0",
        "guzzlehttp/guzzle": "^7.0.1",
        "laravel/framework": "^8.0",
        "laravel/tinker": "^2.0",
        "laravel/ui": "^3.0",
        "laravelcollective/html": "^6.2",
        "spatie/laravel-permission": "^3.17",
        "tcg/voyager": "^1.6"
    },
    "require-dev": {
        "facade/ignition": "^2.3.6",
        "fzaninotto/faker": "^1.9.1",
        "mockery/mockery": "^1.3.1",
        "nunomaduro/collision": "^5.0",
        "phpunit/phpunit": "^9.3"
    },
    "config": {
        "optimize-autoloader": true,
        "preferred-install": "dist",
        "sort-packages": true
    },
    "extra": {
        "laravel": {
            "dont-discover": []
        }
    },
    "autoload": {
        "psr-4": {
            "App\\": "app/",
            "Database\\Factories\\": "database/factories/",
            "Database\\Seeders\\": "database/seeders/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        }
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "scripts": {
        "post-autoload-dump": [
            "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover --ansi"
        ],
        "post-root-package-install": [
            "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "@php artisan key:generate --ansi"
        ]
    }
}

</code>```

this is laravel 8 php 7 and think it could be related to my namespace configuration, because i haven't all understood yet.

hat I have already done :

Delete /vendor and make a new install with composer install
composer dump-autoload
composer update btw, I get the error when I insert the php serve
Please inform me if i should post another file that could be useful.

Here is my composer.json file :

```<code>{
    "name": "laravel/laravel",
    "type": "project",
    "description": "The Laravel Framework.",
    "keywords": [
        "framework",
        "laravel"
    ],
    "license": "MIT",
    "require": {
        "php": "^7.3",
        "fideloper/proxy": "^4.2",
        "fruitcake/laravel-cors": "^2.0",
        "guzzlehttp/guzzle": "^7.0.1",
        "laravel/framework": "^8.0",
        "laravel/tinker": "^2.0",
        "laravel/ui": "^3.0",
        "laravelcollective/html": "^6.2",
        "spatie/laravel-permission": "^3.17",
        "tcg/voyager": "^1.6"
    },
    "require-dev": {
        "facade/ignition": "^2.3.6",
        "fzaninotto/faker": "^1.9.1",
        "mockery/mockery": "^1.3.1",
        "nunomaduro/collision": "^5.0",
        "phpunit/phpunit": "^9.3"
    },
    "config": {
        "optimize-autoloader": true,
        "preferred-install": "dist",
        "sort-packages": true
    },
    "extra": {
        "laravel": {
            "dont-discover": []
        }
    },
    "autoload": {
        "psr-4": {
            "App\\": "app/",
            "Database\\Factories\\": "database/factories/",
            "Database\\Seeders\\": "database/seeders/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        }
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "scripts": {
        "post-autoload-dump": [
            "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover --ansi"
        ],
        "post-root-package-install": [
            "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "@php artisan key:generate --ansi"
        ]
    }
}

</code>```

Body:
composer.json >>>>

{
    "name": "laravel/laravel",
    "type": "project",
    "description": "The Laravel Framework.",
    "keywords": [
        "framework",
        "laravel"
    ],
    "license": "MIT",
    "require": {
        "php": "^7.3",
        "fideloper/proxy": "^4.2",
        "fruitcake/laravel-cors": "^2.0",
        "guzzlehttp/guzzle": "^7.0.1",
        "laravel/framework": "^8.0",
        "laravel/tinker": "^2.0",
        "laravel/ui": "^3.0",
        "laravelcollective/html": "^6.2",
        "spatie/laravel-permission": "^3.17",
        "tcg/voyager": "^1.6"
    },
    "require-dev": {
        "facade/ignition": "^2.3.6",
        "fzaninotto/faker": "^1.9.1",
        "mockery/mockery": "^1.3.1",
        "nunomaduro/collision": "^5.0",
        "phpunit/phpunit": "^9.3"
    },
    "config": {
        "optimize-autoloader": true,
        "preferred-install": "dist",
        "sort-packages": true
    },
    "extra": {
        "laravel": {
            "dont-discover": []
        }
    },
    "autoload": {
        "psr-4": {
            "App\\": "app/",
            "Database\\Factories\\": "database/factories/",
            "Database\\Seeders\\": "database/seeders/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        }
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "scripts": {
        "post-autoload-dump": [
            "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover --ansi"
        ],
        "post-root-package-install": [
            "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "@php artisan key:generate --ansi"
        ]
    }
}

this is laravel 8 php 7 and think it could be related to my namespace configuration, because i haven't all understood yet.

hat I have already done :

Delete /vendor and make a new install with composer install
composer dump-autoload
composer update btw, I get the error when I insert the php serve
Please inform me if i should post another file that could be useful.

Here is my composer.json file :

{
    "name": "laravel/laravel",
    "type": "project",
    "description": "The Laravel Framework.",
    "keywords": [
        "framework",
        "laravel"
    ],
    "license": "MIT",
    "require": {
        "php": "^7.3",
        "fideloper/proxy": "^4.2",
        "fruitcake/laravel-cors": "^2.0",
        "guzzlehttp/guzzle": "^7.0.1",
        "laravel/framework": "^8.0",
        "laravel/tinker": "^2.0",
        "laravel/ui": "^3.0",
        "laravelcollective/html": "^6.2",
        "spatie/laravel-permission": "^3.17",
        "tcg/voyager": "^1.6"
    },
    "require-dev": {
        "facade/ignition": "^2.3.6",
        "fzaninotto/faker": "^1.9.1",
        "mockery/mockery": "^1.3.1",
        "nunomaduro/collision": "^5.0",
        "phpunit/phpunit": "^9.3"
    },
    "config": {
        "optimize-autoloader": true,
        "preferred-install": "dist",
        "sort-packages": true
    },
    "extra": {
        "laravel": {
            "dont-discover": []
        }
    },
    "autoload": {
        "psr-4": {
            "App\\": "app/",
            "Database\\Factories\\": "database/factories/",
            "Database\\Seeders\\": "database/seeders/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        }
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "scripts": {
        "post-autoload-dump": [
            "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover --ansi"
        ],
        "post-root-package-install": [
            "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "@php artisan key:generate --ansi"
        ]
    }
}


问:
How can i exclude certain files from a maven dependency?
I have a maven project that includes a dependency of a local custom maven repository. However, there are files in it i do not want in my main project because they seem to override configs in the main project for some odd reason (application.properties). How can i exclude files (specifically application.properties) from a maven dependency?</p>


问:
use alternate CA for 'go mod download' or 'go get'
I would like to use an alternate CA for a go mod download or go get command.

I do not want to add the certificate authority (CA) to the system's permanent store of trusted certificate authorities.

One use case for this is an IT department that runs some TLS traffic through a system such as Cisco Umbrella that has its own CA that is not a default CA in the system's default bundled CA store (such as /etc/ssl/certs/ca-bundle.crt on some linux distributions or the bundled CAs built in to a browswer such as firefox or chrome).  Another use case would be deployment of go modules signed by a trusted internal certificate authority.

I recently experienced the first use case:

```<code>$ go mod download -x all
.
.
# get https://proxy.golang.org/golang.org/x/term/@v/v0.3.0.mod: Get "https://proxy.golang.org/golang.org/x/term/@v/v0.3.0.mod": x509: certificate signed by unknown authority
</code>```

I am looking for the way to tell go to use an additional CA cert - the equivalent of wget's --ca-certificate:

```<code>wget --ca-certificate Cisco_Umbrella_Root_CA.cer https://proxy.golang.org/golang.org/x/crypto/@v/v0.4.0.mod
</code>```

Update: I tried using SSL_CERT_DIR based on the comment from @Ouroborus and Where is Golang picking up root CAs from?.  Same results:

```<code>env SSL_CERT_FILE=/usr/ports/security/age/tmp/20221230/Cisco_Umbrella_Root_CA-plus-sys.crt go mod download -x all
.
.
# get https://proxy.golang.org/golang.org/x/crypto/@v/v0.4.0.mod: Get "https://proxy.golang.org/golang.org/x/crypto/@v/v0.4.0.mod": x509: certificate signed by unknown authority
</code>```

That file is a 'PEM certificate' according to file(1).  And it works when I feed it to wget (as described above).  The go docs for SSL_CERT_FILE aren't clear (to me) what it expects for the file format, or I missed where that is specified.

Body:
I would like to use an alternate CA for a go mod download or go get command.

I do not want to add the certificate authority (CA) to the system's permanent store of trusted certificate authorities.

One use case for this is an IT department that runs some TLS traffic through a system such as Cisco Umbrella that has its own CA that is not a default CA in the system's default bundled CA store (such as /etc/ssl/certs/ca-bundle.crt on some linux distributions or the bundled CAs built in to a browswer such as firefox or chrome).  Another use case would be deployment of go modules signed by a trusted internal certificate authority.

I recently experienced the first use case:

$ go mod download -x all
.
.
# get https://proxy.golang.org/golang.org/x/term/@v/v0.3.0.mod: Get "https://proxy.golang.org/golang.org/x/term/@v/v0.3.0.mod": x509: certificate signed by unknown authority

I am looking for the way to tell go to use an additional CA cert - the equivalent of wget's --ca-certificate:

wget --ca-certificate Cisco_Umbrella_Root_CA.cer https://proxy.golang.org/golang.org/x/crypto/@v/v0.4.0.mod

Update: I tried using SSL_CERT_DIR based on the comment from @Ouroborus and Where is Golang picking up root CAs from?.  Same results:

env SSL_CERT_FILE=/usr/ports/security/age/tmp/20221230/Cisco_Umbrella_Root_CA-plus-sys.crt go mod download -x all
.
.
# get https://proxy.golang.org/golang.org/x/crypto/@v/v0.4.0.mod: Get "https://proxy.golang.org/golang.org/x/crypto/@v/v0.4.0.mod": x509: certificate signed by unknown authority

That file is a 'PEM certificate' according to file(1).  And it works when I feed it to wget (as described above).  The go docs for SSL_CERT_FILE aren't clear (to me) what it expects for the file format, or I missed where that is specified.


问:
React Native - list from .map() inside a FlatList renderItem?
I have a list of items which I render in a Flatlist.
Each item has a few boolean keys.
If the key is true, I want to render a specific icon for that key.

This is the Flatlist code -

```<code><FlatList
        style={styles.list}
        keyExtractor={(item, index) => index.toString()}
        data={currentList}
        renderItem={({ item, index }) => (
          <Pressable style={styles.item} onPress={() => openCard(item, index)}>
            <View style={styles.imageContainer}></View>
            <View style={styles.itemMain}>
              <Text style={[styles.text, { fontSize: 17 }]}>{item.name}</Text>
              <View style={styles.likesContainer}>
                <Text style={styles.text}>{item.likes} likes </Text>
                <Ionicons name={"heart"} size={20} color={"red"} />

                <Text style={styles.text}>{item.visited} visits </Text>
                <Ionicons name={"location"} size={20} color={"gold"} />
              </View>
              <View style={styles.iconsContainer}>
                <Icons beach={item}></Icons>
              </View>
            </View>
          </Pressable>
        )}
      />
</code>```

This is the Icons component

```<code>const Icons = (props) => {
  const beach = props.beach;
  Object.entries(beach).map((entry) => {
    const [key, value] = entry;
    if (value === "TRUE") {
      return icons.selectIcon(key, 20);
       }

  });
};
</code>```

icons.selectIcon is a function which returns the correct icon and works perfectly fine when used outside of a Flatlist.
When I tried to return a test instead of the function - Nothing was rendered either.

I think it has to do with trying to render a list within a list but I can't find anything in the documentation.

The other long way solution is to write for each key an if statement.

Can I render a list within a list item?
Thanks

Sample object in my object list

```<code>[{"img": "soldierspoint",
"key": 0,
"lat": 17.16966,
"likes": 2,
"lng": -61.83792,
"longDescription": "Now you can run your build with eas build -p android --profile preview. Remember that you can name the profile whatever you like. We named the profile "preview", however, you can call it "local", "simulator", or whatever makes the most sense for you.
"shortDescription": "Quiet and shady.  Easy Hike.",
"visited": 2,
"zAccess": "hike, Car",
"zAccessDes": "",
"zHistorical": "",
"zHistoricalDes": "",
"zInterestingGeography": "",
"zInterestingGeographyDes": "",
 "zLotsOfSand": "TRUE",
"zLotsSandDes": "",
"zNaturalShade": "TRUE",
"zNaturalShadeDes": "",
"zRestaurant": "",
"zRestaurantDes": "",
"zSheltered": "",
"zShelteredDes": "",
"zSnorkeling": "",
"zSnorkelingDes": "",
"zVeryPopular": "",
"zVeryPopularDes": "",
"zVerySmall": "",
"zVerySmallDes": ""}]
</code>```

Body:
I have a list of items which I render in a Flatlist.
Each item has a few boolean keys.
If the key is true, I want to render a specific icon for that key.

This is the Flatlist code -

<FlatList
        style={styles.list}
        keyExtractor={(item, index) => index.toString()}
        data={currentList}
        renderItem={({ item, index }) => (
          <Pressable style={styles.item} onPress={() => openCard(item, index)}>
            <View style={styles.imageContainer}></View>
            <View style={styles.itemMain}>
              <Text style={[styles.text, { fontSize: 17 }]}>{item.name}</Text>
              <View style={styles.likesContainer}>
                <Text style={styles.text}>{item.likes} likes </Text>
                <Ionicons name={"heart"} size={20} color={"red"} />

                <Text style={styles.text}>{item.visited} visits </Text>
                <Ionicons name={"location"} size={20} color={"gold"} />
              </View>
              <View style={styles.iconsContainer}>
                <Icons beach={item}></Icons>
              </View>
            </View>
          </Pressable>
        )}
      />

This is the Icons component

const Icons = (props) => {
  const beach = props.beach;
  Object.entries(beach).map((entry) => {
    const [key, value] = entry;
    if (value === "TRUE") {
      return icons.selectIcon(key, 20);
       }

  });
};

icons.selectIcon is a function which returns the correct icon and works perfectly fine when used outside of a Flatlist.
When I tried to return a test instead of the function - Nothing was rendered either.

I think it has to do with trying to render a list within a list but I can't find anything in the documentation.

The other long way solution is to write for each key an if statement.

Can I render a list within a list item?
Thanks

Sample object in my object list

[{"img": "soldierspoint",
"key": 0,
"lat": 17.16966,
"likes": 2,
"lng": -61.83792,
"longDescription": "Now you can run your build with eas build -p android --profile preview. Remember that you can name the profile whatever you like. We named the profile "preview", however, you can call it "local", "simulator", or whatever makes the most sense for you.
"shortDescription": "Quiet and shady.  Easy Hike.",
"visited": 2,
"zAccess": "hike, Car",
"zAccessDes": "",
"zHistorical": "",
"zHistoricalDes": "",
"zInterestingGeography": "",
"zInterestingGeographyDes": "",
 "zLotsOfSand": "TRUE",
"zLotsSandDes": "",
"zNaturalShade": "TRUE",
"zNaturalShadeDes": "",
"zRestaurant": "",
"zRestaurantDes": "",
"zSheltered": "",
"zShelteredDes": "",
"zSnorkeling": "",
"zSnorkelingDes": "",
"zVeryPopular": "",
"zVeryPopularDes": "",
"zVerySmall": "",
"zVerySmallDes": ""}]


问:
display button after viedo watched
Hi I am trying to display a video for my website members but I need to
show a button to submit the form to me confirming that they watched the video fully without any skip
I have difficulty setting the timer to show the button based on the video length not setting a custom time.
I need to set the time based on the video length and stop the timer if the user pauses the video.

here is my code

```<code><div class="embed-responsive embed-responsive-16by9">
  <video controls id="myVideo" class="embed-responsive-item" src="/assets/MSFS.mp4" allowfullscreen></video></div>
</code>```

JS

```<code>   <script>

      $(document).ready(function() {
      setTimeout(function() {
        $("#proceed").show();
      }, 5000);
    });
    </script>
</code>```

button

```<code><button id="proceed" type="button" class="btn btn-warning" data-toggle="modal" data-target="#exampleModal">Submit</button>
</code>```

basically what is happening the button is displayed after 5 seconds I need to change 5 seconds to the length of the video. Is there any way to get the length of the video and set it instead of manually entering it? How to stop the timer if the video pauses?

Thanks

Title: display button after viedo watched

Body:
Hi I am trying to display a video for my website members but I need to
show a button to submit the form to me confirming that they watched the video fully without any skip
I have difficulty setting the timer to show the button based on the video length not setting a custom time.
I need to set the time based on the video length and stop the timer if the user pauses the video.

here is my code

  <video controls id="myVideo" class="embed-responsive-item" src="/assets/MSFS.mp4" allowfullscreen></video>

JS

button

<button id="proceed" type="button" class="btn btn-warning" data-toggle="modal" data-target="#exampleModal">Submit</button>

basically what is happening the button is displayed after 5 seconds I need to change 5 seconds to the length of the video. Is there any way to get the length of the video and set it instead of manually entering it? How to stop the timer if the video pauses?

Thanks


问:
Second component not rendering below first one - REACT JS
I am making a personal website. The landing page is the first component. The second page is the About component but it is not rendering below the landing component. It is appearing at the top.

App.js file:

```<code>import "./App.css";
import Landing from "./components/Landing/Landing";
import About from "./components/About/About";

function App() {
  return (
    <div className="App">
      <Landing/>
      <About/>
    </div>
  );
}

export default App;

</code>```

**App.css file: **

```<code>
.App{
  display: flex;
  flex-direction: column;
}

body{
  overflow-x: hidden;
}
::-webkit-scrollbar{
  width: 8px;
  }

  ::-webkit-scrollbar-track{
  background: black;
  border-radius: 1ex;
  }

  ::-webkit-scrollbar-thumb{
  background: #427898;
  border-radius: 1ex;
  }

  ::-webkit-scrollbar-corner {
    background: black;
  }

  a{
    text-decoration: none;
    color: inherit
  }
</code>```

About.jsx file:

```<code>import React from 'react'
import css from "./About.module.css"

const About = () => {
  return (
    <div style={{ color: 'white' }}>About</div>
  )
}

export default About
</code>```

I have already tried creating a container class for About and then changing the display in my About.module.css file but the About text still remains at the top of the page unseen.This is the landing page and as you can see I want the About component to now be below the landing page as you scroll down.

Body:
I am making a personal website. The landing page is the first component. The second page is the About component but it is not rendering below the landing component. It is appearing at the top.

App.js file:

import "./App.css";
import Landing from "./components/Landing/Landing";
import About from "./components/About/About";

function App() {
  return (

      <Landing/>
      <About/>

  );
}

export default App;

**App.css file: **

.App{
  display: flex;
  flex-direction: column;
}

body{
  overflow-x: hidden;
}
::-webkit-scrollbar{
  width: 8px;
  }

  ::-webkit-scrollbar-track{
  background: black;
  border-radius: 1ex;
  }

  ::-webkit-scrollbar-thumb{
  background: #427898;
  border-radius: 1ex;
  }

  ::-webkit-scrollbar-corner {
    background: black;
  }

  a{
    text-decoration: none;
    color: inherit
  }

About.jsx file:

import React from 'react'
import css from "./About.module.css"

const About = () => {
  return (

About

  )
}

export default About

I have already tried creating a container class for About and then changing the display in my About.module.css file but the About text still remains at the top of the page unseen.This is the landing page and as you can see I want the About component to now be below the landing page as you scroll down.