问:
Select records that belong to all specified categories
A video can have several categories. I want to select a video that belongs to two categories.

The result returned by this query and that the videos belong to only one of the categories in the condition

SELECT Videos.id, Videos.title
FROM videos Videos
INNER JOIN categories_videos CategoriesVideos
    ON Videos.id = CategoriesVideos.video_id
INNER JOIN categories Categories
    ON Categories.id = CategoriesVideos.category_id AND Categories.id IN (21, 35)
LIMIT 25;
```

I tried to do several joins on the categories table but it doesn't change anything.

Thanks for your help.

答:
When you write your join like this

```<code>AND Categories.id IN(21, 35)
</code>```

you're asking for all videos that has at least one of these Categories.id associated with.

If want only the one who has both, you can try this

```<code>SELECT Videos.id, Videos.title FROM videos Videos
INNER JOIN categories_videos CategoriesVideos
    ON Videos.id = CategoriesVideos.video_id
INNER JOIN categories Categories
    ON Categories.id = CategoriesVideos.category_id
AND Categories.id = 21 AND Categories.id =35
LIMIT 25;
</code>```

Body:
A video can have several categories. I want to select a video that belongs to two categories.

The result returned by this query and that the videos belong to only one of the categories in the condition

SELECT Videos.id, Videos.title
FROM videos Videos
INNER JOIN categories_videos CategoriesVideos
    ON Videos.id = CategoriesVideos.video_id
INNER JOIN categories Categories
    ON Categories.id = CategoriesVideos.category_id AND Categories.id IN (21, 35)
LIMIT 25;

I tried to do several joins on the categories table but it doesn't change anything.

Thanks for your help.

Body:
When you write your join like this

AND Categories.id IN(21, 35)

you're asking for all videos that has at least one of these Categories.id associated with.

If want only the one who has both, you can try this

SELECT Videos.id, Videos.title FROM videos Videos
INNER JOIN categories_videos CategoriesVideos
    ON Videos.id = CategoriesVideos.video_id
INNER JOIN categories Categories
    ON Categories.id = CategoriesVideos.category_id
AND Categories.id = 21 AND Categories.id =35
LIMIT 25;


来源: stackexchange

问:
Grant Create Sequence in PostgreSQL
Is it possible to grant a user/role only the permission to create/alter sequences in a PostgreSQL database/schema not allowing the user to create tables at the same time?

I currently use

GRANT CREATE ON SCHEMA myschema TO "MyRole";

which gives the user full create access to the schema, though he cannot delete or alter any tables that he does not own. My use case is that I use Liquibase to setup the database schema upfront and want to have the application only using a db user that can only read/write data. Unfortunately the application requires a dynamic number of sequences, i.e. it must be possible for the application to create new sequences in the database/schema.

答: The only possible way is to create an event trigger that throws an error if you create anything else than a sequence.</p>

ContentLicense: CC BY-SA 4.0

Title: Grant Create Sequence in PostgreSQL


问:
Code doesn't run when I had one more elsif statement
Can anyone please explain to me why my code doesn't run when I have my second elsif statement in. I'm sure it's something simple but I've been over it a few times, wrote out the code again and still can't work out the bug. It only bugs when line 25 to 30 are in and says

undefined method`[]' on line 35

but this error will change to something else if I run it again.

So this is affecting line_three as a test I am trying "Southern Cross" for the starting location and "Windsor" for the destination.

This is an error message I receive:

```<code>Traceback (most recent call last):
pt_planner.rb:35:in `<main>': undefined method `[]' for nil:NilClass (NoMethodError)
</code>```

another is:

```<code>Traceback (most recent call last):
pt_planner.rb:33:in `<main>': undefined method `-' for nil:NilClass (NoMethodError)
</code>```

Hope this edit helps

```<code>require 'pry'

line_one = ["flinders street", "richmond", "east richmond", "burnley", "hawthorn", "glenferrie"]
line_two = ['Flagstaff', 'Melbourne Central', 'Parliament', 'Richmond', 'Kooyong', 'Tooronga']
line_three = ['Southern Cross', 'Richmond', 'South Yarra' ,'Prahran' 'Windsor']

#1 where would you like to go capture input
puts "what is your starting location?"
user_input_1 = gets.chomp
puts "what is your end location"
user_input_2 = gets.chomp

if line_one.include?(user_input_1) == true and
    line_one.include?(user_input_2) == true
    origin_index = line_one.index(user_input_1)
    destination_index = line_one.index(user_input_2)
    route = line_one
elsif
    line_two.include?(user_input_1) == true and
    line_two.include?(user_input_2) == true
    origin_index = line_two.index(user_input_1)
    destination_index = line_two.index(user_input_2)
    route = line_two
elsif
    line_three.include?(user_input_1) == true and
    line_three.include?(user_input_2) == true
    origin_index = line_three.index(user_input_1)
    destination_index = line_two.index(user_input_2)
    route = line_three
end

stops = destination_index - origin_index

puts "origin: #{route[origin_index]}\ndestination: #{route[destination_index]}\n#{route.slice(origin_index +1, stops)}\n stops total: #{destination_index - origin_index}"

binding.pry
</code>```

答:
You tried to search in wrong array

Change

```<code>destination_index = line_two.index(user_input_2)
</code>```

to

```<code>destination_index = line_three.index(user_input_2)
</code>```

Also you don't need to compare with true. include? returns true or false, that's enough. It's better to use && instead of and. And put condition on one line with elsif

You can refactor like this to check both values are in the array

```<code>([user_input_1, user_input_2] - line_three).empty?
</code>```

Body:
Can anyone please explain to me why my code doesn't run when I have my second elsif statement in. I'm sure it's something simple but I've been over it a few times, wrote out the code again and still can't work out the bug. It only bugs when line 25 to 30 are in and says

undefined method`[]' on line 35

but this error will change to something else if I run it again.

So this is affecting line_three as a test I am trying "Southern Cross" for the starting location and "Windsor" for the destination.

This is an error message I receive:

Traceback (most recent call last):
pt_planner.rb:35:in `<main>': undefined method `[]' for nil:NilClass (NoMethodError)

another is:

Traceback (most recent call last):
pt_planner.rb:33:in `<main>': undefined method `-' for nil:NilClass (NoMethodError)

Hope this edit helps

require 'pry'

line_one = ["flinders street", "richmond", "east richmond", "burnley", "hawthorn", "glenferrie"]
line_two = ['Flagstaff', 'Melbourne Central', 'Parliament', 'Richmond', 'Kooyong', 'Tooronga']
line_three = ['Southern Cross', 'Richmond', 'South Yarra' ,'Prahran' 'Windsor']

#1 where would you like to go capture input
puts "what is your starting location?"
user_input_1 = gets.chomp
puts "what is your end location"
user_input_2 = gets.chomp

if line_one.include?(user_input_1) == true and
    line_one.include?(user_input_2) == true
    origin_index = line_one.index(user_input_1)
    destination_index = line_one.index(user_input_2)
    route = line_one
elsif
    line_two.include?(user_input_1) == true and
    line_two.include?(user_input_2) == true
    origin_index = line_two.index(user_input_1)
    destination_index = line_two.index(user_input_2)
    route = line_two
elsif
    line_three.include?(user_input_1) == true and
    line_three.include?(user_input_2) == true
    origin_index = line_three.index(user_input_1)
    destination_index = line_two.index(user_input_2)
    route = line_three
end

stops = destination_index - origin_index

puts "origin: #{route[origin_index]}\ndestination: #{route[destination_index]}\n#{route.slice(origin_index +1, stops)}\n stops total: #{destination_index - origin_index}"

binding.pry

Body:
You tried to search in wrong array

Change

destination_index = line_two.index(user_input_2)

to

destination_index = line_three.index(user_input_2)

Also you don't need to compare with true. include? returns true or false, that's enough. It's better to use && instead of and. And put condition on one line with elsif

You can refactor like this to check both values are in the array

([user_input_1, user_input_2] - line_three).empty?


问:
How to implement RandomAccessFile's seek() and getFilePointer() using FileInputStream and BufferReader?
I would like to Open a file containing UTF-8 encoded text, Can able to set position, Read 25 lines, Can able to get position.

Unfortunately RandomAccessFile does not support UTF-8 encoding. So I have written this code. I recursive call getParsedLines() method with the returned offset value to read next 25 lines but it prints first 1-25 rows, then print 349-373, 695-719 and so on.

```<code>public long getParsedLines(File file, long offset) {

    int counter = 0;
    FileInputStream fis = null;
    InputStreamReader streamReader = null;
    BufferedReader br = null;
    try {
        fis = new FileInputStream(file);
        fis.getChannel().position(offset);
        streamReader = new InputStreamReader(fis, "UTF8");
        br = new BufferedReader(streamReader);
        String str;
        while (counter <= 24) {
            if ((str = br.readLine()) != null) {
                System.out.println(str);
            } else {
                offset = -1;
                break;
            }
            counter++;
        }
        if (fis != null) {
            offset = fis.getChannel().position();

        }
    } catch (IOException ex) {
    } finally {
        try {
            if (fis != null) {
                fis.close();
            }
        } catch (IOException ex) {
        }

    }

    return offset;
}
</code>```

how can I get last offset correct so I can print 1-25, 26-50, 51-75. 76-100 and so on.

Yes.. For some backward compatibility I have some constraint that I have to read text file "line by line" using readLine() and read only 25-25 lines at a time not the whole text.

答: The BufferedReader reads ahead,so the position on the underlying file > the logical position the BufferedReader has reached. You could try DataInputStream.readLine(), which doesn't, and which is deprecated, and which doesn't handle the issues mentioned in the Javadoc against the deprecation.</p>

ContentLicense: CC BY-SA 3.0

Body:
I would like to Open a file containing UTF-8 encoded text, Can able to set position, Read 25 lines, Can able to get position.

Unfortunately RandomAccessFile does not support UTF-8 encoding. So I have written this code. I recursive call getParsedLines() method with the returned offset value to read next 25 lines but it prints first 1-25 rows, then print 349-373, 695-719 and so on.

public long getParsedLines(File file, long offset) {

    int counter = 0;
    FileInputStream fis = null;
    InputStreamReader streamReader = null;
    BufferedReader br = null;
    try {
        fis = new FileInputStream(file);
        fis.getChannel().position(offset);
        streamReader = new InputStreamReader(fis, "UTF8");
        br = new BufferedReader(streamReader);
        String str;
        while (counter <= 24) {
            if ((str = br.readLine()) != null) {
                System.out.println(str);
            } else {
                offset = -1;
                break;
            }
            counter++;
        }
        if (fis != null) {
            offset = fis.getChannel().position();

        }
    } catch (IOException ex) {
    } finally {
        try {
            if (fis != null) {
                fis.close();
            }
        } catch (IOException ex) {
        }

    }

    return offset;
}

how can I get last offset correct so I can print 1-25, 26-50, 51-75. 76-100 and so on.

Yes.. For some backward compatibility I have some constraint that I have to read text file "line by line" using readLine() and read only 25-25 lines at a time not the whole text.


问:
Azure Data Factory 2, Data flow with derived nullable boolean column, how to set a boolean to null
I have a source csv file like this

```<code>ID, IsEnabled
1,Y,
2,N,
3,,
</code>```

And I'd like my destination csv file to look like this

```<code>ID, IsEnabled
1,TRUE,
2,FALSE,
3,,
</code>```

In order to eventually map the IsEnabled column to a nullable bit in sql.

I've tried this expression without luck (From here: Solved - Azure Data Factory 2, Data flow with derived column, how to set a timestamp to null)

```<code>case(IsEnabled=="N", false(), case(IsEnabled=="Y", true()))
</code>```

I've also tried defining the default format to "Y" and "N" with and without the quotes with no luck.

