问:
Android opengl es draw an image on texture by sending all vertices of the image
I was reading this https://www.khronos.org/opengl/wiki/Primitive and thought that gl_patches will solve my issue but looks like it is not supported in opengl es, I want to send the vertices of the width and height of the whole image through glVertixAttribPointer, so if the image is w=10* h=20 I need it to send 200 points to the vertexShader but I don't know how to do that with the available modes of opengl es glDrawArrays function.

UPDATE:
After updating to opengl es 3.2 I am now able to find GL_PATCHES mode, my question now does it help to use GL_PATCHES to send all vertices of the image to the vertex shader? If yes, how?

why do I need to do that, it is because I want to send a float value for each pixel of the image manipulate the pixels with these values, this means that I need to send a floatBuffer to the vertexShader(then send it to the values to the fragmentShader) according to my understanding I need to send the vertices to match the number of data I need to send in this floatBuffer(I could be wrong tho)

I am using these vertices rn for the vertexShader.

```<code>val vertexArray = floatArrayOf(
        -width / 2f, -height / 2f,  // 0 bottom left
        +width / 2f, -height / 2f,  // 2 bottom right
        -width / 2f, +height / 2f,  // 3 top left
        +width / 2f, +height / 2f,  // 5 top right
        +width / 2f, -height / 2f,  // 2 bottom right
        -width / 2f, +height / 2f  // 3 top left
    )
val texArray = floatArrayOf(
        0.0f, 1.0f,  // 0 bottom left
        1.0f, 1.0f,  // 2 bottom right
        0.0f, 0.0f,  // 3 top left
        1.0f, 0.0f,  // 5 top right
        1.0f, 1.0f,  // 2 bottom right
        0.0f, 0.0f  // 3 top left
    )
</code>```

THEN convert these arrays to buffers(vertexBuffer and texBuffer)

I then use glVertexAttribPointer for each with its location index as follows:

```<code>    glEnableVertexAttribArray(positionLoc)
    checkGlError("glEnableVertexAttribArray")

    // Connect vertexBuffer to "aPosition".
    glVertexAttribPointer(
        positionLoc, coordsPerVertex,
        GL_FLOAT, false, vertexStride, vertexBuffer
    )
    checkGlError("glVertexAttribPointer")

    // Enable the "aTextureCoord" vertex attribute.
    glEnableVertexAttribArray(textureCoordLoc)
    checkGlError("glEnableVertexAttribArray")

    // Connect texBuffer to "aTextureCoord".
    glVertexAttribPointer(
        textureCoordLoc, 2,
        GL_FLOAT, false, texStride, texBuffer
    )
    checkGlError("glVertexAttribPointer")
</code>```

Currently it is drawing the texture successfully but I can't do the shader processing because I can't send the buffer with the processing data for each pixel as I said above.

Body:
I was reading this https://www.khronos.org/opengl/wiki/Primitive and thought that gl_patches will solve my issue but looks like it is not supported in opengl es, I want to send the vertices of the width and height of the whole image through glVertixAttribPointer, so if the image is w=10* h=20 I need it to send 200 points to the vertexShader but I don't know how to do that with the available modes of opengl es glDrawArrays function.

UPDATE:
After updating to opengl es 3.2 I am now able to find GL_PATCHES mode, my question now does it help to use GL_PATCHES to send all vertices of the image to the vertex shader? If yes, how?

why do I need to do that, it is because I want to send a float value for each pixel of the image manipulate the pixels with these values, this means that I need to send a floatBuffer to the vertexShader(then send it to the values to the fragmentShader) according to my understanding I need to send the vertices to match the number of data I need to send in this floatBuffer(I could be wrong tho)

I am using these vertices rn for the vertexShader.

val vertexArray = floatArrayOf(
        -width / 2f, -height / 2f,  // 0 bottom left
        +width / 2f, -height / 2f,  // 2 bottom right
        -width / 2f, +height / 2f,  // 3 top left
        +width / 2f, +height / 2f,  // 5 top right
        +width / 2f, -height / 2f,  // 2 bottom right
        -width / 2f, +height / 2f  // 3 top left
    )
val texArray = floatArrayOf(
        0.0f, 1.0f,  // 0 bottom left
        1.0f, 1.0f,  // 2 bottom right
        0.0f, 0.0f,  // 3 top left
        1.0f, 0.0f,  // 5 top right
        1.0f, 1.0f,  // 2 bottom right
        0.0f, 0.0f  // 3 top left
    )

THEN convert these arrays to buffers(vertexBuffer and texBuffer)

I then use glVertexAttribPointer for each with its location index as follows:

    glEnableVertexAttribArray(positionLoc)
    checkGlError("glEnableVertexAttribArray")

    // Connect vertexBuffer to "aPosition".
    glVertexAttribPointer(
        positionLoc, coordsPerVertex,
        GL_FLOAT, false, vertexStride, vertexBuffer
    )
    checkGlError("glVertexAttribPointer")

    // Enable the "aTextureCoord" vertex attribute.
    glEnableVertexAttribArray(textureCoordLoc)
    checkGlError("glEnableVertexAttribArray")

    // Connect texBuffer to "aTextureCoord".
    glVertexAttribPointer(
        textureCoordLoc, 2,
        GL_FLOAT, false, texStride, texBuffer
    )
    checkGlError("glVertexAttribPointer")

Currently it is drawing the texture successfully but I can't do the shader processing because I can't send the buffer with the processing data for each pixel as I said above.


来源: stackexchange

问:
type '_AnimatedEvaluation<Color?>' is not a subtype of type 'Animation<Color>' in type cast
I was creating a simple animating heart. It was working fine without null safety. When I try to change it in null safety. I got this issue.</p>
```<code>class _HeartState extends State<Heart> with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<Color?> _colorAnimation;
  late Animation<double> _sizeAnimation;
  late Animation<double> _curve;

  bool isFav = false;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      duration: Duration(
        milliseconds: 500,
      ),
      vsync: this,
    );

    _curve = CurvedAnimation(
      parent: _controller,
      curve: Curves.slowMiddle,
    );

    _colorAnimation = ColorTween(begin: Colors.grey[400], end: Colors.red)
        .animate(_curve) as Animation<Color>;

</code>```

ContentLicense: CC BY-SA 4.0

Body:
I was creating a simple animating heart. It was working fine without null safety. When I try to change it in null safety. I got this issue.

class _HeartState extends State<Heart> with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<Color?> _colorAnimation;
  late Animation<double> _sizeAnimation;
  late Animation<double> _curve;

  bool isFav = false;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      duration: Duration(
        milliseconds: 500,
      ),
      vsync: this,
    );

    _curve = CurvedAnimation(
      parent: _controller,
      curve: Curves.slowMiddle,
    );

    _colorAnimation = ColorTween(begin: Colors.grey[400], end: Colors.red)
        .animate(_curve) as Animation<Color>;


问:
Sign in with Google using Google Identity Services gives a blank popup screen when using domain name other than localhost
I am working on a website. To login the users, I am using the Sign in With Google button using Google Identity Services. It was working perfectly on localhost, however, as soon as I executed the code on a remote server and tried to access the domain from a browser on another computer, it shows a blank popup screen. The server log shows no error. I checked the browser console and it gives 2 errors which are as follows -->

Failed to load resource: the server responded with a status of 403 ()
[GSI_LOGGER]: The given origin is not allowed for the given client ID.

I have followed all the fixes given here: The given origin is not allowed for the given client ID (GSI)
to the best of my knowledge, however, have still not been able to fix this problem.
Could someone please guide me as i am fairly new to this.
This is my code, where i have tried to change the headers in NodeJS.


问:
How to disable follow redirect on request nodejs
I tried make request with module request in nodejs. and always get response statuscode 200. but when i tried using curl
curl https://trello.com/myname -I

i got statuscode 302.

here is my code
`

```<code>request({
            uri:'https://trello.com/myname',
            followRedirect: false
        },function(error, response, body){
            console.log(response.statusCode)
        })
</code>```

`
even though followRedirect set to false, but I am still get statuscode 200

Body:
I tried make request with module request in nodejs. and always get response statuscode 200. but when i tried using curl
curl https://trello.com/myname -I

i got statuscode 302.

here is my code
`

request({
            uri:'https://trello.com/myname',
            followRedirect: false
        },function(error, response, body){
            console.log(response.statusCode)
        })

`
even though followRedirect set to false, but I am still get statuscode 200


问:
Sending an App Generated Request with the JavaScript SDK
I am trying to send an app-generated request using the JavaScript SDK, following the PHP example here https://developers.facebook.com/blog/post/464.

I've tried this way:

```<code>FB.api( "/" + recipient + "/apprequests", "POST", {
    message: "Notification Message",
    data: "Notification data"
}, function( response ) {
    console.log( response );
} );
</code>```

Where 'recipient' is the id of the user who should receive the request.

The above code worked only when sending request to the user that is currently logged in.

When sending a request to another user (who is connected to the app), the FB.api call returned the following error:

```<code>{
    "message": "(#2) User can't send this request: Unknown error",
    "type":"OAuthException"
}
</code>```

Is it possible to send app-generated requests using the JavaScript SDK and if so, what is the correct way to do it?

ContentLicense: CC BY-SA 3.0

Body:
I am trying to send an app-generated request using the JavaScript SDK, following the PHP example here https://developers.facebook.com/blog/post/464.

I've tried this way:

FB.api( "/" + recipient + "/apprequests", "POST", {
    message: "Notification Message",
    data: "Notification data"
}, function( response ) {
    console.log( response );
} );

Where 'recipient' is the id of the user who should receive the request.

The above code worked only when sending request to the user that is currently logged in.

When sending a request to another user (who is connected to the app), the FB.api call returned the following error:

{
    "message": "(#2) User can't send this request: Unknown error",
    "type":"OAuthException"
}

Is it possible to send app-generated requests using the JavaScript SDK and if so, what is the correct way to do it?


问:
How can I update a whole collection in MongoDB, with new values that need to be asynchronously calculated based off another collection
With MongoDB, what is the best practice to update a field in every document of a collection, but with value that needs to be calculated async.

For example,

I have a list of businesses that users can rate and post reviews on (think of it as something like yelp, where you can rate and review a business ). Now Id like to run jobs periodically ,  to re-calculate and update its rating, based on review collection/ table that stores all the customer ratings and reviews.

the business collection/table scheme looks something like

```<code>{
    _id: ObjectId,
    name: string,
    address: string,
    rating: number,  // 0 - 5
    highlighted_review: string,
    ...
}
</code>```

and then the review collection/table looks something like

```<code>{
   _id: ObjectId,
   business_id: ObjectId, // key
   review: string,
   rating: number,
   created_by: ObjectId (a user ID)
   images: string[] (users can add images to their reviews)
   ...
}
</code>```

Now Id like to periodically update the business collection with updated rating and hightlighted_reiew, which should be calculated based on the new reviews / ratings (lets say, we wanna get the average out of all the new ratings / reviews, and then update). What is the best practice to do such thing?

Id really appreciate your insight.

Thanks
Shaun

Body:
With MongoDB, what is the best practice to update a field in every document of a collection, but with value that needs to be calculated async.

For example,

I have a list of businesses that users can rate and post reviews on (think of it as something like yelp, where you can rate and review a business ). Now Id like to run jobs periodically ,  to re-calculate and update its rating, based on review collection/ table that stores all the customer ratings and reviews.

