问:
How to customize Laravel default notifications architecture along with custom columns in notifications table migration without repeating provided code
As Laravel shipped with a default notification module. It provides us following notifications_table.

id
type
notifiable_type
notifiable_id
data
read_at
created_at
updated_at

fd71b94e-a0fc-42d5-9cfc-d0019cd83468
Notifications\PushNotification
User
23
{"user_name":"Bak thonas","texts":"testing"}
null
2023-01-09 12:43:02
2023-01-09 12:43:02

I added some custom columns by overriding the notification-table migration according to my requirement. After adding these columns notifications_table looks something like that,

id
type
notifiable_type
notifiable_id
relation_type
relation_id
subject_en
subject_ar
message_en
message_ar
data
read_at
created_at
updated_at

fd71b94e-a0fc-42d5-9cfc-d0019cd83468
Notifications\PushNotification
User
23
B
22
Welcome
مرحبا
Welcome to platform!
مرحبا بكم في Platform!
{"user_name":"Bak thonas","texts":"testing"}
null
2023-01-09 12:43:02
2023-01-09 12:43:02

Note: I want to customize the default database channel shipped with Laravel. so this way I would just need to customize that data-building structure before storing it in a database instead repeating everything that is already provided in Laravel by default


来源: stackexchange

问:
StoreReview: Native rating modal doesn't display on all users devices
Store Review docs: https://docs.expo.dev/versions/latest/sdk/storereview/

Hello, we have a problem with the opening of the app review modal with Expo, that only a minor part of users already well selected seem to see and go through the end of rating process. Many click to see it voluntarily and only a minor part actually publish a review.

We have an application with an app review flow customized to optimize good reviews by targeting specific users already using our app regularly.
Before showing the native app rating modal, we display a previous modal asking if the user want to review us or not. And this previous modal is displayed at the end of a flow of usage of our app, so not disturbing the user up front when he just opened the app.

But actually, we go from 50 logs of clicks to open the native rating modal to 8 review added to our app store / play store in total.

Our app already only supports SDKs recent enough to support native rating modal.

Would you know what could be failing that much ?

Here is our code to launch the native rating modal via events coming from our web app in our website (using a webview as a PWA)

```<code>if (message.nativeEvent.data.startsWith('request-review')) {
    StoreReview.hasAction().then((hasAction) => {
        if (hasAction) {
            StoreReview.requestReview().then((res) => {
                console.log(res)
            }).catch((error) => {
                console.log(error);
            });
        } else {
            const reviewUrl = Platform.OS === 'ios' ? Constants.manifest.extra.ios_review_url : Constants.manifest.extra.android_review_url;
            Linking.openURL(reviewUrl);
        }
    });
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Store Review docs: https://docs.expo.dev/versions/latest/sdk/storereview/

Hello, we have a problem with the opening of the app review modal with Expo, that only a minor part of users already well selected seem to see and go through the end of rating process. Many click to see it voluntarily and only a minor part actually publish a review.

We have an application with an app review flow customized to optimize good reviews by targeting specific users already using our app regularly.
Before showing the native app rating modal, we display a previous modal asking if the user want to review us or not. And this previous modal is displayed at the end of a flow of usage of our app, so not disturbing the user up front when he just opened the app.

But actually, we go from 50 logs of clicks to open the native rating modal to 8 review added to our app store / play store in total.

Our app already only supports SDKs recent enough to support native rating modal.

Would you know what could be failing that much ?

Here is our code to launch the native rating modal via events coming from our web app in our website (using a webview as a PWA)

if (message.nativeEvent.data.startsWith('request-review')) {
    StoreReview.hasAction().then((hasAction) => {
        if (hasAction) {
            StoreReview.requestReview().then((res) => {
                console.log(res)
            }).catch((error) => {
                console.log(error);
            });
        } else {
            const reviewUrl = Platform.OS === 'ios' ? Constants.manifest.extra.ios_review_url : Constants.manifest.extra.android_review_url;
            Linking.openURL(reviewUrl);
        }
    });
}


问:
chart.js function delay not affect my graph
I am asking you because I created a chart with chart.js and I would like to assign it a delay before it appears, after reading the docs and different forums I get the following code which unfortunately does not work. Thanking you in advance for your help!

```<code>var cts = document.getElementById('myDonutChart').getContext('2d');
var myDonutChart = new Chart(cts, {
     type: 'doughnut',
     data: {
           labels:[
                   //requete sql
                   'Red',
                   'Blue',
                   'Yellow'
                  ],

            datasets: [{
            label: '# of Votes',
                            data: [
                            //requete sql
                            12,
                            19,
                            3,
                            5,
                            2,
                            3
                            ],
                            backgroundColor: [
                            'rgba(255, 99, 132, 0.2)',
                            'rgba(54, 162, 235, 0.2)',
                            'rgba(255, 206, 86, 0.2)',
                            'rgba(75, 192, 192, 0.2)',
                            'rgba(153, 102, 255, 0.2)',
                            'rgba(255, 159, 64, 0.2)'
                            ],
                            borderColor: [
                            'rgba(255, 99, 132, 1)',
                            'rgba(54, 162, 235, 1)',
                            'rgba(255, 206, 86, 1)',
                            'rgba(75, 192, 192, 1)',
                            'rgba(153, 102, 255, 1)',
                            'rgba(255, 159, 64, 1)'
                            ],
                            borderWidth: 1
                        }]
                        },
                        options: {
                        legend: { display: false },
                        responsive: false,
                        maintainAspectRatio: false,
                        animation: {
                           delay: 4000
                           }
                        }
                    });
</code>```

Reading the doc gives me the result with the delay function or alone it doesn't work and the only solution I found was to add a setimout but I still wanted to find the solution to the delay problem

Body:
I am asking you because I created a chart with chart.js and I would like to assign it a delay before it appears, after reading the docs and different forums I get the following code which unfortunately does not work. Thanking you in advance for your help!

var cts = document.getElementById('myDonutChart').getContext('2d');
var myDonutChart = new Chart(cts, {
     type: 'doughnut',
     data: {
           labels:[
                   //requete sql
                   'Red',
                   'Blue',
                   'Yellow'
                  ],

            datasets: [{
            label: '# of Votes',
                            data: [
                            //requete sql
                            12,
                            19,
                            3,
                            5,
                            2,
                            3
                            ],
                            backgroundColor: [
                            'rgba(255, 99, 132, 0.2)',
                            'rgba(54, 162, 235, 0.2)',
                            'rgba(255, 206, 86, 0.2)',
                            'rgba(75, 192, 192, 0.2)',
                            'rgba(153, 102, 255, 0.2)',
                            'rgba(255, 159, 64, 0.2)'
                            ],
                            borderColor: [
                            'rgba(255, 99, 132, 1)',
                            'rgba(54, 162, 235, 1)',
                            'rgba(255, 206, 86, 1)',
                            'rgba(75, 192, 192, 1)',
                            'rgba(153, 102, 255, 1)',
                            'rgba(255, 159, 64, 1)'
                            ],
                            borderWidth: 1
                        }]
                        },
                        options: {
                        legend: { display: false },
                        responsive: false,
                        maintainAspectRatio: false,
                        animation: {
                           delay: 4000
                           }
                        }
                    });

Reading the doc gives me the result with the delay function or alone it doesn't work and the only solution I found was to add a setimout but I still wanted to find the solution to the delay problem


问:
Difference between access and import in package diagram software
I do have a question about the differences between import and access in the package diagram and how to use them, how to know which package is accessible/visible to x package like in the figure below, I would glad if someone answers the question in the provided image.

I dunno the difference between both import and access, therefore, I haven't tried it yet.


问:
How to use git-filter-repo to remove change on an archive file, after a certain commit, and update every branchs and tags
I would like to rewrite git history using git-filter-repo to remove a file change, because it has become too large. I would like to keep the original file, so do it only after a certain commit, and update every branchs and tags. I've been trying:

```<code>$ git filter-repo --path <path_to_file> --invert-paths --refs <commit_hash>..HEAD
</code>```

but it rewrite (obviously) only the current branch.

What is the right way to do it ?

Body:
I would like to rewrite git history using git-filter-repo to remove a file change, because it has become too large. I would like to keep the original file, so do it only after a certain commit, and update every branchs and tags. I've been trying:

$ git filter-repo --path <path_to_file> --invert-paths --refs <commit_hash>..HEAD

but it rewrite (obviously) only the current branch.

What is the right way to do it ?


问:
NuxtJS 2 + Vite + @nuxtjs/i18n error "does not provide an export named 'hasProtocol"
I have a problem with the @nuxtjs/i18n package when I want to use it with nuxt2 + vite. I get the error shown below when activating the project.

```<code>Uncaught SyntaxError: The requested module '/node_modules/@nuxtjs/i18n/node_modules/ufo/dist/index.cjs?import' does not provide an export named 'hasProtocol' (at plugin.utils.js:2:10)
</code>```

nuxt.config.js

```<code>modules: [
    '@nuxtjs/axios',
    '@nuxtjs/style-resources',
    '@nuxtjs/i18n'
  ],
  i18n: {
    locales: [
      {
        name: 'Polish',
        code: 'pl',
        iso: 'pl-PL',
        file: 'pl.json'
      },
      {
        name: 'English',
        code: 'en',
        iso: 'en-US',
        file: 'en.json'
      }
    ],
    langDir: 'locales/',
    defaultLocale: 'en'

  },