答:
I ended up creating a tranformation for IsEnabled as such

```<code>iif(IsEnabled == "Y", "TRUE", iif(IsEnabled  == "N", "FALSE", ""))
</code>```

I also had to

Import the schema for the csv file

Set IsEnabled to string

Body:
I have a source csv file like this

ID, IsEnabled
1,Y,
2,N,
3,,

And I'd like my destination csv file to look like this

ID, IsEnabled
1,TRUE,
2,FALSE,
3,,

In order to eventually map the IsEnabled column to a nullable bit in sql.

I've tried this expression without luck (From here: Solved - Azure Data Factory 2, Data flow with derived column, how to set a timestamp to null)

case(IsEnabled=="N", false(), case(IsEnabled=="Y", true()))

I've also tried defining the default format to "Y" and "N" with and without the quotes with no luck.

Body:
I ended up creating a tranformation for IsEnabled as such

iif(IsEnabled == "Y", "TRUE", iif(IsEnabled  == "N", "FALSE", ""))

I also had to

Import the schema for the csv file

Set IsEnabled to string


问:
Qlikview - show first and last selected value in list
I need to display first and last selected value in list. I have listbox and when I pick date I got this result in list

I want to get in one box min value selected but when I use minString(Data) I got 22/2022 instead 303/202. And for max I need to get 306/2022.

Can anyone help please?

答:
You can try using the OnOpen document trigger.

enter image description here


问:
How to change SQL query laravel equivalent query
I have written a SQL query as below

```<code>select id from users where fname not in (select fname from blocked_users);
</code>```

It is working as expected. Can anyone help me to convert this to a laravel equivalent query?

Thanks.

答:
Try this -</p>
```<code>DB::table('users')->whereNotIn('fname', function ($query) {
    $query->select('fname')->from('blocked_users');
})->get();
</code>```

Body:
I have written a SQL query as below

select id from users where fname not in (select fname from blocked_users);

It is working as expected. Can anyone help me to convert this to a laravel equivalent query?

Thanks.

Body:
Try this -

DB::table('users')->whereNotIn('fname', function ($query) {
    $query->select('fname')->from('blocked_users');
})->get();


问:
Get count of each unique values groupby another column and transform them into columns
I have a dataframe like below:

id
name
colA
colB

One
Ana
abc
xyz

One
Ana
abc
xyz

One
Ana
bde
xyz

One
Ana
bde
xyz

One
Ana
bde
yhn

One
Ana
bde
yhn

One
Ana
bde
qwe

One
Ana
teh
qwe

Two
Bob
abc
qwe

Two
Bob
teh
qwe

Two
Bob
pop
omg

I need to transform my dataframe as

id
name
abc
bde
teh
pop
xyz
yhn
qwe
omg

One
Ana
2
5
1
0
4
2
2
0

Two
Bob
1
0
1
1
0
0
2
1

I wrote below code to achieve this but it do not gives me expected output and also I have no idea how to perform it for multiple columns. Please help.

df = df.groupby(['id','colA']).size().reset_index(name='colA_counts')

答:
you could try this:

```<code>a = df[["id", "name", "A"]].copy()
b = df[["id", "name", "B"]].copy()
b.columns = ["id", "name", "A"]

result = pd.concat([a, b]).value_counts().reset_index()
result.columns = ["id", "name", "A", "count"]
pd.pivot_table(result, index=["id", "name"], columns=["A"], values="count").fillna(0)
</code>```

What I'm basically doing is, I first create a new DataFrame, concatenated of the original one where both A and B are just called "A" then as you don't make any difference of whether it is A or B. In this I let it count the different values, i.e. combinations of id, name and value.

Then I pivot the table so, that the values in "A" are considered the columns, finally I fill up all those combinations that don't appear in the data with zeros by calling fillna(0).

What I btw don't understand is, where the 1 in the "one ana pop" in your example comes from. Your data is not providing this.

Body:
you could try this:

a = df[["id", "name", "A"]].copy()
b = df[["id", "name", "B"]].copy()
b.columns = ["id", "name", "A"]

result = pd.concat([a, b]).value_counts().reset_index()
result.columns = ["id", "name", "A", "count"]
pd.pivot_table(result, index=["id", "name"], columns=["A"], values="count").fillna(0)

What I'm basically doing is, I first create a new DataFrame, concatenated of the original one where both A and B are just called "A" then as you don't make any difference of whether it is A or B. In this I let it count the different values, i.e. combinations of id, name and value.

Then I pivot the table so, that the values in "A" are considered the columns, finally I fill up all those combinations that don't appear in the data with zeros by calling fillna(0).

What I btw don't understand is, where the 1 in the "one ana pop" in your example comes from. Your data is not providing this.


问:
Using powershell for a google report
I'm new to using powershell, I'm trying to use the PSGSuite module to get a report for all users for the past 30 days. What I've got so far is the following

```<code>
$REQUESTEDDATE = Read-Host -Prompt 'Enter the month for the desired report month in numerical form. e.g Jan 1 Feb 2 Mar 3'
$REPORTDATE = (Get-Date -Month ($REQUESTEDDATE-(-1)) -Hour 0 -Minute 0 -Second 0)
$MonthAgo = $REPORTDATE.AddMonths(-1)
$FIRSTDAYOFMONTH=GET-DATE $MonthAgo -Day 1
$LASTDAYOFMONTH=GET-DATE $FIRSTDAYOFMONTH.AddMonths(1).AddSeconds(-1)
$Times = $FIRSTDAYOFMONTH..$LASTDAYOFMONTH.day | Foreach-Object {
$currentdate = Get-Date -Day $_ -Month $LASTDAYOFMONTH.Month -Year $LASTDAYOFMONTH.Year
$GMAIL = Get-GSUsageReport -Date $currentdate -UserKey xxx -flat

}
</code>```

This is now throwing a "Invalid cast from 'DateTime' to 'Int32' error. There's probably a much easier way to do this, but I'm more of the hardware/networking side thrown onto this while the dev team is working on different projects, so any help is appreciated.

答:
First thing is that I hate all those CAPITALS in your code, so if you don't mind I have changed that.

Next, you can simply run through the dates for as long as the running date is less than the final date (day 1 of the requested date) using a while loop:

```<code>$requestedDate = Read-Host -Prompt 'Enter the month for the desired report month in numerical form. e.g Jan 1 Feb 2 Mar 3'
$reportDate    = (Get-Date -Month $requestedDate -Day 1).Date   # end date set at midnight on day 1
$runningDate   = $reportDate.AddMonths(-1)                      # start at day 1, one month ago

$result = while ($runningDate -lt $reportDate) {
    # perform your command and capture the output in variable $result
    Get-GSUsageReport -Date $runningDate -UserKey xxx -flat
    # increment the running date
    $runningDate = $runningDate.AddDays(1)
}

# show the result
$result
</code>```

Title: Using powershell for a google report

Body:
I'm new to using powershell, I'm trying to use the PSGSuite module to get a report for all users for the past 30 days. What I've got so far is the following

$REQUESTEDDATE = Read-Host -Prompt 'Enter the month for the desired report month in numerical form. e.g Jan 1 Feb 2 Mar 3'
$REPORTDATE = (Get-Date -Month ($REQUESTEDDATE-(-1)) -Hour 0 -Minute 0 -Second 0)
$MonthAgo = $REPORTDATE.AddMonths(-1)
$FIRSTDAYOFMONTH=GET-DATE $MonthAgo -Day 1
$LASTDAYOFMONTH=GET-DATE $FIRSTDAYOFMONTH.AddMonths(1).AddSeconds(-1)
$Times = $FIRSTDAYOFMONTH..$LASTDAYOFMONTH.day | Foreach-Object {
$currentdate = Get-Date -Day $_ -Month $LASTDAYOFMONTH.Month -Year $LASTDAYOFMONTH.Year
$GMAIL = Get-GSUsageReport -Date $currentdate -UserKey xxx -flat

}

This is now throwing a "Invalid cast from 'DateTime' to 'Int32' error. There's probably a much easier way to do this, but I'm more of the hardware/networking side thrown onto this while the dev team is working on different projects, so any help is appreciated.

Body:
First thing is that I hate all those CAPITALS in your code, so if you don't mind I have changed that.

Next, you can simply run through the dates for as long as the running date is less than the final date (day 1 of the requested date) using a while loop:

$requestedDate = Read-Host -Prompt 'Enter the month for the desired report month in numerical form. e.g Jan 1 Feb 2 Mar 3'
$reportDate    = (Get-Date -Month $requestedDate -Day 1).Date   # end date set at midnight on day 1
$runningDate   = $reportDate.AddMonths(-1)                      # start at day 1, one month ago

$result = while ($runningDate -lt $reportDate) {
    # perform your command and capture the output in variable $result
    Get-GSUsageReport -Date $runningDate -UserKey xxx -flat
    # increment the running date
    $runningDate = $runningDate.AddDays(1)
}

# show the result
$result


问:
Try to play a .mov file in Vue, unable to complie
A .mov file is necessary to cater Safari users.
However in vue:

```<code><video
       id="myvideo"
       autoplay
       muted
       loop
       playsinline
     >
       <source src="@/assets/01/output2.mov" type="video/quicktime" />
     </video>
</code>```

When I trying to compile, "npm run serve" to start the local host:

ERROR  Failed to compile with 1 error                    5:40:14 pm

error  in ./src/assets/01/output2.mov