the business collection/table scheme looks something like

{
    _id: ObjectId,
    name: string,
    address: string,
    rating: number,  // 0 - 5
    highlighted_review: string,
    ...
}

and then the review collection/table looks something like

{
   _id: ObjectId,
   business_id: ObjectId, // key
   review: string,
   rating: number,
   created_by: ObjectId (a user ID)
   images: string[] (users can add images to their reviews)
   ...
}

Now Id like to periodically update the business collection with updated rating and hightlighted_reiew, which should be calculated based on the new reviews / ratings (lets say, we wanna get the average out of all the new ratings / reviews, and then update). What is the best practice to do such thing?

Id really appreciate your insight.

Thanks
Shaun


问:
Pyspark show() or collect() wont run in Pycharm
```<code>from pyspark.sql import SparkSession
from pyspark.sql.functions import to_date,month

spark = SparkSession.builder.appName('SparkByExamples.com').getOrCreate()
data = [("James","Smith","USA","2019-06-24 12:01:19.000"),
    ("Michael","Rose","USA","2019-06-24 12:01:19.000"),
    ("Robert","Williams","USA","2019-06-24 12:01:19.000"),
    ("Maria","Jones","USA","2019-06-24 12:01:19.000")
  ]
columns = ["firstname","lastname","country","datetime_column"]
df = spark.createDataFrame(data = data, schema = columns)

df = df.withColumn('month', month(to_date(df['datetime_column'])).cast('int'))
df.show()
</code>```

I have this code on pyspark, but when I try to run it will give me an error like this:

```<code>WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
Python bulunamad22/12/31 15:22:05 WARN ProcfsMetricsGetter: Exception when trying to compute pagesize, as a result reporting of ProcessTree metrics is stopped
22/12/31 15:22:14 ERROR Executor: Exception in task 0.0 in stage 0.0 (TID 0)
org.apache.spark.SparkException: Python worker failed to connect back.

ERROR TaskSetManager: Task 0 in stage 0.0 failed 1 times; aborting job
Traceback (most recent call last):
  File "C:/Users/User/PycharmProjects/tasks/main.py", line 15, in <module>
    df.show()
  File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\pyspark\sql\dataframe.py", line 606, in show
    print(self._jdf.showString(n, 20, vertical))
  File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\py4j\java_gateway.py", line 1322, in __call__
    answer, self.gateway_client, self.target_id, self.name)
  File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\pyspark\sql\utils.py", line 190, in deco
    return f(*a, **kw)
  File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\py4j\protocol.py", line 328, in get_return_value
    format(target_id, ".", name), value)
py4j.protocol.Py4JJavaError: An error occurred while calling o45.showString.
: org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 0.0 failed 1 times, most recent failure: Lost task 0.0 in stage
</code>```

My java version is 11 and pyspark is 3.3.1
Cant think of anything and stuck here, any help would be appreciated.

Body:
from pyspark.sql import SparkSession
from pyspark.sql.functions import to_date,month

spark = SparkSession.builder.appName('SparkByExamples.com').getOrCreate()
data = [("James","Smith","USA","2019-06-24 12:01:19.000"),
    ("Michael","Rose","USA","2019-06-24 12:01:19.000"),
    ("Robert","Williams","USA","2019-06-24 12:01:19.000"),
    ("Maria","Jones","USA","2019-06-24 12:01:19.000")
  ]
columns = ["firstname","lastname","country","datetime_column"]
df = spark.createDataFrame(data = data, schema = columns)

df = df.withColumn('month', month(to_date(df['datetime_column'])).cast('int'))
df.show()

I have this code on pyspark, but when I try to run it will give me an error like this:

WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
Python bulunamad22/12/31 15:22:05 WARN ProcfsMetricsGetter: Exception when trying to compute pagesize, as a result reporting of ProcessTree metrics is stopped
22/12/31 15:22:14 ERROR Executor: Exception in task 0.0 in stage 0.0 (TID 0)
org.apache.spark.SparkException: Python worker failed to connect back.

ERROR TaskSetManager: Task 0 in stage 0.0 failed 1 times; aborting job
Traceback (most recent call last):
  File "C:/Users/User/PycharmProjects/tasks/main.py", line 15, in <module>
    df.show()
  File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\pyspark\sql\dataframe.py", line 606, in show
    print(self._jdf.showString(n, 20, vertical))
  File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\py4j\java_gateway.py", line 1322, in __call__
    answer, self.gateway_client, self.target_id, self.name)
  File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\pyspark\sql\utils.py", line 190, in deco
    return f(*a, **kw)
  File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\py4j\protocol.py", line 328, in get_return_value
    format(target_id, ".", name), value)
py4j.protocol.Py4JJavaError: An error occurred while calling o45.showString.
: org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 0.0 failed 1 times, most recent failure: Lost task 0.0 in stage

My java version is 11 and pyspark is 3.3.1
Cant think of anything and stuck here, any help would be appreciated.


问:
Firestore query between two timestamps
I have an application where the users can create their own events with a start and end timestamp. The problem now is that Firestore not supporting to make a query on two different fields, so I can't search directly like .where('start','<', endOfDay).where('end',>, startOfDay). Btw important is I need to query between two timestamps and not only around one timestamp. The existing question Firestore query by date range will not solve this problem because in that question is only one timestamp!

My goal is that a user can get all events which he has on the current day. As an example, I want to get all events on the red marked day in the following picture.

The only solution, which I currently think is possible, is to split the timespan and put it in an array. As example, an event 1-3 March 2022 will look like ['2022-3-1','2022-3-2','2022-3-3'] where I can make the query then like this .where('days', 'array-contains', '2022-3-2'). But this solution is hideous because I have a lot more storage costs and the user download always more data than he needs.

Title: Firestore query between two timestamps


问:
psutil.Popen doesn't find installed application (ganache)
I have an error while running ganache:

```<code>ValueError: could not read ganache version: b''
</code>```

I tracked it back to this line in ganache.py:

```<code>def get_ganache_version(ganache_executable: str) -> int:

    ganache_version_proc = psutil.Popen([ganache_executable, "--version"], stdout=PIPE)
</code>```

with "ganache_executable"="ganache-cli". This is then used in the same function as:

```<code>ganache_version_match = re.search(r"v([0-9]+)\.", ganache_version_stdout.decode())
if not ganache_version_match:
    raise ValueError("could not read ganache version: {}".format(ganache_version_stdout))
</code>```

I tried executing ganache-cli --version in a Linux terminal and I get the following:

```<code>(base) me@me:~$ ganache-cli --version
This version of µWS is not compatible with your Node.js build:

Error: Cannot find module './uws_linux_x64_111.node'
Falling back to a NodeJS implementation; performance may be degraded.

ganache v7.7.2 (@ganache/cli: 0.8.1, @ganache/core: 0.8.1)
</code>```

which looks ok, but for some reason psutils.Popen returns b''

Body:
I have an error while running ganache:

ValueError: could not read ganache version: b''

I tracked it back to this line in ganache.py:

def get_ganache_version(ganache_executable: str) -> int:

    ganache_version_proc = psutil.Popen([ganache_executable, "--version"], stdout=PIPE)

with "ganache_executable"="ganache-cli". This is then used in the same function as:

ganache_version_match = re.search(r"v([0-9]+)\.", ganache_version_stdout.decode())
if not ganache_version_match:
    raise ValueError("could not read ganache version: {}".format(ganache_version_stdout))

I tried executing ganache-cli --version in a Linux terminal and I get the following:

(base) me@me:~$ ganache-cli --version
This version of µWS is not compatible with your Node.js build:

Error: Cannot find module './uws_linux_x64_111.node'
Falling back to a NodeJS implementation; performance may be degraded.

ganache v7.7.2 (@ganache/cli: 0.8.1, @ganache/core: 0.8.1)

which looks ok, but for some reason psutils.Popen returns b''