</code>```

package.json

```<code>{
  "name": "operator",
  "version": "1.0.0",
  "private": true,
  "scripts": {
    "dev": "nuxt",
    "build": "nuxt build",
    "start": "nuxt start",
    "generate": "nuxt generate",
    "lint:js": "eslint --ext \".js,.vue\" --ignore-path .gitignore .",
    "lint": "yarn lint:js",
    "lintfix": "yarn lint:js --fix"
  },
  "dependencies": {
    "@braid/vue-formulate": "^2.5.3",
    "@nuxtjs/axios": "^5.13.6",
    "@nuxtjs/i18n": "^7.3.1",
    "@nuxtjs/recaptcha": "^1.1.1",
    "core-js": "^3.25.3",
    "nuxt": "^2.15.8",
    "sass": "^1.57.1",
    "ufo": "^1.0.1",
    "vue": "^2.7.10",
    "vue-server-renderer": "^2.7.10",
    "vue-template-compiler": "^2.7.10"
  },
  "devDependencies": {
    "@babel/eslint-parser": "^7.19.1",
    "@nuxtjs/eslint-config": "^11.0.0",
    "@nuxtjs/eslint-module": "^3.1.0",
    "@nuxtjs/style-resources": "^1.2.1",
    "eslint": "^8.24.0",
    "eslint-plugin-nuxt": "^4.0.0",
    "eslint-plugin-vue": "^9.5.1",
    "node-sass": "^8.0.0",
    "nuxt-vite": "^0.2.4",
    "sass-loader": "^13.2.0"
  },
  "resolutions": {
    "postcss-preset-env": "^7.0.0"
  }
}
</code>```

I will be very grateful for any hint, because I have not found a solution to my problem on the Internet

Body:
I have a problem with the @nuxtjs/i18n package when I want to use it with nuxt2 + vite. I get the error shown below when activating the project.

Uncaught SyntaxError: The requested module '/node_modules/@nuxtjs/i18n/node_modules/ufo/dist/index.cjs?import' does not provide an export named 'hasProtocol' (at plugin.utils.js:2:10)

nuxt.config.js

modules: [
    '@nuxtjs/axios',
    '@nuxtjs/style-resources',
    '@nuxtjs/i18n'
  ],
  i18n: {
    locales: [
      {
        name: 'Polish',
        code: 'pl',
        iso: 'pl-PL',
        file: 'pl.json'
      },
      {
        name: 'English',
        code: 'en',
        iso: 'en-US',
        file: 'en.json'
      }
    ],
    langDir: 'locales/',
    defaultLocale: 'en'

  },

package.json

{
  "name": "operator",
  "version": "1.0.0",
  "private": true,
  "scripts": {
    "dev": "nuxt",
    "build": "nuxt build",
    "start": "nuxt start",
    "generate": "nuxt generate",
    "lint:js": "eslint --ext \".js,.vue\" --ignore-path .gitignore .",
    "lint": "yarn lint:js",
    "lintfix": "yarn lint:js --fix"
  },
  "dependencies": {
    "@braid/vue-formulate": "^2.5.3",
    "@nuxtjs/axios": "^5.13.6",
    "@nuxtjs/i18n": "^7.3.1",
    "@nuxtjs/recaptcha": "^1.1.1",
    "core-js": "^3.25.3",
    "nuxt": "^2.15.8",
    "sass": "^1.57.1",
    "ufo": "^1.0.1",
    "vue": "^2.7.10",
    "vue-server-renderer": "^2.7.10",
    "vue-template-compiler": "^2.7.10"
  },
  "devDependencies": {
    "@babel/eslint-parser": "^7.19.1",
    "@nuxtjs/eslint-config": "^11.0.0",
    "@nuxtjs/eslint-module": "^3.1.0",
    "@nuxtjs/style-resources": "^1.2.1",
    "eslint": "^8.24.0",
    "eslint-plugin-nuxt": "^4.0.0",
    "eslint-plugin-vue": "^9.5.1",
    "node-sass": "^8.0.0",
    "nuxt-vite": "^0.2.4",
    "sass-loader": "^13.2.0"
  },
  "resolutions": {
    "postcss-preset-env": "^7.0.0"
  }
}

I will be very grateful for any hint, because I have not found a solution to my problem on the Internet


问:
ElasticSearch search relevancy
I have this 3 documents:

Marvel Sticker for Iphone 13

Marvel Sticker for Iphone 13 Pro

Marvel Sticker for Iphone 13 Pro Max

If I search "Iphone 13" y need to get only the first one instead of the 3 records, How can I achieve that?

looking on search relevancy doc

Title: ElasticSearch search relevancy


问:
Faster displaying in video pipeline in tkinter GUI
I wrote an application that, with some other functions, displays up to 3 video streams in a tkinter GUI.

The streams don't have defined resolutions, so they come with what ever resolutions they have.

With 1 cam, my display thread is 4 times faster then my capture thread. That's ok, I could sync them with events (I am open for better ideas).

But with 3 cams my display thread is 4 times slower then my capture thread and i would like to make it faster.

I don't want to spam the whole class code, so I grabbed only the image pipeline from it.

Perhaps someone knows faster methods to achieve this functionality.

Here is the rough code I am talking about:

```<code>Video Class
    #get source
    self.cap = source
    #set resolution
    self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, set_width)
    self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, set_height)
    #set buffersize
    self.cap.set(cv2.CAP_PROP_BUFFERSIZE, 0)

    self.t_capture = threading.Thread(target=self.capture)
        self.t_capture.name = "capture thread_"+str(self.order)
        self.t_capture.start()

    self.t_display = threading.Thread(target=self.display)
        self.t_display.name = "display thread_"+str(self.order)
        self.t_display.start()

    def Thread Capture #capture thread
        #counter for throughput
        gv.global_capture_counter_1 += 1
        self.ret, self.frame = self.cap.read()

    def Thread Display #display thread
        #counter for throughput
        gv.global_display_counter_1 += 1
        self.rgb_frame = cv2.cvtColor(self.frame, cv2.COLOR_BGR2RGB)
        #resizing depending on displayed videoframes, screensize and windowsize
        self.frame_resized = self.ratio_resize(image = self.rgb_frame, height=aim_height )
        #black bar behind fps text for better reading
        cv2.rectangle(self.frame_resized,(x, y0-text_height),(x+text_width,y0),text_color_bg, -1)
        #fps text
        record_frame = cv2.putText(self.frame_resized,self.FPS_Text,(x, y0),font,font_scale,font_color,font_thickness,line_type)
        #mqtt text
        record_frame2 = cv2.putText(record_frame,line,(x, y0),font_b,gv.global_mqtt_font_scale,font_color_b,font_thickness_b,line_type_b)
        self.pre_frame=Image.fromarray(record_frame2)
        self.ready_frame=ImageTk.PhotoImage(self.pre_frame)
        videolabel_1.configure(image=self.ready_frame)
        videolabel_1.image=self.ready_frame
</code>```

Body:
I wrote an application that, with some other functions, displays up to 3 video streams in a tkinter GUI.

The streams don't have defined resolutions, so they come with what ever resolutions they have.

With 1 cam, my display thread is 4 times faster then my capture thread. That's ok, I could sync them with events (I am open for better ideas).

But with 3 cams my display thread is 4 times slower then my capture thread and i would like to make it faster.

I don't want to spam the whole class code, so I grabbed only the image pipeline from it.

Perhaps someone knows faster methods to achieve this functionality.

Here is the rough code I am talking about:

Video Class
    #get source
    self.cap = source
    #set resolution
    self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, set_width)
    self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, set_height)
    #set buffersize
    self.cap.set(cv2.CAP_PROP_BUFFERSIZE, 0)

    self.t_capture = threading.Thread(target=self.capture)
        self.t_capture.name = "capture thread_"+str(self.order)
        self.t_capture.start()

    self.t_display = threading.Thread(target=self.display)
        self.t_display.name = "display thread_"+str(self.order)
        self.t_display.start()

    def Thread Capture #capture thread
        #counter for throughput
        gv.global_capture_counter_1 += 1
        self.ret, self.frame = self.cap.read()

    def Thread Display #display thread
        #counter for throughput
        gv.global_display_counter_1 += 1
        self.rgb_frame = cv2.cvtColor(self.frame, cv2.COLOR_BGR2RGB)
        #resizing depending on displayed videoframes, screensize and windowsize
        self.frame_resized = self.ratio_resize(image = self.rgb_frame, height=aim_height )
        #black bar behind fps text for better reading
        cv2.rectangle(self.frame_resized,(x, y0-text_height),(x+text_width,y0),text_color_bg, -1)
        #fps text
        record_frame = cv2.putText(self.frame_resized,self.FPS_Text,(x, y0),font,font_scale,font_color,font_thickness,line_type)
        #mqtt text
        record_frame2 = cv2.putText(record_frame,line,(x, y0),font_b,gv.global_mqtt_font_scale,font_color_b,font_thickness_b,line_type_b)
        self.pre_frame=Image.fromarray(record_frame2)
        self.ready_frame=ImageTk.PhotoImage(self.pre_frame)
        videolabel_1.configure(image=self.ready_frame)
        videolabel_1.image=self.ready_frame


问:
Python - new Process utilizing imported file and passing arguments from first file - error not given argument
What I want to achieve, is to load several things in one main file (loader.py in this example), and then run second file passing argument and run as another process.

Example:

file 1 - print_config.py:

```<code>class PrintConfig(object)
    def __init__(self, config):
        for element, value in config.items():
            print(element, value)

def main(config):
    PrintConfig(config)

</code>```

file 2 - loader.py:

```<code>from configparser import ConfigParser
from json import loads as json_loads
from multiprocessing import Process
import print_config

class Loader(object):
# IMPORTING THE CONFIG (I have it and it works fine)
    self.config = load_config()
    p = Process(target=print_config.main, args=(self.config, ))
    p.start()
</code>```

But when I do I got error:

TypeError: main() missing 1 required positional argument: 'config'

Body:
What I want to achieve, is to load several things in one main file (loader.py in this example), and then run second file passing argument and run as another process.

Example:

file 1 - print_config.py:

class PrintConfig(object)
    def __init__(self, config):
        for element, value in config.items():
            print(element, value)

def main(config):
    PrintConfig(config)

file 2 - loader.py:

from configparser import ConfigParser
from json import loads as json_loads
from multiprocessing import Process
import print_config

class Loader(object):
# IMPORTING THE CONFIG (I have it and it works fine)
    self.config = load_config()
    p = Process(target=print_config.main, args=(self.config, ))
    p.start()

But when I do I got error:

TypeError: main() missing 1 required positional argument: 'config'


问:
due to foreign key relations, oracle locks a table which will not be affected by the delete statement (on delete set null / on delete cascade)
We observed that while issuing a delete statement, oracle is locking tables which are not impacted due to the specific delete statement.

Consider 4 tables as below.

```<code>create table TABLE_A (id number(14,0) not null primary key, code varchar2(30));
create table TABLE_B (id number(14,0) not null primary key, code varchar2(30));

