问:
How to authenticate for FCM Rest API using Google REST API in PHP REST API?
I need to send a notification using FCM REST API. However, I am unable to authenticaate using an API key at the moment. The below is the API to hit.

```<code>https://fcm.googleapis.com/v1/projects/proj-name/messages:send?key=XXX
</code>```

The error I receive is as follows:

{
    "error": {
        "code": 401,
        "message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
        "status": "UNAUTHENTICATED"
    }
}
```

The backend is in PHP so there isn't any supported package for it. Hence, I am trying to use it for sending the notification. The above API seem to take oauth 2 access token or login cookie or some auther vaidation method. However, I need to send it from my own REST API. How can I authenticate from PHP to the above API and send the notificaiton properly?

UPDATE::

LINK: Authenticate using Service Account

This API documents on how to authenticate using service accounts. Especially the below lines says the following:

Use credentials to mint access tokens

Unless you are using the Admin SDK, which handle authorization automatically, you'll need to mint the access token and add it to send requests.

Use your Firebase credentials together with the Google Auth Library for your preferred language to retrieve a short-lived OAuth 2.0 access token:

But it does not provide/document any method for minting the short lived access token.

Body:
I need to send a notification using FCM REST API. However, I am unable to authenticaate using an API key at the moment. The below is the API to hit.

https://fcm.googleapis.com/v1/projects/proj-name/messages:send?key=XXX

The error I receive is as follows:

{
    "error": {
        "code": 401,
        "message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
        "status": "UNAUTHENTICATED"
    }
}

The backend is in PHP so there isn't any supported package for it. Hence, I am trying to use it for sending the notification. The above API seem to take oauth 2 access token or login cookie or some auther vaidation method. However, I need to send it from my own REST API. How can I authenticate from PHP to the above API and send the notificaiton properly?

UPDATE::

LINK: Authenticate using Service Account

This API documents on how to authenticate using service accounts. Especially the below lines says the following:

Use credentials to mint access tokens

Unless you are using the Admin SDK, which handle authorization automatically, you'll need to mint the access token and add it to send requests.

Use your Firebase credentials together with the Google Auth Library for your preferred language to retrieve a short-lived OAuth 2.0 access token:

But it does not provide/document any method for minting the short lived access token.


来源: stackexchange

问:
How to disable WebSocket by JS
Is there a way to ensure that no js module in my app uses WebSocket?

I'm writing a web-app, where data safety is very important. But I'm using many third-party libraries, so any of them can hypothetically send user's data away. I can intercept all http connections by service worker. But ServiceWorker doesn't intercept WebSockets.

I consider using WebSocket = undefined in my main js file, but is there a way to restore this global variable somehow later, when I import a module with malicious code?

ContentLicense: CC BY-SA 4.0

Title: How to disable WebSocket by JS


问:
neo4j can be accessed by localhost but failed non-local connection
dbms.default_listen_address=0.0.0.0
on the conf file is uncommentted way before. The conf file was not changed during the last six months and it all went fine. But today suddenly the neo4j browser is unable to be connected by any devices other than localhost. It still works fine on the local host computer but cannot be accessed by the previous address on other devices using the same Wifi.

I tried to access neo4j browser on multiple other devices via chrome and safari and they all turned out the same.
I tried to restart the server but it didn't solve the problem.

What other than the conf file has the capabillity of rejecting non-local connections to Neo4j browser?


问:
Is it possible to open DOCS, XLSX, PDF files from a shared folder to edit the file in the intranet from a Angular-App?
The use-case of this topic is as follows.
The user works within the angular app to capture data for specific cases. In addition to every case the user can upload files in the angular app.
Now if the user reopens the case and wants to edit the uploaded file I'd like to show him links for every file and when he clicks on a link the file should not be delivered from the server with a stream, but should him kind of redirect to the local location of the file on the shared folder like file:///X:/TheShare/file2edit.doc
So Word opens up and the user can make changes to the file and directly save the file on the location. So there is no subsequent upload neccessary for the file to be updated on the servers drive where the shared folder points to.
My working environment is an angular(7) frontend which interacts with a spring-mvc backend.
The user working on windows clients with Firefox/Chrome/Edge and the shared folder is available via samba from an linux server whichs hosts the spring backend.


问:
Gatsby / WooCommerce not processing mediaItems
I'm having major problems trying to build a Gatsby / WooCommerce site - whenever wp-graphql-woocommerce is activated it simply will not process any media items, with this error:

--

```<code>gatsby-source-wordpress  Error category: undefined

Error:
  Internal server error

Debug message:
  in_array(): Argument #2 ($haystack) must be of type array, string given

Error path: mediaItems

info  gatsby-source-wordpress  GraphQL vars: {"first":100,"url":"http://178.62.90.26/graphql","in":["13"],"after":null}
</code>```

--

Steps to reproduce:

I have created a completely fresh install of Wordpress (v6+) on a php8+ environment (Digital Ocean Wordpress 1 click install image)

https://marketplace.digitalocean.com/apps/wordpress

I open the console and finish the wordpress installation process

Next I install wp-graphql (latest master version) and run composer install in the directory, then activate the plugin

Next I install WooCommerce, run through the installation process and create a dummy product

Then I install WP-Gatsby (v2.3.3) and activate.

Next I install the latest version of wp-graphql-woocommerce (v12 master), upload the plugin and activate
I then change the permalink structure and check that the /graphql route is working - everything is fine

At this point I have a single dummy product, a single Hello World post with a featured image attached, and I have only the following plugins installed on the site:

WooCommerce (v7.2.2)

WP Gatsby (v2.3.3)

WP GraphQL (v1.13.7)

WPGraphQL WooCommerce (WooGraphQL) (v0.12.0)

I then clone this simple blog repo:
https://github.com/gatsbyjs/gatsby-starter-wordpress-blog.git

I run yarn install for dependencies.

I change my gatsby-config to point toward my server and add an option in gatsby-source-wordpress to ignore ShippingMethod (or else it takes forever to build), and add some debugging in to help define the issue:

--

```<code>resolve: 'gatsby-source-wordpress',

options: {
 url: process.env.WPGRAPHQL_URL || 'http://178.62.90.26/graphql',

type: {

 ShippingMethod: {
  exclude: true
 },
},
debug: {
 graphql: {
   showQueryVarsOnError: true,
   showQueryOnError: true,
   onlyReportCriticalErrors: false,
 },
},
},

</code>```

--

I then add define( 'GRAPHQL_DEBUG', true ); to my wp-config.php and restart Apache just to be sure

I then run gatsby develop and get the error I mentioned earlier when it gets to MediaItems:

--

```<code>gatsby-source-wordpress  Error category: undefined

Error:
  Internal server error

Debug message:
  in_array(): Argument #2 ($haystack) must be of type array, string given

Error path: mediaItems

info  gatsby-source-wordpress  GraphQL vars: {"first":100,"url":"http://178.62.90.26/graphql","in":["13"],"after":null}
</code>```

--

And it creates 0 MediaItem nodes:

no MediaItems processed

And in my debug.log it’s just this over and over again:

--

```<code>[05-Jan-2023 10:21:40 UTC] PHP Deprecated:  Function WPGraphQL\Connection\TermObjects::get_connection_args is <strong>deprecated</strong> since version 1.13.0! Use \WPGraphQL\Type\Connection\TermObjects::get_connection_args instead. in /var/www/html/wp-includes/functions.php on line 5379

[05-Jan-2023 10:21:40 UTC] PHP Deprecated:  Function WPGraphQL\Connection\Comments::get_connection_config is <strong>deprecated</strong> since version 1.13.0! Use \WPGraphQL\Type\Connection\Comments::get_connection_config instead. in /var/www/html/wp-includes/functions.php on line 5379
</code>```

--

If I deactivate wp-graphql-woocommerce the image is processed absolutely fine and creates the one mediaItem node that I have:

MediaItems processed with wp-graphql-woocommerce disabled

I need the woocommerce aspect of things though so this isn’t a solution. It just seems to happen whenever wp-graphql-woocommerce is activated.

Any help with this would be hugely, hugely appreciated as I’ve been banging my head against a brick wall for a while now and I'm really starting to worry that this isn't going to work

I have tried the following versions of wp-graphql / wp-graphql-woocommerce

wp-graphql - v1.12.2, v1.12.3, v1.13.0, v1.13.4, v1.13.7

wp-graphql-woocommerce - v12, v11.2, v10.7

Node Versions - v16.11.1, v18.12.1

I've tried with both Digital Ocean and AWS Lightsail servers - same outcome

And it just never seems to process the mediaItems. The strangest thing is that this did work in September, however lately it just flatly refuses to process the images whilst wp-graphql-woocommerce is activated

Body:
I'm having major problems trying to build a Gatsby / WooCommerce site - whenever wp-graphql-woocommerce is activated it simply will not process any media items, with this error:

--

gatsby-source-wordpress  Error category: undefined

Error:
  Internal server error

Debug message:
  in_array(): Argument #2 ($haystack) must be of type array, string given

Error path: mediaItems

info  gatsby-source-wordpress  GraphQL vars: {"first":100,"url":"http://178.62.90.26/graphql","in":["13"],"after":null}

--

Steps to reproduce:

I have created a completely fresh install of Wordpress (v6+) on a php8+ environment (Digital Ocean Wordpress 1 click install image)

https://marketplace.digitalocean.com/apps/wordpress

I open the console and finish the wordpress installation process

Next I install wp-graphql (latest master version) and run composer install in the directory, then activate the plugin

Next I install WooCommerce, run through the installation process and create a dummy product

Then I install WP-Gatsby (v2.3.3) and activate.

Next I install the latest version of wp-graphql-woocommerce (v12 master), upload the plugin and activate
I then change the permalink structure and check that the /graphql route is working - everything is fine

At this point I have a single dummy product, a single Hello World post with a featured image attached, and I have only the following plugins installed on the site:

WooCommerce (v7.2.2)

WP Gatsby (v2.3.3)

WP GraphQL (v1.13.7)

WPGraphQL WooCommerce (WooGraphQL) (v0.12.0)

I then clone this simple blog repo:
https://github.com/gatsbyjs/gatsby-starter-wordpress-blog.git

I run yarn install for dependencies.

I change my gatsby-config to point toward my server and add an option in gatsby-source-wordpress to ignore ShippingMethod (or else it takes forever to build), and add some debugging in to help define the issue:

--

resolve: 'gatsby-source-wordpress',

options: {
 url: process.env.WPGRAPHQL_URL || 'http://178.62.90.26/graphql',

type: {

 ShippingMethod: {
  exclude: true
 },
},
debug: {
 graphql: {
   showQueryVarsOnError: true,
   showQueryOnError: true,
   onlyReportCriticalErrors: false,
 },
},
},

--

I then add define( 'GRAPHQL_DEBUG', true ); to my wp-config.php and restart Apache just to be sure

I then run gatsby develop and get the error I mentioned earlier when it gets to MediaItems:

--

gatsby-source-wordpress  Error category: undefined

Error:
  Internal server error

Debug message:
  in_array(): Argument #2 ($haystack) must be of type array, string given

Error path: mediaItems

info  gatsby-source-wordpress  GraphQL vars: {"first":100,"url":"http://178.62.90.26/graphql","in":["13"],"after":null}

--

And it creates 0 MediaItem nodes:

no MediaItems processed

And in my debug.log it’s just this over and over again:

--

[05-Jan-2023 10:21:40 UTC] PHP Deprecated:  Function WPGraphQL\Connection\TermObjects::get_connection_args is deprecated since version 1.13.0! Use \WPGraphQL\Type\Connection\TermObjects::get_connection_args instead. in /var/www/html/wp-includes/functions.php on line 5379

[05-Jan-2023 10:21:40 UTC] PHP Deprecated:  Function WPGraphQL\Connection\Comments::get_connection_config is deprecated since version 1.13.0! Use \WPGraphQL\Type\Connection\Comments::get_connection_config instead. in /var/www/html/wp-includes/functions.php on line 5379

--

If I deactivate wp-graphql-woocommerce the image is processed absolutely fine and creates the one mediaItem node that I have:

MediaItems processed with wp-graphql-woocommerce disabled

I need the woocommerce aspect of things though so this isn’t a solution. It just seems to happen whenever wp-graphql-woocommerce is activated.

Any help with this would be hugely, hugely appreciated as I’ve been banging my head against a brick wall for a while now and I'm really starting to worry that this isn't going to work

I have tried the following versions of wp-graphql / wp-graphql-woocommerce

wp-graphql - v1.12.2, v1.12.3, v1.13.0, v1.13.4, v1.13.7

wp-graphql-woocommerce - v12, v11.2, v10.7

Node Versions - v16.11.1, v18.12.1

I've tried with both Digital Ocean and AWS Lightsail servers - same outcome

And it just never seems to process the mediaItems. The strangest thing is that this did work in September, however lately it just flatly refuses to process the images whilst wp-graphql-woocommerce is activated


问:
Error decrypting using AES GCM in Python; AttributeError: 'Cipher' object has no attribute 'decrypt'
I am sending some information to a https server and receving a response. To increase the privary, I want to use some kind of encryption.

I am sending json data and I am encrypting the data as following

I am using Python3.6

```<code>from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
from cryptography.hazmat.primitives import hashes, hmac
from cryptography.hazmat.backends import default_backend