问:
How to handle Gitlab-API errors returned as array with same message?
I'm creating a project where I communicate with the Gitlab API and I'm currently thinging on how to handle errors. Typically, when error occurs you would show any notification in the frontend (e.g. https://codeseven.github.io/toastr/demo.html).
But according to https://docs.gitlab.com/ee/api/#data-validation-and-error-reporting I'm sometimes getting back arrays of errors. So I thought, "ok, simply show multipl error notifications", but now I tried to create a project with the same name twice and getting back the following errors:

"message": {
  "project_namespace.name": [
    "has already been taken"
  ],
  "name": [
    "has already been taken"
  ],
  "path": [
    "has already been taken"
  ]
}
```

By the way, I only specify the project name and namespace_id. So path and name are the same.

In this case I would show 3 error messages with "has already been taken" which would be a bit confusing in the frontend, seeing the same error 3 times and even without the project name (has already been taken instead of <Projectname> has already been taken). So I wonder how other ppl are handling this behavior? Any idea how to handle this? Would you filter it so that it shows has already been taken only once?

Body:
I'm creating a project where I communicate with the Gitlab API and I'm currently thinging on how to handle errors. Typically, when error occurs you would show any notification in the frontend (e.g. https://codeseven.github.io/toastr/demo.html).
But according to https://docs.gitlab.com/ee/api/#data-validation-and-error-reporting I'm sometimes getting back arrays of errors. So I thought, "ok, simply show multipl error notifications", but now I tried to create a project with the same name twice and getting back the following errors:

"message": {
  "project_namespace.name": [
    "has already been taken"
  ],
  "name": [
    "has already been taken"
  ],
  "path": [
    "has already been taken"
  ]
}

By the way, I only specify the project name and namespace_id. So path and name are the same.

In this case I would show 3 error messages with "has already been taken" which would be a bit confusing in the frontend, seeing the same error 3 times and even without the project name (has already been taken instead of <Projectname> has already been taken). So I wonder how other ppl are handling this behavior? Any idea how to handle this? Would you filter it so that it shows has already been taken only once?


问:
Next.js website works under IP address, but not under domain
So I am really desperate right now. It is new year's eve and I don't want to deal with this stuff anymore, but I don't want to slide into 2023 with a broken web app.

Yesterday, suddenly out of nowhere my Next.js production website stopped working properly. The project works well on my localhost, no issues. Also it works fine on my server (if I access the website via IP_ADRESS:3000). But when I use the production URL, the website opens and looks fine but I cannot interact with it, nothing is clickable, nothing reacts, the links do not work, the inputs are broken.

I'm hosting it on a Ubuntu & Nginx DigitalOcean droplet, with Node & Next.js - also I use Cloudflare (and I think it has something to do with that, since with the bare IP address the website works fine).

I tried a lot of things, put it onto a new server, reinstalled Nginx, reinstalled the SSL certificate, rebuild the production build etc, but it still does not work, when I access it through the website url, so the issue must be with that. Though I am really frustrated right now and I don't know what might be causing this.


问:
Visual Studio Typescript jquery browser error: Failed to resolve module specifier
I have my Visual Studio project with the following wwwroot structure for my TS files.

wwwroot

assets

js

test.ts

This is my test.ts file:

```<code>import * as $ from 'jquery';

import * as bootstrap from 'bootstrap';

$(document).ready(function () {
    console.log('jQuery is ready!');
});
</code>```

This is my tsconfig.json file:

```<code>{

  "compilerOptions": {
    "noEmitOnError": true,
    "noImplicitAny": false,
    "removeComments": false,
    "sourceMap": true,
    "target": "es6",
    "moduleResolution": "node",
    "module": "ES6",
    //"strict": true,
    "types": [ "bootstrap", "jquery" ],
    "typeRoots": [
      "./node_modules/@types", // Default path to search typings.
      "./lib/types" // Directory of typings that located by Libman.
    ]
  },
  "include": [
    "../wwwroot/assets/js/*.ts"
  ],
  "exclude": [
    "node_modules"
  ]
}
</code>```

When building the project I can see the test.js generated successfully.

Then in my test.html file just before the  element I have the reference to my test.js file:

```<code>  <!-- Vendor JS Files -->
  <script src="~/assets/vendor/apexcharts/apexcharts.min.js"></script>
  <script src="~/assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
  <script src="~/assets/vendor/quill/quill.min.js"></script>

  <!-- Template Main JS File -->
    <script src="~/assets/js/main.js"></script>
    <script type="module" src="~/assets/js/test.js"></script>
</code>```

Once I run the project I can see in my console the following error:

```<code>Failed to resolve module specifier "jquery". Relative references must start with either "/", "./", or "../".
</code>```

****** UPDATE ******

I tried to import to the absolute path of the client jquery folder like this:

```<code>import * as $ from '../../lib/jquery/dist/jquery.js';

import * as bootstrap from 'bootstrap';

$(document).ready(function () {
    console.log('jQuery is ready!');
});
</code>```

And now the error is gone, but now I'm getting this:

Uncaught TypeError: $ is not a function
at test.ts:5:1

Any clue how to solve the above issue?

Body:
I have my Visual Studio project with the following wwwroot structure for my TS files.

wwwroot

assets

js

test.ts

This is my test.ts file:

import * as $ from 'jquery';

import * as bootstrap from 'bootstrap';

$(document).ready(function () {
    console.log('jQuery is ready!');
});

This is my tsconfig.json file:

{

  "compilerOptions": {
    "noEmitOnError": true,
    "noImplicitAny": false,
    "removeComments": false,
    "sourceMap": true,
    "target": "es6",
    "moduleResolution": "node",
    "module": "ES6",
    //"strict": true,
    "types": [ "bootstrap", "jquery" ],
    "typeRoots": [
      "./node_modules/@types", // Default path to search typings.
      "./lib/types" // Directory of typings that located by Libman.
    ]
  },
  "include": [
    "../wwwroot/assets/js/*.ts"
  ],
  "exclude": [
    "node_modules"
  ]
}

When building the project I can see the test.js generated successfully.

Then in my test.html file just before the  element I have the reference to my test.js file:

Once I run the project I can see in my console the following error:

Failed to resolve module specifier "jquery". Relative references must start with either "/", "./", or "../".

****** UPDATE ******

I tried to import to the absolute path of the client jquery folder like this:

import * as $ from '../../lib/jquery/dist/jquery.js';

import * as bootstrap from 'bootstrap';

$(document).ready(function () {
    console.log('jQuery is ready!');
});

And now the error is gone, but now I'm getting this:

Uncaught TypeError: $ is not a function
at test.ts:5:1

Any clue how to solve the above issue?


问:
Matrix integration with Keycloak without browser flow using JWT token
I am using the Matrix chat server and already integrated SSO with Keycloak.

I see some APIs by the Matrix server lead to the Keycloak login page to enter credentials.

I do not need this and want to use Keycloak provided JWT token to log in users with the Matrix server. I need to log in the user to the Matrix server in the backend with the same password user set in the application.

Is there any way to do it without a browser login flow?

The Keycloak access token does not work with the Matrix server even though I can connect to the Matrix server from the element.io web app which leads me to the Keycloak login page.


问:
JavaFX MediaPlayer not always playing MP4 file
I have a very simple JavaFX video player which in some runs just doesn't play the MP4 file it should be playing.
Here's the source code (I omitted the imports for convenience):

```<code>public class App extends Application {

    @Override
    public void start(Stage stage) {
        videoPlayer(stage);
    }

    public static void main(String[] args) {
        launch();
    }

    private void videoPlayer(Stage stage) {
        BorderPane pane = new BorderPane();

        File mediaFile = new File("src/main/resources/Lost   End Credits.mp4");

        MediaView moviePlayer;
        MediaPlayer player = new MediaPlayer(new Media(mediaFile.toURI().toString()));

        moviePlayer = new MediaView(player);

        moviePlayer.setPreserveRatio(true);
        moviePlayer.fitWidthProperty().bind(pane.widthProperty());
        moviePlayer.fitHeightProperty().bind(pane.heightProperty());

        player.setAutoPlay(true);
        player.setCycleCount(MediaPlayer.INDEFINITE);

        pane.getChildren().add(moviePlayer);
        player.play();

        Scene scene = new Scene(pane, 600, 600);
        stage.setScene(scene);
        stage.show();
    }

}
</code>```

And these are my dependencies:

```<code><dependencies>
    <dependency>
        <groupId>org.openjfx</groupId>
        <artifactId>javafx-fxml</artifactId>
        <version>11.0.2</version>
    </dependency>
    <dependency>
        <groupId>org.openjfx</groupId>
        <artifactId>javafx-controls</artifactId>
        <version>11.0.2</version>
    </dependency>
    <dependency>
        <groupId>org.openjfx</groupId>
        <artifactId>javafx-media</artifactId>
        <version>14</version>
    </dependency>
    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.6</version>
    </dependency>
</dependencies>
</code>```

I also have some plugins:

```<code><plugins>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.0</version>
        <configuration>
            <release>11</release>
        </configuration>
    </plugin>
    <plugin>
        <groupId>org.openjfx</groupId>
        <artifactId>javafx-maven-plugin</artifactId>
        <version>0.0.6</version>
        <executions>
            <execution>
                <id>default-cli</id>
                <configuration>
                    <mainClass>org.example.App</mainClass>
                </configuration>
            </execution>
        </executions>
    </plugin>
</plugins>
</code>```

And these are multiple runs of the program, notice how some of them (runs 2,8,10) don't display the video (the black screen means it's playing, gray means the video doesn't appear):

https://youtu.be/q4ujOCILeOs

What could be causing this kind of problem?

Tried debugging as much as I can with my current knowledge of JavaFX, I expect to get a clarification about a detail (most likely related to concurrency) that I missed and causes the issue

Body:
I have a very simple JavaFX video player which in some runs just doesn't play the MP4 file it should be playing.
Here's the source code (I omitted the imports for convenience):

public class App extends Application {

    @Override
    public void start(Stage stage) {
        videoPlayer(stage);
    }

    public static void main(String[] args) {
        launch();
    }

    private void videoPlayer(Stage stage) {
        BorderPane pane = new BorderPane();

        File mediaFile = new File("src/main/resources/Lost   End Credits.mp4");

        MediaView moviePlayer;
        MediaPlayer player = new MediaPlayer(new Media(mediaFile.toURI().toString()));

        moviePlayer = new MediaView(player);

        moviePlayer.setPreserveRatio(true);
        moviePlayer.fitWidthProperty().bind(pane.widthProperty());
        moviePlayer.fitHeightProperty().bind(pane.heightProperty());

        player.setAutoPlay(true);
        player.setCycleCount(MediaPlayer.INDEFINITE);

        pane.getChildren().add(moviePlayer);
        player.play();

        Scene scene = new Scene(pane, 600, 600);
        stage.setScene(scene);
        stage.show();
    }

}

And these are my dependencies:

<dependencies>
    <dependency>
        <groupId>org.openjfx</groupId>
        <artifactId>javafx-fxml</artifactId>
        <version>11.0.2</version>
    </dependency>
    <dependency>
        <groupId>org.openjfx</groupId>
        <artifactId>javafx-controls</artifactId>
        <version>11.0.2</version>
    </dependency>
    <dependency>
        <groupId>org.openjfx</groupId>
        <artifactId>javafx-media</artifactId>
        <version>14</version>
    </dependency>
    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.6</version>
    </dependency>
</dependencies>

I also have some plugins:

<plugins>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.0</version>
        <configuration>
            <release>11</release>
        </configuration>
    </plugin>
    <plugin>
        <groupId>org.openjfx</groupId>
        <artifactId>javafx-maven-plugin</artifactId>
        <version>0.0.6</version>
        <executions>
            <execution>
                <id>default-cli</id>
                <configuration>
                    <mainClass>org.example.App</mainClass>
                </configuration>
            </execution>
        </executions>
    </plugin>
</plugins>

And these are multiple runs of the program, notice how some of them (runs 2,8,10) don't display the video (the black screen means it's playing, gray means the video doesn't appear):

https://youtu.be/q4ujOCILeOs

What could be causing this kind of problem?

Tried debugging as much as I can with my current knowledge of JavaFX, I expect to get a clarification about a detail (most likely related to concurrency) that I missed and causes the issue


问:
Unable to connect to the browser using CDP4J
I have a Spring Boot application where I use CDP4J 3.1.0 to test my frontend.

Everything works fine locally but when I try to run it in docker I fail to connect to the browser. See error message below:

Servlet.service() for servlet [dispatcherServlet] in context with path
[] threw exception [Request processing failed:
io.webfolder.cdp.exception.CdpException: Unable to connect to the
browser] with root cause

I try to setup a container with Debian and also install chrome but my knowledge in Docker is not that good to solve this. My Dockerfile looks like this.

I could probably change from buster to something smaller.

FROM openjdk:17-ea-jdk-buster

RUN apt-get update && apt-get install -y \

apt-transport-https \

ca-certificates \

curl \

gnupg \

--no-install-recommends \

&& curl -sSL https://dl.google.com/linux/linux_signing_key.pub | apt-key add -

&& echo "deb https://dl.google.com/linux/chrome/deb/ stable main" > /etc/apt/sources.list.d/google-chrome.list \    && apt-get update &&
apt-get install -y \

google-chrome-stable

curl gnupg \    && rm -rf /var/lib/apt/lists/*

RUN groupadd -r chrome && useradd -r -g chrome -G audio,video chrome \    && mkdir -p /home/chrome && chown -R chrome:chrome /home/chrome

RUN mkdir -p /app WORKDIR /app

COPY target/myapp-0.0.1-SNAPSHOT.jar myapp-0.0.1.jar

USER chrome

EXPOSE 8080
EXPOSE 9222

ENTRYPOINT ["java","-jar","/app/myapp-0.0.1.jar"]

Can anyone guide me to what I am doing wrong?
I have tried to google and find a solution without success.

Edit: I start an browser from my application so it does not need to start it when the container is started.


问:
Deploying Websocket On Laravel
I have a website written in laravel that is working fine, I am currently building a Chat function for it, can I add a websocket to it?
If yes, how to do it or is there any documentation?

I haven't found the right document yet

Title: Deploying Websocket On Laravel


问:
BigQuery - Question about retrieving previous value
I have one question about how to fill column looking for previous values.

My problem is that the column "abandoned" need to follow some rules to be filled. The rules are:

The column "abandoned" should be filled with "yes" or "no", choosing one value or another. Never i get two "yes" values followed.

Always **after ** the column "date_hour_canceled_negotiation" is filled, the column "abandoned" should be filled with "yes" and when the column "date_hour_negotiation" or "date_hour_canceled_negotiation" is filled, in same row, the column "abandoned" should be filled with "no".

Could someone help me please? Any help i appreciate a lot.

I would like to do something like this:

contract
date_hour_access
date_hour_negotiation
date_hour_canceled_negotiation
status_negotiation
abandoned

111111
2022-12-01 10:20:00

yes

111111
2022-12-02 10:20:00

no

111111
2022-12-03 10:20:00

yes

111111
2022-12-04 10:20:00
2022-12-04 10:30:00

active
no

111111
2022-12-05 10:20:00

2022-12-05 10:30:00
canceled
no

111111
2022-12-06 10:20:00

yes

111111
2022-12-07 10:20:00

no


问:
Power Query - Add Column if value exists on another table with HANA slow
I'm pulling two tables in to Excel via HANA (the 'Source' below is the HANA SQL query) and am trying to add an additional column to Table 2 via Power Query based on whether or not a value exists in a column in Table 1.  The dataset is HUGE (probably just under 1,000,000 rows) and I've gotten it to work but it takes hours to add the column and it looks like it's searching tens of millions of rows of data with the column add.  I've moved things around, tried buffering and I've triggered errors and when I've gotten it to work, it's taking hours to refresh.

Need help understanding what's going on, what would make it faster and if there's a different/faster way to achieve the same result.

```<code>= Table2.AddColumn(Source, "Purchased", each if(List.Contains(List.Buffer(Table1[CUSTOMER_ID]),[CUSTOMER_NUMBER])=true) then "YES" else "NO")
</code>```

Please advise

Body:
I'm pulling two tables in to Excel via HANA (the 'Source' below is the HANA SQL query) and am trying to add an additional column to Table 2 via Power Query based on whether or not a value exists in a column in Table 1.  The dataset is HUGE (probably just under 1,000,000 rows) and I've gotten it to work but it takes hours to add the column and it looks like it's searching tens of millions of rows of data with the column add.  I've moved things around, tried buffering and I've triggered errors and when I've gotten it to work, it's taking hours to refresh.

Need help understanding what's going on, what would make it faster and if there's a different/faster way to achieve the same result.

= Table2.AddColumn(Source, "Purchased", each if(List.Contains(List.Buffer(Table1[CUSTOMER_ID]),[CUSTOMER_NUMBER])=true) then "YES" else "NO")

Please advise


问:
C# WPF Image Control is not changing when it bound to view model
I want to change an Image control when I press the hotkey, so I wrote a xaml and a view model below:

<Page
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
      xmlns:local="clr-namespace:EZ2ArchiveClient.View"
      xmlns:EZ2ArchiveClient="clr-namespace:EZ2ArchiveClient" xmlns:viewmodel="clr-namespace:EZ2ArchiveClient.ViewModel" d:DataContext="{d:DesignInstance viewmodel:MainViewModel}" x:Class="EZ2ArchiveClient.View.MainPage"
      mc:Ignorable="d"
      d:DesignHeight="450" d:DesignWidth="600"
      Title="MainPage"
      Loaded="Page_Loaded">

    <DockPanel>
        <Image x:Name="CapturedImage" Source="{Binding CapturedImage}" Stretch="Fill" />
    </DockPanel>
</Page>
```
<pre class="lang-cs prettyprint-override"><code>internal class MainViewModel : INotifyPropertyChanged
{
    private BitmapSource? capturedImage;
    public BitmapSource? CapturedImage
    {
        get
        {
            return capturedImage;
        }
        set
        {
            capturedImage = value;
            OnPropertyChanged("CapturedImage");
        }
    }

    public void HandleCapturedImage()
    {
        Debug.WriteLine("Handled");
        BitmapImage bitmapImage = new BitmapImage();
        bitmapImage.BeginInit();
        bitmapImage.UriSource = new Uri("captured.png", UriKind.Relative);
        bitmapImage.EndInit();
        capturedImage = bitmapImage;
    }

    public event PropertyChangedEventHandler? PropertyChanged;

    protected void OnPropertyChanged(string name)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
    }
}
</code>```

Although not in the source above, I have confirmed that if I press Alt+F12 (a custom hotkey), the image is saved in the program folder under the name captured.png. If hotkey input is detected, the hotkey-detecting function calls HandleCapturedImage as soon as captured.png is saved. But Image control doesn't show me anything. No errors were found even when debugging. How can I solve this problem?

Body:
I want to change an Image control when I press the hotkey, so I wrote a xaml and a view model below:

<Page
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
      xmlns:local="clr-namespace:EZ2ArchiveClient.View"
      xmlns:EZ2ArchiveClient="clr-namespace:EZ2ArchiveClient" xmlns:viewmodel="clr-namespace:EZ2ArchiveClient.ViewModel" d:DataContext="{d:DesignInstance viewmodel:MainViewModel}" x:Class="EZ2ArchiveClient.View.MainPage"
      mc:Ignorable="d"
      d:DesignHeight="450" d:DesignWidth="600"
      Title="MainPage"
      Loaded="Page_Loaded">

    <DockPanel>
        <Image x:Name="CapturedImage" Source="{Binding CapturedImage}" Stretch="Fill" />
    </DockPanel>
</Page>

internal class MainViewModel : INotifyPropertyChanged
{
    private BitmapSource? capturedImage;
    public BitmapSource? CapturedImage
    {
        get
        {
            return capturedImage;
        }
        set
        {
            capturedImage = value;
            OnPropertyChanged("CapturedImage");
        }
    }

    public void HandleCapturedImage()
    {
        Debug.WriteLine("Handled");
        BitmapImage bitmapImage = new BitmapImage();
        bitmapImage.BeginInit();
        bitmapImage.UriSource = new Uri("captured.png", UriKind.Relative);
        bitmapImage.EndInit();
        capturedImage = bitmapImage;
    }

    public event PropertyChangedEventHandler? PropertyChanged;

    protected void OnPropertyChanged(string name)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
    }
}

Although not in the source above, I have confirmed that if I press Alt+F12 (a custom hotkey), the image is saved in the program folder under the name captured.png. If hotkey input is detected, the hotkey-detecting function calls HandleCapturedImage as soon as captured.png is saved. But Image control doesn't show me anything. No errors were found even when debugging. How can I solve this problem?


问:
Laravel job Vonage notification try/catch doesn't go into catch statement
I'm trying to catch Vonage API errors in my Laravel job file so that I can determine whether to deduct credits from a user's account.

My job consists of a function called attemptSend. When I log the before and after, I can see that the message attempt, first and second logs are all logging, but not the message failed despite there being an exception thrown and logged by Laravel.

What am I missing here to catch this?

Here's my job file:

<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Facades\Log;
use App\Notifications\Messages\SendMessageViaVonageEngine;
use App\Models\User;
use App\Models\Message;
use App\Models\Sanctum\PersonalAccessToken;
use Carbon\Carbon;

class ProcessMessage implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * The number of times the job may be attempted.
     *
     * @var int
     */
    public $tries = 1;

    /**
     * The message id
     */
    protected $messageId;

    /**
     * The user id
     */
    protected $userId;

    /**
     * The API key's UUID.
     */
    protected $apiKeyUuid;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($messageId, $userId, $apiKeyUuid)
    {
        $this->messageId = $messageId;
        $this->userId = $userId;
        $this->apiKeyUuid = $apiKeyUuid;
    }

    /**
     * Get API key
     */
    public function getApiKey()
    {
        return PersonalAccessToken::where('tokenable_id', $this->userId)
                                  ->where('uuid', $this->apiKeyUuid)
                                  ->withSum('credit_transactions AS credit_balance', 'delta')
                                  ->first();
    }

    /**
     * Get the message
     */
    public function getMessage()
    {
        return Message::where('id', $this->messageId)
                      ->where('user_id', $this->userId)
                      ->first();
    }

    /**
     * Update message status
     */
    public function updateMessageStatus($message, $status = 'sending', $reason = null)
    {
        $message->status = $status;

        // set reason
        if ($reason) {
            $message->reason = $reason;
        }

        // mark the sent_at date
        if (!$message->sent_at && $status == 'sending') {
            $message->sent_at = Carbon::now();
        }

        $message->save();
    }

    /**
     * Attempt to send
     */
    public function attemptSend($message)
    {
        Log::debug('MESSAGE:ATTEMPT');
        try {
            Log::debug('MESSAGE:SUCCESS-FIRST');
            $sent = Notification::route('vonage', $message->send_to)
                                ->notify(new SendMessageViaVonageEngine($message));
            Log::debug('MESSAGE:SUCCESS-SECOND', [
                'sent' => $sent
            ]);
        } catch (\Exception $e) {
            Log::debug('MESSAGE:FAILED');
            throw new \Exception($e->getMessage());
        }
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $apiKey = $this->getApiKey();
        $message = $this->getMessage();

        if (! $message) {
            throw new \Exception("Message can't be found, was it deleted? Unable to send message.");
            return;
        }

        if (! $apiKey) {
            $this->updateMessageStatus($message, 'dead', "API key not found");
            throw new \Exception("API key can't be found, was it deleted? Unable to send message.");
            return;
        }

        if (! $apiKey->credit_balance || $apiKey->credit_balance <= 0) {
            $this->updateMessageStatus($message, 'dead', "Insufficient credits");
            throw new \Exception("API key: $apiKey->uuid has run out of credits. Unable to send message.");
            return;
        }

        $this->updateMessageStatus($message, 'sending', "Attempting to send");
        $this->attemptSend($message);
    }
}

```