Module parse failed: Unexpected character '' (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
(Source code omitted for this binary file)

Not sure what to do, i try to instaill a package: File Loader, setup some config in vue.config.js:

```<code>module.exports = {
  module: {
    rules: [
      { test: /\.mov$/, use: 'file-loader' }
    ],
  },
}
</code>```

However, after i try to run it again, it saids: "Module is not allowed"

My package.json

```<code>  "dependencies": {
    "bootstrap": "^4.5.3",
    "bootstrap-vue": "^2.21.2",
    "core-js": "^3.6.5",
    "file-loader": "^6.2.0",
    "gsap": "^3.8.0",
    "vue": "^2.6.11",
    "vue-cool-lightbox": "^2.7.4",
    "vue-i18n": "^8.26.3",
    "vue-meta": "^2.4.0",
    "vue-router": "^3.2.0",
    "vue-slick-carousel": "^1.0.6"
  },
  "devDependencies": {
    "@intlify/vue-i18n-loader": "^1.1.0",
    "@vue/cli-plugin-babel": "~4.5.0",
    "@vue/cli-plugin-eslint": "~4.5.0",
    "@vue/cli-plugin-router": "~4.5.0",
    "@vue/cli-service": "~4.5.0",
    "babel-eslint": "^10.1.0",
    "eslint": "^6.7.2",
    "eslint-plugin-vue": "^6.2.2",
    "node-sass": "^4.12.0",
    "sass-loader": "^8.0.2",
    "vue-cli-plugin-i18n": "~2.3.1",
    "vue-template-compiler": "^2.6.11"
  },
</code>```

Thank you all kindly~!

答:
For me it went through like this

```<code>module.exports = {
  productionSourceMap: false,
  transpileDependencies: [
    'vuetify'
  ],
  chainWebpack: config => {
    config.module
      .rule('mov')
      .test(/\.mov$/)
      .use('file-loader')
        .loader('file-loader')
        .end()
  }
}
</code>```

My package.json

```<code>  "dependencies": {
    "@lottiefiles/lottie-interactivity": "^1.2.0",
    "@lottiefiles/lottie-player": "^1.4.5",
    "core-js": "^3.6.5",
    "vue": "^2.6.11",
    "vue-axios": "^3.4.0",
    "vue-meta": "^2.4.0",
    "vue-moment": "^4.1.0",
    "vue-router": "^3.2.0",
    "vuetify": "^2.4.0",
    "vuex": "^3.6.2"
  },
  "devDependencies": {
    "@vue/cli-plugin-babel": "~4.5.0",
    "@vue/cli-plugin-eslint": "~4.5.0",
    "@vue/cli-plugin-router": "~4.5.0",
    "@vue/cli-service": "~4.5.0",
    "axios": "^0.18.0",
    "babel-eslint": "^10.1.0",
    "css-loader": "^6.5.1",
    "eslint": "^6.7.2",
    "eslint-plugin-vue": "^6.2.2",
    "sass": "~1.32.0",
    "sass-loader": "^10.0.0",
    "style-loader": "^3.3.1",
    "stylus": "^0.55.0",
    "stylus-loader": "^6.2.0",
    "vue-cli-plugin-axios": "~0.0.4",
    "vue-cli-plugin-vuetify": "~2.4.3",
    "vue-template-compiler": "^2.6.11",
    "vuetify-loader": "^1.7.0"
  },
</code>```

Body:
A .mov file is necessary to cater Safari users.
However in vue:

<video
       id="myvideo"
       autoplay
       muted
       loop
       playsinline
     >
       <source src="@/assets/01/output2.mov" type="video/quicktime" />
     </video>

When I trying to compile, "npm run serve" to start the local host:

ERROR  Failed to compile with 1 error                    5:40:14 pm

error  in ./src/assets/01/output2.mov

Module parse failed: Unexpected character '' (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
(Source code omitted for this binary file)

Not sure what to do, i try to instaill a package: File Loader, setup some config in vue.config.js:

module.exports = {
  module: {
    rules: [
      { test: /\.mov$/, use: 'file-loader' }
    ],
  },
}

However, after i try to run it again, it saids: "Module is not allowed"

My package.json

  "dependencies": {
    "bootstrap": "^4.5.3",
    "bootstrap-vue": "^2.21.2",
    "core-js": "^3.6.5",
    "file-loader": "^6.2.0",
    "gsap": "^3.8.0",
    "vue": "^2.6.11",
    "vue-cool-lightbox": "^2.7.4",
    "vue-i18n": "^8.26.3",
    "vue-meta": "^2.4.0",
    "vue-router": "^3.2.0",
    "vue-slick-carousel": "^1.0.6"
  },
  "devDependencies": {
    "@intlify/vue-i18n-loader": "^1.1.0",
    "@vue/cli-plugin-babel": "~4.5.0",
    "@vue/cli-plugin-eslint": "~4.5.0",
    "@vue/cli-plugin-router": "~4.5.0",
    "@vue/cli-service": "~4.5.0",
    "babel-eslint": "^10.1.0",
    "eslint": "^6.7.2",
    "eslint-plugin-vue": "^6.2.2",
    "node-sass": "^4.12.0",
    "sass-loader": "^8.0.2",
    "vue-cli-plugin-i18n": "~2.3.1",
    "vue-template-compiler": "^2.6.11"
  },

Thank you all kindly~!

Body:
For me it went through like this

module.exports = {
  productionSourceMap: false,
  transpileDependencies: [
    'vuetify'
  ],
  chainWebpack: config => {
    config.module
      .rule('mov')
      .test(/\.mov$/)
      .use('file-loader')
        .loader('file-loader')
        .end()
  }
}

My package.json

  "dependencies": {
    "@lottiefiles/lottie-interactivity": "^1.2.0",
    "@lottiefiles/lottie-player": "^1.4.5",
    "core-js": "^3.6.5",
    "vue": "^2.6.11",
    "vue-axios": "^3.4.0",
    "vue-meta": "^2.4.0",
    "vue-moment": "^4.1.0",
    "vue-router": "^3.2.0",
    "vuetify": "^2.4.0",
    "vuex": "^3.6.2"
  },
  "devDependencies": {
    "@vue/cli-plugin-babel": "~4.5.0",
    "@vue/cli-plugin-eslint": "~4.5.0",
    "@vue/cli-plugin-router": "~4.5.0",
    "@vue/cli-service": "~4.5.0",
    "axios": "^0.18.0",
    "babel-eslint": "^10.1.0",
    "css-loader": "^6.5.1",
    "eslint": "^6.7.2",
    "eslint-plugin-vue": "^6.2.2",
    "sass": "~1.32.0",
    "sass-loader": "^10.0.0",
    "style-loader": "^3.3.1",
    "stylus": "^0.55.0",
    "stylus-loader": "^6.2.0",
    "vue-cli-plugin-axios": "~0.0.4",
    "vue-cli-plugin-vuetify": "~2.4.3",
    "vue-template-compiler": "^2.6.11",
    "vuetify-loader": "^1.7.0"
  },


问:
Require a selection in Amazon Mechanical Turk <crowd-radio-group>
I'm trying to use AMT's new crowd-form HTML elements to create a HIT.

The documentation for <crowd-radio-group> says

The following attributes are supported by this element.

allow-empty-selection

A Boolean switch that, if present, allows no radio button to be checked.

However, even without that attribute, the form is perfectly happy to allow the user to submit without selecting any of the radio buttons in the group.

Can I get it to require a selection using just the HTML elements, or do I need to add validation code and check it myself?

答:
You can include a custom script in the design page that validates your form when a user clicks submit.

The code is available on Github, as directed here by a more active community of MTurk requesters on Reddit.

The code is as follows:

```<code>function validateForm() {
    var valid = true;
    var radioGroups = document.querySelectorAll("crowd-radio-group");
    for (var i = 0; i < radioGroups.length; i++) {
        var validGroup = false;
        var radioButtons = radioGroups[i].children;
        for (var j = 0; j < radioButtons.length; j++) {
            validGroup = validGroup || radioButtons[j].checked;
        }
        valid = valid && validGroup;
    }
    return valid;
}

window.onload = function() {
    document.querySelector('crowd-form').onsubmit = function(e) {
        if (!validateForm()) {
            alert("Please answer all the questions in order to submit.");
            e.preventDefault();
        }
    }
}
</code>```

As, you can see, the validateForm() function is invoked on submitting the form which checks if all radio-groups have at least one checked button.The user is alerted if the form is incomplete. Any other necessary custom checks can be placed here.

Body:
You can include a custom script in the design page that validates your form when a user clicks submit.

The code is available on Github, as directed here by a more active community of MTurk requesters on Reddit.

The code is as follows:

function validateForm() {
    var valid = true;
    var radioGroups = document.querySelectorAll("crowd-radio-group");
    for (var i = 0; i < radioGroups.length; i++) {
        var validGroup = false;
        var radioButtons = radioGroups[i].children;
        for (var j = 0; j < radioButtons.length; j++) {
            validGroup = validGroup || radioButtons[j].checked;
        }
        valid = valid && validGroup;
    }
    return valid;
}

window.onload = function() {
    document.querySelector('crowd-form').onsubmit = function(e) {
        if (!validateForm()) {
            alert("Please answer all the questions in order to submit.");
            e.preventDefault();
        }
    }
}

As, you can see, the validateForm() function is invoked on submitting the form which checks if all radio-groups have at least one checked button.The user is alerted if the form is incomplete. Any other necessary custom checks can be placed here.


问:
Is there a function to get the UTC date in the Locale String Format?
I want to get the current UTC date in JavaScript, but display it in the local date format (like Date.toLocaleDateString() does).

I first tried to just get the current UTC Date with Date.toUTCString() but that doesn't actually print out in the local format.

I then tried using the options configuration in toLocaleDateString(), but that just printed the local date and not the UTC date in the local format.
e.g. new Date().toLocaleDateString(options = {timeZone: "UTC"})

I then tried formatting using Intl.DateTimeFormat(), but that just gives the same results as Date.toLocaleDateString() does.

If there was a way to get the locale format then I'd be happy to use that format to format the UTC Date, but as far as I can tell there is none.

For example, given the new Date("Sat, 30 Mar 2019 00:27:19 GMT"), In the US, I should print out "3/30/2019", in Europe I should print out "30/3/2019", and so on, for every supported locale.

However, new Date("Sat, 30 Mar 2019 00:27:19 GMT").toLocaleDateString(options = {timeZone: "UTC"}) will print out "3/29/2019" instead.

答:
Check out Intl.DateTimeFormat on MDN!

Using it is as simple as

```<code>// do this once in a central library file
const formatter = new Intl.DateTimeFormat('en', {
  timeZone: 'UTC',
  timeZoneName: 'short',
  month: 'short',
  day: '2-digit',
  hour12: false,
  hour: '2-digit',
  minute: '2-digit',
})

// reuse anywhere for consistency
const myDate = new Date(
  'Thu Feb 10 2022 12:50:14 GMT+0100'
)

formatter.format(myDate) === 'Feb 10, 11:50 UTC' // true
</code>```

Open your console, copy-paste the code and start playing!

Again, Intl.DateTimeFormat on MDN.

Enjoy!

Body:
Check out Intl.DateTimeFormat on MDN!

Using it is as simple as

// do this once in a central library file
const formatter = new Intl.DateTimeFormat('en', {
  timeZone: 'UTC',
  timeZoneName: 'short',
  month: 'short',
  day: '2-digit',
  hour12: false,
  hour: '2-digit',
  minute: '2-digit',
})

// reuse anywhere for consistency
const myDate = new Date(
  'Thu Feb 10 2022 12:50:14 GMT+0100'
)

formatter.format(myDate) === 'Feb 10, 11:50 UTC' // true

Open your console, copy-paste the code and start playing!

Again, Intl.DateTimeFormat on MDN.

Enjoy!


问:
Powershell, output xml to screen
I'm learning PowerShell.  I can load an xml file into a variable and manipulate it.  I can then call the object's save method to save to disk.  I expected there to be a way to output the resulting xml to screen, though.  I can't seem to find one.  Is there a way, other than outputting to file and then file-to-screen?</p>

Title: Powershell, output xml to screen

Body: [System.Xml.Linq.XDocument]::Parse($Xml.OuterXml).ToString()


问:
Compare a time command result as a number in IF
My.sh measures execution time in seconds:

```<code>/usr/bin/time -f '%e'  long-command
</code>```

I need to compare that time, that should be stored in $exptime, to some number, like:

```<code> if (( $exptime < 80  ))  ; then
                    echo "OK" ; exit 0
    elif (( $exptime > 80  ))  ; then
                    echo "NOK" ; exit 1
    else echo "error"
    fi
</code>```

I was trying to assign the output of a command to a variable using command substitution exptime=$(), and I get the result on console, but it doesn't work to compare that number in this script (0/1 of the script is used further). But, instead of just using the number in IF, script is called 2 more times.

There are many questions on How to set a variable to the output of a command in Bash? but I couldn't figure out the solution.

答:
I resolved this by avoiding time and using just long-command followed by exptime=$SECONDS.
Script is iterative and SECONDS starts from 0 each time.

Not sure why time works with simple case of exptime=$( { time  sleep 3 ; } 2>&1 ), where it's used as number, and not with my long-command, where echo shows it's a correct number but later in IF it repeats command with division by 0 (error token is....

Body:
My.sh measures execution time in seconds:

/usr/bin/time -f '%e'  long-command

I need to compare that time, that should be stored in $exptime, to some number, like:

 if (( $exptime < 80  ))  ; then
                    echo "OK" ; exit 0
    elif (( $exptime > 80  ))  ; then
                    echo "NOK" ; exit 1
    else echo "error"
    fi

I was trying to assign the output of a command to a variable using command substitution exptime=$(), and I get the result on console, but it doesn't work to compare that number in this script (0/1 of the script is used further). But, instead of just using the number in IF, script is called 2 more times.

There are many questions on How to set a variable to the output of a command in Bash? but I couldn't figure out the solution.


问:
Setting an attribute from a parents attribute
I have this HTML and i am trying to convert the href from photo.php to #photo etc for each

```<code><ul id="menu">
    <li id="home" class="tab_selected"><a href="home.php">Home</a></li>
    <li id="portfolio"><a href="portfolio.php">Portfolio</a></li>
    <li id="music"><a href="music.php">Music</a></li>
    <li id="video"><a href="video.php">Video</a></li>
    <li id="photo"><a href="photo.php">Photo</a></li>
</ul>
</code>```

I have been trying something like this:

```<code>$('#menu li a').attr('href', "#"+$(this).parent().attr('id'));
</code>```

But the href always comes out undefined.

I am storing the hash in the li#id but if i could not do this it would be even better.

Thanks.

答: The problem is that this doesnt holds the wrong value (it refers to any wrapping context there may be), because you're not in the proper context. Look at either of the (currently) 3 other answers to see how to get around this issue (hint, you want to use each)

Body:
I have this HTML and i am trying to convert the href from photo.php to #photo etc for each

Home

Portfolio

Music

Video

Photo

I have been trying something like this:

$('#menu li a').attr('href', "#"+$(this).parent().attr('id'));

But the href always comes out undefined.

I am storing the hash in the li#id but if i could not do this it would be even better.

Thanks.


问:
Spring SAML handshake failure - Failed to validate untrusted credential against trusted key
I'm using Spring Security SAML extension for integrating with the ACA healthcare (aka Obamacare) website. It uses IDP Initiated SSO. The SAML handshake fails with the following output

```<code>org.opensaml.xml.security.keyinfo.provider.InlineX509DataProvider] Single certificate was present, treating as end-entity certificate
org.opensaml.xml.security.keyinfo.BasicProviderKeyInfoCredentialResolver] Credentials successfully extracted from child {http://www.w3.org/2000/09/xmldsig#}X509Data by provider org.opensaml.xml.security.keyinfo.provider.InlineX509DataProvider
org.opensaml.xml.security.keyinfo.BasicProviderKeyInfoCredentialResolver] A total of 1 credentials were resolved
org.opensaml.xml.security.credential.criteria.EvaluableCredentialCriteriaRegistry] Registry could not locate evaluable criteria for criteria class org.opensaml.xml.security.keyinfo.KeyInfoCriteria
org.opensaml.xml.signature.SignatureValidator] Attempting to validate signature using key from supplied credential
org.opensaml.xml.signature.SignatureValidator] Creating XMLSignature object
org.opensaml.xml.signature.SignatureValidator] Validating signature with signature algorithm URI: http://www.w3.org/2000/09/xmldsig#rsa-sha1
org.opensaml.xml.signature.SignatureValidator] Validation credential key algorithm 'RSA', key instance class 'sun.security.rsa.RSAPublicKeyImpl'
org.opensaml.xml.signature.SignatureValidator] Signature validated with key from supplied credential
org.opensaml.xml.signature.impl.BaseSignatureTrustEngine] Signature validation using candidate credential was successful
org.opensaml.xml.signature.impl.BaseSignatureTrustEngine] Successfully verified signature using KeyInfo-derived credential
org.opensaml.xml.signature.impl.BaseSignatureTrustEngine] Attempting to establish trust of KeyInfo-derived credential
org.opensaml.xml.security.trust.ExplicitKeyTrustEvaluator] Failed to validate untrusted credential against trusted key
org.opensaml.xml.signature.impl.BaseSignatureTrustEngine] Failed to establish trust of KeyInfo-derived credential
org.opensaml.xml.signature.impl.BaseSignatureTrustEngine] Failed to verify signature and/or establish trust using any KeyInfo-derived credentials
org.opensaml.xml.signature.impl.ExplicitKeySignatureTrustEngine] Attempting to verify signature using trusted credentials
org.opensaml.xml.signature.SignatureValidator] Attempting to validate signature using key from supplied credential
org.opensaml.xml.signature.SignatureValidator] Creating XMLSignature object
org.opensaml.xml.signature.SignatureValidator] Validating signature with signature algorithm URI: http://www.w3.org/2000/09/xmldsig#rsa-sha1
org.opensaml.xml.signature.SignatureValidator] Validation credential key algorithm 'RSA', key instance class 'sun.security.rsa.RSAPublicKeyImpl'
org.apache.xml.security.signature.XMLSignature] Signature verification failed.
org.opensaml.xml.signature.SignatureValidator] Signature did not validate against the credential's key
org.opensaml.xml.signature.impl.BaseSignatureTrustEngine] Signature validation using candidate validation credential failed
org.opensaml.xml.validation.ValidationException: Signature did not validate against the credential's key
    at org.opensaml.xml.signature.SignatureValidator.validate(SignatureValidator.java:79)
</code>```

My securityContext has the following:

```<code>    <bean id="metadata" class="org.springframework.security.saml.metadata.CachingMetadataManager">
    <constructor-arg>
        <list>
            <bean class="org.springframework.security.saml.metadata.ExtendedMetadataDelegate">
                <constructor-arg>
                    <bean class="org.opensaml.saml2.metadata.provider.FilesystemMetadataProvider">
                        <constructor-arg>
                            <value type="java.io.File">classpath:${MC_METADATA}</value>
                        </constructor-arg>
                        <property name="parserPool" ref="parserPool" />
                    </bean>
                </constructor-arg>
                <constructor-arg>
                    <map>
                        <entry key="${MC_ALIAS_1}">
                            <bean class="org.springframework.security.saml.metadata.ExtendedMetadata">
                                <property name="local" value="true" />
                                <property name="alias" value="${MC_ALIAS_1}" />
                                <property name="securityProfile" value="metaiop" />
                                <property name="requireArtifactResolveSigned" value="false" />
                                <property name="requireLogoutRequestSigned" value="false" />
                                <property name="requireLogoutResponseSigned" value="false" />
                                <property name="idpDiscoveryEnabled" value="false" />
                            </bean>
                        </entry>

                    </map>
                </constructor-arg>
            </bean>
        </list>
    </constructor-arg>
    <property name="defaultExtendedMetadata">
        <bean class="org.springframework.security.saml.metadata.ExtendedMetadata">
            <property name="local" value="true" />
            <property name="alias" value="${MC_ALIAS_1}" />
            <property name="securityProfile" value="metaiop" />
            <property name="requireArtifactResolveSigned" value="false" />
            <property name="requireLogoutRequestSigned" value="false" />
            <property name="requireLogoutResponseSigned" value="false" />
            <property name="idpDiscoveryEnabled" value="false" />
        </bean>
    </property>
    <property name="hostedSPName" value="${MC_ALIAS_1}" />
</bean>
</code>```

The incoming SAML contains X509Certificate and I have copied it to my metadata file under signing. I also tried adding 'metadataTrustCheck' as false but still the same error. Communication happens over HTTPS and my test server (receiving the SAML) uses self-signed certs.

Any ideas as to what may be missing/wrong?

答:
In my case was a metadata entityID missplacing.

In the IDP metadata file I had, the entityID was wrong. It was, in fact, the value of SP entityID, which was not correct.

Once I fixed it (by setting the correct entityID IDP value) application could establish trust.

So if you don't know the IDP entityID ask for it to the IDP administrator.

I.E.:

```<code><md:EntityDescriptor
xmlns:md="urn:oasis:names:tc:SAML:2.0:metadata"
entityID="«YOUR IDP ENTITY_ID»"
>
<md:IDPSSODescriptor protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol" >
    <md:KeyDescriptor xmlns:ds="http://www.w3.org/2000/09/xmldsig#" use="signing">
...
</code>```

Body:
I'm using Spring Security SAML extension for integrating with the ACA healthcare (aka Obamacare) website. It uses IDP Initiated SSO. The SAML handshake fails with the following output

org.opensaml.xml.security.keyinfo.provider.InlineX509DataProvider] Single certificate was present, treating as end-entity certificate
org.opensaml.xml.security.keyinfo.BasicProviderKeyInfoCredentialResolver] Credentials successfully extracted from child {http://www.w3.org/2000/09/xmldsig#}X509Data by provider org.opensaml.xml.security.keyinfo.provider.InlineX509DataProvider
org.opensaml.xml.security.keyinfo.BasicProviderKeyInfoCredentialResolver] A total of 1 credentials were resolved
org.opensaml.xml.security.credential.criteria.EvaluableCredentialCriteriaRegistry] Registry could not locate evaluable criteria for criteria class org.opensaml.xml.security.keyinfo.KeyInfoCriteria
org.opensaml.xml.signature.SignatureValidator] Attempting to validate signature using key from supplied credential
org.opensaml.xml.signature.SignatureValidator] Creating XMLSignature object
org.opensaml.xml.signature.SignatureValidator] Validating signature with signature algorithm URI: http://www.w3.org/2000/09/xmldsig#rsa-sha1
org.opensaml.xml.signature.SignatureValidator] Validation credential key algorithm 'RSA', key instance class 'sun.security.rsa.RSAPublicKeyImpl'
org.opensaml.xml.signature.SignatureValidator] Signature validated with key from supplied credential
org.opensaml.xml.signature.impl.BaseSignatureTrustEngine] Signature validation using candidate credential was successful
org.opensaml.xml.signature.impl.BaseSignatureTrustEngine] Successfully verified signature using KeyInfo-derived credential
org.opensaml.xml.signature.impl.BaseSignatureTrustEngine] Attempting to establish trust of KeyInfo-derived credential
org.opensaml.xml.security.trust.ExplicitKeyTrustEvaluator] Failed to validate untrusted credential against trusted key
org.opensaml.xml.signature.impl.BaseSignatureTrustEngine] Failed to establish trust of KeyInfo-derived credential
org.opensaml.xml.signature.impl.BaseSignatureTrustEngine] Failed to verify signature and/or establish trust using any KeyInfo-derived credentials
org.opensaml.xml.signature.impl.ExplicitKeySignatureTrustEngine] Attempting to verify signature using trusted credentials
org.opensaml.xml.signature.SignatureValidator] Attempting to validate signature using key from supplied credential
org.opensaml.xml.signature.SignatureValidator] Creating XMLSignature object
org.opensaml.xml.signature.SignatureValidator] Validating signature with signature algorithm URI: http://www.w3.org/2000/09/xmldsig#rsa-sha1
org.opensaml.xml.signature.SignatureValidator] Validation credential key algorithm 'RSA', key instance class 'sun.security.rsa.RSAPublicKeyImpl'
org.apache.xml.security.signature.XMLSignature] Signature verification failed.
org.opensaml.xml.signature.SignatureValidator] Signature did not validate against the credential's key
org.opensaml.xml.signature.impl.BaseSignatureTrustEngine] Signature validation using candidate validation credential failed
org.opensaml.xml.validation.ValidationException: Signature did not validate against the credential's key
    at org.opensaml.xml.signature.SignatureValidator.validate(SignatureValidator.java:79)