salt = os.urandom(16)

password = b'password'
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=salt,
iterations=10000
)
key = kdf.derive(password)

cipher = Cipher(algorithms.AES(key), modes.GCM(salt), backend=default_backend())
decryptor = cipher.decryptor()
encryptor = cipher.encryptor()

headers = {'Content-Type': 'application/json'}

data = {'xxxx': xxxx, 'xxxx': xxxx}

encrypted_data = encryptor.update(json.dumps(data).encode('utf-8')) + encryptor.finalize()
tag = encryptor.tag
</code>```

Now, I am trying to decrypt the data as following

```<code>encrypted_data_b64 = request['encrypted_data']
tag_b64 = request['tag']
salt_b64 = request['salt']

encrypted_data = base64.b64decode(encrypted_data_b64)
tag = base64.b64decode(tag_b64)
salt = base64.b64decode(salt_b64)

password = b'password'
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=salt,
iterations=10000
)
key = kdf.derive(password)

cipher = Cipher(algorithms.AES(key), modes.GCM(salt), backend=default_backend())
decrypted_data = cipher.decrypt(encrypted_data, tag)
</code>```

getting error :

AttributeError: 'Cipher' object has no attribute 'decrypt'

Also, tried

```<code>decryptor = cipher.decryptor()
decrypted_data = decryptor.update(encrypted_data) + decryptor.finalize()
</code>```

Gettting error:

```<code>"Authentication tag must be provided when decrypting." ValueError: Authentication tag must be provided when decrypting.
</code>```

So, I tried

decrypted_data = decryptor.update(encrypted_data) +
decryptor.finalize(tag) TypeError: finalize() takes 1 positional
argument but 2 were given

Any suggestion will be helpful.

Body:
I am sending some information to a https server and receving a response. To increase the privary, I want to use some kind of encryption.

I am sending json data and I am encrypting the data as following

I am using Python3.6

from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
from cryptography.hazmat.primitives import hashes, hmac
from cryptography.hazmat.backends import default_backend

salt = os.urandom(16)

password = b'password'
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=salt,
iterations=10000
)
key = kdf.derive(password)

cipher = Cipher(algorithms.AES(key), modes.GCM(salt), backend=default_backend())
decryptor = cipher.decryptor()
encryptor = cipher.encryptor()

headers = {'Content-Type': 'application/json'}

data = {'xxxx': xxxx, 'xxxx': xxxx}

encrypted_data = encryptor.update(json.dumps(data).encode('utf-8')) + encryptor.finalize()
tag = encryptor.tag

Now, I am trying to decrypt the data as following

encrypted_data_b64 = request['encrypted_data']
tag_b64 = request['tag']
salt_b64 = request['salt']

encrypted_data = base64.b64decode(encrypted_data_b64)
tag = base64.b64decode(tag_b64)
salt = base64.b64decode(salt_b64)

password = b'password'
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=salt,
iterations=10000
)
key = kdf.derive(password)

cipher = Cipher(algorithms.AES(key), modes.GCM(salt), backend=default_backend())
decrypted_data = cipher.decrypt(encrypted_data, tag)

getting error :

AttributeError: 'Cipher' object has no attribute 'decrypt'

Also, tried

decryptor = cipher.decryptor()
decrypted_data = decryptor.update(encrypted_data) + decryptor.finalize()

Gettting error:

"Authentication tag must be provided when decrypting." ValueError: Authentication tag must be provided when decrypting.

So, I tried

decrypted_data = decryptor.update(encrypted_data) +
decryptor.finalize(tag) TypeError: finalize() takes 1 positional
argument but 2 were given

Any suggestion will be helpful.


问:
Web Application Code Coverage using JaCoCo
I have been assigned a task where I want to generate the code coverage report of web application execution (development code) when a manual or automation test script is executed, I have to identify (using any tool) what percent of development code has been executed against that particular action.
After doing my RnD, I found that this can be achieved using JaCoCo (Java Code Coverage). JaCoCo uses class file instrumentation to record execution coverage data. Class files are instrumented on-the-fly using a Java agent. I have used the java command in the java agent flag.

Points to Mention

Application front-end is Angular, backend is Java/BPM and is deployed on JBoss Server.

Backend code contain multiple modules.

Testcase are executed from my local machines, that hits the application deployed on the server.

APPROACH

I have added the below mentioned command in /app/JBoss-EAP-7.2/bin/standalone.sh file because this is the file that is executed when the server starts.

```<code>Javaagent:<path_to>/jacocoagent.jar=classdumpdir=<path_to>/jacocoClassDump, destfile=<path_to>/jacocoST.exec
</code>```

Restart JBoss server. [After this jacocoST.exec file is created in the respective folder]

Run automated testcase using maven on my local machine.

Stop the JBoss server. [so that jacocoST.exec file is updated]

Run the command:

```<code> java -jar <path_to>/jacococli.jar report <path_to>/jacoco-it.exec --  classfiles=<path_to>/jacocoClassDump --html /app/Jacocoreport --xml                                                                                cov.xml
</code>```

The above steps show error Can't add different class with same name

Why do I get the error "Can't add different class with same name"?

The FAQ that I’ve come across from JaCoCo Official Documentation

For coverage report generation all classes within a group must have unique names. You get this error during report generation if JaCoCo is supplied with multiple different class files with the same name. To fix this remove those duplicate classes or create separate reports or report groups for each version.

The main problem is the error which I am getting. According to FAQ, they suggest to delete duplicate files but there are no duplicate class files (each class files has unique number at the end).If somebody has done such work so please guide me, Are the steps which I followed right?

Body:
I have been assigned a task where I want to generate the code coverage report of web application execution (development code) when a manual or automation test script is executed, I have to identify (using any tool) what percent of development code has been executed against that particular action.
After doing my RnD, I found that this can be achieved using JaCoCo (Java Code Coverage). JaCoCo uses class file instrumentation to record execution coverage data. Class files are instrumented on-the-fly using a Java agent. I have used the java command in the java agent flag.

Points to Mention

Application front-end is Angular, backend is Java/BPM and is deployed on JBoss Server.

Backend code contain multiple modules.

Testcase are executed from my local machines, that hits the application deployed on the server.

APPROACH

I have added the below mentioned command in /app/JBoss-EAP-7.2/bin/standalone.sh file because this is the file that is executed when the server starts.

Javaagent:<path_to>/jacocoagent.jar=classdumpdir=<path_to>/jacocoClassDump, destfile=<path_to>/jacocoST.exec

Restart JBoss server. [After this jacocoST.exec file is created in the respective folder]

Run automated testcase using maven on my local machine.

Stop the JBoss server. [so that jacocoST.exec file is updated]

Run the command:

 java -jar <path_to>/jacococli.jar report <path_to>/jacoco-it.exec --  classfiles=<path_to>/jacocoClassDump --html /app/Jacocoreport --xml                                                                                cov.xml

The above steps show error Can't add different class with same name

Why do I get the error "Can't add different class with same name"?

The FAQ that I’ve come across from JaCoCo Official Documentation

For coverage report generation all classes within a group must have unique names. You get this error during report generation if JaCoCo is supplied with multiple different class files with the same name. To fix this remove those duplicate classes or create separate reports or report groups for each version.

The main problem is the error which I am getting. According to FAQ, they suggest to delete duplicate files but there are no duplicate class files (each class files has unique number at the end).If somebody has done such work so please guide me, Are the steps which I followed right?


问:
R language Post (with json) error: 415 Unsupported Media Type
I have created a web api using ASP.NET. The api only utilizes POST, receiving a json as a body.The web api works fine with Postman but I have problems using it with R.

A post with json using RStudio I get the error : Client error: (415) Unsupported Media Type.

Where is the error?

The verbose ( with code) from R studio is:

```<code>query = list(datarunID = "4",action = "CLIENTGETJOB",TreeRecordId = "73",result = "dfd")
> ListJSON = toJSON(query,pretty = FALSE,auto_unbox = TRUE)
> ListJSON
{"datarunID":"4","action":"CLIENTGETJOB","TreeRecordId":"73","result":"dfd"}
> url1 <- "http://localhost:29999/api/cycle"
> r <- POST(url = url1,body = ListJSON,encode = "json",verbose(data_out = TRUE, data_in = TRUE, info = TRUE) )
*  Connected to localhost (::1) port 29999 (#3)
-> POST /api/cycle HTTP/1.1
-> Host: localhost:29999
-> User-Agent: libcurl/7.64.1 r-curl/4.3.3 httr/1.4.4
-> Accept-Encoding: deflate, gzip
-> Accept: application/json, text/xml, application/xml, */*
-> Content-Length: 76
>> {"datarunID":"4","action":"CLIENTGETJOB","TreeRecordId":"73","result":"dfd"}
*  upload completely sent off: 76 out of 76 bytes
<- HTTP/1.1 415 Unsupported Media Type
<- Transfer-Encoding: chunked
<- Content-Type: application/problem+json; charset=utf-8
<- Server: Microsoft-IIS/10.0
<- X-Powered-By: ASP.NET
<- Date: Thu, xxxxx GMT
<<  af
<<  {"type":"https://tools.ietf.org/html/rfc7231#section-6.5.13","title":"Unsupported Media Type","status":415,"traceId":"00-67xxxxxxxxa537c45-00"}

</code>```

The Json that works with Postman is :

```<code>{
    "datarunID":"4",
    "action":"CLIENTGETJOB",
    "TreeRecordId" : "73",
    "result" : "dfd"
}
</code>```

Body:
I have created a web api using ASP.NET. The api only utilizes POST, receiving a json as a body.The web api works fine with Postman but I have problems using it with R.

A post with json using RStudio I get the error : Client error: (415) Unsupported Media Type.

Where is the error?

The verbose ( with code) from R studio is:

query = list(datarunID = "4",action = "CLIENTGETJOB",TreeRecordId = "73",result = "dfd")
> ListJSON = toJSON(query,pretty = FALSE,auto_unbox = TRUE)
> ListJSON
{"datarunID":"4","action":"CLIENTGETJOB","TreeRecordId":"73","result":"dfd"}
> url1 <- "http://localhost:29999/api/cycle"
> r <- POST(url = url1,body = ListJSON,encode = "json",verbose(data_out = TRUE, data_in = TRUE, info = TRUE) )
*  Connected to localhost (::1) port 29999 (#3)
-> POST /api/cycle HTTP/1.1
-> Host: localhost:29999
-> User-Agent: libcurl/7.64.1 r-curl/4.3.3 httr/1.4.4
-> Accept-Encoding: deflate, gzip
-> Accept: application/json, text/xml, application/xml, */*
-> Content-Length: 76
>> {"datarunID":"4","action":"CLIENTGETJOB","TreeRecordId":"73","result":"dfd"}
*  upload completely sent off: 76 out of 76 bytes
<- HTTP/1.1 415 Unsupported Media Type
<- Transfer-Encoding: chunked
<- Content-Type: application/problem+json; charset=utf-8
<- Server: Microsoft-IIS/10.0
<- X-Powered-By: ASP.NET
<- Date: Thu, xxxxx GMT
<<  af
<<  {"type":"https://tools.ietf.org/html/rfc7231#section-6.5.13","title":"Unsupported Media Type","status":415,"traceId":"00-67xxxxxxxxa537c45-00"}

The Json that works with Postman is :

{
    "datarunID":"4",
    "action":"CLIENTGETJOB",
    "TreeRecordId" : "73",
    "result" : "dfd"
}


问:
UDP listener and broadcast message to main Activity
I have an android app with MainActivity.
I have succesfully deployed a BroadCastReceiver and I can receive messages.

Now I have another class that listens for new UDP messages on specific port. I would like to pass the received messages to my MainActivity so I could update some values here.

For some reason I cannot make BroadCasting from this class.

Here is the code:
MainActivity.kt

```<code>@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        //hide top bar
        supportActionBar?.hide()

        //register broadcastreceiver
        registerReceiver(mPlugInReceiver, getIntentFilter())
        Log.d(TAG, "Registered broadcastreceiver")

        //sending test message to broadcastreceiver, this works
        val intent = Intent()
        intent.action = "MESSAGE_RECEIVED"
        intent.putExtra("MESSAGE_STRING", "sending test message to broadcastreceiver")
        sendBroadcast(intent)

        //start UDP server
        val udpServer = udpServer()
        Thread(udpServer).start()
    }
</code>```

udpServer.kt

```<code>class udpServer : Runnable {
    private val UDP_PORT = 58651

    override fun run() {
        var run = true
        Log.d(MainActivity.TAG, "udpServer started")

        while (run) {
            try {
                val udpSocket = DatagramSocket(UDP_PORT)
                val message = ByteArray(8000)
                val packet = DatagramPacket(message, message.size)
                //Log.i(MainActivity.TAG, "UDP server about to wait to receive")
                udpSocket.receive(packet)
                val text = String(message, 0, packet.length)
                //Log.d(MainActivity.TAG, text)

                //This does not work
                val intent = Intent()
                intent.action = "MESSAGE_RECEIVED"
                intent.putExtra("MESSAGE_STRING", "sending test message to broadcastreceiver")

                //This throws error: "create function 'sendBroadcast'"
                sendBroadcast(intent)

            } catch (e: IOException) {
                //Log.e(MainActivity.TAG, "error: ", e)
                //run = false
            }
        }
    }
}
</code>```

I tried to use companion object to pass data, but it doesn't work either.

Body:
I have an android app with MainActivity.
I have succesfully deployed a BroadCastReceiver and I can receive messages.

Now I have another class that listens for new UDP messages on specific port. I would like to pass the received messages to my MainActivity so I could update some values here.

For some reason I cannot make BroadCasting from this class.

Here is the code:
MainActivity.kt

@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        //hide top bar
        supportActionBar?.hide()

        //register broadcastreceiver
        registerReceiver(mPlugInReceiver, getIntentFilter())
        Log.d(TAG, "Registered broadcastreceiver")

        //sending test message to broadcastreceiver, this works
        val intent = Intent()
        intent.action = "MESSAGE_RECEIVED"
        intent.putExtra("MESSAGE_STRING", "sending test message to broadcastreceiver")
        sendBroadcast(intent)

        //start UDP server
        val udpServer = udpServer()
        Thread(udpServer).start()
    }