问:
Mongo Save function callback not triggering
Mongo save callback is not triggering, but the document is getting saved in the db, Heres my code:

MongoDb Version :  6.0.1

Mongoose Version : 6.8.2

The call back not returning anything, but the documents are getting saved without any issues, why the call back is not triggering?

```<code>const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const url = 'mongodb://127.0.0.1:27017/musicapp';
const cors = require('cors');
var jquery = require('jquery');

//Mongodb
mongoose.connect(url, { useNewUrlParser: true });
mongoose.set('strictQuery', true);
var conn = mongoose.connection;

conn.on('connected', function () {
  console.log("Database Connected");
})

var artistSchema = new mongoose.Schema({
  artistName: String,
  artistDob: String,
  artistBio: String
})

const artists = mongoose.model("artist", artistSchema);

function addArtist(aName, aDOB, aBIO) {
  const newArtist = new artists({
    artistName: aName,
    artistDob: aDOB,
    artistBio: aBIO
  })
  newArtist.save((err, data, numAffected) => {
    if (!err) {
      return true;
    }
    else {
      return false;
    }
  });

}

//MongoDb
app.get("/", (req, res) => {
  res.sendFile(__dirname + "/index.html")
})

app.post("/addsongs", cors(), (req, res) => {
  console.log("Add songs");
})

app.post("/addartist", cors(), (req, res) => {
  var artistName = req.body.modalartistname;
  var artistDOB = req.body.modalartistdob;
  var artistBio = req.body.modalartistbio;
  var addedArtist = addArtist(artistName, artistDOB, artistBio);
  if (addedArtist) {
    res.sendStatus(200);
  }
  else {
    console.log("Failure")
    res.sendStatus(400);
  }
  //console.log("Artist Added Sucessfully");
})

app.listen(3000, function () {
  console.log("The Server is up and running");
})
</code>```

Body:
Mongo save callback is not triggering, but the document is getting saved in the db, Heres my code:

MongoDb Version :  6.0.1

Mongoose Version : 6.8.2

The call back not returning anything, but the documents are getting saved without any issues, why the call back is not triggering?

const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const url = 'mongodb://127.0.0.1:27017/musicapp';
const cors = require('cors');
var jquery = require('jquery');

//Mongodb
mongoose.connect(url, { useNewUrlParser: true });
mongoose.set('strictQuery', true);
var conn = mongoose.connection;

conn.on('connected', function () {
  console.log("Database Connected");
})

var artistSchema = new mongoose.Schema({
  artistName: String,
  artistDob: String,
  artistBio: String
})

const artists = mongoose.model("artist", artistSchema);

function addArtist(aName, aDOB, aBIO) {
  const newArtist = new artists({
    artistName: aName,
    artistDob: aDOB,
    artistBio: aBIO
  })
  newArtist.save((err, data, numAffected) => {
    if (!err) {
      return true;
    }
    else {
      return false;
    }
  });

}

//MongoDb
app.get("/", (req, res) => {
  res.sendFile(__dirname + "/index.html")
})

app.post("/addsongs", cors(), (req, res) => {
  console.log("Add songs");
})

app.post("/addartist", cors(), (req, res) => {
  var artistName = req.body.modalartistname;
  var artistDOB = req.body.modalartistdob;
  var artistBio = req.body.modalartistbio;
  var addedArtist = addArtist(artistName, artistDOB, artistBio);
  if (addedArtist) {
    res.sendStatus(200);
  }
  else {
    console.log("Failure")
    res.sendStatus(400);
  }
  //console.log("Artist Added Sucessfully");
})

app.listen(3000, function () {
  console.log("The Server is up and running");
})


问:
Elementor Import content
When I import the demo content, all Elementor widgets move in the single “Text widget” – in other words, the WordPress importer “does not recognize” the widgets and sections. All is in the one/same text widget.

When used short xml file or insert short data inside _elementor_data , widget work fine .
if insert long data or alot widget all Elementor widgets move in the single “Text widget” again ?

all Elementor widgets move in the single “Text widget'

Title: Elementor Import content


问:
How to record audio from voice channel in discord.js v14
I managed to create a AudioReceiveStream but have no idea how to pipe this to a mp3 file or how to read this stream.

This is my code so far:

// Import the discord.js voice module
const voiceModule = require('@discordjs/voice');

async function voiceListener(interaction) {
    // Get voice connection
    const connection = voiceModule.getVoiceConnection(interaction.guildId);
    const listener = new voiceModule.AudioReceiveStream();
}
```

How do I get audio from the stream then write it to a mp3 file?

Body:
I managed to create a AudioReceiveStream but have no idea how to pipe this to a mp3 file or how to read this stream.

This is my code so far:

// Import the discord.js voice module
const voiceModule = require('@discordjs/voice');

async function voiceListener(interaction) {
    // Get voice connection
    const connection = voiceModule.getVoiceConnection(interaction.guildId);
    const listener = new voiceModule.AudioReceiveStream();
}

How do I get audio from the stream then write it to a mp3 file?


问:
Sharp Memory display via SPI from Arduino Nano RP2040 C++
I have an Adafruit Sharp Memory display connected via SPI to Arduino Nano Connect RP2040. I don't use Arduino IDE nor libraries. I write the code in C++ like I would write for RP2040 on Pi Pico, so I'm using Pico/RP2040 libraries. I'm building it and then just copying the .uf2 file to Arduino.

I'm trying to control the display but without success and I have no idea what I'm doing wrong. Here is my code, where I'm sending a command which should clear the display but it does not:

```<code>#include <stdio.h>
#include <stdlib.h>
#include "pico/stdlib.h"
#include "hardware/spi.h"
#include "hardware/gpio.h"

// ---SPI
// Pins for Arduino
#define SCK_PIN  13     // SCLK / SCK
#define MOSI_PIN 11     // MOSI / COPI
#define SS_PIN   10     // SS / CS

// ---Sharp display
#define WIDTH 144
#define HEIGHT 168

int main() {

    stdio_init_all();
    printf("START \n");

    bool vcom_bool_{false};

    spi_init(spi0, 2000000);
    spi_set_format( spi0, 8, SPI_CPOL_0, SPI_CPHA_0, SPI_MSB_FIRST);
    gpio_set_function(MOSI_PIN, GPIO_FUNC_SPI);
    gpio_set_function(SCK_PIN, GPIO_FUNC_SPI);

    gpio_init(SS_PIN);
    gpio_set_dir(SS_PIN, GPIO_OUT);
    gpio_put(SS_PIN, 0);  // this display is low on inactive

    while(true)
    {
        printf("VCOM = %b \n", vcom_bool_);

        gpio_put(SS_PIN, 1);

        // Clear the display
        uint8_t buf[2];
        if(vcom_bool_)
        {
            buf[0] = 0b01100000;
            vcom_bool_ = false;
        }
        else
        {
            buf[0] = 0b00100000;
            vcom_bool_ = true;
        }
        buf[1] = 0b00000000;
        spi_write_blocking(spi0, buf, 2);

        gpio_put(SS_PIN, 0);
        sleep_ms(10);

        sleep_ms(500);
    }
}

</code>```

Display and wiring are ok, because when I run example code from Adafruit (it is using Arduino's libraries) it works.

I follow this documentation from Sharp: https://www.sharpsde.com/fileadmin/products/Displays/2016_SDE_App_Note_for_Memory_LCD_programming_V1.3.pdf

I also reviewed the code from Adafruit and the SPI communication seems to be done in the same way.

What am I doing wrong?
Is there some issue with using Pico libraries for Arduino Nano RP2040? I did I2C communication in the same way (Pico/RP2040 libraries, .uf2 copied to Arduino Nano RP2040) and it worked.

Body:
I have an Adafruit Sharp Memory display connected via SPI to Arduino Nano Connect RP2040. I don't use Arduino IDE nor libraries. I write the code in C++ like I would write for RP2040 on Pi Pico, so I'm using Pico/RP2040 libraries. I'm building it and then just copying the .uf2 file to Arduino.

I'm trying to control the display but without success and I have no idea what I'm doing wrong. Here is my code, where I'm sending a command which should clear the display but it does not:

#include <stdio.h>
#include <stdlib.h>
#include "pico/stdlib.h"
#include "hardware/spi.h"
#include "hardware/gpio.h"

// ---SPI
// Pins for Arduino
#define SCK_PIN  13     // SCLK / SCK
#define MOSI_PIN 11     // MOSI / COPI
#define SS_PIN   10     // SS / CS

// ---Sharp display
#define WIDTH 144
#define HEIGHT 168

int main() {

    stdio_init_all();
    printf("START \n");

    bool vcom_bool_{false};

    spi_init(spi0, 2000000);
    spi_set_format( spi0, 8, SPI_CPOL_0, SPI_CPHA_0, SPI_MSB_FIRST);
    gpio_set_function(MOSI_PIN, GPIO_FUNC_SPI);
    gpio_set_function(SCK_PIN, GPIO_FUNC_SPI);

    gpio_init(SS_PIN);
    gpio_set_dir(SS_PIN, GPIO_OUT);
    gpio_put(SS_PIN, 0);  // this display is low on inactive

    while(true)
    {
        printf("VCOM = %b \n", vcom_bool_);

        gpio_put(SS_PIN, 1);

        // Clear the display
        uint8_t buf[2];
        if(vcom_bool_)
        {
            buf[0] = 0b01100000;
            vcom_bool_ = false;
        }
        else
        {
            buf[0] = 0b00100000;
            vcom_bool_ = true;
        }
        buf[1] = 0b00000000;
        spi_write_blocking(spi0, buf, 2);

        gpio_put(SS_PIN, 0);
        sleep_ms(10);

        sleep_ms(500);
    }
}

Display and wiring are ok, because when I run example code from Adafruit (it is using Arduino's libraries) it works.

I follow this documentation from Sharp: https://www.sharpsde.com/fileadmin/products/Displays/2016_SDE_App_Note_for_Memory_LCD_programming_V1.3.pdf

I also reviewed the code from Adafruit and the SPI communication seems to be done in the same way.

What am I doing wrong?
Is there some issue with using Pico libraries for Arduino Nano RP2040? I did I2C communication in the same way (Pico/RP2040 libraries, .uf2 copied to Arduino Nano RP2040) and it worked.


问:
It it correct to reexport std library from the cpp module?
I want to use C++20 modules with MSVC compiler and with CMake. It seems to be pretty hard and not unversal to setup standard library headers compilation as module units, so I did the following:

stdlib.ixx:

export module stdlib;

export import std.core; // std.core is MSVC specific thing
```
<p><code>main.cpp</code>:</p>
<pre class="lang-cpp prettyprint-override"><code>import stdlib;

int main() {
    std::vector<std::string> vec = { "Hello, world 1!", "Hello, world 2!" };

    for (const auto& v : vec) {
        std::cout << v << std::endl;
    }

    return 0;
}
</code>```

CMakeLists.txt:

```<code>cmake_minimum_required(VERSION 3.24)
project(test1)

set(CMAKE_CXX_STANDARD 23)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

add_compile_options(/experimental:module /translateInclude)

add_executable(test1 main.cpp stdlib.ixx)
</code>```

Seems that this code works right, but it is correct/good/appropriate solution accoring to modern C++?

Body:
I want to use C++20 modules with MSVC compiler and with CMake. It seems to be pretty hard and not unversal to setup standard library headers compilation as module units, so I did the following:

stdlib.ixx:

export module stdlib;

export import std.core; // std.core is MSVC specific thing

main.cpp:

import stdlib;

int main() {
    std::vector<std::string> vec = { "Hello, world 1!", "Hello, world 2!" };

    for (const auto& v : vec) {
        std::cout << v << std::endl;
    }

    return 0;
}

CMakeLists.txt:

cmake_minimum_required(VERSION 3.24)
project(test1)

set(CMAKE_CXX_STANDARD 23)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

add_compile_options(/experimental:module /translateInclude)

add_executable(test1 main.cpp stdlib.ixx)

Seems that this code works right, but it is correct/good/appropriate solution accoring to modern C++?


问:
How to fix "TypeError: loop of ufunc does not support argument 0 of type Mul which has no callable tanh method"?
I am trying to get the nullclines of Morris-Lecar model using the equation and solve commands from sympy module, but it tells me "loop of ufunc does not support argument 0 of type Mul which has no callable tanh method"
how can I solve this and draw the nullclines?

This is my code

```<code>import scipy as sp
import sympy as spy
from scipy.integrate import odeint

V, V_1, V_2, V_3, V_4, n , g_Ca, g_K, g_L, C_M, I, V_Ca, V_K, V_L, I, phsi\
    = spy.symbols('V V_1 V_2 V_3 V_4 n  g_Ca g_K g_L C_M I V_Ca V_K V_L I phsi')

def m_infinity(V): return (1.0 + sp.tanh((V - V_1) / V_2)) / 2.0
def n_infinity(V): return (1.0 + sp.tanh((V - V_3) / V_4)) / 2.0
def tau_n(V):   return 1 /( phsi* sp.cosh((V - V_3) / (2*V_4)))
def I_L(V):     return g_L               * (V - V_L)
def I_K(V, n):  return g_K  * n          * (V - V_K)
def I_Ca(V):    return g_Ca * m_infinity(V) * (V - V_Ca)