create table TABLE_C (id number(14,0) not null primary key, code varchar2(30), TABLE_A_id number(14,0));
create table TABLE_D (id number(14,0) not null primary key, code varchar2(30), TABLE_C_id number(14,0), TABLE_B_id number(14,0));

</code>```

Create foreign key references.

```<code>alter table TABLE_C  add constraint TABLE_C_fk1  foreign key (TABLE_A_id) references TABLE_A on delete set null;

alter table TABLE_D  add constraint TABLE_D_fk1  foreign key (TABLE_C_id) references TABLE_C on delete cascade;
alter table TABLE_D  add constraint TABLE_D_fk2  foreign key (TABLE_B_id) references TABLE_B on delete cascade;

</code>```

While deleting a record from TABLE_A as below, it will also update the TABLE_A_id column to null in TABLE_C table if the id exists in that table.
No changes expected in other tables.

```<code>delete TABLE_A where id = 1234;
</code>```

This is working as expected in terms of the data modified. But when we look at the tables which are getting locked during this transaction we observed that all 4 tables are being locked.

```<code>LOCKED_MODE                              OBJECT_NAME
---------------------------------------- --------------------------------------------------------------------------------------------------------------------------------
Row-X (SX)                               TABLE_A
Row-X (SX)                               TABLE_C
Row-X (SX)                               TABLE_B
Row-X (SX)                               TABLE_D
</code>```

used following query to fetch the details of locked objects during the transaction.

```<code>SELECT Decode(lo.locked_mode, 0, 'None',
                              1, 'Null (NULL)',
                              2, 'Row-S (SS)',
                              3, 'Row-X (SX)',
                              4, 'Share (S)',
                              5, 'S/Row-X (SSX)',
                              6, 'Exclusive (X)',
                              lo.locked_mode) locked_mode,
        o.object_name
FROM   v$locked_object lo
       JOIN dba_objects o ON o.object_id = lo.object_id
       JOIN v$session s ON lo.session_id = s.sid
</code>```

Why oracle locks all 4 tables in this scenario ?
Can someone explain the reason ?

Body:
We observed that while issuing a delete statement, oracle is locking tables which are not impacted due to the specific delete statement.

Consider 4 tables as below.

create table TABLE_A (id number(14,0) not null primary key, code varchar2(30));
create table TABLE_B (id number(14,0) not null primary key, code varchar2(30));

create table TABLE_C (id number(14,0) not null primary key, code varchar2(30), TABLE_A_id number(14,0));
create table TABLE_D (id number(14,0) not null primary key, code varchar2(30), TABLE_C_id number(14,0), TABLE_B_id number(14,0));

Create foreign key references.

alter table TABLE_C  add constraint TABLE_C_fk1  foreign key (TABLE_A_id) references TABLE_A on delete set null;

alter table TABLE_D  add constraint TABLE_D_fk1  foreign key (TABLE_C_id) references TABLE_C on delete cascade;
alter table TABLE_D  add constraint TABLE_D_fk2  foreign key (TABLE_B_id) references TABLE_B on delete cascade;

While deleting a record from TABLE_A as below, it will also update the TABLE_A_id column to null in TABLE_C table if the id exists in that table.
No changes expected in other tables.

delete TABLE_A where id = 1234;

This is working as expected in terms of the data modified. But when we look at the tables which are getting locked during this transaction we observed that all 4 tables are being locked.

LOCKED_MODE                              OBJECT_NAME
---------------------------------------- --------------------------------------------------------------------------------------------------------------------------------
Row-X (SX)                               TABLE_A
Row-X (SX)                               TABLE_C
Row-X (SX)                               TABLE_B
Row-X (SX)                               TABLE_D

used following query to fetch the details of locked objects during the transaction.

SELECT Decode(lo.locked_mode, 0, 'None',
                              1, 'Null (NULL)',
                              2, 'Row-S (SS)',
                              3, 'Row-X (SX)',
                              4, 'Share (S)',
                              5, 'S/Row-X (SSX)',
                              6, 'Exclusive (X)',
                              lo.locked_mode) locked_mode,
        o.object_name
FROM   v$locked_object lo
       JOIN dba_objects o ON o.object_id = lo.object_id
       JOIN v$session s ON lo.session_id = s.sid

Why oracle locks all 4 tables in this scenario ?
Can someone explain the reason ?


问:
How to migrate data from H2 database backup to mysql
I have a backup of my old H2 database in file format mv.db. I changed my schema somewhat(some columns in some tables are renamed or removed). And I now use mysql instead of H2. My goal is to move the data to my new database but I could not find any information about this case.</p>


问:
Cannot decode a Base64 string
I am trying to convert a valid Base64 string to a byte array in my C# code. I cannot insert that string in whole because it's more that 80000 characters long, but here's its part:

```<code>[encoded data, 17588 characters]
</code>```

I get strings like this from some consecutive UDP datagrams I want to receive. The common format is:

```<code>{A number (1–2 chars)}+{Datagram ID (1–2 chars)}+{Image data}
</code>```

(Long to explain what is "A number". It is same in all datagrams, but it is necessary.)

I use Convert.FromBase64String("62dj91UT7...") to do it, but it throws the following exception:

The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.

As far as I know, it occurs when the string contains illegal for Base64 characters or hasn't got padding. But my string is valid.  It has padding. It was checked with this Base64 validator. What else is needed?

UPDATE: I have also used another Base64 validator. It shows "the string is valid".

UPDATE 2: here is the code I currently use. It works if "A number" and "Datagram ID" consist of only one character, but fails in case of 2 character. It also fails on some reason when I try to compile and run it in Visual Studio 2022.

Title: Cannot decode a Base64 string

Body:
I am trying to convert a valid Base64 string to a byte array in my C# code. I cannot insert that string in whole because it's more that 80000 characters long, but here's its part:

[encoded data, 17588 characters]

I get strings like this from some consecutive UDP datagrams I want to receive. The common format is:

{A number (1–2 chars)}+{Datagram ID (1–2 chars)}+{Image data}

(Long to explain what is "A number". It is same in all datagrams, but it is necessary.)

I use Convert.FromBase64String("62dj91UT7...") to do it, but it throws the following exception:

The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.

As far as I know, it occurs when the string contains illegal for Base64 characters or hasn't got padding. But my string is valid.  It has padding. It was checked with this Base64 validator. What else is needed?

UPDATE: I have also used another Base64 validator. It shows "the string is valid".

UPDATE 2: here is the code I currently use. It works if "A number" and "Datagram ID" consist of only one character, but fails in case of 2 character. It also fails on some reason when I try to compile and run it in Visual Studio 2022.


问:
Running container on host network inside WSL2 does not open port
I am running nginx docker container in wsl2:

```<code>docker run --network host --name nginx-on-host -d nginx:1.23.2-alpine
</code>```

I suppose that it should open 80 port (since default nginx port is 80) as it does when I run this command in raw Ubuntu + Docker, but it does not open 80 port.

I checked opend ports on wsl2 as well as on Windows host.

Wsl2:

```<code>sudo netstat -tulpn
</code>```

Cmd:

```<code>netstat -aon |  find /I "LISTENING"
</code>```

Any ideas why is it so?

Body:
I am running nginx docker container in wsl2:

docker run --network host --name nginx-on-host -d nginx:1.23.2-alpine

I suppose that it should open 80 port (since default nginx port is 80) as it does when I run this command in raw Ubuntu + Docker, but it does not open 80 port.

I checked opend ports on wsl2 as well as on Windows host.

Wsl2:

sudo netstat -tulpn

Cmd:

netstat -aon |  find /I "LISTENING"

Any ideas why is it so?


问:
Python Graphql Ariadne - how to parse the input query payload in resolver
Am struggling to access the query that's passed from the playground ,

Basically want to use that to build a sql query backend.

e.g.:

```<code>query {
    resource {
        id
        name
    }
}
</code>```

I want the exact payload accessible at resolver

Body:
Am struggling to access the query that's passed from the playground ,

Basically want to use that to build a sql query backend.

e.g.:

query {
    resource {
        id
        name
    }
}

I want the exact payload accessible at resolver


问:
Accessing summary results message of Impala using pyodbc
When I execute a query in the Impala interface, it gives me back a message for some statements like create table, drop view etc (see below). However, when I execute the query using pyodbc I cannot figure out how to access the message that is shown in the Impala interface.

Is there any way to got the message through pyodbc?

My pyodbc code is like this:

from pyodbc import connect

odbc_connection = {
                "Driver": f"Cloudera ODBC Driver for Impala",
                "Host": '...',
                "Port": ...,
            }

cnxn = connect(**odbc_connection, autocommit=True)

cursor = cnxn.cursor()

cursor.execute('DROP VIEW IF EXISTS my_table.my_view')
```


问:
I am using DB2 database and performing the following Update using Begin/end block
```<code>BEGIN
UPDATE ...;
COMMIT;
   EXCEPTION
    WHEN OTHERS THEN
     dbms_output.put_line('Some Message' || sqlerror);
   END;
END;
</code>```

I am having syntax error because of Exception block.

Body:
BEGIN
UPDATE ...;
COMMIT;
   EXCEPTION
    WHEN OTHERS THEN
     dbms_output.put_line('Some Message' || sqlerror);
   END;
END;

I am having syntax error because of Exception block.


问:
Not Able to fetch Title in Python Selenium

I am trying to fetch title from the source code.
I have written multiple xpaths but i am getting an

Error : DeprecationWarning: find_elements_by_* commands are deprecated. Please use find_elements() instead

```<code>enter code here
try:
    #title = browser.find_element_by_xpath('/html/body/div[1]/main/div[2]/div[1]/div[2]/div/div[1]/div[1]/h1/img').text.strip()
    #title = browser.find_element(By.XPATH, "//h1[@class='cp-typography--hero-title-logo']/img").text
    #title = browser.find_elements(By.CSS_SELECTOR, "content-page__programmatic-header").text.strip()
    print("Title: "+title)
except:
    print("Missing Title")
</code>```

help me with this

Body:
I am trying to fetch title from the source code.
I have written multiple xpaths but i am getting an

Error : DeprecationWarning: find_elements_by_* commands are deprecated. Please use find_elements() instead

enter code here
try:
    #title = browser.find_element_by_xpath('/html/body/div[1]/main/div[2]/div[1]/div[2]/div/div[1]/div[1]/h1/img').text.strip()
    #title = browser.find_element(By.XPATH, "//h1[@class='cp-typography--hero-title-logo']/img").text
    #title = browser.find_elements(By.CSS_SELECTOR, "content-page__programmatic-header").text.strip()
    print("Title: "+title)