udpServer.kt

class udpServer : Runnable {
    private val UDP_PORT = 58651

    override fun run() {
        var run = true
        Log.d(MainActivity.TAG, "udpServer started")

        while (run) {
            try {
                val udpSocket = DatagramSocket(UDP_PORT)
                val message = ByteArray(8000)
                val packet = DatagramPacket(message, message.size)
                //Log.i(MainActivity.TAG, "UDP server about to wait to receive")
                udpSocket.receive(packet)
                val text = String(message, 0, packet.length)
                //Log.d(MainActivity.TAG, text)

                //This does not work
                val intent = Intent()
                intent.action = "MESSAGE_RECEIVED"
                intent.putExtra("MESSAGE_STRING", "sending test message to broadcastreceiver")

                //This throws error: "create function 'sendBroadcast'"
                sendBroadcast(intent)

            } catch (e: IOException) {
                //Log.e(MainActivity.TAG, "error: ", e)
                //run = false
            }
        }
    }
}

I tried to use companion object to pass data, but it doesn't work either.


问:
Solana Web3 | Transaction success and returns no signature in some cases
I'm working on a web3-powered application with Solana blockchain integrated inside. I successfully connected with Solana and do the blockchain operations using their web3 APIs.

The connection status is set to a "confirmed" flag for transaction results.
Recently I noticed that some of the transactions were not returning the transaction signatures but these transactions are successful in blockchain (I checked through the wallet addresses in solscan.io )

Without the signature that is returned, I'm not able to understand the status of the transactions. Also, I created an auto-retry program for re-executing transactions w/o blockchain signatures and in this program, the transactions will re-execute again because there are no blockchain signatures returned.

How to handle this problem?

Please help, Thanks in advance.


问:
How to Bold, Italic, underline, attach hyperlink dynamic text without using RichText Widget in Flutter
How to Bold, Italic, underline, attach hyperlink dynamic text

example: when we add description in stackoverflow and trello

My Input:
Click here

Output that I want:
Click here


问:
Category page in elastic ui and nextjs (typescript)
I'm integrating Elasticsearh UI with nextjs as per the tutorial codesandbox, the search and autocomplete page works fine. However I am having problems in the category page.
When using default data everything works fine, But when using data from Elastic local I get the error:

```<code># Browser
An unexpected error occurred: Unexpected token '<', "<!DOCTYPE "... is not valid JSON
# command line
error - TypeError: Cannot read properties of null (reading 'name')
# ...
error - TypeError: Cannot convert undefined or null to object
</code>```

and

```<code>TS2322: Type '{ searchQuery: { filters: { field: string; values: any[]; }[]; facets: { price: { type: string; ranges: ({ from: number; to: number; name: string; } | { from: number; name: string; to?: undefined; })[]; }; categories: { ...; }; manufacturer: { ...; }; rating: { ...; }; }; result_fields: { ...; }; disjunctiveFacets: ...' is not assignable to type 'SearchDriverOptions'.   Types of property 'searchQuery' are incompatible.     Type '{ filters: { field: string; values: any[]; }[]; facets: { price: { type: string; ranges: ({ from: number; to: number; name: string; } | { from: number; name: string; to?: undefined; })[]; }; categories: { type: string; size: number; }; manufacturer: { ...; }; rating: { ...; }; }; result_fields: { ...; }; disjunctive...' is not assignable to type 'SearchQuery'.       Type '{ filters: { field: string; values: any[]; }[]; facets: { price: { type: string; ranges: ({ from: number; to: number; name: string; } | { from: number; name: string; to?: undefined; })[]; }; categories: { type: string; size: number; }; manufacturer: { ...; }; rating: { ...; }; }; result_fields: { ...; }; disjunctive...' is not assignable to type '{ conditionalFacets?: Record<string, ConditionalRule>; filters?: Filter[]; facets?: Record<string, FacetConfiguration>; disjunctiveFacets?: string[]; disjunctiveFacetsAnalyticsTags?: string[]; result_fields?: Record<...>; search_fields?: Record<...>; }'.         Types of property 'filters' are incompatible.           Type '{ field: string; values: any[]; }[]' is not assignable to type 'Filter[]'.             Property 'type' is missing in type '{ field: string; values: any[]; }' but required in type 'Filter'.  index.d.ts(29, 5): 'type' is declared here. SearchProvider.d.ts(9, 5): The expected type comes from property 'config' which is declared here on type 'IntrinsicAttributes & SearchProviderProps'
</code>```

I also had a few similar errors before and, related to facets due to wrong declaration of fields in document.py (I use Django to generate the index).

Maybe I was missing flelds or it was formatted wrong. Any help is highly appreciated.

I've searched a lot and most of the tutorials are just about the search page. With nextjs, I changed Category.js to [category].tsx. Error caused by this line: filters: [{ field: 'parent_category', values: [category] }],

# /category/[category].tsx
const categoryPageconfig = (category) => ({
  ...Config,
  searchQuery: {
    ...Config.searchQuery,
    filters: [{ field: 'parent_category', values: [category] }],
    facets: {
      ...Config.searchQuery.facets,
      price: {
        type: 'range',
        ranges: [
          { from: 0, to: 200000, name: 'Under 200.000' },
          { from: 200000, to: 500000, name: '200.000 to 500.000' },
          { from: 500000, to: 1000000, name: '500.000 to 1.000.000' },
          { from: 1000000, to: 2000000, name: '1.000.000 to 2.000.0000' },
          { from: 2000000, to: 5000000, name: '2.000.000 to 5.000.000' },
          { from: 5000000, name: '5.000.000 & Above' },
        ],
      },
    },
  },
});