### Morris-Lecar Model
dVdt = (I - I_Ca(V) - I_K(V, n) - I_L(V)) / C_M
dndt = (n_infinity(V) - n) / tau_n(V)

###getting the nullclines functions
Vnull = spy.solve(spy.Eq(dVdt,0), n)[0]
nnull = spy.solve(spy.Eq(dndt, 0), n)[0]
print(Vnull)
print(nnull)
</code>```

the output is

```<code>TypeError: loop of ufunc does not support argument 0 of type Mul which has no callable tanh method
</code>```

I want the output to look something like this

```<code>n = (1.0 + sp.tanh((V - V_3) / V_4)) / 2.0 #which is equal to n_infinity(v)
n  = (I - g_Ca* m_infinity(V)*(V - V_Ca) - g_L*(V - V_L))/((V - V_K)*g_K)
</code>```

Body:
I am trying to get the nullclines of Morris-Lecar model using the equation and solve commands from sympy module, but it tells me "loop of ufunc does not support argument 0 of type Mul which has no callable tanh method"
how can I solve this and draw the nullclines?

This is my code

import scipy as sp
import sympy as spy
from scipy.integrate import odeint

V, V_1, V_2, V_3, V_4, n , g_Ca, g_K, g_L, C_M, I, V_Ca, V_K, V_L, I, phsi\
    = spy.symbols('V V_1 V_2 V_3 V_4 n  g_Ca g_K g_L C_M I V_Ca V_K V_L I phsi')

def m_infinity(V): return (1.0 + sp.tanh((V - V_1) / V_2)) / 2.0
def n_infinity(V): return (1.0 + sp.tanh((V - V_3) / V_4)) / 2.0
def tau_n(V):   return 1 /( phsi* sp.cosh((V - V_3) / (2*V_4)))
def I_L(V):     return g_L               * (V - V_L)
def I_K(V, n):  return g_K  * n          * (V - V_K)
def I_Ca(V):    return g_Ca * m_infinity(V) * (V - V_Ca)

### Morris-Lecar Model
dVdt = (I - I_Ca(V) - I_K(V, n) - I_L(V)) / C_M
dndt = (n_infinity(V) - n) / tau_n(V)

###getting the nullclines functions
Vnull = spy.solve(spy.Eq(dVdt,0), n)[0]
nnull = spy.solve(spy.Eq(dndt, 0), n)[0]
print(Vnull)
print(nnull)

the output is

TypeError: loop of ufunc does not support argument 0 of type Mul which has no callable tanh method

I want the output to look something like this

n = (1.0 + sp.tanh((V - V_3) / V_4)) / 2.0 #which is equal to n_infinity(v)
n  = (I - g_Ca* m_infinity(V)*(V - V_Ca) - g_L*(V - V_L))/((V - V_K)*g_K)


问:
How can I load a pre-trained onnx model in rembg Python script?
I try to load the pre-trained u2net_human_seg.onnx model in my python program to use it for better background removing.
When I try it, I get an error: _pickle.UnpicklingError: invalid load key, '\x08'.

My code:

```<code>import rembg
from PIL import Image
import torch
import numpy as np

def remove_background(input_path):
    input = Image.open(input_path)
    output = remove(input)
    output.save(input_path)

def remove(input):
    input_tensor = torch.from_numpy(np.array(input)).float()

    output = model(input_tensor)

    output_image = Image.fromarray(output.detach().numpy())
    return output_image

if __name__ == '__main__':
    model = torch.load("models/u2net_human_seg.onnx")
    remove_background("images/test.jpg")
</code>```

My input is test, where 2 people are visible. The paths' should be correct...
I didn't find similar cases online as no one seems to load a model in a custom application.

Body:
I try to load the pre-trained u2net_human_seg.onnx model in my python program to use it for better background removing.
When I try it, I get an error: _pickle.UnpicklingError: invalid load key, '\x08'.

My code:

import rembg
from PIL import Image
import torch
import numpy as np

def remove_background(input_path):
    input = Image.open(input_path)
    output = remove(input)
    output.save(input_path)

def remove(input):
    input_tensor = torch.from_numpy(np.array(input)).float()

    output = model(input_tensor)

    output_image = Image.fromarray(output.detach().numpy())
    return output_image

if __name__ == '__main__':
    model = torch.load("models/u2net_human_seg.onnx")
    remove_background("images/test.jpg")

My input is test, where 2 people are visible. The paths' should be correct...
I didn't find similar cases online as no one seems to load a model in a custom application.


问:
Detecting/Capturing UAC prompt in Windows
I'm making a program which runs on an infinite loop and reports when UAC is launched or when the certain condition is met. I'm trying to detect whenever UAC prompt is triggered by capturing window title of running applications.

I've also used pyautogui to capture screenshot of the UAC prompt window and then locate it using locateOnScreen() method but when UAC is lauched pyautogui returns exactly the same exception that is mentioned below. pywintypes.error: (1400, 'GetClassName', 'Invalid window handle.')

Example:

...
While True:
    hWnd = win32gui.GetForegroundWindow()
    tWnd = win32gui.GetWindowText(hWnd)
    print(tWnd)
    time.sleep(1)
...

# Captured screenshot of UAC prompt using keyboard shortcuts and then
# tried to detect it using pyautogui but it also returns None.

img = Image.open(PATH_TO_IMAGE) # using PIL lib
lWnd = pyautogui.locateOnScreen(img)
print(lWnd)
```

This grabs the title text of every window but as soon as UAC prompt is launched, it throws an exception pywintypes.error: (1400, 'GetClassName', 'Invalid window handle.') Whereas it should print the title of UAC Prompt which is "User Account Control".

What should I do to achieve this?

Body:
I'm making a program which runs on an infinite loop and reports when UAC is launched or when the certain condition is met. I'm trying to detect whenever UAC prompt is triggered by capturing window title of running applications.

I've also used pyautogui to capture screenshot of the UAC prompt window and then locate it using locateOnScreen() method but when UAC is lauched pyautogui returns exactly the same exception that is mentioned below. pywintypes.error: (1400, 'GetClassName', 'Invalid window handle.')

Example:

...
While True:
    hWnd = win32gui.GetForegroundWindow()
    tWnd = win32gui.GetWindowText(hWnd)
    print(tWnd)
    time.sleep(1)
...

# Captured screenshot of UAC prompt using keyboard shortcuts and then
# tried to detect it using pyautogui but it also returns None.

img = Image.open(PATH_TO_IMAGE) # using PIL lib
lWnd = pyautogui.locateOnScreen(img)
print(lWnd)

This grabs the title text of every window but as soon as UAC prompt is launched, it throws an exception pywintypes.error: (1400, 'GetClassName', 'Invalid window handle.') Whereas it should print the title of UAC Prompt which is "User Account Control".

What should I do to achieve this?


问:
Modifying a dropdown message to an embed
I want to change a message with a dropdown menu to a message with an embed, but it doesn't change

This is the code

```<code>dropdownTran.callback = dropdownTran_callback
tranview = View(timeout=180)
tranview.add_item(dropdownTran)
msg = await ctx.respond("Please select from the drop-down menu below", view = tranview)
...

...
embed=discord.Embed(title="Translator")
embed.add_field(name=origin, value=text, inline= True)
embed.add_field(name=language, value=res['message']['result']['translatedText'], inline=True)
await msg.edit(embed=embed)
</code>```

This is the error

```<code>Traceback (most recent call last):
  File "C:\Users\Name\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 414, in _scheduled_task
    await item.callback(interaction)
  File "d:\python\main.py", line 263, in dropdownTran_callback
    await msg.edit(embed=embed)
AttributeError: 'Interaction' object has no attribute 'edit'
</code>```

I've tried this

```<code>await msg.edit(content="Result",embed=embed)
</code>```
```<code>await msg.remove
await interaction.response.send_message(embed=embed)
</code>```

Body:
I want to change a message with a dropdown menu to a message with an embed, but it doesn't change

This is the code

dropdownTran.callback = dropdownTran_callback
tranview = View(timeout=180)
tranview.add_item(dropdownTran)
msg = await ctx.respond("Please select from the drop-down menu below", view = tranview)
...

...
embed=discord.Embed(title="Translator")
embed.add_field(name=origin, value=text, inline= True)
embed.add_field(name=language, value=res['message']['result']['translatedText'], inline=True)
await msg.edit(embed=embed)

This is the error

Traceback (most recent call last):
  File "C:\Users\Name\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 414, in _scheduled_task
    await item.callback(interaction)
  File "d:\python\main.py", line 263, in dropdownTran_callback
    await msg.edit(embed=embed)
AttributeError: 'Interaction' object has no attribute 'edit'

I've tried this

await msg.edit(content="Result",embed=embed)

await msg.remove
await interaction.response.send_message(embed=embed)


问:
OpenCV c++ mouseevent not working/or very slow with wacom graphic device
I want to draw something with opencv c++ using my wacom graphic device. I've written some code that works great with the mouse, but with the wacom graphic device it is only working sometimes and very slow. The problem is the EVENT_LBUTTONDOWN, which is only detected after a considerable time delay. Here is my code:</p>
```<code>    #include <iostream>
#include <list>

#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>

using namespace std;
using namespace cv;
const cv::Vec3b color_black{0, 0, 0};
const cv::Vec3b color_azure{255, 127, 0};

int width = 800;
int height = 600;
cv::Mat image = cv::Mat(cv::Size(width, height), CV_8UC3, color_black);

std::list<cv::Point> polygon;
bool isMouseDown = false;

void repaint(){
    cv::rectangle(image, cv::Rect(0, 0, width, height), color_black, 1);

    std::list<cv::Point>::iterator it = polygon.begin();
    if(it== polygon.end()){
        return;
    }
    cv::Point prev = *it;
    it++;
    while(it!=polygon.end() ){
        cv::line(image, prev, *it, color_azure, 2);
        prev = *it;
        it++;
    }
   //show the image
     imshow("My Window", image);
}

void CallBackFunc(int event, int x, int y, int flags, void* userdata)
{
     if  ( event == EVENT_LBUTTONDOWN )
     {
          isMouseDown = true;
          polygon.clear();
          repaint();

     }
     else if ( event == EVENT_MOUSEMOVE )

     {
          if(isMouseDown){
                polygon.push_back(cv::Point(x,y));
                repaint();
          }
     }
     else if (event == EVENT_LBUTTONUP){
        isMouseDown = false;
     }
}

int main(int argc, char** argv)
{
     // Read image from file

     //Create a window
     namedWindow("My Window", 1);

     //set the callback function for any mouse event
     setMouseCallback("My Window", CallBackFunc, NULL);

     //show the image
     imshow("My Window", image);

     // Wait until user press some key
     waitKey(0);

     return 0;

}
</code>```

Body:
I want to draw something with opencv c++ using my wacom graphic device. I've written some code that works great with the mouse, but with the wacom graphic device it is only working sometimes and very slow. The problem is the EVENT_LBUTTONDOWN, which is only detected after a considerable time delay. Here is my code:

    #include <iostream>
#include <list>

#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>

using namespace std;
using namespace cv;
const cv::Vec3b color_black{0, 0, 0};
const cv::Vec3b color_azure{255, 127, 0};