My securityContext has the following:

    <bean id="metadata" class="org.springframework.security.saml.metadata.CachingMetadataManager">
    <constructor-arg>
        <list>
            <bean class="org.springframework.security.saml.metadata.ExtendedMetadataDelegate">
                <constructor-arg>
                    <bean class="org.opensaml.saml2.metadata.provider.FilesystemMetadataProvider">
                        <constructor-arg>
                            <value type="java.io.File">classpath:${MC_METADATA}</value>
                        </constructor-arg>
                        <property name="parserPool" ref="parserPool" />
                    </bean>
                </constructor-arg>
                <constructor-arg>
                    <map>
                        <entry key="${MC_ALIAS_1}">
                            <bean class="org.springframework.security.saml.metadata.ExtendedMetadata">
                                <property name="local" value="true" />
                                <property name="alias" value="${MC_ALIAS_1}" />
                                <property name="securityProfile" value="metaiop" />
                                <property name="requireArtifactResolveSigned" value="false" />
                                <property name="requireLogoutRequestSigned" value="false" />
                                <property name="requireLogoutResponseSigned" value="false" />
                                <property name="idpDiscoveryEnabled" value="false" />
                            </bean>
                        </entry>

                    </map>
                </constructor-arg>
            </bean>
        </list>
    </constructor-arg>
    <property name="defaultExtendedMetadata">
        <bean class="org.springframework.security.saml.metadata.ExtendedMetadata">
            <property name="local" value="true" />
            <property name="alias" value="${MC_ALIAS_1}" />
            <property name="securityProfile" value="metaiop" />
            <property name="requireArtifactResolveSigned" value="false" />
            <property name="requireLogoutRequestSigned" value="false" />
            <property name="requireLogoutResponseSigned" value="false" />
            <property name="idpDiscoveryEnabled" value="false" />
        </bean>
    </property>
    <property name="hostedSPName" value="${MC_ALIAS_1}" />