except:
    print("Missing Title")

help me with this


问:
MRO (Method Resolution Order) in Python for this code
I got this code:

```<code>class A:
    def gg(self):
        print ('Class A')

class B(A):
    def gg(self):
        print('First Class B')
        super().gg()
        print('Class B')

class C(A):
    def gg(self):
        print('First Class C')
        super().gg()
        print('Class C')

class D (B,C):

    def gg(self):
        print('First Class D')
        super().gg()
        print('Class D')

good = D()

good.gg()

</code>```

The print expected in my opinion should be:

"First Class D" as is the first element in the function

"First Class B" as it goes through super and is the first element of the firt inherit class

"Class A" as it goes through the second element (a super) of the first inherit class and this is the first element of the reinherit class

"Class B" as it goes through the third element of the first inherit class

"First Class C" as it goes though the first element of the second inherit class

"Class A" as it goes through the second element (a super) of the second inherit class and this is the first element of the reinherit class

"Class C" as it goes though the third element of the second inherit class

"Class D" as it goes to the las element of the class

Instead, the print is this one:

```<code>First Class D
First Class B
First Class C
Class A
Class C
Class B
Class D
</code>```

I do not understand any of this prints. Overall, what I do not understand is how it can go from "First Class B" to "First Class C" without passing through the prints "Class A" and "Class B". But what is even more difficult to understand is how can it goes from the prints "Class A" to "Class C" if I am inherting first the class B as we saw that the print 'First Class B" goes before "First Class C" and is not printing 'Class B' before 'Class C'. Also it will be nice if you explain why my expectations are wrong step by step

Body:
I got this code:

class A:
    def gg(self):
        print ('Class A')

class B(A):
    def gg(self):
        print('First Class B')
        super().gg()
        print('Class B')

class C(A):
    def gg(self):
        print('First Class C')
        super().gg()
        print('Class C')

class D (B,C):

    def gg(self):
        print('First Class D')
        super().gg()
        print('Class D')

good = D()

good.gg()

The print expected in my opinion should be:

"First Class D" as is the first element in the function

"First Class B" as it goes through super and is the first element of the firt inherit class

"Class A" as it goes through the second element (a super) of the first inherit class and this is the first element of the reinherit class

"Class B" as it goes through the third element of the first inherit class

"First Class C" as it goes though the first element of the second inherit class

"Class A" as it goes through the second element (a super) of the second inherit class and this is the first element of the reinherit class

"Class C" as it goes though the third element of the second inherit class

"Class D" as it goes to the las element of the class

Instead, the print is this one:

First Class D
First Class B
First Class C
Class A
Class C
Class B
Class D

I do not understand any of this prints. Overall, what I do not understand is how it can go from "First Class B" to "First Class C" without passing through the prints "Class A" and "Class B". But what is even more difficult to understand is how can it goes from the prints "Class A" to "Class C" if I am inherting first the class B as we saw that the print 'First Class B" goes before "First Class C" and is not printing 'Class B' before 'Class C'. Also it will be nice if you explain why my expectations are wrong step by step


问:
There is a problem after re editing protected cells. It duplicates the protected range. How to prevent duplicate?
This script lock range and works fine. But if you edit locked cell, it locks locked cell again. How to control it?

```<code>`function onEdit(e){
let protection = e.range.protect();
protection.removeEditors(protection.getEditors());
if (protection.canDomainEdit())  {
protection.setDomainEdit(false);
}
}function onEdit(e){
if (e.value == null){
let prot = SpreadsheetApp.getActiveSheet().getProtections(SpreadsheetApp.ProtectionType.RANGE);
 for (let i in prot){
 if (prot[i].getRange().getA1Notation() == e.range.getA1Notation())
  prot[i].remove();
 }
 } else {
 let protection = e.range.protect();
 protection.removeEditors(protection.getEditors());
 if (protection.canDomainEdit())
 protection.setDomainEdit(false);
 }}`
</code>```

Body:
This script lock range and works fine. But if you edit locked cell, it locks locked cell again. How to control it?

`function onEdit(e){
let protection = e.range.protect();
protection.removeEditors(protection.getEditors());
if (protection.canDomainEdit())  {
protection.setDomainEdit(false);
}
}function onEdit(e){
if (e.value == null){
let prot = SpreadsheetApp.getActiveSheet().getProtections(SpreadsheetApp.ProtectionType.RANGE);
 for (let i in prot){
 if (prot[i].getRange().getA1Notation() == e.range.getA1Notation())
  prot[i].remove();
 }
 } else {
 let protection = e.range.protect();
 protection.removeEditors(protection.getEditors());
 if (protection.canDomainEdit())
 protection.setDomainEdit(false);
 }}`


问:
osmdroid: Polyline.isCloseTo() always returns false
In my android app I am trying to check, if a Geopoint is close to a Polyline, so I am using the built-in isCloseTo function.

I create the polyline:

```<code>Polyline startLine = new Polyline();
startLine.addPoint(new Geopoint(lat1, long1));
startLine.addPoint(new Geopoint(lat2, long2));
startLine.addPoint(new Geopoint(lat3, long3));
startLine.addPoint(new Geopoint(lat4, long4));
startLine.addPoint(new Geopoint(lat5, long5));
</code>```

After that I add the Polyline to the mapview:

```<code>map.getOverlayManager().add(startLine);
</code>```

After that I create a new Geopoint and a tolerance double to test the closeness:

```<code>GeoPoint testPoint = new GeoPoint(lat6, long6);
double testTolerance = 5.0;
</code>```

Then I test the closeness:

```<code>startLine.isCloseTo(testPoint, testTolerance, map);
</code>```

The above line always returns false no matter what I set the tolerance to (I have tried it with 5.0, 10.0, even 1000.0) and how close the point is (even setting testPoint to the exact same point as one of the startLine points, results in false).

Have I misunderstood how the isCloseTo function is supposed to work? Is there a mistake in the way I am using it?

Body:
In my android app I am trying to check, if a Geopoint is close to a Polyline, so I am using the built-in isCloseTo function.

I create the polyline:

Polyline startLine = new Polyline();
startLine.addPoint(new Geopoint(lat1, long1));
startLine.addPoint(new Geopoint(lat2, long2));
startLine.addPoint(new Geopoint(lat3, long3));
startLine.addPoint(new Geopoint(lat4, long4));
startLine.addPoint(new Geopoint(lat5, long5));

After that I add the Polyline to the mapview:

map.getOverlayManager().add(startLine);

After that I create a new Geopoint and a tolerance double to test the closeness:

GeoPoint testPoint = new GeoPoint(lat6, long6);
double testTolerance = 5.0;

Then I test the closeness:

startLine.isCloseTo(testPoint, testTolerance, map);

The above line always returns false no matter what I set the tolerance to (I have tried it with 5.0, 10.0, even 1000.0) and how close the point is (even setting testPoint to the exact same point as one of the startLine points, results in false).

Have I misunderstood how the isCloseTo function is supposed to work? Is there a mistake in the way I am using it?


问:
Dax Query- To Calculate MAXID and Sum of Amount
I have below sample data:

```<code>IncidentID  TransactionID   Recordeddate    Name    Amount
10             1             13/01/2023 Recovery 1000
10             2             13/01/2023 Reserve  2000
10             3             13/01/2023 Reserve  3000
10             4             14/01/2023 Reserve  4000
11             5             14/01/2023     Recovery 3000
11             6             14/01/2023 Payment  4000
12             7             14/01/2023 Reserve  5000
13             8             14/01/2023 Reserve  4000
13             9             14/01/2023 Payment  2000
</code>```

I need to calculate sum of amount for each incident id, for each date only Max Transaction ID and Name should be Reserve only.

I tried doing it be below expression:

```<code>Table2 = summarize(Table,Table[IncidentID],Table[RecordedDate],Table[Name],"MAXID",
calculate(max(TransactionID),AllExcept(IncidentID,RecordDate,Name)))
</code>```

this table is giving me required filtered table, but i am not able to add amount column.
If i add amount column grouping is not working, and i need to get amount included so that i can calculate sum of amount.

Expected- Not able to add amount column in this, as adding amount it is not giving required results.

Body:
I have below sample data:

IncidentID  TransactionID   Recordeddate    Name    Amount
10             1             13/01/2023 Recovery 1000
10             2             13/01/2023 Reserve  2000
10             3             13/01/2023 Reserve  3000
10             4             14/01/2023 Reserve  4000
11             5             14/01/2023     Recovery 3000
11             6             14/01/2023 Payment  4000
12             7             14/01/2023 Reserve  5000
13             8             14/01/2023 Reserve  4000
13             9             14/01/2023 Payment  2000

I need to calculate sum of amount for each incident id, for each date only Max Transaction ID and Name should be Reserve only.

I tried doing it be below expression:

Table2 = summarize(Table,Table[IncidentID],Table[RecordedDate],Table[Name],"MAXID",
calculate(max(TransactionID),AllExcept(IncidentID,RecordDate,Name)))

this table is giving me required filtered table, but i am not able to add amount column.
If i add amount column grouping is not working, and i need to get amount included so that i can calculate sum of amount.

Expected- Not able to add amount column in this, as adding amount it is not giving required results.


问:
Spring Security 6 : can't access to secured method after authentication
After successful basic authentication (login/password in body) when I access to an other secured controller's method I have a 401 error.
I'm not sure but it seems the security context is not set.

Do you have an idea or a line of research?

Use case with swagger

call http://localhost:8080/api/v1/auth/login as admin => success and SecurityContextHolder.getContext() has an authentication as UsernamePasswordAuthenticationToken

call http://localhost:8080/api/v1/auth/me => success. authentication is always UsernamePasswordAuthenticationToken and the user admin is returned

call http://localhost:8080/api/v1/distributors/isauthenticated => failed and return a 401 http status.

The step 3 logs