int width = 800;
int height = 600;
cv::Mat image = cv::Mat(cv::Size(width, height), CV_8UC3, color_black);

std::list<cv::Point> polygon;
bool isMouseDown = false;

void repaint(){
    cv::rectangle(image, cv::Rect(0, 0, width, height), color_black, 1);

    std::list<cv::Point>::iterator it = polygon.begin();
    if(it== polygon.end()){
        return;
    }
    cv::Point prev = *it;
    it++;
    while(it!=polygon.end() ){
        cv::line(image, prev, *it, color_azure, 2);
        prev = *it;
        it++;
    }
   //show the image
     imshow("My Window", image);
}

void CallBackFunc(int event, int x, int y, int flags, void* userdata)
{
     if  ( event == EVENT_LBUTTONDOWN )
     {
          isMouseDown = true;
          polygon.clear();
          repaint();

     }
     else if ( event == EVENT_MOUSEMOVE )

     {
          if(isMouseDown){
                polygon.push_back(cv::Point(x,y));
                repaint();
          }
     }
     else if (event == EVENT_LBUTTONUP){
        isMouseDown = false;
     }
}

int main(int argc, char** argv)
{
     // Read image from file

     //Create a window
     namedWindow("My Window", 1);

     //set the callback function for any mouse event
     setMouseCallback("My Window", CallBackFunc, NULL);

     //show the image
     imshow("My Window", image);

     // Wait until user press some key
     waitKey(0);

     return 0;

}


问:
How to type hint results of specific function calls with generic return signature
I believe it is easier to ask this question using a concrete example:

import matplotlib.pyplot as plt

_, ax = plt.subplots()
# Pyright: Cannot access member "plot" for type "ndarray[Any, dtype[Any]]"
# Member "plot" is unknown
ax.plot([1, 2, 3], [3, 4, 1])

plt.show()
```

The code above runs as expected, but the static type checker (I am using Pyright) has trouble figuring out the type of ax. The problem is that the return type of plt.subplots depends on its arguments (and possibly on the context it is being used), so its return signature is rather general, i.e.
tuple[FigureBase | Unknown, Any | ndarray[Any, dtype[Any]] | Unknown].

However, in this particular case I know that the result is expected to be of type tuple[plt.Figure, plt.Axes]. So I guess the question is what is the way to declare this in the code, so that the static type checker can reason about ax.plot?

Body:
I believe it is easier to ask this question using a concrete example:

import matplotlib.pyplot as plt

_, ax = plt.subplots()
# Pyright: Cannot access member "plot" for type "ndarray[Any, dtype[Any]]"
# Member "plot" is unknown
ax.plot([1, 2, 3], [3, 4, 1])

plt.show()

The code above runs as expected, but the static type checker (I am using Pyright) has trouble figuring out the type of ax. The problem is that the return type of plt.subplots depends on its arguments (and possibly on the context it is being used), so its return signature is rather general, i.e.
tuple[FigureBase | Unknown, Any | ndarray[Any, dtype[Any]] | Unknown].

However, in this particular case I know that the result is expected to be of type tuple[plt.Figure, plt.Axes]. So I guess the question is what is the way to declare this in the code, so that the static type checker can reason about ax.plot?


问:
Minikube: Can't pull image from private repo on dockerhub
I have pushed some docker images to my private repo on dockerhub, which I am now trying to use to create deployments in a Minikube Kubernetes cluster.

I have done the following:

```<code>docker login -u [username] -p [password]

docker tag [mslearn-microservices-pizzabackend] [username]/[mslearn-microservices-pizzabackend]

docker tag [mslearn-microservices-pizzafrontend] [username]/[mslearn-microservices-pizzafrontend]
</code>```

I can see both the images in my private dockerhub repo. To be able to use them in a deployment, I have done the following:

```<code>kubectl create secret docker-registry dockerhub-credentials --docker-server="docker.io" --docker-username="[username]" --docker-password="[password]" --docker-email="[email]"
</code>```

After that, I try to create a deployment for the first image using the following manifest:

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: mslearn-microservices-pizzabackend
spec:
  replicas: 1
  selector:
    matchLabels:
      app: mslearn-microservices-pizzabackend
  template:
    metadata:
      labels:
        app: mslearn-microservices-pizzabackend
    spec:
      imagePullSecrets:
      - name: dockerhub-credentials
      containers:
      - name: mslearn-microservices-pizzabackend
        image: [username]/mslearn-microservices-pizzabackend:latest
        ports:
        - containerPort: 80
        env:
        - name: ASPNETCORE_URLS
          value: http://*:80
---
apiVersion: v1
kind: Service
metadata:
  name: mslearn-microservices-pizzabackend
spec:
  type: ClusterIP
  ports:
  - port: 80
  selector:
    app: mslearn-microservices-pizzabackend
</code>```

But when I check the events of the pod that gets created by the deployment, I can see the following:

```<code>Events:
  Type     Reason     Age               From               Message
  ----     ------     ----              ----               -------
  Normal   Scheduled  18s               default-scheduler  Successfully assigned default/mslearn-microservices-pizzabackend-79dcd6677d-cgh7z to minikube
  Normal   BackOff    15s               kubelet            Back-off pulling image "[username]/mslearn-microservices-pizzabackend:latest"
  Warning  Failed     15s               kubelet            Error: ImagePullBackOff
  Normal   Pulling    3s (x2 over 18s)  kubelet            Pulling image "[username]/mslearn-microservices-pizzabackend:latest"
  Warning  Failed     1s (x2 over 16s)  kubelet            Failed to pull image "[username]/mslearn-microservices-pizzabackend:latest": rpc error: code = Unknown desc = Error response from daemon: pull access denied for [username]/mslearn-microservices-pizzabackend, repository does not exist or may require 'docker login': denied: requested access to the resource is denied
  Warning  Failed     1s (x2 over 16s)  kubelet            Error: ErrImagePull
</code>```

I have tried searching for solutions on the web and I can see that other people have had similiar issues, but none of their solutions have worked for me.

Any suggestions?

Body:
I have pushed some docker images to my private repo on dockerhub, which I am now trying to use to create deployments in a Minikube Kubernetes cluster.

I have done the following:

docker login -u [username] -p [password]

docker tag [mslearn-microservices-pizzabackend] [username]/[mslearn-microservices-pizzabackend]

docker tag [mslearn-microservices-pizzafrontend] [username]/[mslearn-microservices-pizzafrontend]

I can see both the images in my private dockerhub repo. To be able to use them in a deployment, I have done the following:

kubectl create secret docker-registry dockerhub-credentials --docker-server="docker.io" --docker-username="[username]" --docker-password="[password]" --docker-email="[email]"

After that, I try to create a deployment for the first image using the following manifest:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: mslearn-microservices-pizzabackend
spec:
  replicas: 1
  selector:
    matchLabels:
      app: mslearn-microservices-pizzabackend
  template:
    metadata:
      labels:
        app: mslearn-microservices-pizzabackend
    spec:
      imagePullSecrets:
      - name: dockerhub-credentials
      containers:
      - name: mslearn-microservices-pizzabackend
        image: [username]/mslearn-microservices-pizzabackend:latest
        ports:
        - containerPort: 80
        env:
        - name: ASPNETCORE_URLS
          value: http://*:80
---
apiVersion: v1
kind: Service
metadata:
  name: mslearn-microservices-pizzabackend
spec:
  type: ClusterIP
  ports:
  - port: 80
  selector:
    app: mslearn-microservices-pizzabackend

But when I check the events of the pod that gets created by the deployment, I can see the following:

Events:
  Type     Reason     Age               From               Message
  ----     ------     ----              ----               -------
  Normal   Scheduled  18s               default-scheduler  Successfully assigned default/mslearn-microservices-pizzabackend-79dcd6677d-cgh7z to minikube
  Normal   BackOff    15s               kubelet            Back-off pulling image "[username]/mslearn-microservices-pizzabackend:latest"
  Warning  Failed     15s               kubelet            Error: ImagePullBackOff
  Normal   Pulling    3s (x2 over 18s)  kubelet            Pulling image "[username]/mslearn-microservices-pizzabackend:latest"
  Warning  Failed     1s (x2 over 16s)  kubelet            Failed to pull image "[username]/mslearn-microservices-pizzabackend:latest": rpc error: code = Unknown desc = Error response from daemon: pull access denied for [username]/mslearn-microservices-pizzabackend, repository does not exist or may require 'docker login': denied: requested access to the resource is denied
  Warning  Failed     1s (x2 over 16s)  kubelet            Error: ErrImagePull

I have tried searching for solutions on the web and I can see that other people have had similiar issues, but none of their solutions have worked for me.

Any suggestions?


问:
Depedency issues, cloned react project
I cloned a React/typescript package from GitHub, but cannot get it to work. When I do npm install, the compiler complains that my typescript version is too new:

WARNING: You are currently running a version of TypeScript which is not officially supported by @typescript-eslint/typescript-estree

Is there some way, I can use exactly the node and packages versions as listed in the package.json?

I've also tried npm install --legacy-pee-deps, but that wasn't fruitful either, still get the problem. Also, I tried setting npm config set save-exact true before installing packages.

Thanks!

Title: Depedency issues, cloned react project


问:
Rank Elasticsearch results by the shortest hit
I am building a ngram search example with ES. Is is possible to take account the shortest length of all the hits?

Here's an example:

Documents:

{"aliases": ["ElonMuskTesla", "MuskTesla"]}

{"aliases": ["ElonMusk"]}

Default Result:

When searching for "Musk" against the field "aliases", the first document will have the highest score, because it has two hits matching "Musk".

What I want:

But I want the second document to appear on the top, because in my case, it's more relavant to the serach term (shortest means most similar).

I guess this might be achieved by the script score query, but don't know exactly how after browsing a bunch of seemingly related questions.

[Appendix] Mapping & Settings:

{
   "settings":{
      "analysis":{
         "tokenizer":{
            "ngram":{
               "type":"ngram",
               "min_gram":2,
               "max_gram":40
            }
         },
         "analyzer":{
            "ngram_analyzer":{
               "tokenizer":"ngram",
               "filter":[
                  "lowercase"
               ]
            },
            "lower_analyzer":{
               "tokenizer":"keyword",
               "filter":[
                  "lowercase"
               ]
            }
         }
      }
   },
   "mappings":{
      "properties":{
         "aliases":{
            "type":"text",
            "analyzer":"ngram_analyzer",
            "term_vector":"with_positions_offsets",
            "search_analyzer":"lower_analyzer"
         }
      }
   }
}
```


问:
TRIGGERS_function
please help me to find the solution i have a project .

so my project is about a mobile repair store , we have some tables :

customers, mobiles, repairjob

```<code>//customer table
CREATE TABLE CUSTOMERS (
 CUSTOMER_CPR NUMBER(9) PRIMARY KEY,
 FIRST_NAME VARCHAR2(30) NOT NULL,
MID VARCHAR2(30)
 LAST_NAME VARCHAR2(30) NOT NULL,
 EMAIL VARCHAR2(30) NOT NULL UNIQUE,
 HOME_TEL NUMBER(8) UNIQUE,
HOUSE_NO VARCHAR2(30) NOT NULL,
ROAD_NO VARCHAR2(30) NOT NULL,
BLOCK_NO VARCHAR2(30) NOT NULL,
CITY VARCHAR2(30) NOT NULL
);