export default function CategoryPage(props) {
  const router = useRouter();
  const { category } = router.query;
  # const category = props?.match?.params.category;

  return (
    <>
      <BrowseHeader category={category} />
      <SearchProvider config={categoryPageconfig(category)}>
       ...
      </SearchProvider>
    </>
  );
}
```

Body:
I'm integrating Elasticsearh UI with nextjs as per the tutorial codesandbox, the search and autocomplete page works fine. However I am having problems in the category page.
When using default data everything works fine, But when using data from Elastic local I get the error:

# Browser
An unexpected error occurred: Unexpected token '<', "<!DOCTYPE "... is not valid JSON
# command line
error - TypeError: Cannot read properties of null (reading 'name')
# ...
error - TypeError: Cannot convert undefined or null to object

and

TS2322: Type '{ searchQuery: { filters: { field: string; values: any[]; }[]; facets: { price: { type: string; ranges: ({ from: number; to: number; name: string; } | { from: number; name: string; to?: undefined; })[]; }; categories: { ...; }; manufacturer: { ...; }; rating: { ...; }; }; result_fields: { ...; }; disjunctiveFacets: ...' is not assignable to type 'SearchDriverOptions'.   Types of property 'searchQuery' are incompatible.     Type '{ filters: { field: string; values: any[]; }[]; facets: { price: { type: string; ranges: ({ from: number; to: number; name: string; } | { from: number; name: string; to?: undefined; })[]; }; categories: { type: string; size: number; }; manufacturer: { ...; }; rating: { ...; }; }; result_fields: { ...; }; disjunctive...' is not assignable to type 'SearchQuery'.       Type '{ filters: { field: string; values: any[]; }[]; facets: { price: { type: string; ranges: ({ from: number; to: number; name: string; } | { from: number; name: string; to?: undefined; })[]; }; categories: { type: string; size: number; }; manufacturer: { ...; }; rating: { ...; }; }; result_fields: { ...; }; disjunctive...' is not assignable to type '{ conditionalFacets?: Record<string, ConditionalRule>; filters?: Filter[]; facets?: Record<string, FacetConfiguration>; disjunctiveFacets?: string[]; disjunctiveFacetsAnalyticsTags?: string[]; result_fields?: Record<...>; search_fields?: Record<...>; }'.         Types of property 'filters' are incompatible.           Type '{ field: string; values: any[]; }[]' is not assignable to type 'Filter[]'.             Property 'type' is missing in type '{ field: string; values: any[]; }' but required in type 'Filter'.  index.d.ts(29, 5): 'type' is declared here. SearchProvider.d.ts(9, 5): The expected type comes from property 'config' which is declared here on type 'IntrinsicAttributes & SearchProviderProps'

I also had a few similar errors before and, related to facets due to wrong declaration of fields in document.py (I use Django to generate the index).

Maybe I was missing flelds or it was formatted wrong. Any help is highly appreciated.

I've searched a lot and most of the tutorials are just about the search page. With nextjs, I changed Category.js to [category].tsx. Error caused by this line: filters: [{ field: 'parent_category', values: [category] }],

# /category/[category].tsx
const categoryPageconfig = (category) => ({
  ...Config,
  searchQuery: {
    ...Config.searchQuery,
    filters: [{ field: 'parent_category', values: [category] }],
    facets: {
      ...Config.searchQuery.facets,
      price: {
        type: 'range',
        ranges: [
          { from: 0, to: 200000, name: 'Under 200.000' },
          { from: 200000, to: 500000, name: '200.000 to 500.000' },
          { from: 500000, to: 1000000, name: '500.000 to 1.000.000' },
          { from: 1000000, to: 2000000, name: '1.000.000 to 2.000.0000' },
          { from: 2000000, to: 5000000, name: '2.000.000 to 5.000.000' },
          { from: 5000000, name: '5.000.000 & Above' },
        ],
      },
    },
  },
});

export default function CategoryPage(props) {
  const router = useRouter();
  const { category } = router.query;
  # const category = props?.match?.params.category;

  return (
    <>
      <BrowseHeader category={category} />
      <SearchProvider config={categoryPageconfig(category)}>
       ...
      </SearchProvider>
    </>
  );
}


问:
Observers don't get notified when LiveData is set through FileObserver
I have a sharedViewModel with LiveData properties.

MainActivity:

```<code>    private val logViewModel by viewModels<LogViewModel>()

    fun startLocationUpdates() {
       val locationItem = LocationItem(...)
       logViewModel.addLogEntry(locationItem)
    }

    override fun onCreate(savedInstanceState: Bundle?) {

        val observer = object : FileObserver(applicationContext.filesDir.path + "/" + jsonFileName) {
            override fun onEvent(event: Int, file: String?) {
                if (event == FileObserver.MODIFY) {
                    loadLogViewModel()
                }
            }
        }
        observer.startWatching()
    }

    fun loadLogViewModel() {
        val json = getData(this)
        val myType = object : TypeToken<ArrayList<LocationItem>>() {}.type
        if (json != null) {
            val listItems: ArrayList<LocationItem> = gson.fromJson(json, myType)
            for (item in listItems) {
                logViewModel.addLogEntry(item)
            }
        }
    }

</code>```

LogFragment:

```<code>private val logViewModel: LogViewModel by activityViewModels()