```<code>2023-01-10 10:16:48,523 [http-nio-8080-exec-1] DEBUG o.s.w.s.m.m.a.RequestMappingHandlerMapping         : Mapped to fr.gregoire.passpro.backend.controller.DistributorsController#test()
2023-01-10 10:16:48,524 [http-nio-8080-exec-1] INFO  Spring Security Debugger                           :

************************************************************

Request received for GET '/api/v1/distributors/isauthenticated':

org.apache.catalina.connector.RequestFacade@5d0e637c

servletPath:/api/v1/distributors/isauthenticated
pathInfo:null
headers:
host: localhost:8080
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:108.0) Gecko/20100101 Firefox/108.0
accept: */*
accept-language: fr,fr-FR;q=0.8,en-US;q=0.5,en;q=0.3
accept-encoding: gzip, deflate, br
referer: http://localhost:8080/swagger-ui/index.html
connection: keep-alive
cookie: JSESSIONID=F6F38EADC8BA2ADF82A519C33507D25F
sec-fetch-dest: empty
sec-fetch-mode: cors
sec-fetch-site: same-origin

Security filter chain: no match

************************************************************

2023-01-10 10:16:48,524 [http-nio-8080-exec-1] DEBUG o.s.w.s.m.m.a.RequestMappingHandlerMapping         : Mapped to fr.gregoire.passpro.backend.controller.DistributorsController#test()
2023-01-10 10:16:48,524 [http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.DispatcherServlet  : GET "/api/v1/distributors/isauthenticated", parameters={}
2023-01-10 10:16:48,524 [http-nio-8080-exec-1] DEBUG o.s.w.s.m.m.a.RequestMappingHandlerMapping         : Mapped to fr.gregoire.passpro.backend.controller.DistributorsController#test()
2023-01-10 10:16:48,524 [http-nio-8080-exec-1] DEBUG o.s.s.a.m.AuthorizationManagerBeforeMethodInterceptor : Authorizing method invocation ReflectiveMethodInvocation: public void fr.gregoire.passpro.backend.controller.DistributorsController.test() throws java.lang.Exception; target is of class [fr.gregoire.passpro.backend.controller.DistributorsController]
2023-01-10 10:16:48,525 [http-nio-8080-exec-1] DEBUG o.s.w.s.m.m.a.ExceptionHandlerExceptionResolver    : Using @ExceptionHandler fr.gregoire.passpro.backend.resterror.RestExceptionHandler#handleAuthenticationException(AuthenticationException)
2023-01-10 10:16:48,526 [http-nio-8080-exec-1] DEBUG o.s.w.s.m.m.annotation.HttpEntityMethodProcessor   : Using 'application/json', given [*/*] and supported [application/json, application/*+json]
2023-01-10 10:16:48,526 [http-nio-8080-exec-1] DEBUG o.s.w.s.m.m.annotation.HttpEntityMethodProcessor   : Writing [fr.gregoire.passpro.backend.resterror.RestErrors@55eb7689]
2023-01-10 10:16:48,527 [http-nio-8080-exec-1] DEBUG o.s.w.s.m.m.a.ExceptionHandlerExceptionResolver    : Resolved [org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext]
2023-01-10 10:16:48,528 [http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.DispatcherServlet  : Completed 401 UNAUTHORIZED

</code>```

Quick info

spring boot 3

spring security 6

Code

```<code>package fr.gregoire.passpro.backend.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.HttpStatusEntryPoint;
import org.springframework.security.web.context.DelegatingSecurityContextRepository;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.security.web.context.RequestAttributeSecurityContextRepository;
import org.springframework.security.web.context.SecurityContextRepository;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;

@Configuration
@EnableWebSecurity(debug = true)
@EnableMethodSecurity(securedEnabled = true)
public class SecurityConfig {

  @Autowired
  UserDetailsService userDetailsService;

  @Bean
  public SecurityContextRepository securityContextRepository() {
    return new HttpSessionSecurityContextRepository();
  }

  @Bean
  public AuthenticationManager authenticationManager(UserDetailsService userDetailsService) throws Exception {
    return new ProviderManager(daoAuthenticationProvider());
  }

  @Bean
  public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
  }

  @Bean
  public DaoAuthenticationProvider daoAuthenticationProvider() {
    DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
    provider.setUserDetailsService(userDetailsService);
    provider.setPasswordEncoder(passwordEncoder());
    return provider;
  }

  @Bean
  SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    HttpSessionRequestCache requestCache = new HttpSessionRequestCache();
    requestCache.setMatchingRequestParameterName("continue");
    // @formatter:off
    http
    .headers().frameOptions().disable().and()
    .cors().and()
    .csrf().disable()
    .formLogin().disable()
    .exceptionHandling().authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED)).and()
    .securityMatcher("/api/*/auth/**")
    .authorizeHttpRequests(authz -> authz.requestMatchers("/api/*/auth/**").permitAll()
                                        .requestMatchers("/api/v1/auth/me").permitAll()
                                        .requestMatchers("/api/*/public/**").permitAll()
                                        .requestMatchers("/api/*/catalogs/*/documents/*/file").permitAll()
                                        .requestMatchers(req -> req.getRequestURI().contains("mail-images")).permitAll()
                                        .requestMatchers(req -> req.getRequestURI().contains("api-docs")).permitAll()
                                        .requestMatchers(req -> req.getRequestURI().contains("swagger-ui")).permitAll()
                                        .requestMatchers(req -> req.getRequestURI().contains("h2-console")).permitAll()
                                        .anyRequest().authenticated())
    .authenticationProvider(daoAuthenticationProvider())
    .securityContext((securityContext) -> securityContext.requireExplicitSave(false)) // Spring secu 5.8
    .securityContext((securityContext) -> securityContext.securityContextRepository(new DelegatingSecurityContextRepository(
      new RequestAttributeSecurityContextRepository(),
      securityContextRepository()
    )))
    ;
    // @formatter:on

    return http.build();
  }
}
</code>```
```<code>package fr.gregoire.passpro.backend.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.session.SessionAuthenticationException;
import org.springframework.security.web.context.SecurityContextRepository;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import fr.gregoire.passpro.backend.dto.LoginDto;
import fr.gregoire.passpro.backend.dto.UserDto;
import fr.gregoire.passpro.backend.exception.NotFoundException;
import fr.gregoire.passpro.backend.mapper.UserDtoMapper;
import fr.gregoire.passpro.backend.model.UserEntity;
import fr.gregoire.passpro.backend.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;

@Validated
@RestController
@RequestMapping(path = "/api/v1/auth", produces = MediaType.APPLICATION_JSON_VALUE)
public class AuthenticationController {

  @Autowired
  private SecurityContextRepository securityContextRepository;

  @Autowired
  private AuthenticationManager authenticationManager;

  @Autowired
  private UserService userService;

  @Autowired
  private UserDtoMapper userDtoMapper;

  @PostMapping("/login")
  public ResponseEntity<UserDto> login(@NotNull @Valid @RequestBody LoginDto loginDto, HttpServletRequest request, HttpServletResponse response) {
    final Authentication authentication = this.authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginDto.getLogin(), loginDto.getPassword()));

    SecurityContextHolder.getContext()
      .setAuthentication(authentication);
    securityContextRepository.saveContext(SecurityContextHolder.getContext(), request, response);

    return ResponseEntity.ok(this.userDtoMapper.modelToDto((UserEntity) authentication.getPrincipal()));
  }

  @PostMapping("/logout")
  @ResponseStatus(HttpStatus.NO_CONTENT)
  public void logout() {
    SecurityContextHolder.clearContext();
  }

  @GetMapping("/me")
  public ResponseEntity<UserDto> getAuthenticatedUser() throws NotFoundException {
    Authentication authentication = SecurityContextHolder.getContext()
      .getAuthentication();

    if (null == authentication || !authentication.isAuthenticated() || !(authentication.getPrincipal() instanceof UserEntity)) {
      throw new SessionAuthenticationException("UNAUTHORIZED");
    }

    return ResponseEntity.ok(this.userDtoMapper.modelToDto(this.userService.findById(((UserEntity) authentication.getPrincipal()).getId())));
  }
}
</code>```
```<code>@Validated
@RestController
@RequestMapping(path = "/api/v1/distributors", produces = MediaType.APPLICATION_JSON_VALUE)
public class DistributorsController {

  @GetMapping("/isauthenticated")
  @Secured(RoleEnumConstants.ROLE_ADMIN)
  public void test() throws Exception {
    Authentication authentication = SecurityContextHolder.getContext()
      .getAuthentication();
    System.out.println(authentication.getClass()
      .getCanonicalName());
    System.out.println(authentication.getCredentials());
    System.out.println(authentication.isAuthenticated());
    System.out.println(authentication.getDetails());
    System.out.println(authentication.getAuthorities());
  }
}
</code>```

Thanks for your help and have a nice day,
Nicolas

Body:
After successful basic authentication (login/password in body) when I access to an other secured controller's method I have a 401 error.
I'm not sure but it seems the security context is not set.

Do you have an idea or a line of research?

Use case with swagger

call http://localhost:8080/api/v1/auth/login as admin => success and SecurityContextHolder.getContext() has an authentication as UsernamePasswordAuthenticationToken

call http://localhost:8080/api/v1/auth/me => success. authentication is always UsernamePasswordAuthenticationToken and the user admin is returned

call http://localhost:8080/api/v1/distributors/isauthenticated => failed and return a 401 http status.

The step 3 logs

2023-01-10 10:16:48,523 [http-nio-8080-exec-1] DEBUG o.s.w.s.m.m.a.RequestMappingHandlerMapping         : Mapped to fr.gregoire.passpro.backend.controller.DistributorsController#test()
2023-01-10 10:16:48,524 [http-nio-8080-exec-1] INFO  Spring Security Debugger                           :

************************************************************

Request received for GET '/api/v1/distributors/isauthenticated':

org.apache.catalina.connector.RequestFacade@5d0e637c