</bean>

The incoming SAML contains X509Certificate and I have copied it to my metadata file under signing. I also tried adding 'metadataTrustCheck' as false but still the same error. Communication happens over HTTPS and my test server (receiving the SAML) uses self-signed certs.

Any ideas as to what may be missing/wrong?

Body:
In my case was a metadata entityID missplacing.

In the IDP metadata file I had, the entityID was wrong. It was, in fact, the value of SP entityID, which was not correct.

Once I fixed it (by setting the correct entityID IDP value) application could establish trust.

So if you don't know the IDP entityID ask for it to the IDP administrator.

I.E.:

<md:EntityDescriptor
xmlns:md="urn:oasis:names:tc:SAML:2.0:metadata"
entityID="«YOUR IDP ENTITY_ID»"
>
<md:IDPSSODescriptor protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol" >
    <md:KeyDescriptor xmlns:ds="http://www.w3.org/2000/09/xmldsig#" use="signing">
...


问:
How to make a condition that checks if value equals 1 or 0 without resulting in a boolean evaluation in PHP
I'm making an API and in one of the endpoints the variable user_type that can only be a 0 or a 1

```<code>api/user?user_type=0 || api/user?user_type=1
</code>```

Inside my controller i check if the variable equals to one of those two values, the problem is that the comprobation results in a boolean one, and if in the endpoint i add a text value for user_type results in true because the variable exists.

Is there any way of evaluating without triggering a boolean result? Something like this:

```<code>if($variable != 0 && $variable != 1){ return true } //It should be false if $variable == 'text' and true if variable == 0 or 1
</code>```

答:
PHP8 satisfies your condition without any modification. Or you can use one of the below conditions -
0 and 1 within quotes.
OR
Check with ! == and ===</p>

Body:
I'm making an API and in one of the endpoints the variable user_type that can only be a 0 or a 1

api/user?user_type=0 || api/user?user_type=1

Inside my controller i check if the variable equals to one of those two values, the problem is that the comprobation results in a boolean one, and if in the endpoint i add a text value for user_type results in true because the variable exists.

Is there any way of evaluating without triggering a boolean result? Something like this:

if($variable != 0 && $variable != 1){ return true } //It should be false if $variable == 'text' and true if variable == 0 or 1


问:
ng template binding with button tooltip is not working
tolTemplate is not getting bind with [tooltip]

```<code><ng-template #tolTemplate>
  Just another:
</ng-template>
<button type="button" class="btn btn-success" [tooltip]="tolTemplate">
  Show me tooltip with html
</button>
</code>```

Any idea, how to resolve this.

\

答:
Try to add to button attribute contentType or content-type (depends on version angular).

```<code><ng-template #tolTemplate>
  Just another:
</ng-template>
<button type="button" class="btn btn-success" [tooltip]="tolTemplate" contentType="template">
  Show me tooltip with html
</button>
</code>```

Body:
tolTemplate is not getting bind with [tooltip]

<ng-template #tolTemplate>
  Just another:
</ng-template>
<button type="button" class="btn btn-success" [tooltip]="tolTemplate">
  Show me tooltip with html
</button>

Any idea, how to resolve this.

\

Body:
Try to add to button attribute contentType or content-type (depends on version angular).

<ng-template #tolTemplate>
  Just another:
</ng-template>
<button type="button" class="btn btn-success" [tooltip]="tolTemplate" contentType="template">
  Show me tooltip with html
</button>


问:
Vue watch for two variable mutually linked on change leads to infinite loop
I have a vue app like

```<code>
var VueAppExport = new Vue({
    el: '#nav_section_downloads',
    delimiters: ['[[', ']]'], //to avoid conflict with django template
    data: {
        xport: {width: 1000, height: 1000, lock: true}
    },
    watch: {
        'xport.width' : {
            handler: function(newValue, oldValue) {
                if (this.xport.lock){
                    this.xport.height = parseInt(this.xport.height) + parseInt(newValue) - parseInt(oldValue);
                }
            },
        },
        'xport.height' : {
            handler: function(newValue, oldValue) {
                if (this.xport.lock){
                    this.xport.width = parseInt(this.xport.width) + parseInt(newValue) - parseInt(oldValue);
                }
            },
        },
    },

})

</code>```

I want the scenario where if width or height value changes then commensurately height/width value change when lock is true.

Problem with my code is infinite looping. watching changes in width and in case of change changing height while at the same time watching height and then changing width is feeding each other infinitely.

I tried to set value by compute method but in compute setter old value is not available.

Is there any way out to perform this task.

答:
Did you try to watch whole object xport like:

```<code>watch: {
  xport: {
    handler(val, oldVal){
    // do stuff
    },
    deep: true
  }
}
</code>```

Body:
I have a vue app like

var VueAppExport = new Vue({
    el: '#nav_section_downloads',
    delimiters: ['[[', ']]'], //to avoid conflict with django template
    data: {
        xport: {width: 1000, height: 1000, lock: true}
    },
    watch: {
        'xport.width' : {
            handler: function(newValue, oldValue) {
                if (this.xport.lock){
                    this.xport.height = parseInt(this.xport.height) + parseInt(newValue) - parseInt(oldValue);
                }
            },
        },
        'xport.height' : {
            handler: function(newValue, oldValue) {
                if (this.xport.lock){
                    this.xport.width = parseInt(this.xport.width) + parseInt(newValue) - parseInt(oldValue);
                }
            },
        },
    },

})

I want the scenario where if width or height value changes then commensurately height/width value change when lock is true.

Problem with my code is infinite looping. watching changes in width and in case of change changing height while at the same time watching height and then changing width is feeding each other infinitely.

I tried to set value by compute method but in compute setter old value is not available.

Is there any way out to perform this task.

Body:
Did you try to watch whole object xport like:

watch: {
  xport: {
    handler(val, oldVal){
    // do stuff
    },
    deep: true
  }
}


问:
not getting the data from Serializer
view.py

@csrf_exempt

def blog_list(request):

```<code>if request.method == 'GET':
    post = Post.objects.all()
    serializer = BlogSerializer(post, many=True)
    return JsonResponse(serializer.data,safe=False)

elif request.method == 'POST':
    data = JSONParser().parse(request)
    serializer = BlogSerializer(data=data)
    if serializer.is_valid():
        serializer.save()
        return JsonResponse(serializer.data, status=201)
    return JsonResponse(serializer.errors, status=400)
</code>```

class BlogSerializer(serializers.Serializer):

```<code>class Meta:
    model = Post
    fields = ['author', 'title',  'text',  'published_date']
</code>```

class Post(models.Model):

```<code>author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)

def publish(self):
    self.published_date = timezone.now()
    self.save()

def __str__(self):
    return self.title
</code>```

答:
First you need to understand a few things about this code

```<code>def blog_list(request):
    if request.method == 'GET':
        post = Post.objects.all()
        serializer = BlogSerializer(post, many=True)
        return JsonResponse(serializer.data,safe=False)

    elif request.method == 'POST':
        data = JSONParser().parse(request)
        serializer = BlogSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data, status=201)
        return JsonResponse(serializer.errors, status=400)
</code>```

Here request referes to a request object, which contains all the data inside the request (method, body, data, headers, etc), and not just the request data. So, you want to parse request.body, instead of request.

```<code>data = JSONParser().parse(request.body)
</code>```

Title: not getting the data from Serializer

Body:
view.py

@csrf_exempt

def blog_list(request):

if request.method == 'GET':
    post = Post.objects.all()
    serializer = BlogSerializer(post, many=True)
    return JsonResponse(serializer.data,safe=False)

elif request.method == 'POST':
    data = JSONParser().parse(request)
    serializer = BlogSerializer(data=data)
    if serializer.is_valid():
        serializer.save()
        return JsonResponse(serializer.data, status=201)
    return JsonResponse(serializer.errors, status=400)

class BlogSerializer(serializers.Serializer):

class Meta:
    model = Post
    fields = ['author', 'title',  'text',  'published_date']

class Post(models.Model):

author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)

def publish(self):
    self.published_date = timezone.now()
    self.save()

def __str__(self):
    return self.title

Body:
First you need to understand a few things about this code

def blog_list(request):
    if request.method == 'GET':
        post = Post.objects.all()
        serializer = BlogSerializer(post, many=True)
        return JsonResponse(serializer.data,safe=False)

    elif request.method == 'POST':
        data = JSONParser().parse(request)
        serializer = BlogSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data, status=201)
        return JsonResponse(serializer.errors, status=400)

Here request referes to a request object, which contains all the data inside the request (method, body, data, headers, etc), and not just the request data. So, you want to parse request.body, instead of request.

data = JSONParser().parse(request.body)


问:
Multiple Background Images in IE, Using CSS to create multiple background images in IE
This is my first time posting here. I have a problem. I've been trying for ages to get multiple background images to work in both Chrome/Safari and IE. Of course it works in all browsers except IE.

This my code:

```<code>#container {
  width: 828px;
  margin: auto;
  padding: 0;
  text-align: left;
  position: relative;
  overflow: visible;
  background-image: url('images/body.png'), url('images/filler.png');
  background-repeat: no-repeat, repeat-y;
}
</code>```

The reason I am using two background images is because I want the illustrated part to stay at the top, and have the white page background in the same div layer repeat when more content is added.

Right now this code works perfectly in Chrome, but NEITHER of the background images show up in Internet Explorer.

Help?

答:
If it´s possible I suggest you use two container elements.

HTML

```<code><div id="container">
  <div id="inner-container">
  </div>
</div>
</code>```

CSS

```<code>#container {
  background: url('images/filler.png') repeat-y;
}
#inner-container {
  background: transparent url('images/body.png') no-repeat left top;
}
</code>```

Body:
This is my first time posting here. I have a problem. I've been trying for ages to get multiple background images to work in both Chrome/Safari and IE. Of course it works in all browsers except IE.

This my code:

#container {
  width: 828px;
  margin: auto;
  padding: 0;
  text-align: left;
  position: relative;
  overflow: visible;
  background-image: url('images/body.png'), url('images/filler.png');
  background-repeat: no-repeat, repeat-y;
}

The reason I am using two background images is because I want the illustrated part to stay at the top, and have the white page background in the same div layer repeat when more content is added.

Right now this code works perfectly in Chrome, but NEITHER of the background images show up in Internet Explorer.

Help?

Body:
If it´s possible I suggest you use two container elements.

HTML

<div id="container">
  <div id="inner-container">
  </div>
</div>

CSS

#container {
  background: url('images/filler.png') repeat-y;
}
#inner-container {
  background: transparent url('images/body.png') no-repeat left top;
}


问:
Is using eval together with argparse save?
I use argparse and eval to change loglevels of logging.

parser = argparse.ArgumentParser(
        description="Adds New Location to the Snipe-IT Server")