logViewModel.locationListItems.observe(requireActivity()) {
    locationItemAdapter.updateLocations()
}
</code>```

LogViewModel:

```<code>class LogViewModel : ViewModel() {
    var locationListItems: MutableLiveData<LocationItem> = MutableLiveData<LocationItem>()

    fun addLogEntry(locationItem: LocationItem) {
        locationListItems.postValue(locationItem)
    }
}
</code>```

When I execute startLocationUpdates() it all works as expected. The observer gets notifications.

But when the logfile (json) is changed through the WorkManager (potentially within a different process/thread) and the FileObserver kicks in to load the JSON file and adds them to the LogViewModel, the Live data is not firing anything.

Why does it make a difference if the fileObserver is doing it, or if startLocationUpdates() would be doing it? I can only assume this is a threading issue. But I thought LivaData deals with that?

Body:
I have a sharedViewModel with LiveData properties.

MainActivity:

    private val logViewModel by viewModels<LogViewModel>()

    fun startLocationUpdates() {
       val locationItem = LocationItem(...)
       logViewModel.addLogEntry(locationItem)
    }

    override fun onCreate(savedInstanceState: Bundle?) {

        val observer = object : FileObserver(applicationContext.filesDir.path + "/" + jsonFileName) {
            override fun onEvent(event: Int, file: String?) {
                if (event == FileObserver.MODIFY) {
                    loadLogViewModel()
                }
            }
        }
        observer.startWatching()
    }

    fun loadLogViewModel() {
        val json = getData(this)
        val myType = object : TypeToken<ArrayList<LocationItem>>() {}.type
        if (json != null) {
            val listItems: ArrayList<LocationItem> = gson.fromJson(json, myType)
            for (item in listItems) {
                logViewModel.addLogEntry(item)
            }
        }
    }

LogFragment:

private val logViewModel: LogViewModel by activityViewModels()

logViewModel.locationListItems.observe(requireActivity()) {
    locationItemAdapter.updateLocations()
}

LogViewModel:

class LogViewModel : ViewModel() {
    var locationListItems: MutableLiveData<LocationItem> = MutableLiveData<LocationItem>()

    fun addLogEntry(locationItem: LocationItem) {
        locationListItems.postValue(locationItem)
    }
}

When I execute startLocationUpdates() it all works as expected. The observer gets notifications.

But when the logfile (json) is changed through the WorkManager (potentially within a different process/thread) and the FileObserver kicks in to load the JSON file and adds them to the LogViewModel, the Live data is not firing anything.

Why does it make a difference if the fileObserver is doing it, or if startLocationUpdates() would be doing it? I can only assume this is a threading issue. But I thought LivaData deals with that?


问:
How to set custom headers in UrlWebViewSource property to load WebView in .Net MAUI
I am working on a .Net MAUI project that has Login Page which Authenticates and gets a Token from web server. I am using WebView control to load Homepage of my web application by passing HomeUrl in Web view source property, but It's redirected to login page with in the WebView, to skip this redirection need to pass token as cookie within header along with Home Url.

I am passing HomeUrl in WebView Control source property, but along with Url,

Expecting: Need to pass cookies(token) in the headers to load HomePage within WebView which skips Authentication.


问:
Access MongoDB running in a container from local (host) machine [pymongo]
I know this should have been a straight-forward issue as I did it before (but forgot how): I have my MongoDB running on a docker container as a service in my docker-compose that includes an API built with FastAPI. I'm able to connect to the database from my api container with the following code:

from pymongo.mongo_client import MongoClient
from pymongo.server_api import ServerApi

client = MongoClient('mongodb://USERNAME:PASSWORD@mongo:27017/', server_api=ServerApi('1'),
                     serverSelectionTimeoutMS=5000)

client.server_info()

```
<p>Now when I try to do the same from a Jupyter notebook on my local machine, I get this error:</p>
```ServerSelectionTimeoutError: mongo:27017: [Errno 8] nodename nor servname provided, or
not known, Timeout: 5.0s, Topology Description: <TopologyDescription id:
63b6adb8b6aabb1624b50879, topology_type: Unknown, servers: [<ServerDescription
('mongo', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('mongo:27017:
[Errno 8] nodename nor servname provided, or not known')>]>
```
<p>This is my <code>docker-compose</code> configuration that used to work just fine when I was able to connect to my mongodb from local (so I don't think there is an issue here):</p>
<pre class="lang-yaml prettyprint-override"><code>version: '3.8'

services:
  api:
    container_name: XXXXX
    restart: unless-stopped
    build:
      context: .
      dockerfile: ./API/API.Dockerfile
    volumes:
      - "./:/API"
      - type: bind
        source: XXXXX
        target: /Data
    ports:
      - "5001:5001"
    depends_on:
      - mongo
    env_file:
      - ./secrets/secrets.env

  mongo:
    container_name: mongo
    ports:
      - 27017:27017
    image: mongo
    restart: always
    env_file:
      - ./secrets/secrets.env

  mongo-express:
    container_name: Mongo_Express
    image: mongo-express
    restart: always
    ports:
      - 8081:8081
    env_file:
      - ./secrets/secrets.env
</code>```

Body:
I know this should have been a straight-forward issue as I did it before (but forgot how): I have my MongoDB running on a docker container as a service in my docker-compose that includes an API built with FastAPI. I'm able to connect to the database from my api container with the following code:

from pymongo.mongo_client import MongoClient
from pymongo.server_api import ServerApi

client = MongoClient('mongodb://USERNAME:PASSWORD@mongo:27017/', server_api=ServerApi('1'),
                     serverSelectionTimeoutMS=5000)

client.server_info()

Now when I try to do the same from a Jupyter notebook on my local machine, I get this error:

ServerSelectionTimeoutError: mongo:27017: [Errno 8] nodename nor servname provided, or
not known, Timeout: 5.0s, Topology Description: <TopologyDescription id:
63b6adb8b6aabb1624b50879, topology_type: Unknown, servers: [<ServerDescription
('mongo', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('mongo:27017:
[Errno 8] nodename nor servname provided, or not known')>]>

This is my docker-compose configuration that used to work just fine when I was able to connect to my mongodb from local (so I don't think there is an issue here):

version: '3.8'

services:
  api:
    container_name: XXXXX
    restart: unless-stopped
    build:
      context: .
      dockerfile: ./API/API.Dockerfile
    volumes:
      - "./:/API"
      - type: bind
        source: XXXXX
        target: /Data
    ports:
      - "5001:5001"
    depends_on:
      - mongo
    env_file:
      - ./secrets/secrets.env

  mongo:
    container_name: mongo
    ports:
      - 27017:27017
    image: mongo
    restart: always
    env_file:
      - ./secrets/secrets.env

  mongo-express:
    container_name: Mongo_Express
    image: mongo-express
    restart: always
    ports:
      - 8081:8081
    env_file:
      - ./secrets/secrets.env


问:
React application wont render Blog.js and PostDetails.js correctly
I am working on a blog website using create-react-app.

I have a Blog.js file, which should render a PostList.js, Post.js which reads content from a local posts.json file that stores my posts. Once a user clicks on a Post that features inside the PostList I want to direct the user to a new subpage that shows the content from the PostDetails.js file.

However, when I start the development server and navigate to the Blog.js page nothing is rendered besides the Navbar and Footer. Any idea why that is? I would also like to know if my code looks correct given that I want to direct the user to a new page once they click on a post inside the Postlist.

I have attached the different files below, and at the very bottom is a visual of how the components are placed inside each other on the Blog.js page.

App.js

```<code>import Layout from "./components/layout/Layout";
import Blog  from "./Blog";
import Home from "./pages/Home";
import Contact from "./pages/Contact";
import Navbar from "./components/layout/Navbar";
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import PostDetails from "./components/PostDetails";

function App() {
  return (
    <Router>
      <div>
        <h1>SME Analyst</h1>
        <div className="App">
          <Navbar />
          <Routes>
            <Route path="/" element={<Home />}/>
            <Route path="/blog" component={Blog} />
            <Route path="/contact" element={<Contact />}/>
            <Route path="/blog/:postId" component={PostDetails} />
          </Routes>
          <Layout />
        </div>
      </div>
    </Router>
  );
}

export default App;

</code>```

Blog.js

```<code>import React, { useState, useEffect } from 'react';
import { Route } from 'react-router-dom';
import PostList from './components/PostList';
import PostDetails from './components/PostDetails';

const Blog = () => {
  const [posts, setPosts] = useState([]);

  useEffect(() => {
    fetch('./data/posts.json')
      .then(response => response.json())
      .then(data => setPosts(data));
  }, []);

  const handlePostClick = id => {
    // navigate to the subpage for the post with the specified id
  };

  return (
    <div>
      <h1>My Blog</h1>
      <Route path="/blog/:postId" render={routeProps => <PostDetails {...routeProps} />} />
      <PostList posts={posts} onPostClick={handlePostClick} />
    </div>
  );
};

export default Blog;

</code>```

PostList.js

```<code>import React from 'react';
import Post from './Post';

const PostList = ({ posts, onPostClick }) => (
  <div>
    {posts.map(post => (
      <Post key={post.id} post={post} onClick={() => onPostClick(post.id)} />
    ))}
  </div>
);

export default PostList;

</code>```

Post.js

```<code>import { useNavigate } from 'react-router-dom';

const Post = ({ post, onClick }) => {
  const navigate = useNavigate();

  const handleClick = () => {
    navigate.push(`posts.json/${post.id}`);
  };

  return (
    <div onClick={handleClick}>
      <h2>{post.title}</h2>
      <p>{post.content}</p>
    </div>
  );
};

export default Post;

</code>```

PostDetails.js

```<code>import React from 'react';
import getPostById from '../api';

const PostDetails = ({ postId }) => {
  const post = getPostById(postId); // this would be a function that retrieves the post with the specified id from your database or data store

  return (
    <div>
      <h1>{post.title}</h1>
      <p>{post.content}</p>
    </div>
  );
};

export default PostDetails;

</code>```

posts.json

```<code>[
  {
      "id": 1,
      "title": "Ecommerce and SMEs",
      "date": "04-01-2023",
      "summary": "Why Ecommerce and SMEs are a match made in heaven",
      "body": "Online commerce has become increasingly important for small businesses in recent years. It allows them to reach a wider audience, operate more efficiently, and gather data on customer behavior. It is an essential part of any small business' marketing and sales strategy, as it provides a cost-effective and efficient way to reach and sell to customers both locally and globally."
  },
  {
      "id": 2,
      "title": "Blog Post 2",
      "date": "02-01-2023",
      "summary": "Lorem ipsum dolor",
      "body": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque nisl eros, pulvinar facilisis justo mollis, auctor consequat urna. Morbi a bibendum metus. Donec scelerisque sollicitudin enim eu venenatis. Duis tincidunt laoreet ex, in pretium orci vestibulum eget. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Duis pharetra luctus lacus ut vestibulum. Maecenas ipsum lacus, lacinia quis posuere ut, pulvinar vitae dolor. Integer eu nibh at nisi ullamcorper sagittis id vel leo. Integer feugiat faucibus libero, at maximus nisl suscipit posuere. Morbi nec enim nunc. Phasellus bibendum turpis ut ipsum egestas, sed sollicitudin elit convallis. Cras pharetra mi tristique sapien vestibulum lobortis. Nam eget bibendum metus, non dictum mauris. Nulla at tellus sagittis, viverra est a, bibendum metus."
  }
]

</code>```

Blog UI

Body:
I am working on a blog website using create-react-app.

I have a Blog.js file, which should render a PostList.js, Post.js which reads content from a local posts.json file that stores my posts. Once a user clicks on a Post that features inside the PostList I want to direct the user to a new subpage that shows the content from the PostDetails.js file.

However, when I start the development server and navigate to the Blog.js page nothing is rendered besides the Navbar and Footer. Any idea why that is? I would also like to know if my code looks correct given that I want to direct the user to a new page once they click on a post inside the Postlist.

I have attached the different files below, and at the very bottom is a visual of how the components are placed inside each other on the Blog.js page.

App.js

import Layout from "./components/layout/Layout";
import Blog  from "./Blog";
import Home from "./pages/Home";
import Contact from "./pages/Contact";
import Navbar from "./components/layout/Navbar";
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import PostDetails from "./components/PostDetails";

function App() {
  return (
    <Router>

SME Analyst

          <Navbar />
          <Routes>
            <Route path="/" element={<Home />}/>
            <Route path="/blog" component={Blog} />
            <Route path="/contact" element={<Contact />}/>
            <Route path="/blog/:postId" component={PostDetails} />
          </Routes>
          <Layout />

    </Router>
  );
}

export default App;

Blog.js

import React, { useState, useEffect } from 'react';
import { Route } from 'react-router-dom';
import PostList from './components/PostList';
import PostDetails from './components/PostDetails';

const Blog = () => {
  const [posts, setPosts] = useState([]);

  useEffect(() => {
    fetch('./data/posts.json')
      .then(response => response.json())
      .then(data => setPosts(data));
  }, []);

  const handlePostClick = id => {
    // navigate to the subpage for the post with the specified id
  };

  return (

My Blog

      <Route path="/blog/:postId" render={routeProps => <PostDetails {...routeProps} />} />
      <PostList posts={posts} onPostClick={handlePostClick} />

  );
};

export default Blog;

PostList.js

import React from 'react';
import Post from './Post';

const PostList = ({ posts, onPostClick }) => (

    {posts.map(post => (
      <Post key={post.id} post={post} onClick={() => onPostClick(post.id)} />
    ))}

);

export default PostList;

Post.js

import { useNavigate } from 'react-router-dom';

const Post = ({ post, onClick }) => {
  const navigate = useNavigate();

  const handleClick = () => {
    navigate.push(`posts.json/${post.id}`);
  };

  return (

{post.title}

{post.content}

  );
};

export default Post;

PostDetails.js

import React from 'react';
import getPostById from '../api';

const PostDetails = ({ postId }) => {
  const post = getPostById(postId); // this would be a function that retrieves the post with the specified id from your database or data store

  return (

{post.title}

{post.content}

  );
};

export default PostDetails;

posts.json

[
  {
      "id": 1,
      "title": "Ecommerce and SMEs",
      "date": "04-01-2023",
      "summary": "Why Ecommerce and SMEs are a match made in heaven",
      "body": "Online commerce has become increasingly important for small businesses in recent years. It allows them to reach a wider audience, operate more efficiently, and gather data on customer behavior. It is an essential part of any small business' marketing and sales strategy, as it provides a cost-effective and efficient way to reach and sell to customers both locally and globally."
  },
  {
      "id": 2,
      "title": "Blog Post 2",
      "date": "02-01-2023",
      "summary": "Lorem ipsum dolor",
      "body": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque nisl eros, pulvinar facilisis justo mollis, auctor consequat urna. Morbi a bibendum metus. Donec scelerisque sollicitudin enim eu venenatis. Duis tincidunt laoreet ex, in pretium orci vestibulum eget. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Duis pharetra luctus lacus ut vestibulum. Maecenas ipsum lacus, lacinia quis posuere ut, pulvinar vitae dolor. Integer eu nibh at nisi ullamcorper sagittis id vel leo. Integer feugiat faucibus libero, at maximus nisl suscipit posuere. Morbi nec enim nunc. Phasellus bibendum turpis ut ipsum egestas, sed sollicitudin elit convallis. Cras pharetra mi tristique sapien vestibulum lobortis. Nam eget bibendum metus, non dictum mauris. Nulla at tellus sagittis, viverra est a, bibendum metus."
  }
]

Blog UI


问:
Can I monetize my R Shiny app using monetizer package?
I have an R Shiny app. I have deployed it at Shinyapp.io and I want it to show ads when the users use it. Can I do that using the monetizer R package? if not, is there other ways to show ads on Shiny apps and make money?

If yes, how am I going to do that? It is mentioned in this instruction that it is possible to monetize packages by the monetizer. So I thought maybe I should organize my app as an R package at first. So, I did it. My question is after doing that, how can I use the monetizer package? If I've understood correctly, following the mentioned instruction, It can be done by creating a zzz.R file in the R directory of the package and placing the function market_all(ad = "Have I mentioned my blog, Variance Explained?") in it.
I did so but it didn't work. The app can't run after that. What is wrong with it? Should the zzz.R file be created in another way?

I appreciate any help everybody can provide and I also tag @David Robinson who has written the monetizer package. Hopefully, he can kindly help me with that.

To help you reproduce what I have now, I explain what exactly I did for organizing my app as an R package. I followed the workflow mentioned in this chapter of mastering Shiny book. I also use this book's example instead of a minimal example.

First I ran usethis::use_description(), which created a DESCRIPTION file. Next, I movedmonthFeedback.R, birthstone.R, app.R to the R directory and wrapped shinyApp() into a function. In the end, I can Re-run the app with myApp().

R/monthFeedback.R:

```<code>monthFeedbackUI <- function(id) {
  textOutput(NS(id, "feedback"))
}
monthFeedbackServer <- function(id, month) {
  stopifnot(is.reactive(month))

  moduleServer(id, function(input, output, session) {
    output$feedback <- renderText({
      if (month() == "October") {
        "You picked a great month!"
      } else {
        "Eh, you could do better."
      }
    })
  })
}
</code>```

R/birthstone.R:

```<code>birthstoneUI <- function(id) {
 p(
   "The birthstone for ", textOutput(NS(id, "month"), inline = TRUE),
   " is ", textOutput(NS(id, "stone"), inline = TRUE)
 )
}
birthstoneServer <- function(id, month) {
 stopifnot(is.reactive(month))

 moduleServer(id, function(input, output, session) {
   stone <- reactive(stones$stone[stones$month == month()])
   output$month <- renderText(month())
   output$stone <- renderText(stone())
 })
}
</code>```

R/app.R:

```<code>library(shiny)

myApp <- function(...) {
  stones <- vroom::vroom("birthstones.csv")
  months <- c(
    "January", "February", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December"
  )

  ui <- navbarPage(
    "Sample app",
    tabPanel("Pick a month",
      selectInput("month", "What's your favourite month?", choices = months)
    ),
    tabPanel("Feedback", monthFeedbackUI("tab1")),
    tabPanel("Birthstone", birthstoneUI("tab2"))
  )
  server <- function(input, output, session) {
    monthFeedbackServer("tab1", reactive(input$month))
    birthstoneServer("tab2", reactive(input$month))
  }
  shinyApp(ui, server, ...)
}
</code>```

Body:
I have an R Shiny app. I have deployed it at Shinyapp.io and I want it to show ads when the users use it. Can I do that using the monetizer R package? if not, is there other ways to show ads on Shiny apps and make money?

If yes, how am I going to do that? It is mentioned in this instruction that it is possible to monetize packages by the monetizer. So I thought maybe I should organize my app as an R package at first. So, I did it. My question is after doing that, how can I use the monetizer package? If I've understood correctly, following the mentioned instruction, It can be done by creating a zzz.R file in the R directory of the package and placing the function market_all(ad = "Have I mentioned my blog, Variance Explained?") in it.
I did so but it didn't work. The app can't run after that. What is wrong with it? Should the zzz.R file be created in another way?

I appreciate any help everybody can provide and I also tag @David Robinson who has written the monetizer package. Hopefully, he can kindly help me with that.

To help you reproduce what I have now, I explain what exactly I did for organizing my app as an R package. I followed the workflow mentioned in this chapter of mastering Shiny book. I also use this book's example instead of a minimal example.

First I ran usethis::use_description(), which created a DESCRIPTION file. Next, I movedmonthFeedback.R, birthstone.R, app.R to the R directory and wrapped shinyApp() into a function. In the end, I can Re-run the app with myApp().

R/monthFeedback.R:

monthFeedbackUI <- function(id) {
  textOutput(NS(id, "feedback"))
}
monthFeedbackServer <- function(id, month) {
  stopifnot(is.reactive(month))

  moduleServer(id, function(input, output, session) {
    output$feedback <- renderText({
      if (month() == "October") {
        "You picked a great month!"
      } else {
        "Eh, you could do better."
      }
    })
  })
}

R/birthstone.R:

birthstoneUI <- function(id) {
 p(
   "The birthstone for ", textOutput(NS(id, "month"), inline = TRUE),
   " is ", textOutput(NS(id, "stone"), inline = TRUE)
 )
}
birthstoneServer <- function(id, month) {
 stopifnot(is.reactive(month))

 moduleServer(id, function(input, output, session) {
   stone <- reactive(stones$stone[stones$month == month()])
   output$month <- renderText(month())
   output$stone <- renderText(stone())
 })
}

R/app.R:

library(shiny)

myApp <- function(...) {
  stones <- vroom::vroom("birthstones.csv")
  months <- c(
    "January", "February", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December"
  )

  ui <- navbarPage(
    "Sample app",
    tabPanel("Pick a month",
      selectInput("month", "What's your favourite month?", choices = months)
    ),
    tabPanel("Feedback", monthFeedbackUI("tab1")),
    tabPanel("Birthstone", birthstoneUI("tab2"))
  )
  server <- function(input, output, session) {
    monthFeedbackServer("tab1", reactive(input$month))
    birthstoneServer("tab2", reactive(input$month))
  }
  shinyApp(ui, server, ...)
}


问:
Unable to remove a managed identity in enterprise applications
I am  a global admin and owner of the Azure infrastructure.I am trying to delete the managed identity but the delete option under properties is grayed out .

I tried to remove from powershell and I am getting a forbidden error , what other access do I require to be able to delete.

PS /home/xxxx>  Remove-AzureADServicePrincipal -objectid xxxxxxx-e0c9-4330-ab87-53d156f4fbba

Remove-AzureADServicePrincipal: Error occurred while executing RemoveServicePrincipal
Code: Authorization_RequestDenied
Message: Insufficient privileges to complete the operation.
RequestId: 1338bb02-d660-4676-9471-da4dae9122bf
DateTimeStamp: Thu, 05 Jan 2023 10:52:19 GMT
HttpStatusCode: Forbidden
HttpStatusDescription: Forbidden
HttpResponseStatus: Completed


问:
Whats the best way to pass a value into a controller in laravel
I'm trying to make a profile page with the ability to upload different documents. At the moment I have 3 different modals where the user can upload 3 different types of documents. I want to make this process as effective as possible so I was thinking of naming the 3 documents a specific name such as UserCV and then accessing the documents on the front end using this name and the user`s ID. But I was just wondering what the best way for me to pass this name value from my modal to my controller. As I was planning on making an input field that can't be edited on the modal but feel like there must be a better way.

The current way I'm doing it :

Modal :

```<code><div class="modal fade" id="IDModal" tabindex="-1" aria-labelledby="ModalLabel" aria-hidden="true">
<div class="modal-dialog">
    <div class="modal-content">
        <div class="modal-header">
            <h5 class="modal-title" id="exampleModalLabel">Upload Id</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
            <form action="{{ route('id.upload.post') }}" method="POST" enctype="multipart/form-data">
            @csrf
                <div class="row">
                    <div class="input-group mb-3">
                        <input type="text" id="document_name" name="doc_name" value="UserIDCard" readonly>
                        <input type="file" class="form-control" id="idInput" name="id_upload">
                        <button type="submit" class="btn btn-secondary input-group-text" for="idInput">Upload</button>
                    </div>

                </div>
            </form>
        </div>
</div>
</code>```

Controller :

```<code>public function uploadID(Request $request){
    $request->validate([
        'id_upload' => 'required|mimes:jpeg,png,jpg,gif,svg|max:2048',
    ]);

    $file = $request->file('id_upload');

    if ($path = $request->file('id_upload')->storePublicly('images/user-documents', 's3'))
    {
        $request->user()->documents()->create([
            'name' => $request->doc_name,
            'path' => Storage::url($path),
            'bytes' => $file->getSize()
        ]);

        $message = 'You have successfully upload image.';
        $type = 'success';
    }
    else
    {
        $message = 'Sorry - something went wrong with the file upload';
        $type = 'warning';
    }

    return redirect()->back()
        ->with('message', $message)
        ->with('message-type', $type);
}
</code>```

Body:
I'm trying to make a profile page with the ability to upload different documents. At the moment I have 3 different modals where the user can upload 3 different types of documents. I want to make this process as effective as possible so I was thinking of naming the 3 documents a specific name such as UserCV and then accessing the documents on the front end using this name and the user`s ID. But I was just wondering what the best way for me to pass this name value from my modal to my controller. As I was planning on making an input field that can't be edited on the modal but feel like there must be a better way.

The current way I'm doing it :

Modal :

Upload Id

            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>

            <form action="{{ route('id.upload.post') }}" method="POST" enctype="multipart/form-data">
            @csrf

                        <input type="text" id="document_name" name="doc_name" value="UserIDCard" readonly>
                        <input type="file" class="form-control" id="idInput" name="id_upload">
                        <button type="submit" class="btn btn-secondary input-group-text" for="idInput">Upload</button>

            </form>

Controller :

public function uploadID(Request $request){
    $request->validate([
        'id_upload' => 'required|mimes:jpeg,png,jpg,gif,svg|max:2048',
    ]);

    $file = $request->file('id_upload');

    if ($path = $request->file('id_upload')->storePublicly('images/user-documents', 's3'))
    {
        $request->user()->documents()->create([
            'name' => $request->doc_name,
            'path' => Storage::url($path),
            'bytes' => $file->getSize()
        ]);

        $message = 'You have successfully upload image.';
        $type = 'success';
    }
    else
    {
        $message = 'Sorry - something went wrong with the file upload';
        $type = 'warning';
    }

    return redirect()->back()
        ->with('message', $message)
        ->with('message-type', $type);
}


问:
how to implement onScroll PiP enable in react native
i am trying to  auto enable PiP onScroll or click on home button
how to implement onScroll PiP enable in react native please guide me.</p>


问:
Security issue after migrating DataTransformer to StateProvider

API Platform 2.6

I have the following operation in my current code, using a DataTransformer + a Symfony voter for security:

#[ApiResource(
    itemOperations: [
        'contents' => [
            'security' => 'is_granted("FRIDGE_READ", object)',
            'method' => 'get',
            'path' => '/fridges/{id}/contents',
            'output' => FridgeContents::class,
        ],
    ],
)]
class Fridge {}
```
<pre class="lang-php prettyprint-override"><code>class FridgeContentsOutputDataTransformer implements DataTransformerInterface
{
    public function supportsTransformation($data, string $to, array $context = []): bool
    {
        return FridgeContents::class === $to && $data instanceof Fridge;
    }

    public function transform($fridge, string $to, array $context = []): FridgeContents
    {
        // ...transform data...

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

The voter responsible for the FRIDGE_READ attribute receives the Fridge instance as subject, allowing me to only grant access to users who own that fridge.

API Platform 2.7

Now that DataTransformers are being deprecated, I refactored it to a StateProvider, as stated in the doc:

#[ApiResource(
    operations: [
        new Get(
            uriTemplate: '/fridges/{id}/contents',
            security: 'is_granted("FRIDGE_READ", object)',
            output: FridgeContents::class,
            provider: FridgeContentsProvider::class,
        ),
    ],
)]
class Fridge {}
```
<pre class="lang-php prettyprint-override"><code>class FridgeContentsProvider implements ProviderInterface
{
    public function __construct(
        private readonly ProviderInterface $itemProvider,
    ) {
    }

    public function provide(Operation $operation, array $uriVariables = [], array $context = []): FridgeContents
    {
        /** @var Fridge $fridge */
        $fridge = $this->itemProvider->provide($operation, $uriVariables, $context);

        // ...transform data...

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

I'm not sure if this is intended, but my voter is no longer receiving the Fridge instance here, but the output FridgeContentsItem object.

Is it a bug, or am I doing something wrong?

Possible workaround

I moved the security check to my StateProvider, but now my security is scattered between resources & providers...

    public function provide(Operation $operation, array $uriVariables = [], array $context = []): FridgeContents
    {
        /** @var Fridge $fridge */
        $fridge = $this->itemProvider->provide($operation, $uriVariables, $context);

        if (!$this->security->isGranted('FRIDGE_READ', $fridge)) {
            throw new AccessDeniedHttpException();
        }
```

Thanks in advance for any input.

Body:
API Platform 2.6

I have the following operation in my current code, using a DataTransformer + a Symfony voter for security:

#[ApiResource(
    itemOperations: [
        'contents' => [
            'security' => 'is_granted("FRIDGE_READ", object)',
            'method' => 'get',
            'path' => '/fridges/{id}/contents',
            'output' => FridgeContents::class,
        ],
    ],
)]
class Fridge {}

class FridgeContentsOutputDataTransformer implements DataTransformerInterface
{
    public function supportsTransformation($data, string $to, array $context = []): bool
    {
        return FridgeContents::class === $to && $data instanceof Fridge;
    }

    public function transform($fridge, string $to, array $context = []): FridgeContents
    {
        // ...transform data...

        return $fridgeContents;
    }
}

The voter responsible for the FRIDGE_READ attribute receives the Fridge instance as subject, allowing me to only grant access to users who own that fridge.

API Platform 2.7

Now that DataTransformers are being deprecated, I refactored it to a StateProvider, as stated in the doc:

#[ApiResource(
    operations: [
        new Get(
            uriTemplate: '/fridges/{id}/contents',
            security: 'is_granted("FRIDGE_READ", object)',
            output: FridgeContents::class,
            provider: FridgeContentsProvider::class,
        ),
    ],
)]
class Fridge {}

class FridgeContentsProvider implements ProviderInterface
{
    public function __construct(
        private readonly ProviderInterface $itemProvider,
    ) {
    }

    public function provide(Operation $operation, array $uriVariables = [], array $context = []): FridgeContents
    {
        /** @var Fridge $fridge */
        $fridge = $this->itemProvider->provide($operation, $uriVariables, $context);

        // ...transform data...

        return $fridgeContents;
    }
}

I'm not sure if this is intended, but my voter is no longer receiving the Fridge instance here, but the output FridgeContentsItem object.

Is it a bug, or am I doing something wrong?

Possible workaround

I moved the security check to my StateProvider, but now my security is scattered between resources & providers...

    public function provide(Operation $operation, array $uriVariables = [], array $context = []): FridgeContents
    {
        /** @var Fridge $fridge */
        $fridge = $this->itemProvider->provide($operation, $uriVariables, $context);

        if (!$this->security->isGranted('FRIDGE_READ', $fridge)) {
            throw new AccessDeniedHttpException();
        }

Thanks in advance for any input.


问:
Why am I getting a 403 forbidden error on Mac Monterey with PHP 8.0?
On this Mac I have PHP version 7.4 installed, and my locally hosted sites work fine with it. I installed PHP 8.0, and when I switch to it, I get a 403 error when accessing my sites. Switching back to 7.4, they work fine again. Does anyone know what could be causing this error?

Mac Monterey version 12.5.1

Site configuration example in my httpd-vhosts.conf file:

```<code><VirtualHost *:80>
  DocumentRoot "/Users/my.name/Sites/mysite"
  ServerName mysite.loc
  <Directory />
      Options FollowSymLinks
      AllowOverride all
  </Directory>
  <Directory /Users/my.name/Sites/>
      Options FollowSymLinks
      AllowOverride all
      Order allow,deny
      allow from all
</Directory>
</code>```

In httpd.conf I have the following line:

```<code>LoadModule php_module /usr/local/opt/php@8.0/lib/httpd/modules/libphp.so "Certificate Name"
</code>```

Running the command "sudo apachectl configtest" gives the following result:

```<code>Allowing module loading process to continue for module at /usr/local/opt/php@8.0/lib/httpd/modules/libphp.so because module signature matches authority "Certificate Name" specified in LoadModule directive
AH00112: Warning: DocumentRoot [/usr/docs/dummy-host.example.com] does not exist
AH00112: Warning: DocumentRoot [/usr/docs/dummy-host2.example.com] does not exist
Syntax OK
</code>```

Thanks for any help in advance.

Body:
On this Mac I have PHP version 7.4 installed, and my locally hosted sites work fine with it. I installed PHP 8.0, and when I switch to it, I get a 403 error when accessing my sites. Switching back to 7.4, they work fine again. Does anyone know what could be causing this error?

Mac Monterey version 12.5.1

Site configuration example in my httpd-vhosts.conf file:

<VirtualHost *:80>
  DocumentRoot "/Users/my.name/Sites/mysite"
  ServerName mysite.loc
  <Directory />
      Options FollowSymLinks
      AllowOverride all
  </Directory>
  <Directory /Users/my.name/Sites/>
      Options FollowSymLinks
      AllowOverride all
      Order allow,deny
      allow from all
</Directory>

In httpd.conf I have the following line:

LoadModule php_module /usr/local/opt/php@8.0/lib/httpd/modules/libphp.so "Certificate Name"

Running the command "sudo apachectl configtest" gives the following result:

Allowing module loading process to continue for module at /usr/local/opt/php@8.0/lib/httpd/modules/libphp.so because module signature matches authority "Certificate Name" specified in LoadModule directive
AH00112: Warning: DocumentRoot [/usr/docs/dummy-host.example.com] does not exist
AH00112: Warning: DocumentRoot [/usr/docs/dummy-host2.example.com] does not exist
Syntax OK

Thanks for any help in advance.


问:
Problema with python (pip) in ParrotOS
When I try to run programs that require pip on my parrot and it gives me the following error: and i cant understand what happens this and how to solved.

```<code>return _run_code(code, main_globals, None,
  File "/usr/lib/python3.9/runpy.py", line 87, in _run_code
    exec(code, run_globals)
  File "/usr/lib/python3/dist-packages/pip/__main__.py", line 23, in <module>
    from pip._internal.cli.main import main as _main  # isort:skip # noqa
  File "/usr/lib/python3/dist-packages/pip/_internal/cli/main.py", line 10, in <module>
    from pip._internal.cli.autocompletion import autocomplete
  File "/usr/lib/python3/dist-packages/pip/_internal/cli/autocompletion.py", line 9, in <module>
    from pip._internal.cli.main_parser import create_main_parser
  File "/usr/lib/python3/dist-packages/pip/_internal/cli/main_parser.py", line 7, in <module>
    from pip._internal.cli import cmdoptions
  File "/usr/lib/python3/dist-packages/pip/_internal/cli/cmdoptions.py", line 23, in <module>
    from pip._vendor.packaging.utils import canonicalize_name
  File "/usr/lib/python3/dist-packages/pip/_vendor/__init__.py", line 94, in <module>
    vendored("requests.packages.urllib3.contrib.pyopenssl")
  File "/usr/lib/python3/dist-packages/pip/_vendor/__init__.py", line 36, in vendored
    __import__(modulename, globals(), locals(), level=0)
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 664, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 627, in _load_backward_compatible
  File "<frozen zipimport>", line 259, in load_module
  File "/usr/share/python-wheels/urllib3-1.26.5-py2.py3-none-any.whl/urllib3/contrib/pyopenssl.py", line 50, in <module>
  File "/usr/lib/python3/dist-packages/OpenSSL/__init__.py", line 8, in <module>
    from OpenSSL import crypto, SSL
  File "/usr/lib/python3/dist-packages/OpenSSL/crypto.py", line 1556, in <module>
    class X509StoreFlags(object):
  File "/usr/lib/python3/dist-packages/OpenSSL/crypto.py", line 1577, in X509StoreFlags
    CB_ISSUER_CHECK = _lib.X509_V_FLAG_CB_ISSUER_CHECK
AttributeError: module 'lib' has no attribute 'X509_V_FLAG_CB_ISSUER_CHECK'
</code>```

i try this:

```<code>sudo apt-get remove python3-pip
sudo apt-get install python3-pip
sudo pip3 install pip --upgrade
sudo pip install pyopenssl --upgrade
</code>```

And nothing gives me result

Title: Problema with python (pip) in ParrotOS

Body:
When I try to run programs that require pip on my parrot and it gives me the following error: and i cant understand what happens this and how to solved.

return _run_code(code, main_globals, None,
  File "/usr/lib/python3.9/runpy.py", line 87, in _run_code
    exec(code, run_globals)
  File "/usr/lib/python3/dist-packages/pip/__main__.py", line 23, in <module>
    from pip._internal.cli.main import main as _main  # isort:skip # noqa
  File "/usr/lib/python3/dist-packages/pip/_internal/cli/main.py", line 10, in <module>
    from pip._internal.cli.autocompletion import autocomplete
  File "/usr/lib/python3/dist-packages/pip/_internal/cli/autocompletion.py", line 9, in <module>
    from pip._internal.cli.main_parser import create_main_parser
  File "/usr/lib/python3/dist-packages/pip/_internal/cli/main_parser.py", line 7, in <module>
    from pip._internal.cli import cmdoptions
  File "/usr/lib/python3/dist-packages/pip/_internal/cli/cmdoptions.py", line 23, in <module>
    from pip._vendor.packaging.utils import canonicalize_name
  File "/usr/lib/python3/dist-packages/pip/_vendor/__init__.py", line 94, in <module>
    vendored("requests.packages.urllib3.contrib.pyopenssl")
  File "/usr/lib/python3/dist-packages/pip/_vendor/__init__.py", line 36, in vendored
    __import__(modulename, globals(), locals(), level=0)
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 664, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 627, in _load_backward_compatible
  File "<frozen zipimport>", line 259, in load_module
  File "/usr/share/python-wheels/urllib3-1.26.5-py2.py3-none-any.whl/urllib3/contrib/pyopenssl.py", line 50, in <module>
  File "/usr/lib/python3/dist-packages/OpenSSL/__init__.py", line 8, in <module>
    from OpenSSL import crypto, SSL
  File "/usr/lib/python3/dist-packages/OpenSSL/crypto.py", line 1556, in <module>
    class X509StoreFlags(object):
  File "/usr/lib/python3/dist-packages/OpenSSL/crypto.py", line 1577, in X509StoreFlags
    CB_ISSUER_CHECK = _lib.X509_V_FLAG_CB_ISSUER_CHECK
AttributeError: module 'lib' has no attribute 'X509_V_FLAG_CB_ISSUER_CHECK'

i try this:

sudo apt-get remove python3-pip
sudo apt-get install python3-pip
sudo pip3 install pip --upgrade
sudo pip install pyopenssl --upgrade

And nothing gives me result


问:
React.js Vite TS app returns 404 when refreshed on route (only on the host not on the local) i tested it on render and vercel
whenever i refresh page except the home page it's gave me 404 only for host
i'm using vite +reactjs +ts

in vite config file i did that to do rewrite but it's not working

```<code>const rewriteSlashToIndexHtml = () => {
  return {
    name: 'rewrite-slash-to-index-html',
    apply: 'serve',
    enforce: 'post',
    configureServer(server) {
      // rewrite / as index.html
      server.middlewares.use('/', (req, _, next) => {
        if (req.url === '/') {
          req.url = '/index.html'
        }
        next()
      })
    },
  }
}
</code>```

and used it here

```<code>const defaultConfig: DefaultConfig = {
  plugins: [
    react({ include: "**/*.tsx", }),
    rewriteSlashToIndexHtml()
  ],
  server: {
    proxy: {
      '/api': {
        target: 'https://tame-lime-rooster-tie.cyclic.app',
        changeOrigin: true,
        configure: (proxy, options) => {
          proxy.on('proxyReq', (proxyReq, req, res) => {
            if (!req.headers.cookie) {
              return;
            }
            console.log('req.headers.cookie', req.headers.cookie)
            proxyReq.setHeader('cookie', req.headers.cookie);
          });
        },
        secure: false
      }
    }
  }
}
</code>```

but it didn't help me

Body:
whenever i refresh page except the home page it's gave me 404 only for host
i'm using vite +reactjs +ts

in vite config file i did that to do rewrite but it's not working

const rewriteSlashToIndexHtml = () => {
  return {
    name: 'rewrite-slash-to-index-html',
    apply: 'serve',
    enforce: 'post',
    configureServer(server) {
      // rewrite / as index.html
      server.middlewares.use('/', (req, _, next) => {
        if (req.url === '/') {
          req.url = '/index.html'
        }
        next()
      })
    },
  }
}

and used it here

const defaultConfig: DefaultConfig = {
  plugins: [
    react({ include: "**/*.tsx", }),
    rewriteSlashToIndexHtml()
  ],
  server: {
    proxy: {
      '/api': {
        target: 'https://tame-lime-rooster-tie.cyclic.app',
        changeOrigin: true,
        configure: (proxy, options) => {
          proxy.on('proxyReq', (proxyReq, req, res) => {
            if (!req.headers.cookie) {
              return;
            }
            console.log('req.headers.cookie', req.headers.cookie)
            proxyReq.setHeader('cookie', req.headers.cookie);
          });
        },
        secure: false
      }
    }
  }
}

but it didn't help me


问:
How to watch deleted database items in Notion API?
It's pretty easy to fecth and watch created nor updated items of a Notion Database.
But I can't see any way to watch deleted items of a database.

The fetch query doesn't return them anymore, and it's look there is no filter to do so.

How can we manage to watch deleted items ?
Thanks !


问:
Arduino - Sending a GET request to a server, get 200 OK but no additional response
I'm working on an Arduino project (Arduino Mega 2560). I'm using the library uartWIFI, and I can successfully send a GET request to my server. The page I'm connecting to is supposed to echo "test" when you GET it, but the output is empty.

Here is my HTTP-connection code in the Arduino:

void httpRequest() {
  // if there's a successful connection:
  if (wifi.ipConfig(TCP,server, 80))
  {

    Serial.println("-----------");
    DebugSerial.println("connecting...");

    // send the HTTP PUT request:
    // We now create a URI for the request
    String url = "/a.php?";
    url += "name=test";
    Serial.print("Requesting URL: ");
    Serial.println(url);

    wifi.Send("GET " + url + " HTTP/1.0\r\n\r\n");
    // note the time that the connection was made:
    lastConnectionTime = millis();
  }
  else
  {
    // if you couldn't make a connection:
    DebugSerial.println("connection failed");
    DebugSerial.println("disconnecting.");
    wifi.closeMux();
  }
}
```
<p>The output I'm expecting is "test", but here is the response I get back, as printed to the serial monitor.
Response</p>
<p>When I curl the URL, I get the expected response.</p>
<p>EDIT: Added the rest of the code, when the function i posted earlier gets called</p>
<pre class="lang-cpp prettyprint-override"><code>void loop()
{

  char message[320];
   // if you're not connected, and ten seconds have passed since
  // your last connection, then connect again and send data:
  if((millis() - lastConnectionTime > postingInterval)) {
    httpRequest();
  }
  // if there's incoming data from the net connection.
  // send it out the serial port.  This is for debugging
  // purposes only:
  delay(1000);
  if(wifi.ReceiveMessage(message))
  {
      Serial.println("Receive: ");
      DebugSerial.println(message);
  }

  delay(100);

}
</code>```

Body:
I'm working on an Arduino project (Arduino Mega 2560). I'm using the library uartWIFI, and I can successfully send a GET request to my server. The page I'm connecting to is supposed to echo "test" when you GET it, but the output is empty.

Here is my HTTP-connection code in the Arduino:

void httpRequest() {
  // if there's a successful connection:
  if (wifi.ipConfig(TCP,server, 80))
  {

    Serial.println("-----------");
    DebugSerial.println("connecting...");

    // send the HTTP PUT request:
    // We now create a URI for the request
    String url = "/a.php?";
    url += "name=test";
    Serial.print("Requesting URL: ");
    Serial.println(url);

    wifi.Send("GET " + url + " HTTP/1.0\r\n\r\n");
    // note the time that the connection was made:
    lastConnectionTime = millis();
  }
  else
  {
    // if you couldn't make a connection:
    DebugSerial.println("connection failed");
    DebugSerial.println("disconnecting.");
    wifi.closeMux();
  }
}

The output I'm expecting is "test", but here is the response I get back, as printed to the serial monitor.
Response

When I curl the URL, I get the expected response.

EDIT: Added the rest of the code, when the function i posted earlier gets called

void loop()
{

  char message[320];
   // if you're not connected, and ten seconds have passed since
  // your last connection, then connect again and send data:
  if((millis() - lastConnectionTime > postingInterval)) {
    httpRequest();
  }
  // if there's incoming data from the net connection.
  // send it out the serial port.  This is for debugging
  // purposes only:
  delay(1000);
  if(wifi.ReceiveMessage(message))
  {
      Serial.println("Receive: ");
      DebugSerial.println(message);
  }

  delay(100);

}


问:
Importing/exporting modules issues after updating Angular from 12 to 15, and JS version from ES2015 to ES2022
I'm running out of ideas how to solve problems with importing classes/interfaces/services.

Basically I'm gettin dozens of warning like this after upgrade to Angular 15 from 12 (with the guide):

```<code>WARNING in ./libs/data-models/src/lib/data-models.ts 87:0-1770
export 'ILights' (reexported as 'ILights') was not found in './models/entities/lights_ifc' (module has no exports)
</code>```

And ILights is nothing more than just a simple interface:

```<code>export interface ILights {
  pk: number;
  timeUpdated: Date;
  lightId: string;
  groupName: string | null;
  type: LightsType;
  state: LightsState;
}
</code>```

These are warnings but I also got this kind of error:

```<code>C:\Users\Dominik\Desktop\Work\web_gui\dist\apps\api\main.js:843
/* harmony export */   "AlarmsRepository": () => (/* binding */ AlarmsRepository)
                                                                ^
ReferenceError: Cannot access 'AlarmsRepository' before initialization
    at Module.AlarmsRepository (C:\Users\Dominik\Desktop\Work\web_gui\dist\apps\api\main.js:843:65)
    at Object../apps/api/src/alarms/alarms.service.ts (C:\Users\Dominik\Desktop\Work\web_gui\dist\apps\api\webpack:\web-app-random-name\apps\api\src\alarms\alarms.service.ts:48:83)
    at __webpack_require__ (C:\Users\Dominik\Desktop\Work\web_gui\dist\apps\api\webpack:\web-app-random-name\webpack\bootstrap:19:1)
    at Object../apps/api/src/gateway/message.queue.ts (C:\Users\Dominik\Desktop\Work\web_gui\dist\apps\api\main.js:7216:84)
    at __webpack_require__ (C:\Users\Dominik\Desktop\Work\web_gui\dist\apps\api\webpack:\web-app-random-name\webpack\bootstrap:19:1)
    at Object../apps/api/src/rabbitmq/rabbitmqFpi.provider.ts (C:\Users\Dominik\Desktop\Work\web_gui\dist\apps\api\main.js:11803:84)
    at __webpack_require__ (C:\Users\Dominik\Desktop\Work\web_gui\dist\apps\api\webpack:\web-app-random-name\webpack\bootstrap:19:1)
    at Object../apps/api/src/alarms/alarms.repository.ts (C:\Users\Dominik\Desktop\Work\web_gui\dist\apps\api\main.js:849:92)
    at __webpack_require__ (C:\Users\Dominik\Desktop\Work\web_gui\dist\apps\api\webpack:\web-app-random-name\webpack\bootstrap:19:1)
    at Object../apps/api/src/airplanes/airplanes.repository.ts (C:\Users\Dominik\Desktop\Work\web_gui\dist\apps\api\main.js:291:87)
No errors found.

</code>```

and this is the line from the logs, it's pointing to constructor element that it looks like this because previously we had circural dependecies issues:

```<code>@Inject(forwardRef(() => AlarmsRepository)) private readonly alarmRepository: AlarmsRepository
</code>```

Maybe I'm using wrong ES versions but I'm not sure about it.. More details here:

Angular:

```<code>@angular-devkit/architect          0.1500.4
@angular-devkit/build-angular      15.0.4
@angular-devkit/core               15.0.4
@angular-devkit/schematics         15.0.4
@angular/cdk                       15.0.3
@angular/material                  15.0.3
@angular/material-moment-adapter   15.0.3
@schematics/angular                15.0.4
rxjs                               7.8.0
typescript                         4.8.4
webpack                            5.75.0
</code>```

tsconfig.json:

```<code>{
  "compileOnSave": false,
  "compilerOptions": {
    "rootDir": ".",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "importHelpers": true,
    "target": "ES2022",
    "module": "ES2022",
    "typeRoots": ["node_modules/@types"],
    "lib": ["ES2021", "dom"],
    "skipLibCheck": true,
    "skipDefaultLibCheck": true,
    "baseUrl": ".",
    "strictNullChecks": true,
    "allowSyntheticDefaultImports": true,
    "downlevelIteration": true,
    "useDefineForClassFields": false,
    "paths": {
      //paths are here
    }
  },
  "exclude": ["node_modules", "tmp"]
}
</code>```

and before update it was:

```<code>    "target": "es2015",
    "module": "es2020",
    "lib": ["es2017", "dom"],
</code>```

Do you have any ideas or tips that could help me with solving this errors?

Body:
I'm running out of ideas how to solve problems with importing classes/interfaces/services.

Basically I'm gettin dozens of warning like this after upgrade to Angular 15 from 12 (with the guide):

WARNING in ./libs/data-models/src/lib/data-models.ts 87:0-1770
export 'ILights' (reexported as 'ILights') was not found in './models/entities/lights_ifc' (module has no exports)

And ILights is nothing more than just a simple interface:

export interface ILights {
  pk: number;
  timeUpdated: Date;
  lightId: string;
  groupName: string | null;
  type: LightsType;
  state: LightsState;
}

These are warnings but I also got this kind of error:

C:\Users\Dominik\Desktop\Work\web_gui\dist\apps\api\main.js:843
/* harmony export */   "AlarmsRepository": () => (/* binding */ AlarmsRepository)
                                                                ^
ReferenceError: Cannot access 'AlarmsRepository' before initialization
    at Module.AlarmsRepository (C:\Users\Dominik\Desktop\Work\web_gui\dist\apps\api\main.js:843:65)
    at Object../apps/api/src/alarms/alarms.service.ts (C:\Users\Dominik\Desktop\Work\web_gui\dist\apps\api\webpack:\web-app-random-name\apps\api\src\alarms\alarms.service.ts:48:83)
    at __webpack_require__ (C:\Users\Dominik\Desktop\Work\web_gui\dist\apps\api\webpack:\web-app-random-name\webpack\bootstrap:19:1)
    at Object../apps/api/src/gateway/message.queue.ts (C:\Users\Dominik\Desktop\Work\web_gui\dist\apps\api\main.js:7216:84)
    at __webpack_require__ (C:\Users\Dominik\Desktop\Work\web_gui\dist\apps\api\webpack:\web-app-random-name\webpack\bootstrap:19:1)
    at Object../apps/api/src/rabbitmq/rabbitmqFpi.provider.ts (C:\Users\Dominik\Desktop\Work\web_gui\dist\apps\api\main.js:11803:84)
    at __webpack_require__ (C:\Users\Dominik\Desktop\Work\web_gui\dist\apps\api\webpack:\web-app-random-name\webpack\bootstrap:19:1)
    at Object../apps/api/src/alarms/alarms.repository.ts (C:\Users\Dominik\Desktop\Work\web_gui\dist\apps\api\main.js:849:92)
    at __webpack_require__ (C:\Users\Dominik\Desktop\Work\web_gui\dist\apps\api\webpack:\web-app-random-name\webpack\bootstrap:19:1)
    at Object../apps/api/src/airplanes/airplanes.repository.ts (C:\Users\Dominik\Desktop\Work\web_gui\dist\apps\api\main.js:291:87)
No errors found.

and this is the line from the logs, it's pointing to constructor element that it looks like this because previously we had circural dependecies issues:

@Inject(forwardRef(() => AlarmsRepository)) private readonly alarmRepository: AlarmsRepository

Maybe I'm using wrong ES versions but I'm not sure about it.. More details here:

Angular:

@angular-devkit/architect          0.1500.4
@angular-devkit/build-angular      15.0.4
@angular-devkit/core               15.0.4
@angular-devkit/schematics         15.0.4
@angular/cdk                       15.0.3
@angular/material                  15.0.3
@angular/material-moment-adapter   15.0.3
@schematics/angular                15.0.4
rxjs                               7.8.0
typescript                         4.8.4
webpack                            5.75.0

tsconfig.json:

{
  "compileOnSave": false,
  "compilerOptions": {
    "rootDir": ".",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "importHelpers": true,
    "target": "ES2022",
    "module": "ES2022",
    "typeRoots": ["node_modules/@types"],
    "lib": ["ES2021", "dom"],
    "skipLibCheck": true,
    "skipDefaultLibCheck": true,
    "baseUrl": ".",
    "strictNullChecks": true,
    "allowSyntheticDefaultImports": true,
    "downlevelIteration": true,
    "useDefineForClassFields": false,
    "paths": {
      //paths are here
    }
  },
  "exclude": ["node_modules", "tmp"]
}

and before update it was:

    "target": "es2015",
    "module": "es2020",
    "lib": ["es2017", "dom"],

Do you have any ideas or tips that could help me with solving this errors?