servletPath:/api/v1/distributors/isauthenticated
pathInfo:null
headers:
host: localhost:8080
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:108.0) Gecko/20100101 Firefox/108.0
accept: */*
accept-language: fr,fr-FR;q=0.8,en-US;q=0.5,en;q=0.3
accept-encoding: gzip, deflate, br
referer: http://localhost:8080/swagger-ui/index.html
connection: keep-alive
cookie: JSESSIONID=F6F38EADC8BA2ADF82A519C33507D25F
sec-fetch-dest: empty
sec-fetch-mode: cors
sec-fetch-site: same-origin

Security filter chain: no match

************************************************************

2023-01-10 10:16:48,524 [http-nio-8080-exec-1] DEBUG o.s.w.s.m.m.a.RequestMappingHandlerMapping         : Mapped to fr.gregoire.passpro.backend.controller.DistributorsController#test()
2023-01-10 10:16:48,524 [http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.DispatcherServlet  : GET "/api/v1/distributors/isauthenticated", parameters={}
2023-01-10 10:16:48,524 [http-nio-8080-exec-1] DEBUG o.s.w.s.m.m.a.RequestMappingHandlerMapping         : Mapped to fr.gregoire.passpro.backend.controller.DistributorsController#test()
2023-01-10 10:16:48,524 [http-nio-8080-exec-1] DEBUG o.s.s.a.m.AuthorizationManagerBeforeMethodInterceptor : Authorizing method invocation ReflectiveMethodInvocation: public void fr.gregoire.passpro.backend.controller.DistributorsController.test() throws java.lang.Exception; target is of class [fr.gregoire.passpro.backend.controller.DistributorsController]
2023-01-10 10:16:48,525 [http-nio-8080-exec-1] DEBUG o.s.w.s.m.m.a.ExceptionHandlerExceptionResolver    : Using @ExceptionHandler fr.gregoire.passpro.backend.resterror.RestExceptionHandler#handleAuthenticationException(AuthenticationException)
2023-01-10 10:16:48,526 [http-nio-8080-exec-1] DEBUG o.s.w.s.m.m.annotation.HttpEntityMethodProcessor   : Using 'application/json', given [*/*] and supported [application/json, application/*+json]
2023-01-10 10:16:48,526 [http-nio-8080-exec-1] DEBUG o.s.w.s.m.m.annotation.HttpEntityMethodProcessor   : Writing [fr.gregoire.passpro.backend.resterror.RestErrors@55eb7689]
2023-01-10 10:16:48,527 [http-nio-8080-exec-1] DEBUG o.s.w.s.m.m.a.ExceptionHandlerExceptionResolver    : Resolved [org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext]
2023-01-10 10:16:48,528 [http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.DispatcherServlet  : Completed 401 UNAUTHORIZED

Quick info

spring boot 3

spring security 6

Code

package fr.gregoire.passpro.backend.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.HttpStatusEntryPoint;
import org.springframework.security.web.context.DelegatingSecurityContextRepository;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.security.web.context.RequestAttributeSecurityContextRepository;
import org.springframework.security.web.context.SecurityContextRepository;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;

@Configuration
@EnableWebSecurity(debug = true)
@EnableMethodSecurity(securedEnabled = true)
public class SecurityConfig {

  @Autowired
  UserDetailsService userDetailsService;

  @Bean
  public SecurityContextRepository securityContextRepository() {
    return new HttpSessionSecurityContextRepository();
  }

  @Bean
  public AuthenticationManager authenticationManager(UserDetailsService userDetailsService) throws Exception {
    return new ProviderManager(daoAuthenticationProvider());
  }

  @Bean
  public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
  }

  @Bean
  public DaoAuthenticationProvider daoAuthenticationProvider() {
    DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
    provider.setUserDetailsService(userDetailsService);
    provider.setPasswordEncoder(passwordEncoder());
    return provider;
  }

  @Bean
  SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    HttpSessionRequestCache requestCache = new HttpSessionRequestCache();
    requestCache.setMatchingRequestParameterName("continue");
    // @formatter:off
    http
    .headers().frameOptions().disable().and()
    .cors().and()
    .csrf().disable()
    .formLogin().disable()
    .exceptionHandling().authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED)).and()
    .securityMatcher("/api/*/auth/**")
    .authorizeHttpRequests(authz -> authz.requestMatchers("/api/*/auth/**").permitAll()
                                        .requestMatchers("/api/v1/auth/me").permitAll()
                                        .requestMatchers("/api/*/public/**").permitAll()
                                        .requestMatchers("/api/*/catalogs/*/documents/*/file").permitAll()
                                        .requestMatchers(req -> req.getRequestURI().contains("mail-images")).permitAll()
                                        .requestMatchers(req -> req.getRequestURI().contains("api-docs")).permitAll()
                                        .requestMatchers(req -> req.getRequestURI().contains("swagger-ui")).permitAll()
                                        .requestMatchers(req -> req.getRequestURI().contains("h2-console")).permitAll()
                                        .anyRequest().authenticated())
    .authenticationProvider(daoAuthenticationProvider())
    .securityContext((securityContext) -> securityContext.requireExplicitSave(false)) // Spring secu 5.8
    .securityContext((securityContext) -> securityContext.securityContextRepository(new DelegatingSecurityContextRepository(
      new RequestAttributeSecurityContextRepository(),
      securityContextRepository()
    )))
    ;
    // @formatter:on

    return http.build();
  }
}

package fr.gregoire.passpro.backend.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.session.SessionAuthenticationException;
import org.springframework.security.web.context.SecurityContextRepository;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import fr.gregoire.passpro.backend.dto.LoginDto;
import fr.gregoire.passpro.backend.dto.UserDto;
import fr.gregoire.passpro.backend.exception.NotFoundException;
import fr.gregoire.passpro.backend.mapper.UserDtoMapper;
import fr.gregoire.passpro.backend.model.UserEntity;
import fr.gregoire.passpro.backend.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;

@Validated
@RestController
@RequestMapping(path = "/api/v1/auth", produces = MediaType.APPLICATION_JSON_VALUE)
public class AuthenticationController {

  @Autowired
  private SecurityContextRepository securityContextRepository;

  @Autowired
  private AuthenticationManager authenticationManager;

  @Autowired
  private UserService userService;

  @Autowired
  private UserDtoMapper userDtoMapper;

  @PostMapping("/login")
  public ResponseEntity<UserDto> login(@NotNull @Valid @RequestBody LoginDto loginDto, HttpServletRequest request, HttpServletResponse response) {
    final Authentication authentication = this.authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginDto.getLogin(), loginDto.getPassword()));

    SecurityContextHolder.getContext()
      .setAuthentication(authentication);
    securityContextRepository.saveContext(SecurityContextHolder.getContext(), request, response);

    return ResponseEntity.ok(this.userDtoMapper.modelToDto((UserEntity) authentication.getPrincipal()));
  }

  @PostMapping("/logout")
  @ResponseStatus(HttpStatus.NO_CONTENT)
  public void logout() {
    SecurityContextHolder.clearContext();
  }

  @GetMapping("/me")
  public ResponseEntity<UserDto> getAuthenticatedUser() throws NotFoundException {
    Authentication authentication = SecurityContextHolder.getContext()
      .getAuthentication();

    if (null == authentication || !authentication.isAuthenticated() || !(authentication.getPrincipal() instanceof UserEntity)) {
      throw new SessionAuthenticationException("UNAUTHORIZED");
    }

    return ResponseEntity.ok(this.userDtoMapper.modelToDto(this.userService.findById(((UserEntity) authentication.getPrincipal()).getId())));
  }
}

@Validated
@RestController
@RequestMapping(path = "/api/v1/distributors", produces = MediaType.APPLICATION_JSON_VALUE)
public class DistributorsController {

  @GetMapping("/isauthenticated")
  @Secured(RoleEnumConstants.ROLE_ADMIN)
  public void test() throws Exception {
    Authentication authentication = SecurityContextHolder.getContext()
      .getAuthentication();
    System.out.println(authentication.getClass()
      .getCanonicalName());
    System.out.println(authentication.getCredentials());
    System.out.println(authentication.isAuthenticated());
    System.out.println(authentication.getDetails());
    System.out.println(authentication.getAuthorities());
  }
}

Thanks for your help and have a nice day,
Nicolas