parser.add_argument('-l', '--loglevel', type=str, default='WARNING', choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'])
args = parser.parse_args()
logging.basicConfig(level=eval(f"logging.{args.loglevel}"))
```

I wonder if it is save to use eval in this case? I don't know if choices limit in this case the inputs.

答:
No, it is not quite safe. It won't be too hard for a knowledgable malicious user to hack the argparse module to be able to pass any thing they want through the CLI.

However, at this point they might as well just write their own malicious program than trying to use yours as an attack vector.

Even if one deems this very specific usage of eval safer because its input is validated, knowingly using a function that exposes a huge attack surface when a safe and easy alternative is available (getattr in this case) is a very questionable decision.

Moreover, the codebase might change in the future (eg. the sanitization code might be removed or modified) leaving the eval usage more vulnerable than it already was.

Regardless, just use getattr. eval is almost never the correct solution.

```<code>logging.basicConfig(level=getattr(logging, args.loglevel))
</code>```

Body:
I use argparse and eval to change loglevels of logging.

parser = argparse.ArgumentParser(
        description="Adds New Location to the Snipe-IT Server")
parser.add_argument('-l', '--loglevel', type=str, default='WARNING', choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'])
args = parser.parse_args()
logging.basicConfig(level=eval(f"logging.{args.loglevel}"))

I wonder if it is save to use eval in this case? I don't know if choices limit in this case the inputs.

Body:
No, it is not quite safe. It won't be too hard for a knowledgable malicious user to hack the argparse module to be able to pass any thing they want through the CLI.

However, at this point they might as well just write their own malicious program than trying to use yours as an attack vector.

Even if one deems this very specific usage of eval safer because its input is validated, knowingly using a function that exposes a huge attack surface when a safe and easy alternative is available (getattr in this case) is a very questionable decision.

Moreover, the codebase might change in the future (eg. the sanitization code might be removed or modified) leaving the eval usage more vulnerable than it already was.

Regardless, just use getattr. eval is almost never the correct solution.

logging.basicConfig(level=getattr(logging, args.loglevel))


问:
QuerySelector is not a function
Each time I click + button on the code below, I have this error. I am completely new to JS and need your help, how to solve it out and show totalsum of selected items ( user input * dish price ).

window.onload = function () {
  const totalPrice = calcOrder(); // calculate sum
  document.querySelector('.total-price').innerHTML = totalPrice; // put on page
}

// Calculate total sum
function calcOrder() {
  let result = 0;
  const menus = document.querySelectorAll('.single-menu');

  for (let i = 0; i < menus.length; i++) {
    const price = Number(menus.querySelector('.price').innerText);
    const qty = Number(menus.querySelector('input').value);
    result += price * qty;
  }

  return result;
}

function stepperDecrement(btn) {
  const inputEl = btn.nextElementSibling;
  const calcStep = inputEl.step - 1;
  const newValue = parseInt(inputEl.value) + calcStep;
  if (newValue >= inputEl.min && newValue <= inputEl.max) {
    inputEl.value = newValue;
  }
  const totalPrice = calcOrder(); // calculate sum
  document.querySelector('.total-price').innerHTML = totalPrice; // выводим на странице
}
function stepperIncrement(btn) {
  const inputEl = btn.previousElementSibling;
  const calcStep = inputEl.step * 1;
  const newValue = parseInt(inputEl.value) + calcStep;
  if (newValue >= inputEl.min && newValue <= inputEl.max) {
    inputEl.value = newValue;
  }
  const totalPrice = calcOrder(); // calculate sum
  document.querySelector('.total-price').innerHTML = totalPrice; // выводим на странице
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background: linear-gradient(rgba(0, 0, 0, 0.93), rgba(0, 0, 0, 0.93)),
    url("../images/saveInPhotoshop.png") no-repeat;
  background-size: cover;
}

/* MENU */
.wrapper {
  color: white;

  width: 1200px;
  margin: 100px auto;
}

.title {
  text-align: center;
  margin-bottom: 60px;
}

.title h4 {
  text-transform: capitalize;
  font-size: 36px;
  position: relative;
  display: inline-block;
  padding-bottom: 10px;
}

.title h4 span {
  display: block;
  font-size: 18px;
  font-style: italic;
  margin-bottom: 10px;
}

.title h4:before {
  position: absolute;
  content: "";
  width: 100px;
  height: 2px;
  background-color: #ff7720;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
}

.menu {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.single-menu {
  flex-basis: 580px;
  margin-bottom: 40px;
  padding-bottom: 40px;
  border-bottom: 1px solid #ddd;
}

.single-menu:nth-child(5),
.single-menu:nth-child(6) {
  border-bottom: 0;
}

.single-menu {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.single-menu:hover img {
  border-radius: 0;
}

.single-menu img {
  max-width: 180px;
  margin-right: 30px;
  border-radius: 50%;
  border: 1px solid #ddd;
  padding: 3px;
  transition: 0.5s;
}

.single-menu h4 {
  text-transform: capitalize;
  font-size: 22px;
  border-bottom: 1px dashed #333;
  margin-bottom: 5px;
  padding-bottom: 5px;
}

.single-menu h4 span {
  float: right;
  color: #ff7720;
  font-style: italic;
}

.filter-menu {
  width: 200px;
  margin-left: auto;
  margin-right: 75px;
}

.filter-menu-desc {
  width: 460px;
}

.menu-description {
  width: 350px;
}

.price {
  margin-left: 10px;
}

/* Button */

.myContainer {
  width: 100px;
  top: 50%;
  left: 50%;
  display: flex;
  border-radius: 45px;
  box-shadow: 0 20px 30px rgba(0, 0, 0, 0.15);
}

input[type="number"] {
  -moz-appearance: textfield;
  text-align: center;
  font-size: 20px;
  border: none;
  background-color: #e0e0e0;
  color: #302020;
}

input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

button {
  color: #ff7720;
  background-color: #d3d2d2;
  border: none;
  font-size: 35px;
  cursor: pointer;
}

.decrement {
  padding: 15px 5px 15px 25px;
  border-radius: 45px 0 0 45px;
}

.increment {
  padding: 15px 25px 15px 5px;
  border-radius: 0 45px 45px 0;
}</code>```

Dish number three15.00

DRINKS

Description

        <button class="decrement" type="button" onclick="stepperDecrement(this)">-</button>
        <input value="0" name="dishIdQuantityMap[8]" type="number" min="0" max="100" step="1" readonly />
        <button class="increment" type="button" onclick="stepperIncrement(this)">+</button>

Dish number one25.00

DRINKS

Custom description

        <button class="decrement" type="button" onclick="stepperDecrement(this)">-</button>
        <input value="0" name="dishIdQuantityMap[6]" type="number" min="0" max="100" step="1" readonly />
        <button class="increment" type="button" onclick="stepperIncrement(this)">+</button>

Dish number two32.00

DRINKS

Description

        <button class="decrement" type="button" onclick="stepperDecrement(this)">-</button>
        <input value="0" name="dishIdQuantityMap[7]" type="number" min="0" max="100" step="1" readonly />
        <button class="increment" type="button" onclick="stepperIncrement(this)">+</button>

Dish number 4215.00

DRINKS

Description

        <button class="decrement" type="button" onclick="stepperDecrement(this)">-</button>
        <input value="0" name="dishIdQuantityMap[9]" type="number" min="0" max="100" step="1" readonly />
        <button class="increment" type="button" onclick="stepperIncrement(this)">+</button>

dsa2231.00

DRINKS

dadsads

        <button class="decrement" type="button" onclick="stepperDecrement(this)">-</button>
        <input value="0" name="dishIdQuantityMap[1]" type="number" min="0" max="100" step="1" readonly />
        <button class="increment" type="button" onclick="stepperIncrement(this)">+</button>

    Input your address
    <input type="text" class="form-control" id="address" required name="address" value="">
    <button type="submit" value="Submit" class="btn btn-outline-light mt-3 btn-lg">Confirm order</button>

</form>```

答:
const menus = document.querySelectorAll('.single-menu'); will return a NodeList as response. so menus is an array. You should use menus[i].querySelector('.price').innerText to access the node.

Also the element with class name total-price is not available.

Working Fiddle

window.onload = function () {
  const totalPrice = calcOrder(); // calculate sum
  document.querySelector('.total-price').innerHTML = totalPrice; // put on page
}

// Calculate total sum
function calcOrder() {
  let result = 0;
  const menus = document.querySelectorAll('.single-menu');

  for (let i = 0; i < menus.length; i++) {
    const price = Number(menus[i].querySelector('.price').innerText);
    const qty = Number(menus[i].querySelector('input').value);
    result += price * qty;
  }

  return result;
}

function stepperDecrement(btn) {
  const inputEl = btn.nextElementSibling;
  const calcStep = inputEl.step;
  const newValue = parseInt(inputEl.value) - calcStep;
  if (newValue >= inputEl.min && newValue <= inputEl.max) {
    inputEl.value = newValue;
  }
  const totalPrice = calcOrder(); // calculate sum
  document.querySelector('.total-price').innerHTML = totalPrice; // выводим на странице
}

function stepperIncrement(btn) {
  const inputEl = btn.previousElementSibling;
  const calcStep = inputEl.step * 1;
  const newValue = parseInt(inputEl.value) + calcStep;
  if (newValue >= inputEl.min && newValue <= inputEl.max) {
    inputEl.value = newValue;
  }
  const totalPrice = calcOrder(); // calculate sum
  document.querySelector('.total-price').innerHTML = totalPrice; // выводим на странице
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background: linear-gradient(rgba(0, 0, 0, 0.93), rgba(0, 0, 0, 0.93)),
    url("../images/saveInPhotoshop.png") no-repeat;
  background-size: cover;
}

/* MENU */
.wrapper {
  color: white;

  width: 1200px;
  margin: 100px auto;
}

.title {
  text-align: center;
  margin-bottom: 60px;
}

.title h4 {
  text-transform: capitalize;
  font-size: 36px;
  position: relative;
  display: inline-block;
  padding-bottom: 10px;
}

.title h4 span {
  display: block;
  font-size: 18px;
  font-style: italic;
  margin-bottom: 10px;
}

.title h4:before {
  position: absolute;
  content: "";
  width: 100px;
  height: 2px;
  background-color: #ff7720;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
}

.menu {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.single-menu {
  flex-basis: 580px;
  margin-bottom: 40px;
  padding-bottom: 40px;
  border-bottom: 1px solid #ddd;
}

.single-menu:nth-child(5),
.single-menu:nth-child(6) {
  border-bottom: 0;
}

.single-menu {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.single-menu:hover img {
  border-radius: 0;
}

.single-menu img {
  max-width: 180px;
  margin-right: 30px;
  border-radius: 50%;
  border: 1px solid #ddd;
  padding: 3px;
  transition: 0.5s;
}

.single-menu h4 {
  text-transform: capitalize;
  font-size: 22px;
  border-bottom: 1px dashed #333;
  margin-bottom: 5px;
  padding-bottom: 5px;
}

.single-menu h4 span {
  float: right;
  color: #ff7720;
  font-style: italic;
}

.filter-menu {
  width: 200px;
  margin-left: auto;
  margin-right: 75px;
}

.filter-menu-desc {
  width: 460px;
}

.menu-description {
  width: 350px;
}

.price {
  margin-left: 10px;
}

/* Button */

.myContainer {
  width: 100px;
  top: 50%;
  left: 50%;
  display: flex;
  border-radius: 45px;
  box-shadow: 0 20px 30px rgba(0, 0, 0, 0.15);
}

input[type="number"] {
  -moz-appearance: textfield;
  text-align: center;
  font-size: 20px;
  border: none;
  background-color: #e0e0e0;
  color: #302020;
}

input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

button {
  color: #ff7720;
  background-color: #d3d2d2;
  border: none;
  font-size: 35px;
  cursor: pointer;
}

.decrement {
  padding: 15px 5px 15px 25px;
  border-radius: 45px 0 0 45px;
}

.increment {
  padding: 15px 25px 15px 5px;
  border-radius: 0 45px 45px 0;
}</code>```

Dish number three15.00

DRINKS

Description

        <button class="decrement" type="button" onclick="stepperDecrement(this)">-</button>
        <input value="0" name="dishIdQuantityMap[8]" type="number" min="0" max="100" step="1" readonly />
        <button class="increment" type="button" onclick="stepperIncrement(this)">+</button>

Dish number one25.00

DRINKS

Custom description

        <button class="decrement" type="button" onclick="stepperDecrement(this)">-</button>
        <input value="0" name="dishIdQuantityMap[6]" type="number" min="0" max="100" step="1" readonly />
        <button class="increment" type="button" onclick="stepperIncrement(this)">+</button>

Dish number two32.00

DRINKS

Description

        <button class="decrement" type="button" onclick="stepperDecrement(this)">-</button>
        <input value="0" name="dishIdQuantityMap[7]" type="number" min="0" max="100" step="1" readonly />
        <button class="increment" type="button" onclick="stepperIncrement(this)">+</button>

Dish number 4215.00

DRINKS

Description

        <button class="decrement" type="button" onclick="stepperDecrement(this)">-</button>
        <input value="0" name="dishIdQuantityMap[9]" type="number" min="0" max="100" step="1" readonly />
        <button class="increment" type="button" onclick="stepperIncrement(this)">+</button>

dsa2231.00

DRINKS

dadsads

        <button class="decrement" type="button" onclick="stepperDecrement(this)">-</button>
        <input value="0" name="dishIdQuantityMap[1]" type="number" min="0" max="100" step="1" readonly />
        <button class="increment" type="button" onclick="stepperIncrement(this)">+</button>

    Input your address
    <input type="text" class="form-control" id="address" required name="address" value="">
    <button type="submit" value="Submit" class="btn btn-outline-light mt-3 btn-lg">Confirm order</button>

</form>```

Title: QuerySelector is not a function

Body:
Each time I click + button on the code below, I have this error. I am completely new to JS and need your help, how to solve it out and show totalsum of selected items ( user input * dish price ).

window.onload = function () {
  const totalPrice = calcOrder(); // calculate sum
  document.querySelector('.total-price').innerHTML = totalPrice; // put on page
}

// Calculate total sum
function calcOrder() {
  let result = 0;
  const menus = document.querySelectorAll('.single-menu');

  for (let i = 0; i < menus.length; i++) {
    const price = Number(menus.querySelector('.price').innerText);
    const qty = Number(menus.querySelector('input').value);
    result += price * qty;
  }

  return result;
}

function stepperDecrement(btn) {
  const inputEl = btn.nextElementSibling;
  const calcStep = inputEl.step - 1;
  const newValue = parseInt(inputEl.value) + calcStep;
  if (newValue >= inputEl.min && newValue <= inputEl.max) {
    inputEl.value = newValue;
  }
  const totalPrice = calcOrder(); // calculate sum
  document.querySelector('.total-price').innerHTML = totalPrice; // выводим на странице
}
function stepperIncrement(btn) {
  const inputEl = btn.previousElementSibling;
  const calcStep = inputEl.step * 1;
  const newValue = parseInt(inputEl.value) + calcStep;
  if (newValue >= inputEl.min && newValue <= inputEl.max) {
    inputEl.value = newValue;
  }
  const totalPrice = calcOrder(); // calculate sum
  document.querySelector('.total-price').innerHTML = totalPrice; // выводим на странице
}

body {
  background: linear-gradient(rgba(0, 0, 0, 0.93), rgba(0, 0, 0, 0.93)),
    url("../images/saveInPhotoshop.png") no-repeat;
  background-size: cover;
}

/* MENU */
.wrapper {
  color: white;

  width: 1200px;
  margin: 100px auto;
}

.title {
  text-align: center;
  margin-bottom: 60px;
}

.title h4 {
  text-transform: capitalize;
  font-size: 36px;
  position: relative;
  display: inline-block;
  padding-bottom: 10px;
}

.title h4 span {
  display: block;
  font-size: 18px;
  font-style: italic;
  margin-bottom: 10px;
}

.title h4:before {
  position: absolute;
  content: "";
  width: 100px;
  height: 2px;
  background-color: #ff7720;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
}

.menu {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.single-menu {
  flex-basis: 580px;
  margin-bottom: 40px;
  padding-bottom: 40px;
  border-bottom: 1px solid #ddd;
}

.single-menu:nth-child(5),
.single-menu:nth-child(6) {
  border-bottom: 0;
}

.single-menu {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.single-menu:hover img {
  border-radius: 0;
}

.single-menu img {
  max-width: 180px;
  margin-right: 30px;
  border-radius: 50%;
  border: 1px solid #ddd;
  padding: 3px;
  transition: 0.5s;
}

.single-menu h4 {
  text-transform: capitalize;
  font-size: 22px;
  border-bottom: 1px dashed #333;
  margin-bottom: 5px;
  padding-bottom: 5px;
}

.single-menu h4 span {
  float: right;
  color: #ff7720;
  font-style: italic;
}

.filter-menu {
  width: 200px;
  margin-left: auto;
  margin-right: 75px;
}

.filter-menu-desc {
  width: 460px;
}

.menu-description {
  width: 350px;
}

.price {
  margin-left: 10px;
}

/* Button */

.myContainer {
  width: 100px;
  top: 50%;
  left: 50%;
  display: flex;
  border-radius: 45px;
  box-shadow: 0 20px 30px rgba(0, 0, 0, 0.15);
}

input[type="number"] {
  -moz-appearance: textfield;
  text-align: center;
  font-size: 20px;
  border: none;
  background-color: #e0e0e0;
  color: #302020;
}

input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

button {
  color: #ff7720;
  background-color: #d3d2d2;
  border: none;
  font-size: 35px;
  cursor: pointer;
}

.decrement {
  padding: 15px 5px 15px 25px;
  border-radius: 45px 0 0 45px;
}

.increment {
  padding: 15px 25px 15px 5px;
  border-radius: 0 45px 45px 0;
}

Dish number three15.00

DRINKS

Description

        <button class="decrement" type="button" onclick="stepperDecrement(this)">-</button>
        <input value="0" name="dishIdQuantityMap[8]" type="number" min="0" max="100" step="1" readonly />
        <button class="increment" type="button" onclick="stepperIncrement(this)">+</button>

Dish number one25.00

DRINKS

Custom description

        <button class="decrement" type="button" onclick="stepperDecrement(this)">-</button>
        <input value="0" name="dishIdQuantityMap[6]" type="number" min="0" max="100" step="1" readonly />
        <button class="increment" type="button" onclick="stepperIncrement(this)">+</button>

Dish number two32.00

DRINKS

Description

        <button class="decrement" type="button" onclick="stepperDecrement(this)">-</button>
        <input value="0" name="dishIdQuantityMap[7]" type="number" min="0" max="100" step="1" readonly />
        <button class="increment" type="button" onclick="stepperIncrement(this)">+</button>

Dish number 4215.00

DRINKS

Description

        <button class="decrement" type="button" onclick="stepperDecrement(this)">-</button>
        <input value="0" name="dishIdQuantityMap[9]" type="number" min="0" max="100" step="1" readonly />
        <button class="increment" type="button" onclick="stepperIncrement(this)">+</button>

dsa2231.00

DRINKS

dadsads

        <button class="decrement" type="button" onclick="stepperDecrement(this)">-</button>
        <input value="0" name="dishIdQuantityMap[1]" type="number" min="0" max="100" step="1" readonly />
        <button class="increment" type="button" onclick="stepperIncrement(this)">+</button>

    Input your address
    <input type="text" class="form-control" id="address" required name="address" value="">
    <button type="submit" value="Submit" class="btn btn-outline-light mt-3 btn-lg">Confirm order</button>

</form>

Body:
const menus = document.querySelectorAll('.single-menu'); will return a NodeList as response. so menus is an array. You should use menus[i].querySelector('.price').innerText to access the node.

Also the element with class name total-price is not available.

Working Fiddle

window.onload = function () {
  const totalPrice = calcOrder(); // calculate sum
  document.querySelector('.total-price').innerHTML = totalPrice; // put on page
}

// Calculate total sum
function calcOrder() {
  let result = 0;
  const menus = document.querySelectorAll('.single-menu');

  for (let i = 0; i < menus.length; i++) {
    const price = Number(menus[i].querySelector('.price').innerText);
    const qty = Number(menus[i].querySelector('input').value);
    result += price * qty;
  }

  return result;
}

function stepperDecrement(btn) {
  const inputEl = btn.nextElementSibling;
  const calcStep = inputEl.step;
  const newValue = parseInt(inputEl.value) - calcStep;
  if (newValue >= inputEl.min && newValue <= inputEl.max) {
    inputEl.value = newValue;
  }
  const totalPrice = calcOrder(); // calculate sum
  document.querySelector('.total-price').innerHTML = totalPrice; // выводим на странице
}

function stepperIncrement(btn) {
  const inputEl = btn.previousElementSibling;
  const calcStep = inputEl.step * 1;
  const newValue = parseInt(inputEl.value) + calcStep;
  if (newValue >= inputEl.min && newValue <= inputEl.max) {
    inputEl.value = newValue;
  }
  const totalPrice = calcOrder(); // calculate sum
  document.querySelector('.total-price').innerHTML = totalPrice; // выводим на странице
}

body {
  background: linear-gradient(rgba(0, 0, 0, 0.93), rgba(0, 0, 0, 0.93)),
    url("../images/saveInPhotoshop.png") no-repeat;
  background-size: cover;
}

/* MENU */
.wrapper {
  color: white;

  width: 1200px;
  margin: 100px auto;
}

.title {
  text-align: center;
  margin-bottom: 60px;
}

.title h4 {
  text-transform: capitalize;
  font-size: 36px;
  position: relative;
  display: inline-block;
  padding-bottom: 10px;
}

.title h4 span {
  display: block;
  font-size: 18px;
  font-style: italic;
  margin-bottom: 10px;
}

.title h4:before {
  position: absolute;
  content: "";
  width: 100px;
  height: 2px;
  background-color: #ff7720;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
}

.menu {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.single-menu {
  flex-basis: 580px;
  margin-bottom: 40px;
  padding-bottom: 40px;
  border-bottom: 1px solid #ddd;
}

.single-menu:nth-child(5),
.single-menu:nth-child(6) {
  border-bottom: 0;
}

.single-menu {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.single-menu:hover img {
  border-radius: 0;
}

.single-menu img {
  max-width: 180px;
  margin-right: 30px;
  border-radius: 50%;
  border: 1px solid #ddd;
  padding: 3px;
  transition: 0.5s;
}

.single-menu h4 {
  text-transform: capitalize;
  font-size: 22px;
  border-bottom: 1px dashed #333;
  margin-bottom: 5px;
  padding-bottom: 5px;
}

.single-menu h4 span {
  float: right;
  color: #ff7720;
  font-style: italic;
}

.filter-menu {
  width: 200px;
  margin-left: auto;
  margin-right: 75px;
}

.filter-menu-desc {
  width: 460px;
}

.menu-description {
  width: 350px;
}

.price {
  margin-left: 10px;
}

/* Button */

.myContainer {
  width: 100px;
  top: 50%;
  left: 50%;
  display: flex;
  border-radius: 45px;
  box-shadow: 0 20px 30px rgba(0, 0, 0, 0.15);
}

input[type="number"] {
  -moz-appearance: textfield;
  text-align: center;
  font-size: 20px;
  border: none;
  background-color: #e0e0e0;
  color: #302020;
}

input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

button {
  color: #ff7720;
  background-color: #d3d2d2;
  border: none;
  font-size: 35px;
  cursor: pointer;
}

.decrement {
  padding: 15px 5px 15px 25px;
  border-radius: 45px 0 0 45px;
}

.increment {
  padding: 15px 25px 15px 5px;
  border-radius: 0 45px 45px 0;
}

<div class="menu">

  <div class="single-menu">

    <img src="https://via.placeholder.com/150" />
    <div class="menu-content">
      <h4>Dish number three<span class="price">15.00</span></h4>
      <p class="mb-0 text-color:red">DRINKS</p>
      <p class="menu-description">Description</p>
      <div class="myContainer m-1">
        <button class="decrement" type="button" onclick="stepperDecrement(this)">-</button>
        <input value="0" name="dishIdQuantityMap[8]" type="number" min="0" max="100" step="1" readonly />
        <button class="increment" type="button" onclick="stepperIncrement(this)">+</button>
      </div>
    </div>
  </div>

  <div class="single-menu">

    <img src="https://via.placeholder.com/150" />
    <div class="menu-content">
      <h4>Dish number one<span class="price">25.00</span></h4>
      <p class="mb-0 text-color:red">DRINKS</p>
      <p class="menu-description">Custom description</p>
      <div class="myContainer m-1">
        <button class="decrement" type="button" onclick="stepperDecrement(this)">-</button>
        <input value="0" name="dishIdQuantityMap[6]" type="number" min="0" max="100" step="1" readonly />
        <button class="increment" type="button" onclick="stepperIncrement(this)">+</button>
      </div>
    </div>
  </div>

  <div class="single-menu">

    <img src="https://via.placeholder.com/150" />
    <div class="menu-content">
      <h4>Dish number two<span class="price">32.00</span></h4>
      <p class="mb-0 text-color:red">DRINKS</p>
      <p class="menu-description">Description</p>
      <div class="myContainer m-1">
        <button class="decrement" type="button" onclick="stepperDecrement(this)">-</button>
        <input value="0" name="dishIdQuantityMap[7]" type="number" min="0" max="100" step="1" readonly />
        <button class="increment" type="button" onclick="stepperIncrement(this)">+</button>
      </div>
    </div>
  </div>

  <div class="single-menu">

    <img src="https://via.placeholder.com/150" />
    <div class="menu-content">
      <h4>Dish number 4<span class="price">215.00</span></h4>
      <p class="mb-0 text-color:red">DRINKS</p>
      <p class="menu-description">Description</p>
      <div class="myContainer m-1">
        <button class="decrement" type="button" onclick="stepperDecrement(this)">-</button>
        <input value="0" name="dishIdQuantityMap[9]" type="number" min="0" max="100" step="1" readonly />
        <button class="increment" type="button" onclick="stepperIncrement(this)">+</button>
      </div>
    </div>
  </div>

  <div class="single-menu">

    <img src="/dish-images/1/49d.jpg" />

    <div class="menu-content">
      <h4>dsa2<span class="price">231.00</span></h4>
      <p class="mb-0 text-color:red">DRINKS</p>
      <p class="menu-description">dadsads</p>
      <div class="myContainer m-1">
        <button class="decrement" type="button" onclick="stepperDecrement(this)">-</button>
        <input value="0" name="dishIdQuantityMap[1]" type="number" min="0" max="100" step="1" readonly />
        <button class="increment" type="button" onclick="stepperIncrement(this)">+</button>
      </div>
    </div>
  </div>
</div>

<div class="d-flex justify-content-center">
  <p style="color: white" class="total-price"></p>
  <div class="mb-3 text-center fw-bold col-8" style="font-size:1.5rem">
    <label for="address" class="form-label">Input your address</label>
    <input type="text" class="form-control" id="address" required name="address" value="">
    <button type="submit" value="Submit" class="btn btn-outline-light mt-3 btn-lg">Confirm order</button>

  </div>

</div>
</form>


问:
Map in map : TypeError: Cannot read properties of undefined (reading 'map')
I have these datas :

```<code>[
    {
        "id": "1",
        "name": "test1",
        "secondary": [
            "testS1", "testS2"
        ]
    },
    {
        "id": "2",
        "name": "test2",
        "secondary": [
            "testS3", "testS4"
        ]
    }
]
</code>```

I map all exercices from a json file, and now I wish to loop props.exercices.secondary of each object.
Here is my try :

```<code>export default function AllExos(props) {
    return <div>
        {props.exercices.map(exo => {
            return <div key={exo.name}>
                <div>
                     <h2>{exo.id}</h2>
                     <p>Display secondary :
                            {exo.secondary.map(k => {
                                return <span key={k}>{k}</span>
                            })}
                     </p>
                 </div>
             </div>
        })}
    </div>
}
</code>```

I don't understand why I get the error TypeError: Cannot read properties of undefined (reading 'map'). I am looping in the 'props.exercices', right ?

答:
Try this condition props.exercices && props.exercices.length > 0 &&</p>
```<code> export default function AllExos(props) {
    return <div>
        {props.exercices && props.exercices.length > 0 &&
          props.exercices.map(exo => {
            return <div key={exo.name}>
             <div>
                 <h2>{exo.id}</h2>
                 <p>Display secondary :
                        {exo.secondary.map(k => {
                            return <span key={k}>{k}</span>
                        })}
                 </p>
              </div>
          </div>
       })}
    </div>
  }
</code>```

Body:
I have these datas :

[
    {
        "id": "1",
        "name": "test1",
        "secondary": [
            "testS1", "testS2"
        ]
    },
    {
        "id": "2",
        "name": "test2",
        "secondary": [
            "testS3", "testS4"
        ]
    }
]

I map all exercices from a json file, and now I wish to loop props.exercices.secondary of each object.
Here is my try :

export default function AllExos(props) {
    return

        {props.exercices.map(exo => {
            return

{exo.id}

Display secondary :
                            {exo.secondary.map(k => {
                                return {k}
                            })}

        })}

}

I don't understand why I get the error TypeError: Cannot read properties of undefined (reading 'map'). I am looping in the 'props.exercices', right ?

Body:
Try this condition props.exercices && props.exercices.length > 0 &&

 export default function AllExos(props) {
    return <div>
        {props.exercices && props.exercices.length > 0 &&
          props.exercices.map(exo => {
            return <div key={exo.name}>
             <div>
                 <h2>{exo.id}</h2>
                 <p>Display secondary :
                        {exo.secondary.map(k => {
                            return <span key={k}>{k}</span>
                        })}
                 </p>
              </div>
          </div>
       })}
    </div>
  }


问:
How to calculate the SVG Path for an arc (of a circle)
Given a circle centered at (200,200), radius 25, how do I draw an arc from 270 degree to 135 degree and one that goes from 270 to 45 degree?

0 degree means it is right on the x-axis (the right side) (meaning it is 3 o' clock position)
270 degree means it is 12 o'clock position, and 90 means it is 6 o'clock position

More generally, what is a path for an arc for part of a circle with

```<code>x, y, r, d1, d2, direction
</code>```

meaning

```<code>center (x,y), radius r, degree_start, degree_end, direction
</code>```

答:
I'd use the code from other answers, where they all appear to be copying from each other, but I would make the start point a function of the start angle and the end point a function of the end angle.

I would make the large arc flag independent of the order by using absolute value, and make the angles independent of numerical magnitude by working modulo 360 degrees.

```<code>var start = polarToCartesian(x, y, radius, startAngle);
var end = polarToCartesian(x, y, radius,   endAngle);

largeArcFlag = Math.abs((endAngle - startAngle) % 360) <= 180 ? "0" : "1";
clockwiseFlag = (endAngle > startAngle) ? "1" : "0";

var d = [
    "M", start.x, start.y,
    "A", radius, radius, 0, largeArcFlag, clockwiseFlag, end.x, end.y
  ].join(" ");
</code>```

Apologies to Wiley; I hadn't read to the end and see he has spotted the same thing. If you like my post, upvote his instead!

Body:
Given a circle centered at (200,200), radius 25, how do I draw an arc from 270 degree to 135 degree and one that goes from 270 to 45 degree?

0 degree means it is right on the x-axis (the right side) (meaning it is 3 o' clock position)
270 degree means it is 12 o'clock position, and 90 means it is 6 o'clock position

More generally, what is a path for an arc for part of a circle with

x, y, r, d1, d2, direction

meaning

center (x,y), radius r, degree_start, degree_end, direction

Body:
I'd use the code from other answers, where they all appear to be copying from each other, but I would make the start point a function of the start angle and the end point a function of the end angle.

I would make the large arc flag independent of the order by using absolute value, and make the angles independent of numerical magnitude by working modulo 360 degrees.

var start = polarToCartesian(x, y, radius, startAngle);
var end = polarToCartesian(x, y, radius,   endAngle);

largeArcFlag = Math.abs((endAngle - startAngle) % 360) <= 180 ? "0" : "1";
clockwiseFlag = (endAngle > startAngle) ? "1" : "0";

var d = [
    "M", start.x, start.y,
    "A", radius, radius, 0, largeArcFlag, clockwiseFlag, end.x, end.y
  ].join(" ");

Apologies to Wiley; I hadn't read to the end and see he has spotted the same thing. If you like my post, upvote his instead!


问:
NET Core 6.0 : Is possible to create generic methods to get a List<T> from EF Core?
I have the following methods to take from 5 different views a list of said view from EF Core 6.0 :

```<code>    public List<Vw_Customers> GetCustomers(THEDBContext dbContext)
    {
        return dbContext.Vw_Customers.ToList();
    }

    public List<VW_Cars> GetCars(THEDBContext dbContext)
    {
        return dbContext.VW_Cars.ToList();
    }
</code>```

and so on...

It works, but I have to make "n" methods to take data from my database.

Is there a way where I can get the specific List passing the class of the view, like

```<code>    public List<dynamic> GetData(THEDBContext dbContext, Class myViewClass)
    {
        return dbContext.myViewClass.ToList();
    }
</code>```

?

Searching around StackOverflow I found to use dbContext.Set<MyClass> but it doesn't work with latest EF Core version.

答:
You can do something like this

```<code>public  class MyClass<T> where T : class
{
    public List<T> GetData(THEDBContext dbContext)
    {
       return dbContext.Set<T>().ToList();
    }

 }
</code>```

This is the generic way to return data from dbcontext, I assume you use 'dynamic' word to describe it will be something not fixed. Otherwise if you want to use dynamic type  It is not genereic at all and I don't recomend it you to use in this case.

You should look some documentations and  tutorials in order to understand how generic classes and methods works.

Body:
I have the following methods to take from 5 different views a list of said view from EF Core 6.0 :

    public List<Vw_Customers> GetCustomers(THEDBContext dbContext)
    {
        return dbContext.Vw_Customers.ToList();
    }

    public List<VW_Cars> GetCars(THEDBContext dbContext)
    {
        return dbContext.VW_Cars.ToList();
    }

and so on...

It works, but I have to make "n" methods to take data from my database.

Is there a way where I can get the specific List passing the class of the view, like

    public List<dynamic> GetData(THEDBContext dbContext, Class myViewClass)
    {
        return dbContext.myViewClass.ToList();
    }

?

Searching around StackOverflow I found to use dbContext.Set<MyClass> but it doesn't work with latest EF Core version.

Body:
You can do something like this

public  class MyClass<T> where T : class
{
    public List<T> GetData(THEDBContext dbContext)
    {
       return dbContext.Set<T>().ToList();
    }

 }

This is the generic way to return data from dbcontext, I assume you use 'dynamic' word to describe it will be something not fixed. Otherwise if you want to use dynamic type  It is not genereic at all and I don't recomend it you to use in this case.

You should look some documentations and  tutorials in order to understand how generic classes and methods works.