//mobiles table
CREATE TABLE MOBILES (
    MOB_ID NUMBER(8,0) PRIMARY KEY,
    MODEL VARCHAR2(30) NOT NULL,
    MOB_DECRIPTION VARCHAR2(100),
    SERIAL_NUM VARCHAR2(30) UNIQUE,
    MAKE VARCHAR2(50),
customer_cpr number(9),
);

//repair job table
CREATE TABLE REPAIR JOB (
 JOB_NUM NUMBER primary key,
customer_cpr number(9)
 EMP_ID NUMBER(8,0) NOT NULL,
 DATE_RECEIVED DATE,
 DATE_TO_RETURN DATE,
ITEM_ID NUMBER

);
</code>```

so my question is to make a trigger function , we have assumed that the customer cannot have more than 3 repair jobs or can't fix more than 3 mobiles at one time  until it finishes all. so how i make a triiger function ?

Title: TRIGGERS_function

Body:
please help me to find the solution i have a project .

so my project is about a mobile repair store , we have some tables :

customers, mobiles, repairjob

//customer table
CREATE TABLE CUSTOMERS (
 CUSTOMER_CPR NUMBER(9) PRIMARY KEY,
 FIRST_NAME VARCHAR2(30) NOT NULL,
MID VARCHAR2(30)
 LAST_NAME VARCHAR2(30) NOT NULL,
 EMAIL VARCHAR2(30) NOT NULL UNIQUE,
 HOME_TEL NUMBER(8) UNIQUE,
HOUSE_NO VARCHAR2(30) NOT NULL,
ROAD_NO VARCHAR2(30) NOT NULL,
BLOCK_NO VARCHAR2(30) NOT NULL,
CITY VARCHAR2(30) NOT NULL
);

//mobiles table
CREATE TABLE MOBILES (
    MOB_ID NUMBER(8,0) PRIMARY KEY,
    MODEL VARCHAR2(30) NOT NULL,
    MOB_DECRIPTION VARCHAR2(100),
    SERIAL_NUM VARCHAR2(30) UNIQUE,
    MAKE VARCHAR2(50),
customer_cpr number(9),
);

//repair job table
CREATE TABLE REPAIR JOB (
 JOB_NUM NUMBER primary key,
customer_cpr number(9)
 EMP_ID NUMBER(8,0) NOT NULL,
 DATE_RECEIVED DATE,
 DATE_TO_RETURN DATE,
ITEM_ID NUMBER

);

so my question is to make a trigger function , we have assumed that the customer cannot have more than 3 repair jobs or can't fix more than 3 mobiles at one time  until it finishes all. so how i make a triiger function ?


问:
Defining custom operators on polymorphic structure in C++ / RTTI usage relevance
Assume we have a class hierarchy in C++ as follows:

```<code>class A{
//...
};

class B : public A{
//...
};
</code>```

A may represent an abstract base class and have a complicated structure of derived classes.
We define a Sum class which represents a sum of two A objects.
Hence we'd like to overload the + operator to take two A objects and return the corresponding Sum object:

```<code>Sum operator+(const &A a1, const &A a2){
//...
}
</code>```

As A is an abstract class, we may want to implement operator+() differently for its subclasses.
For example, if A is RealFunction and B is Polynomial, we expect the result of addition of two polynomials to be a polynomial (the dynamic type) instead of the general Sum object (as we know how to add polynomials effectively).

What design is preferred in this situation? It seems that using RTTI to check the types would fit, but many people on stack said it should be avoided.

Body:
Assume we have a class hierarchy in C++ as follows:

class A{
//...
};

class B : public A{
//...
};

A may represent an abstract base class and have a complicated structure of derived classes.
We define a Sum class which represents a sum of two A objects.
Hence we'd like to overload the + operator to take two A objects and return the corresponding Sum object:

Sum operator+(const &A a1, const &A a2){
//...
}

As A is an abstract class, we may want to implement operator+() differently for its subclasses.
For example, if A is RealFunction and B is Polynomial, we expect the result of addition of two polynomials to be a polynomial (the dynamic type) instead of the general Sum object (as we know how to add polynomials effectively).

What design is preferred in this situation? It seems that using RTTI to check the types would fit, but many people on stack said it should be avoided.


问:
Configure NextJS on Mac OSX to use SOCKS proxy
I do development on my laptop, currently running Mac OSX Ventura. At the moment, I find myself sitting on a network that uses pi-hole, and is blocking many of the destinations that my NextJS backend needs to reach.

I've spun up an EC2 instance and used SSH to tunnel through it, and have confirmed that I can set the SOCKS proxy in Safari and it works fine. However, SOCKS is application specific. How do I tell my NextJS dev environment to use the local proxy?


问:
"serve -s build" starts over my create-react-app "npm start"
I have posted about my another problem that related to this problen.

So for some reason when I start my react app with npm start and then trying to start server at the same port using serve module serve -s build my main PC returns a warning as it should be.
PC

But when I do same thing with the same project on my laptop it doesn't returns any errors. Serve server starts above my npm start server, so browser returns data without websocket connection, that allows to use auto page updates. And if I end serve server I'm localhost:3000 returns data that npm start should return.
Laptop

If I do this in reversed order (start serve server and then npm start react noticing that 3000 port is busy.
Laptop Reversed order

So in other words my apps can't see that 3000 port is busy when I'm starting server using npm start

I think that there is some kind of create-react-app settings that i don't know.


问:
Variable not printing after being set with OptionMenu (tkinter)
I'm trying to learn Tkinter, and learning how to set a variable that can be worked on later on in the code from the choice selected from an optionmenu. Only been coding tkinter or python for about 2 days properly now and unsure why this doesn't work.

my code:

```<code>
root = Tk()
root.title("test")

p1aspVARIABLE = str()

def tellmethevariable():
    if p1aspVARIABLE == "AA":
        print(p1aspVARIABLE)
    else:
       print("Not 'AA'")

def tellmeP1Asp(choice):
    choice = p1aspCHOICE.get()
    print(choice)
    p1aspVARIABLE = choice
    print(p1aspVARIABLE)

alleles = ["AA", "Ab", "bb"]

p1aspCHOICE = StringVar()
p1aspCHOICE.set(alleles[0])

alleledropdown = OptionMenu(root, p1aspCHOICE, *alleles, command=tellmeP1Asp)

button1 = Button(root, command=tellmethevariable)

alleledropdown.grid(row=0, column=0)
button1.grid(row=0, column=1)

root.mainloop()
</code>```

I don't understand why the code is able to print out the p1aspCHOICE when ran from the "tellmeP1Asp", but not when done through "tellmethevariable"?
I'm not sure how to get the p1aspVARIABLE to properly change to what was chosen in the OptionMenu list?

I'm not knowledgeable enough of what I'm doing wrong to properly google this, have been trying for a few hours now but to no avail.

What I tried:
I've set this up in countless ways over the last few hours, mostly last night before giving up. This is actually one of the only versions of this code that ran.

What I was expecting:
When the button1 Button is clicked, for it to either print the choice (if it was "AA", so it would print "AA"), or, if it wasn't "AA", it would print "Not 'AA'"

Body:
I'm trying to learn Tkinter, and learning how to set a variable that can be worked on later on in the code from the choice selected from an optionmenu. Only been coding tkinter or python for about 2 days properly now and unsure why this doesn't work.

my code:

root = Tk()
root.title("test")

p1aspVARIABLE = str()

def tellmethevariable():
    if p1aspVARIABLE == "AA":
        print(p1aspVARIABLE)
    else:
       print("Not 'AA'")

def tellmeP1Asp(choice):
    choice = p1aspCHOICE.get()
    print(choice)
    p1aspVARIABLE = choice
    print(p1aspVARIABLE)

alleles = ["AA", "Ab", "bb"]

p1aspCHOICE = StringVar()
p1aspCHOICE.set(alleles[0])

alleledropdown = OptionMenu(root, p1aspCHOICE, *alleles, command=tellmeP1Asp)

button1 = Button(root, command=tellmethevariable)

alleledropdown.grid(row=0, column=0)
button1.grid(row=0, column=1)

root.mainloop()

I don't understand why the code is able to print out the p1aspCHOICE when ran from the "tellmeP1Asp", but not when done through "tellmethevariable"?
I'm not sure how to get the p1aspVARIABLE to properly change to what was chosen in the OptionMenu list?

I'm not knowledgeable enough of what I'm doing wrong to properly google this, have been trying for a few hours now but to no avail.

What I tried:
I've set this up in countless ways over the last few hours, mostly last night before giving up. This is actually one of the only versions of this code that ran.

What I was expecting:
When the button1 Button is clicked, for it to either print the choice (if it was "AA", so it would print "AA"), or, if it wasn't "AA", it would print "Not 'AA'"


问:
Databricks, Folder Management and SQL. What is happening behind the scenes?
New Databricks user.
Im able to create subfolders in the user directory I am provided.
E.g. I am provided /mnt/DUAXXX/USERID/files
and I can create /mnt/DUAXXX/USERID/files/subfolder.

However, I cannot figure out how to create tables in this subfolder and use the resulting dataset.
I issue the following command, because the source datasets reside in this location:

```<code>%python
use DUAXXX
</code>```

However, I want to create the resulting dataset in the subfolder.
Ive tried something like:

```<code>create table test
location 'mnt/DUAXXX/USERID/files/subfolder'
select * from
data
</code>```

This completes, but when I navigate using the Databricks GUI 'Data' tab, the test dataset appears in the DUAXXX folder.
However, when I issue the following command:
dbutils.fs.ls(f"dbfs:/mnt/DUAXXX/USERID/files/subfolder")
I see numerous sorts of .snappy.parquet files.
I know these files are created by the above code.

Its as though the underlying data is stored where I want them in this .snappy.parquet format, but Databricks is creating a link to all these files in the DUAXXX folder.

I realize a lot of this is likely down to how the administrations implemented Databricks, and I have no access to those people.  Does anyone know what is actually going on here?
Ultimately, all I am trying to do is create subfolders to organize my datasets, rather than have everything in a single folder.

Thanks.

Body:
New Databricks user.
Im able to create subfolders in the user directory I am provided.
E.g. I am provided /mnt/DUAXXX/USERID/files
and I can create /mnt/DUAXXX/USERID/files/subfolder.

However, I cannot figure out how to create tables in this subfolder and use the resulting dataset.
I issue the following command, because the source datasets reside in this location:

%python
use DUAXXX

However, I want to create the resulting dataset in the subfolder.
Ive tried something like:

create table test
location 'mnt/DUAXXX/USERID/files/subfolder'
select * from
data

This completes, but when I navigate using the Databricks GUI 'Data' tab, the test dataset appears in the DUAXXX folder.
However, when I issue the following command:
dbutils.fs.ls(f"dbfs:/mnt/DUAXXX/USERID/files/subfolder")
I see numerous sorts of .snappy.parquet files.
I know these files are created by the above code.

Its as though the underlying data is stored where I want them in this .snappy.parquet format, but Databricks is creating a link to all these files in the DUAXXX folder.

I realize a lot of this is likely down to how the administrations implemented Databricks, and I have no access to those people.  Does anyone know what is actually going on here?
Ultimately, all I am trying to do is create subfolders to organize my datasets, rather than have everything in a single folder.

Thanks.