问:
java.lang.IllegalStateException: Cannot load configuration class and application run failed so i installed jars still the same
2023-01-10 14:55:11,729[0;39m [1;31mERROR[0;39m [[34mrestartedMain[0;39m] [33mo.s.b.SpringApplication[0;39m: Application run failed
java.lang.IllegalStateException: Cannot load configuration class: com.dyteam.testApps.webserver.RestServer
at org.springframework.context.annotation.ConfigurationClassPostProcessor.enhanceConfigurationClasses(ConfigurationClassPostProcessor.java:416)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanFactory(ConfigurationClassPostProcessor.java:254)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:284)
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:128)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:693)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:531)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:752)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:388)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:327)
at com.dyteam.testApps.webserver.RestServer.main(RestServer.java:28)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Caused by: java.lang.ExceptionInInitializerError: null
at org.springframework.context.annotation.ConfigurationClassEnhancer.newEnhancer(ConfigurationClassEnhancer.java:122)
at org.springframework.context.annotation.ConfigurationClassEnhancer.enhance(ConfigurationClassEnhancer.java:110)
at org.springframework.context.annotation.ConfigurationClassPostProcessor.enhanceConfigurationClasses(ConfigurationClassPostProcessor.java:405)
... 15 common frames omitted
Caused by: org.springframework.cglib.core.CodeGenerationException: java.lang.reflect.InaccessibleObjectException-->Unable to make protected final java.lang.Class java.lang.ClassLoader.defineClass(java.lang.String,byte[],int,int,java.security.ProtectionDomain) throws java.lang.ClassFormatError accessible: module java.base does not "opens java.lang" to unnamed module @71075444
at org.springframework.cglib.core.ReflectUtils.defineClass(ReflectUtils.java:464)
at org.springframework.cglib.core.AbstractClassGenerator.generate(AbstractClassGenerator.java:336)
at org.springframework.cglib.core.AbstractClassGenerator$ClassLoaderData$3.apply(AbstractClassGenerator.java:93)
at org.springframework.cglib.core.AbstractClassGenerator$ClassLoaderData$3.apply(AbstractClassGenerator.java:91)
at org.springframework.cglib.core.internal.LoadingCache$2.call(LoadingCache.java:54)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
at org.springframework.cglib.core.internal.LoadingCache.createEntry(LoadingCache.java:61)
at org.springframework.cglib.core.internal.LoadingCache.get(LoadingCache.java:34)
at org.springframework.cglib.core.AbstractClassGenerator$ClassLoaderData.get(AbstractClassGenerator.java:116)
at org.springframework.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:291)
at org.springframework.cglib.core.KeyFactory$Generator.create(KeyFactory.java:221)
at org.springframework.cglib.core.KeyFactory.create(KeyFactory.java:174)
at org.springframework.cglib.core.KeyFactory.create(KeyFactory.java:153)
at org.springframework.cglib.proxy.Enhancer.(Enhancer.java:73)
... 18 common frames omitted
Caused by: java.lang.reflect.InaccessibleObjectException: Unable to make protected final java.lang.Class java.lang.ClassLoader.defineClass(java.lang.String,byte[],int,int,java.security.ProtectionDomain) throws java.lang.ClassFormatError accessible: module java.base does not "opens java.lang" to unnamed module @71075444
at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:354)
at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:297)
at java.base/java.lang.reflect.Method.checkCanSetAccessible(Method.java:199)
at java.base/java.lang.reflect.Method.setAccessible(Method.java:193)
at org.springframework.cglib.core.ReflectUtils$1.run(ReflectUtils.java:61)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:569)
at org.springframework.cglib.core.ReflectUtils.(ReflectUtils.java:52)
at org.springframework.cglib.core.KeyFactory$Generator.generateClass(KeyFactory.java:243)
at org.springframework.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:25)
at org.springframework.cglib.core.AbstractClassGenerator.generate(AbstractClassGenerator.java:329)
... 30 common frames omitted
[37m2023-01-10 14:55:11,732[0;39m [34mINFO [0;39m [[34mrestartedMain[0;39m] [33mo.s.b.w.s.c.AnnotationConfigServletWebServerApplicationContext[0;39m: Closing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@3fee750c: startup date [Tue Jan 10 14:55:10 IST 2023]; root of context hierarchy

i tried to clean the maven ,install and update ,also install the jars i am notgetting what to do and the project was imported


问:
GoCD Error - A specified logon session does not exist. It may already have been terminated
I run an automation test case on GoCD. It will open the Excel file and verify data in this file. But I met the message:

error: Retrieving the COM class factory for component with CLSID
{00024500-0000-0000-C000-000000000046} failed due to the following
error: 80070520 A specified logon session does not exist. It may
already have been terminated. (Exception from HRESULT: 0x80070520).

I do not know what happened and how to fix it?
Very appreciated any comment!


问:
CSS grid not rendering the same on firefox and chrome
Here is the code snippet : https://codesandbox.io/s/zen-stallman-p71018

My css grid does not render in the same way on firefox and chrome, despite the fact that the computed rules are the same on both browsers.

The computed height of the grid is the same value on both browsers, and the code for the grid template is the same as well :

    display: grid;
    grid-template-columns: [col0] 33% [col1] 17% [col2] 25% [col3] 12.5% [col4] 12.5% [col5];
    grid-template-rows: [row0] 50% [row1] 33% [row2] 17% [row3];
```

There is no problem on firefox :

But on chrome, the rows take a different height:

I tried to change the parent's height of the grid, and obtained an unpleasant result (the row still took too much height making white space, even when the height stop the right place).

I tried to check if the computed rules were the same on both browsers, and they are.

Body:
Here is the code snippet : https://codesandbox.io/s/zen-stallman-p71018

My css grid does not render in the same way on firefox and chrome, despite the fact that the computed rules are the same on both browsers.

The computed height of the grid is the same value on both browsers, and the code for the grid template is the same as well :

    display: grid;
    grid-template-columns: [col0] 33% [col1] 17% [col2] 25% [col3] 12.5% [col4] 12.5% [col5];
    grid-template-rows: [row0] 50% [row1] 33% [row2] 17% [row3];

There is no problem on firefox :

But on chrome, the rows take a different height:

I tried to change the parent's height of the grid, and obtained an unpleasant result (the row still took too much height making white space, even when the height stop the right place).

I tried to check if the computed rules were the same on both browsers, and they are.


问:
How to Increase image quality in streamlit
I am viewing images by using streamlit without converting to RGB below is the line of code which I am using

st.image("image.jpg")
```

But the problem is I need to read some numbers inside the image but the image is blurred which means that I am not able to read the numbers present in the image.

Increasing the size of the image does not work.

Body:
I am viewing images by using streamlit without converting to RGB below is the line of code which I am using

st.image("image.jpg")

But the problem is I need to read some numbers inside the image but the image is blurred which means that I am not able to read the numbers present in the image.

Increasing the size of the image does not work.


问:
HTTP/1.1 500 Internal Server Error in ASP.Net
I have published my website to hosting but i got the problem "HTTP/1.1 500 Internal Server Error" and my website shows "Error. An error occurred while processing your request"
I turned off customError mode and this is what it shows

Server Error in '/' Application. Invalid URI: The format of the URI
could not be determined. Description: An unhandled exception occurred
during the execution of the current web request. Please review the
stack trace for more information about the error and where it
originated in the code.

Exception Details: System.UriFormatException: Invalid URI: The format
of the URI could not be determined.

Source Error:

An unhandled exception was generated during the execution of the
current web request. Information regarding the origin and location of
the exception can be identified using the exception stack trace below.

Stack Trace: [UriFormatException: Invalid URI: The format of the URI could not be determined.]    System.Uri.CreateThis(String uri, Boolean dontEscape, UriKind uriKind) +8516254    System.Net.WebRequest.Create(String requestUriString) +44    CheckWebsite.Controllers.HomeController.WebRequestTest(String url) in D:\Projects\CheckWebsite\CheckWebsite\Controllers\HomeController.cs:111 CheckWebsite.Controllers.HomeController.Index() in D:\Projects\CheckWebsite\CheckWebsite\Controllers\HomeController.cs:26 lambda_method(Closure , ControllerBase , Object[] ) +87    System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2
parameters) +35

System.Web.Mvc.Async.<>c.b__9_0(IAsyncResult
asyncResult, ActionInvocation innerInvokeState) +39

System.Web.Mvc.Async.WrappedAsyncResult2.CallEndDelegate(IAsyncResult asyncResult) +77    System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +69    System.Web.Mvc.Async.<>c__DisplayClass11_0.<InvokeActionMethodFilterAsynchronouslyRecursive>b__0() +80    System.Web.Mvc.Async.<>c__DisplayClass11_2.<InvokeActionMethodFilterAsynchronouslyRecursive>b__2() +387    System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +69    System.Web.Mvc.Async.<>c__DisplayClass3_6.<BeginInvokeAction>b__4() +50    System.Web.Mvc.Async.<>c__DisplayClass3_1.<BeginInvokeAction>b__1(IAsyncResult asyncResult) +188    System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +59    System.Web.Mvc.<>c.<BeginExecuteCore>b__152_1(IAsyncResult asyncResult, ExecuteCoreState innerState) +26    System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult
asyncResult) +73

System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +52
System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +39    System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +38    System.Web.Mvc.<>c.<BeginProcessRequest>b__20_1(IAsyncResult asyncResult, ProcessRequestState innerState) +40    System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult
asyncResult) +73

System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)
+38    System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
+602    System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +195    System.Web.HttpApplication.ExecuteStep(IExecutionStep
step, Boolean& completedSynchronously) +128`

And I checked the server log and it says "500 GET / - HTTP/2"

How can I resolve this situation and get the website up and running?

My website works good when I try it on localhost but for some reason it can't run on the server.
I've seen some articles but I can't apply it.

And this is my code:

```<code>public static bool WebRequestTest(string url)
{
    try
    {
        System.Net.WebRequest myRequest = System.Net.WebRequest.Create(url);
        System.Net.WebResponse myResponse = myRequest.GetResponse();
    }
    catch (System.Net.WebException)
    {
        return false;
    }
    return true;
}

public ActionResult Index()
{
  List<QLWebsite> obj = strDM.getDomain(0);
  for (int i = 0; i < obj.Count; i++)
  {
    if (WebRequestTest(obj[i].Domain) == false)
    {
      obj[i].status = false;
      strDM.EditDomain(obj[i]);
    }
    else
    {
      obj[i].status = true;
      strDM.EditDomain(obj[i]);
    }
  }
  return View(obj);
}
</code>```

Body:
I have published my website to hosting but i got the problem "HTTP/1.1 500 Internal Server Error" and my website shows "Error. An error occurred while processing your request"
I turned off customError mode and this is what it shows

Server Error in '/' Application. Invalid URI: The format of the URI
could not be determined. Description: An unhandled exception occurred
during the execution of the current web request. Please review the
stack trace for more information about the error and where it
originated in the code.

Exception Details: System.UriFormatException: Invalid URI: The format
of the URI could not be determined.

Source Error:

An unhandled exception was generated during the execution of the
current web request. Information regarding the origin and location of
the exception can be identified using the exception stack trace below.

Stack Trace: [UriFormatException: Invalid URI: The format of the URI could not be determined.]    System.Uri.CreateThis(String uri, Boolean dontEscape, UriKind uriKind) +8516254    System.Net.WebRequest.Create(String requestUriString) +44    CheckWebsite.Controllers.HomeController.WebRequestTest(String url) in D:\Projects\CheckWebsite\CheckWebsite\Controllers\HomeController.cs:111 CheckWebsite.Controllers.HomeController.Index() in D:\Projects\CheckWebsite\CheckWebsite\Controllers\HomeController.cs:26 lambda_method(Closure , ControllerBase , Object[] ) +87    System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2
parameters) +35

System.Web.Mvc.Async.<>c.b__9_0(IAsyncResult
asyncResult, ActionInvocation innerInvokeState) +39

System.Web.Mvc.Async.WrappedAsyncResult2.CallEndDelegate(IAsyncResult asyncResult) +77    System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +69    System.Web.Mvc.Async.<>c__DisplayClass11_0.<InvokeActionMethodFilterAsynchronouslyRecursive>b__0() +80    System.Web.Mvc.Async.<>c__DisplayClass11_2.<InvokeActionMethodFilterAsynchronouslyRecursive>b__2() +387    System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +69    System.Web.Mvc.Async.<>c__DisplayClass3_6.<BeginInvokeAction>b__4() +50    System.Web.Mvc.Async.<>c__DisplayClass3_1.<BeginInvokeAction>b__1(IAsyncResult asyncResult) +188    System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +59    System.Web.Mvc.<>c.<BeginExecuteCore>b__152_1(IAsyncResult asyncResult, ExecuteCoreState innerState) +26    System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult
asyncResult) +73

System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +52
System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +39    System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +38    System.Web.Mvc.<>c.<BeginProcessRequest>b__20_1(IAsyncResult asyncResult, ProcessRequestState innerState) +40    System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult
asyncResult) +73

System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)
+38    System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
+602    System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +195    System.Web.HttpApplication.ExecuteStep(IExecutionStep
step, Boolean& completedSynchronously) +128`

And I checked the server log and it says "500 GET / - HTTP/2"

How can I resolve this situation and get the website up and running?

My website works good when I try it on localhost but for some reason it can't run on the server.
I've seen some articles but I can't apply it.

And this is my code:

public static bool WebRequestTest(string url)
{
    try
    {
        System.Net.WebRequest myRequest = System.Net.WebRequest.Create(url);
        System.Net.WebResponse myResponse = myRequest.GetResponse();
    }
    catch (System.Net.WebException)
    {
        return false;
    }
    return true;
}

public ActionResult Index()
{
  List<QLWebsite> obj = strDM.getDomain(0);
  for (int i = 0; i < obj.Count; i++)
  {
    if (WebRequestTest(obj[i].Domain) == false)
    {
      obj[i].status = false;
      strDM.EditDomain(obj[i]);
    }
    else
    {
      obj[i].status = true;
      strDM.EditDomain(obj[i]);
    }
  }
  return View(obj);
}


问:
redux-saga function not being called after the action is dispatched from the component
i am trying to render my cart collection from my mongodb into my cart component, for that i have created a  GET api which is working fine (checked through postman) but when i am dispatching the action i have created to call the redux-saga function, the action function is being called but the redux-saga function is not being called.

//cartAction.js

```<code>import { CART_LIST } from "./constant";

// action for cartSaga to fetch cart list API.
export const cartList = () => {
    console.log('cartList action is called');
    return {
     type: CART_LIST,
     payload: 'data'

    }
};
</code>```

//cartSaga.js

```<code>import { takeEvery, put } from "redux-saga/effects";
import { CART_LIST, SET_CART_LIST } from "./constant";

function* getCartItems() {
    let cartList = yield fetch('http://localhost:7000/cart/');
    cartList = yield cartList.json();
    console.log("data from cartSaga", cartList);
    yield put({ type: SET_CART_LIST, data: cartList})
}

function* cartSaga() {
    yield takeEvery(CART_LIST, getCartItems)
}
export default cartSaga;
</code>```

the console.log in cartAction.js is running but cartSaga.js function cartSaga is not.  i have checked it from my end but can not find the issue, Kindly help.

i have checked the type in my cartAction.js, it is the same as in my cartSaga.js function cartSaga, i.e CART_LIST. i have also checked the imports but could not find anything wrong.

Body:
i am trying to render my cart collection from my mongodb into my cart component, for that i have created a  GET api which is working fine (checked through postman) but when i am dispatching the action i have created to call the redux-saga function, the action function is being called but the redux-saga function is not being called.

//cartAction.js

import { CART_LIST } from "./constant";

// action for cartSaga to fetch cart list API.
export const cartList = () => {
    console.log('cartList action is called');
    return {
     type: CART_LIST,
     payload: 'data'

    }
};

//cartSaga.js

import { takeEvery, put } from "redux-saga/effects";
import { CART_LIST, SET_CART_LIST } from "./constant";

function* getCartItems() {
    let cartList = yield fetch('http://localhost:7000/cart/');
    cartList = yield cartList.json();
    console.log("data from cartSaga", cartList);
    yield put({ type: SET_CART_LIST, data: cartList})
}

function* cartSaga() {
    yield takeEvery(CART_LIST, getCartItems)
}
export default cartSaga;

the console.log in cartAction.js is running but cartSaga.js function cartSaga is not.  i have checked it from my end but can not find the issue, Kindly help.

i have checked the type in my cartAction.js, it is the same as in my cartSaga.js function cartSaga, i.e CART_LIST. i have also checked the imports but could not find anything wrong.


问:
having problems in enabling sound feature in my dictionary api code
I am trying to enable a sound feature on my dictionary API but am having problems with my code since its not working</p>
```<code>const url = "https://api.dictionaryapi.dev/api/v2/entries/en/";
const result = document.getElementById("result");
const sound = document.getElementById("sound");
const btn = document.getElementById("search-btn");

btn.addEventListener("click", () => {
    let inpWord = document.getElementById("inp-word").value;
    fetch(`${url}${inpWord}`)
        .then((response) => response.json())
        .then((data) => {
            console.log(data);
            result.innerHTML = `
            <div class="word">
                    <h3>${inpWord}</h3>
                    <button onclick="playSound()">
                        <i class="fas fa-volume-up"></i>
                    </button>
                </div>
</code>```

Body:
I am trying to enable a sound feature on my dictionary API but am having problems with my code since its not working

const url = "https://api.dictionaryapi.dev/api/v2/entries/en/";
const result = document.getElementById("result");
const sound = document.getElementById("sound");
const btn = document.getElementById("search-btn");

btn.addEventListener("click", () => {
    let inpWord = document.getElementById("inp-word").value;
    fetch(`${url}${inpWord}`)
        .then((response) => response.json())
        .then((data) => {
            console.log(data);
            result.innerHTML = `

${inpWord}

                    <button onclick="playSound()">

                    </button>


问:
An error occurred while loading the image in VScode
I am recently developing new android project. I am trying to save image files into the server directory.

I use Retrofit for HttpConnection with server.

Storing image files into the server directory works well, but the image is not available. Everytime I upload files into the server, it says An error occurred while loading the image. I have been looking for solutions and trying to fix this problem, but I have no idea what causes this problem.

Here is my android code :

```<code>                                       ArrayList<MultipartBody.Part> files = new ArrayList<>();

                                    for(int a = 0; a < list.size(); a++) {
                                        // list = uri image list for recyclerview.

                                        RequestBody fileBody = RequestBody.create(MediaType.parse("image/jpeg"), String.valueOf(list.get(a)));

                                        String fileName = "photo" + a + ".jpg";

                                        MultipartBody.Part filePart = MultipartBody.Part.createFormData("uploaded_file"+a, fileName, fileBody);

                                        files.add(filePart);
                                    }

                                    Call<String> uploadPost = posts.uploadPost(files,hashMap);
                                    uploadPost.enqueue(new Callback<String>() {
                                        @Override
                                        public void onResponse(Call<String> call, Response<String> response) {
                                            if(response.isSuccessful() && response.body() != null) {

                                                Intent intent = new Intent(upload_sale.this, MainActivity.class);
                                                startActivity(intent);
                                                finish();
                                            }
                                        }

                                        @Override
                                        public void onFailure(Call<String> call, Throwable t) {
                                            Log.d("upload_post",t.getMessage());
                                        }
                                    });
</code>```

Here is the php code :

```<code>  $authNum = $_POST['authNum'];
  $title = $_POST['title'];
  $des = $_POST['description'];
  $price = $_POST['price'];
  $area = $_POST['area'];
  $longitude = $_POST['longitude'];
  $latitude = $_POST['latitude'];
  $count = $_POST['count'];
  $count_int = (int)$count;

if(isset($_FILES['uploaded_file0']['name'])) {
for($i = 0; $i<$count_int; $i++) {
    $basename = basename($_FILES['uploaded_file'.$i]['name']);
    $file_path = $file_path . $basename;
   if(isset($_FILES['uploaded_file'.$i])) {
    move_uploaded_file($_FILES['uploaded_file'.$i]['tmp_name'],"./postImage/".$fn.$basename);
    $query_img =
     "INSERT INTO post_img(path,authNum,img_del,post_authNum)
     VALUES ('http://3.36.34.173/postImage/".$fn.$basename."',$authNum,'../postImage/".$fn.$basename."','$post_authNum')
    ";

   }
</code>```

Thank you in advance.enter image description here

Body:
I am recently developing new android project. I am trying to save image files into the server directory.

I use Retrofit for HttpConnection with server.

Storing image files into the server directory works well, but the image is not available. Everytime I upload files into the server, it says An error occurred while loading the image. I have been looking for solutions and trying to fix this problem, but I have no idea what causes this problem.

Here is my android code :

                                       ArrayList<MultipartBody.Part> files = new ArrayList<>();

                                    for(int a = 0; a < list.size(); a++) {
                                        // list = uri image list for recyclerview.

                                        RequestBody fileBody = RequestBody.create(MediaType.parse("image/jpeg"), String.valueOf(list.get(a)));

                                        String fileName = "photo" + a + ".jpg";

                                        MultipartBody.Part filePart = MultipartBody.Part.createFormData("uploaded_file"+a, fileName, fileBody);

                                        files.add(filePart);
                                    }

                                    Call<String> uploadPost = posts.uploadPost(files,hashMap);
                                    uploadPost.enqueue(new Callback<String>() {
                                        @Override
                                        public void onResponse(Call<String> call, Response<String> response) {
                                            if(response.isSuccessful() && response.body() != null) {

                                                Intent intent = new Intent(upload_sale.this, MainActivity.class);
                                                startActivity(intent);
                                                finish();
                                            }
                                        }

                                        @Override
                                        public void onFailure(Call<String> call, Throwable t) {
                                            Log.d("upload_post",t.getMessage());
                                        }
                                    });

Here is the php code :

  $authNum = $_POST['authNum'];
  $title = $_POST['title'];
  $des = $_POST['description'];
  $price = $_POST['price'];
  $area = $_POST['area'];
  $longitude = $_POST['longitude'];
  $latitude = $_POST['latitude'];
  $count = $_POST['count'];
  $count_int = (int)$count;

if(isset($_FILES['uploaded_file0']['name'])) {
for($i = 0; $i<$count_int; $i++) {
    $basename = basename($_FILES['uploaded_file'.$i]['name']);
    $file_path = $file_path . $basename;
   if(isset($_FILES['uploaded_file'.$i])) {
    move_uploaded_file($_FILES['uploaded_file'.$i]['tmp_name'],"./postImage/".$fn.$basename);
    $query_img =
     "INSERT INTO post_img(path,authNum,img_del,post_authNum)
     VALUES ('http://3.36.34.173/postImage/".$fn.$basename."',$authNum,'../postImage/".$fn.$basename."','$post_authNum')
    ";

   }

Thank you in advance.enter image description here