问:
convert uppertriangular matrix to a symmetric matrix in R
I have a dataframe  with 20 rows where each row is a 10 x 10 upper triangular co-variance matrix with diagonal and I want to convert it to a symmetric 10X10  matrix. I had been following the post: a vector to an upper Triangle matrix by row in R
But when I do that it gives me a list instead of matrix. </p>

<p>Also I want to do it recursively for each row and store the resulting 20 matrices in a list. For reproducible example here is a dataframe with 20 rows. Each row is 3x3 uppertriangular matrix with diagonal. </p>

```<code>g <- data.frame(a=runif(20),b=runif(20),c=runif(20),d=runif(20),e=runif(20),f=runif(20))
g1<-c(g[1,])
g2= matrix(0, 3, 3)
g2[upper.tri(g2, diag=TRUE)]=g1
g2
# list of 9 elements instead of matrix
#[[1]]
 # [1] 0.2625916

 # [[2]]
 # [1] 0

 # [[3]]
 # [1] 0

 # [[4]]
 # [1] 0.6255627

 # [[5]]
 # [1] 0.829801

 # [[6]]
 # [1] 0

 # [[7]]
 # [1] 0.3386346

 # [[8]]
  #[1] 0.9517039

 # [[9]]
 # [1] 0.5886387
</code>```

答:
@Heikki's answer only works for 3x3 matrices (given the column-filling)

as a workaround, you can fill the upper triangular part, transpose the temporary matrix (so the upper triangular becomes the correct lower triangular), then fill the upper triangular again:

```<code>g2[upper.tri(g2, diag=TRUE)] <- unlist(g1)
g2 <- t(g2)
g2[upper.tri(g2, diag=TRUE)] <- unlist(g1)
</code>```

this will work for larger matrices too. Example:

```<code>X <- matrix(0, k <- 4, k)
X[upper.tri(X, diag=T)] <- 1:(k*(k+1)/2)
X <- t(X)
X[upper.tri(X, diag=T)] <- 1:(k*(k+1)/2)

     [,1] [,2] [,3] [,4]
[1,]    1    2    4    7
[2,]    2    3    5    8
[3,]    4    5    6    9
[4,]    7    8    9   10
</code>```

Body:
I have a dataframe  with 20 rows where each row is a 10 x 10 upper triangular co-variance matrix with diagonal and I want to convert it to a symmetric 10X10  matrix. I had been following the post: a vector to an upper Triangle matrix by row in R
But when I do that it gives me a list instead of matrix.

Also I want to do it recursively for each row and store the resulting 20 matrices in a list. For reproducible example here is a dataframe with 20 rows. Each row is 3x3 uppertriangular matrix with diagonal.

g <- data.frame(a=runif(20),b=runif(20),c=runif(20),d=runif(20),e=runif(20),f=runif(20))
g1<-c(g[1,])
g2= matrix(0, 3, 3)
g2[upper.tri(g2, diag=TRUE)]=g1
g2
# list of 9 elements instead of matrix
#[[1]]
 # [1] 0.2625916

 # [[2]]
 # [1] 0

 # [[3]]
 # [1] 0

 # [[4]]
 # [1] 0.6255627

 # [[5]]
 # [1] 0.829801

 # [[6]]
 # [1] 0

 # [[7]]
 # [1] 0.3386346

 # [[8]]
  #[1] 0.9517039

 # [[9]]
 # [1] 0.5886387

Body:
@Heikki's answer only works for 3x3 matrices (given the column-filling)

as a workaround, you can fill the upper triangular part, transpose the temporary matrix (so the upper triangular becomes the correct lower triangular), then fill the upper triangular again:

g2[upper.tri(g2, diag=TRUE)] <- unlist(g1)
g2 <- t(g2)
g2[upper.tri(g2, diag=TRUE)] <- unlist(g1)

this will work for larger matrices too. Example:

X <- matrix(0, k <- 4, k)
X[upper.tri(X, diag=T)] <- 1:(k*(k+1)/2)
X <- t(X)
X[upper.tri(X, diag=T)] <- 1:(k*(k+1)/2)

     [,1] [,2] [,3] [,4]
[1,]    1    2    4    7
[2,]    2    3    5    8
[3,]    4    5    6    9
[4,]    7    8    9   10


来源: stackexchange

问:
How can we use RepoDB with code first approach?
If we want to create an Asp.Net Core project with code first approach and using RepoDB, how can we manage the operations such as migrations? Do we need an additional ORM like EF, EF Core?

Thanks.

答: As RepoDb does not support code first migration, it is highly recommended to use EF for your scenario. Or, you can also use some migration tools to manage your DB migration (ie: Evolve, Fluent Migrator, etc) and use RepoDb as your ORM.</p>

ContentLicense: CC BY-SA 4.0


问:
output for a value index in pandas, returns a boolean array
when searching for a unique value index in a pandas dataframe, it works perfectly. but when that value is not unique, the output seems to be an array of booleans:

load the file in:

```<code>import pandas as pd

df = pd.read_csv('test_file.csv')
print(df.head(10))
</code>```

and lets say this is the file i am dealing with:

```<code>   test
0    10
1    20
2    10
3    20
4    20
5    20
6    10
7    10
8    10
9    30
</code>```

now when i try to get the index of a value that is not unique in the column:

```<code>output_index = df.set_index('test').index.get_loc(10)
print(output_index)
</code>```

output:

```<code>[ True False  True False False False  True  True  True False]
</code>```

but the same code works just fine when its done for a unique value:

```<code>output_index = df.set_index('test').index.get_loc(30)
print(output_index)
</code>```

output:

```<code>9
</code>```

so what is the correct way to get the index(es) of a value that has occured more than once in a dataframe?

答:
try this: </p>

```<code>output_index = df[df['test'] == 10].index
</code>```

<p>if you need a list: </p>

```<code>output_index = df[df['test'] == 10].index.to_list()
</code>```

Body:
when searching for a unique value index in a pandas dataframe, it works perfectly. but when that value is not unique, the output seems to be an array of booleans:

load the file in:

import pandas as pd

df = pd.read_csv('test_file.csv')
print(df.head(10))

and lets say this is the file i am dealing with:

   test
0    10
1    20
2    10
3    20
4    20
5    20
6    10
7    10
8    10
9    30

now when i try to get the index of a value that is not unique in the column:

output_index = df.set_index('test').index.get_loc(10)
print(output_index)

output:

[ True False  True False False False  True  True  True False]

but the same code works just fine when its done for a unique value:

output_index = df.set_index('test').index.get_loc(30)
print(output_index)

output:

9

so what is the correct way to get the index(es) of a value that has occured more than once in a dataframe?

Body:
try this:

output_index = df[df['test'] == 10].index

if you need a list:

output_index = df[df['test'] == 10].index.to_list()


答:
df.index returns the row labels for a particular value.

If the value is repeated in the dataframe, it will return all the indexes, like below:

```<code>df.index[df['test'].eq(10)].tolist()
</code>```

Output:

```<code>[0, 2, 6, 7, 8]
</code>```

If the value is unique, it will return:

```<code>df.index[df['test'].eq(30)].tolist()
</code>```

Output:

```<code>[9]
</code>```

Title: output for a value index in pandas, returns a boolean array

Body:
df.index returns the row labels for a particular value.

If the value is repeated in the dataframe, it will return all the indexes, like below:

df.index[df['test'].eq(10)].tolist()

Output:

[0, 2, 6, 7, 8]

If the value is unique, it will return:

df.index[df['test'].eq(30)].tolist()

Output:

[9]


问:
Get HTTP Command in client and MEMO
Hello

I want use "Get" command such as:

Get https://api.demo.website.com/api/2/public/something

This is a public info and does not need authentication.

When I use the URL in a browser, I receive proper respond, also in another software of mine, I copy paste this code below, always showing me bland result in memo.

Maybe I will start from scratch to avoid the bug, but can anyone tell me if there is something wrong i this code?

```<code>TMemoryStream *Response=new TMemoryStream;
TNameValueArray nva;
NetHTTPRequest1->URL=URLEdit->Text;
NetHTTPRequest1->Get(URLEdit->Text, Response, nva);
Memo1->Lines->LoadFromStream(Response);
</code>```

答:
When Get() is finished writing to the MemoryStream, the stream's Position is left at the end of the stream, so there is no data available for the Memo to load. You need to reset the Position back to the beginning before loading the stream into the Memo:

NetHTTPRequest1->Get(URLEdit->Text, Response, nva);
Response->Position = 0; // <-- ADD THIS
Memo1->Lines->LoadFromStream(Response);
```

Title: Get HTTP Command in client and MEMO

Body:
Hello

I want use "Get" command such as:

Get https://api.demo.website.com/api/2/public/something

This is a public info and does not need authentication.

When I use the URL in a browser, I receive proper respond, also in another software of mine, I copy paste this code below, always showing me bland result in memo.

Maybe I will start from scratch to avoid the bug, but can anyone tell me if there is something wrong i this code?

TMemoryStream *Response=new TMemoryStream;
TNameValueArray nva;
NetHTTPRequest1->URL=URLEdit->Text;
NetHTTPRequest1->Get(URLEdit->Text, Response, nva);
Memo1->Lines->LoadFromStream(Response);


问:
Recursive function for listing all files in sub directories
I'm trying to write a function that returns a list of all files on current folder and all of its sub folders. I wrote this code:

```<code>#include <iostream>
#include <dirent.h>
#include <cstring>

using namespace std;

int main() {
   DIR* dir; dirent* pdir;
   //From my workspace
   dir=opendir(".");
   while (pdir=readdir(dir)) {
       if(/**********This pdir is a directory**********/) {
           /**********RECURSIVE CALL SHOULD BE HERE**********/
           cout<<pdir->d_name<<endl;
       }
   }
   closedir(dir);
   return 0;
}
</code>```

I searched for it in google and I don't know how to:

Check if the current pdir is directory

Go inside the directory and perform the recursive call on it

Meanwhile I have everything on main because I still don't know what arguments the recursive function should have.

Any hints?

答:
Here how I use it</p>

```<code>std::vector<std::string> get_all_files_recursive(const fs::path& path)
    {
        std::vector<std::string> result;

        for (const auto& p : fs::recursive_directory_iterator(path))
        {
            if (!fs::is_directory(p))
            {
                fs::path path = p.path();
                result.push_back(path.u8string());
            }
        }

        return result;
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to write a function that returns a list of all files on current folder and all of its sub folders. I wrote this code:

#include <iostream>
#include <dirent.h>
#include <cstring>

using namespace std;

int main() {
   DIR* dir; dirent* pdir;
   //From my workspace
   dir=opendir(".");
   while (pdir=readdir(dir)) {
       if(/**********This pdir is a directory**********/) {
           /**********RECURSIVE CALL SHOULD BE HERE**********/
           cout<<pdir->d_name<<endl;
       }
   }
   closedir(dir);
   return 0;
}

I searched for it in google and I don't know how to:

Check if the current pdir is directory

Go inside the directory and perform the recursive call on it

Meanwhile I have everything on main because I still don't know what arguments the recursive function should have.

Any hints?

Body:
Here how I use it

std::vector<std::string> get_all_files_recursive(const fs::path& path)
    {
        std::vector<std::string> result;

        for (const auto& p : fs::recursive_directory_iterator(path))
        {
            if (!fs::is_directory(p))
            {
                fs::path path = p.path();
                result.push_back(path.u8string());
            }
        }

        return result;
    }


问:
ionic cordova android disable soft keyboard when touch input filed
I need to disable the soft keyboard when the user focuses on an input field.
I am using ionic 4 and cordova 8 for android.

I have to do this because the app will be used on a device with a physical keyboard and I would therefore like to use this physical keyboard

how can I do?

Thanks

答:
try to add

```<code>ng-readonly="true"
</code>```

to your input in the HTML file

Body:
try to add

ng-readonly="true"

to your input in the HTML file


问:
Looking for stats on popularity of JavaScript libraries
Does anyone know if there's a site that tracks the popularity of the big/various JavaScript libraries?</p>

答: Here's an unscientific but nonetheless interesting comparison.  It's interesting because it showed Dojo peaked and jQuery is really ascendant, suggesting jQuery has eaten Dojo's market share.</p>

OwnerDisplayName: magenta

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: cletus


问:
Latest Value from the KStream for a given key
I have KTable like below

```<code>KTable<productId1,productValue1>
KTable<productId2,productValue2>
KTable<productId3,productValue2>
</code>```

Then i have KStream<custId,productId>, the productId is of any of productId1, productId2, productId3. I want to have the corresponding productValue.

The response would be like KStream<custId, productValueN>

If the KStream receives productId as productId2, then the response would be KStream<custId, productValue2>

How this could be possible?
Thanks

答:
Unfortunately KTables don't support KeyValueMappers: KStream/KTable joins are performed strictly by comparing keys.  GlobalKTables support this, making the whole process of joining much easier (see my other answer).

To get this to work then, you need to rekey the customers topic KStream to use the product ID, so that you can perform the join with the products topic KTable.

Once you've obtained the product name, you can rekey the resulting joined stream back to the customer ID.  For example:

```<code>// Key: product ID, value: product name
KTable<String, String> productsTable =
    streamsBuilder.table(PRODUCTS_TOPIC, Consumed.with(stringSerde, stringSerde),
            Materialized.<String, String, KeyValueStore<Bytes, byte[]>>as("productsStore")
                    .withKeySerde(stringSerde)
                    .withValueSerde(stringSerde));

streamsBuilder.stream(CUSTOMERS_TOPIC, Consumed.with(stringSerde, stringSerde))
    // Key: customer ID, value: product ID
    .map((customerId, productId) -> KeyValue.pair(productId, String.format("%s|%s", customerId, productId)),
            Named.as("mapToProductIdAndCustomerIdProductId"))
    // Key: product ID, value: customer ID | product ID
    .join(productsTable, (customerIdProductId, productName) -> {
                String[] parts = customerIdProductId.split("\\|");
                String customerId = parts[0];
                return String.format("%s|%s", customerId, productName);
            },
            Joined.<String, String, String>as("customersProductsInnerJoin")
                    .withKeySerde(stringSerde)
                    .withValueSerde(stringSerde))
    // Key: product ID, value: customer ID | product name
    .map((productId, customerIdProductName) -> {
        String[] parts = customerIdProductName.split("\\|");
        String customerId = parts[0];
        String productName = parts[1];
        return KeyValue.pair(customerId, productName);
    }, Named.as("mapToCustomerIdAndProductName"))
    // Key: customer ID, value: product name
    .print(Printed.toSysOut());
</code>```

Body:
I have KTable like below

KTable<productId1,productValue1>
KTable<productId2,productValue2>
KTable<productId3,productValue2>

Then i have KStream<custId,productId>, the productId is of any of productId1, productId2, productId3. I want to have the corresponding productValue.

The response would be like KStream<custId, productValueN>

If the KStream receives productId as productId2, then the response would be KStream<custId, productValue2>

How this could be possible?
Thanks

Body:
Unfortunately KTables don't support KeyValueMappers: KStream/KTable joins are performed strictly by comparing keys.  GlobalKTables support this, making the whole process of joining much easier (see my other answer).

To get this to work then, you need to rekey the customers topic KStream to use the product ID, so that you can perform the join with the products topic KTable.

Once you've obtained the product name, you can rekey the resulting joined stream back to the customer ID.  For example:

// Key: product ID, value: product name
KTable<String, String> productsTable =
    streamsBuilder.table(PRODUCTS_TOPIC, Consumed.with(stringSerde, stringSerde),
            Materialized.<String, String, KeyValueStore<Bytes, byte[]>>as("productsStore")
                    .withKeySerde(stringSerde)
                    .withValueSerde(stringSerde));

streamsBuilder.stream(CUSTOMERS_TOPIC, Consumed.with(stringSerde, stringSerde))
    // Key: customer ID, value: product ID
    .map((customerId, productId) -> KeyValue.pair(productId, String.format("%s|%s", customerId, productId)),
            Named.as("mapToProductIdAndCustomerIdProductId"))
    // Key: product ID, value: customer ID | product ID
    .join(productsTable, (customerIdProductId, productName) -> {
                String[] parts = customerIdProductId.split("\\|");
                String customerId = parts[0];
                return String.format("%s|%s", customerId, productName);
            },
            Joined.<String, String, String>as("customersProductsInnerJoin")
                    .withKeySerde(stringSerde)
                    .withValueSerde(stringSerde))
    // Key: product ID, value: customer ID | product name
    .map((productId, customerIdProductName) -> {
        String[] parts = customerIdProductName.split("\\|");
        String customerId = parts[0];
        String productName = parts[1];
        return KeyValue.pair(customerId, productName);
    }, Named.as("mapToCustomerIdAndProductName"))
    // Key: customer ID, value: product name
    .print(Printed.toSysOut());


问:
Can't get defaultRedirect to work
In my web.config, I have:

```<code><system.web>
    <customErrors mode="On" defaultRedirect="Error.cshtml" />
</system.web>
</code>```

In Views/Shared/Error.cshtml, I have:

```<code>@model System.Web.Mvc.HandleErrorInfo
@{
    ViewBag.Title = "Error";
}
<h2>
    Sorry, an error occurred while processing your request.
</h2>
</code>```

If I put an invalid URL/route into my browser, I get this:

Server Error in '/' Application.

The resource cannot be found.

Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly.

Requested URL: /Error.cshtml

Why can't Error.cshtml be found? The file is definitely in Views/Shared.

答:
The defaultRedirect won't go directly to a view. Your defaultRedirect looks like a razor view file which it can't process. For example: Where does it get the model from? It isn't, and can't, be specified in the config file so it can't process a view.

If you want more dynamic error pages in MVC you might want to read custom error pages and error handling in MVC 3

Title: Can't get defaultRedirect to work

Body:
In my web.config, I have:

<system.web>
    <customErrors mode="On" defaultRedirect="Error.cshtml" />
</system.web>

In Views/Shared/Error.cshtml, I have:

@model System.Web.Mvc.HandleErrorInfo
@{
    ViewBag.Title = "Error";
}

    Sorry, an error occurred while processing your request.

If I put an invalid URL/route into my browser, I get this:

Server Error in '/' Application.

The resource cannot be found.

Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly.

Requested URL: /Error.cshtml

Why can't Error.cshtml be found? The file is definitely in Views/Shared.


问:
Rails 'remote:true' ignored when params provided
In a Rails (5.2.4.2) app

I am using button_to + remote: true, and this is working as expected -> ajax call fired, all is OK.

But then I add 'params' to the button_to. Params are added to the form as hidden input (as expected) but when I click on the button, the request made is not remote, and all the page content is updated.

Problematic: button_to + remote + params -> this code seems to ignore the remote:true, although I see data-remote="true" in the form tag

```<code><%= button_to ent_path(ent),
      {remote: true,
      method: :patch,
      class:"btn btn-primary",
      params: {ent: {active_a: false}}
    } do
%>
  <span>TEEEST</span>
<% end %>
</code>```

Working as expected:

```<code><%= button_to ent_path(ent),
      {remote: true,
      method: :patch,
      class:"btn btn-primary",
    } do
%>
  <span>TEEEST</span>
<% end %>
</code>```

So my purpose is to have the button_to remote and update the ent record, changing the active_a attribute depending on some logic

答:
You want to pass any extra parameters via the link path, like this

<%= button_to ent_path(ent, active_a: false),
      {remote: true,
      method: :patch,
      class:"btn btn-primary",
    } do
%>
  TEEEST
<% end %>
```

Body:
In a Rails (5.2.4.2) app

I am using button_to + remote: true, and this is working as expected -> ajax call fired, all is OK.

But then I add 'params' to the button_to. Params are added to the form as hidden input (as expected) but when I click on the button, the request made is not remote, and all the page content is updated.

Problematic: button_to + remote + params -> this code seems to ignore the remote:true, although I see data-remote="true" in the form tag

<%= button_to ent_path(ent),
      {remote: true,
      method: :patch,
      class:"btn btn-primary",
      params: {ent: {active_a: false}}
    } do
%>
  TEEEST
<% end %>

Working as expected:

<%= button_to ent_path(ent),
      {remote: true,
      method: :patch,
      class:"btn btn-primary",
    } do
%>
  TEEEST
<% end %>

So my purpose is to have the button_to remote and update the ent record, changing the active_a attribute depending on some logic

Body:
You want to pass any extra parameters via the link path, like this

<%= button_to ent_path(ent, active_a: false),
      {remote: true,
      method: :patch,
      class:"btn btn-primary",
    } do
%>
  <span>TEEEST</span>
<% end %>


问:
React-Native :java.lang.UnsatisfiedLinkError: couldn't find DSO to load: libhermes.so
I have just updated my project to use react-native version 0.60.2 . But when I am trying to run an application on Android device it gets crashed after launch screen. I got the following error logs :

```<code>E/AndroidRuntime: FATAL EXCEPTION: create_react_context
    Process: com.tjspeed, PID: 3909
    java.lang.UnsatisfiedLinkError: couldn't find DSO to load: libhermes.so
        at com.facebook.soloader.SoLoader.doLoadLibraryBySoName(SoLoader.java:738)
        at com.facebook.soloader.SoLoader.loadLibraryBySoName(SoLoader.java:591)
        at com.facebook.soloader.SoLoader.loadLibrary(SoLoader.java:529)
        at com.facebook.soloader.SoLoader.loadLibrary(SoLoader.java:484)
        at com.facebook.hermes.reactexecutor.HermesExecutor.<clinit>(HermesExecutor.java:20)
        at com.facebook.hermes.reactexecutor.HermesExecutorFactory.create(HermesExecutorFactory.java:27)
        at com.facebook.react.ReactInstanceManager$5.run(ReactInstanceManager.java:949)
        at java.lang.Thread.run(Thread.java:760)
</code>```

Few suggestions available here : https://github.com/facebook/react-native/issues/25601 but unfortunately none of them worked for me. Please suggest the workaround.

答:
If any one is still facing the issue even after applying trying all the steps above then here is the solution

In the MainApplication.java, add this import:

```<code>import com.facebook.react.BuildConfig;
</code>```

Body:
I have just updated my project to use react-native version 0.60.2 . But when I am trying to run an application on Android device it gets crashed after launch screen. I got the following error logs :

E/AndroidRuntime: FATAL EXCEPTION: create_react_context
    Process: com.tjspeed, PID: 3909
    java.lang.UnsatisfiedLinkError: couldn't find DSO to load: libhermes.so
        at com.facebook.soloader.SoLoader.doLoadLibraryBySoName(SoLoader.java:738)
        at com.facebook.soloader.SoLoader.loadLibraryBySoName(SoLoader.java:591)
        at com.facebook.soloader.SoLoader.loadLibrary(SoLoader.java:529)
        at com.facebook.soloader.SoLoader.loadLibrary(SoLoader.java:484)
        at com.facebook.hermes.reactexecutor.HermesExecutor.<clinit>(HermesExecutor.java:20)
        at com.facebook.hermes.reactexecutor.HermesExecutorFactory.create(HermesExecutorFactory.java:27)
        at com.facebook.react.ReactInstanceManager$5.run(ReactInstanceManager.java:949)
        at java.lang.Thread.run(Thread.java:760)

Few suggestions available here : https://github.com/facebook/react-native/issues/25601 but unfortunately none of them worked for me. Please suggest the workaround.

Body:
If any one is still facing the issue even after applying trying all the steps above then here is the solution

In the MainApplication.java, add this import:

import com.facebook.react.BuildConfig;


问:
password_reset email template doesn't render html tag
I'm trying to override content for default password_reset_email.html with some html tag but it doesn't work. Here is my modification. For testing purpose, I'm just using p tag. But i doesn't work. I'm totally unaware what going wrong.

Here is my process.

urls.py

```<code>path('accounts/', include('django.contrib.auth.urls')),
</code>```

and here is my html templates

```<code>{% load i18n %}
{% autoescape on %}
{% blocktrans %}You're receiving this email because you requested a password reset for your user account at
{{ site_name }}.{% endblocktrans %}

{% trans "Please go to the following page and choose a new password:" %}
{% block reset_link %}
{{ protocol }}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %}
{% endblock %}
<p>Hello world</p>
{% trans 'Your username, in case you’ve forgotten:' %} {{ user.get_username }}

{% trans "Thanks for using our site!" %}

{% blocktrans %}The {{ site_name }} team{% endblocktrans %}

{% endautoescape %}
</code>```

and here is the output

答:
The email_template_name is standard one that is send in raw text, not in HTML. Indeed, in the PasswordResetView we see:

```<code>class PasswordResetView(PasswordContextMixin, FormView):
    <b>email_template_name = 'registration/password_reset_email.html'</b>
    extra_email_context = None
    form_class = PasswordResetForm
    from_email = None
    <b>html_email_template_name = None</b>
    subject_template_name = 'registration/password_reset_subject.txt'
    success_url = reverse_lazy('password_reset_done')
    template_name = 'registration/password_reset_form.html'
    title = _('Password reset')
    token_generator = default_token_generator

    @method_decorator(csrf_protect)
    def dispatch(self, *args, **kwargs):
        return super().dispatch(*args, **kwargs)

    def form_valid(self, form):
        opts = {
            'use_https': self.request.is_secure(),
            'token_generator': self.token_generator,
            'from_email': self.from_email,
            'email_template_name': self.email_template_name,
            'subject_template_name': self.subject_template_name,
            'request': self.request,
            'html_email_template_name': self.html_email_template_name,
            'extra_email_context': self.extra_email_context,
        }
        form.save(**opts)
        return super().form_valid(form)</code>```

In case you thus alter the registration/password_reset_email.html, it will still send the email as raw text, so an email client will render it as raw text.

What you can do is simply make a new path that takes precedence, and where you override the html_email_template_name:

```<code># urls.py

urlpatterns = [
    path('accounts/password_reset/',
        views.PasswordResetView.as_view(
            <b>html_email_template_name='registration/password_reset_email.html'</b>
        ),
        name='password_reset'
    ),
    path('accounts/', include('django.contrib.auth.urls')),
    # …
]</code>```

It is important that this path appears before the path that includes the django.contrib.auth.urls, since otherwise it will still take the "old" path.

Body:
I'm trying to override content for default password_reset_email.html with some html tag but it doesn't work. Here is my modification. For testing purpose, I'm just using p tag. But i doesn't work. I'm totally unaware what going wrong.

Here is my process.

urls.py

path('accounts/', include('django.contrib.auth.urls')),

and here is my html templates

{% load i18n %}
{% autoescape on %}
{% blocktrans %}You're receiving this email because you requested a password reset for your user account at
{{ site_name }}.{% endblocktrans %}

{% trans "Please go to the following page and choose a new password:" %}
{% block reset_link %}
{{ protocol }}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %}
{% endblock %}

Hello world

{% trans 'Your username, in case you’ve forgotten:' %} {{ user.get_username }}

{% trans "Thanks for using our site!" %}

{% blocktrans %}The {{ site_name }} team{% endblocktrans %}

{% endautoescape %}

and here is the output

Body:
The email_template_name is standard one that is send in raw text, not in HTML. Indeed, in the PasswordResetView we see:

class PasswordResetView(PasswordContextMixin, FormView):
    email_template_name = 'registration/password_reset_email.html'
    extra_email_context = None
    form_class = PasswordResetForm
    from_email = None
    html_email_template_name = None
    subject_template_name = 'registration/password_reset_subject.txt'
    success_url = reverse_lazy('password_reset_done')
    template_name = 'registration/password_reset_form.html'
    title = _('Password reset')
    token_generator = default_token_generator

    @method_decorator(csrf_protect)
    def dispatch(self, *args, **kwargs):
        return super().dispatch(*args, **kwargs)

    def form_valid(self, form):
        opts = {
            'use_https': self.request.is_secure(),
            'token_generator': self.token_generator,
            'from_email': self.from_email,
            'email_template_name': self.email_template_name,
            'subject_template_name': self.subject_template_name,
            'request': self.request,
            'html_email_template_name': self.html_email_template_name,
            'extra_email_context': self.extra_email_context,
        }
        form.save(**opts)
        return super().form_valid(form)

In case you thus alter the registration/password_reset_email.html, it will still send the email as raw text, so an email client will render it as raw text.

What you can do is simply make a new path that takes precedence, and where you override the html_email_template_name:

# urls.py

urlpatterns = [
    path('accounts/password_reset/',
        views.PasswordResetView.as_view(
            html_email_template_name='registration/password_reset_email.html'
        ),
        name='password_reset'
    ),
    path('accounts/', include('django.contrib.auth.urls')),
    # …
]

It is important that this path appears before the path that includes the django.contrib.auth.urls, since otherwise it will still take the "old" path.


问:
Is incrementing a _Bool defined?
A _Bool is defined by the C standard to be an unsigned type containing either 0 or 1. If a value of 1 of type _Bool is incremented, there are, as far as I can see, two options:

The value wraps around from 1 to 0

The value is incremented to 2, which is nonzero, and hence is changed into 1 when converted back to a _Bool

On GCC and Clang on my system, the behaviour seems to be the latter. Is this well-defined by the standard?

答:
As the __Bool converted to the scalar can have value of  0 or 1, the actual increment operation is an equivalent to</p>

```<code>__Bool x = false;
int v = x;
v = !!(v + 1);
x = v;
</code>```

Title: Is incrementing a _Bool defined?

Body:
As the __Bool converted to the scalar can have value of  0 or 1, the actual increment operation is an equivalent to

__Bool x = false;
int v = x;
v = !!(v + 1);
x = v;


问:
Build android apps with Kotlin in termux
I am currently trying to build an android app but I rarely have access to a pc. Instead I do have an android phone which Is powerful enough and I use termux in it. I just want to know if there is any way I could build an android app in it. Even if it is by installing a Linux distro on it like Ubuntu etc. Thanks</p>

答: https://developer.android.com/studio/install - you can download android studio for ubuntu, so would properly work on your phone as well </p>


问:
pyspark taking a log of column
```<code>length = df.count()
df = df.withColumn("log", log(col("power"),lit(length)))
</code>```

The following lines throw such an error. Can you please help me take a log of a column using another value or another column as a base.

```<code>TypeError                                 Traceback (most recent call last)
<ipython-input-102-c0894b6127d1> in <module>()
      1 #df.show()
      2
----> 3 df = df.withColumn("log", log(col("power"),lit(2)))

5 frames
/content/spark-2.4.5-bin-hadoop2.7/python/pyspark/sql/column.py in __iter__(self)
    342
    343     def __iter__(self):
--> 344         raise TypeError("Column is not iterable")
    345
    346     # string methods

TypeError: Column is not iterable
</code>```

答:
If you want to use funtions that are not build-in on spark dataframes you can use user-defined functions, in your case it would look like this:</p>

```<code>from pyspark.sql.functions import udf
from math import log

@udf("float")
def log_udf(s):
  return log(s,2)

df.withColumn("log", log_udf("power")).show()
</code>```

Title: pyspark taking a log of column

Body:
length = df.count()
df = df.withColumn("log", log(col("power"),lit(length)))

The following lines throw such an error. Can you please help me take a log of a column using another value or another column as a base.

TypeError                                 Traceback (most recent call last)
<ipython-input-102-c0894b6127d1> in <module>()
      1 #df.show()
      2
----> 3 df = df.withColumn("log", log(col("power"),lit(2)))

5 frames
/content/spark-2.4.5-bin-hadoop2.7/python/pyspark/sql/column.py in __iter__(self)
    342
    343     def __iter__(self):
--> 344         raise TypeError("Column is not iterable")
    345
    346     # string methods

TypeError: Column is not iterable

Body:
If you want to use funtions that are not build-in on spark dataframes you can use user-defined functions, in your case it would look like this:

from pyspark.sql.functions import udf
from math import log

@udf("float")
def log_udf(s):
  return log(s,2)

df.withColumn("log", log_udf("power")).show()


问:
Maven dependencies are failing with a 501 error
Recently Maven build jobs running in Jenkins are failing with the below exception saying that they couldn't pull dependencies from Maven Central and should use HTTPS. I'm not sure how to change the requests from HTTP to HTTPS. Could someone guide me on this matter?

[ERROR] Unresolveable build extension:

Plugin org.apache.maven.wagon:wagon-ssh:2.1 or one of its dependencies could not be resolved:

Failed to collect dependencies for org.apache.maven.wagon:wagon-ssh:jar:2.1 ():

Failed to read artifact descriptor for org.apache.maven.wagon:wagon-ssh:jar:2.1:

Could not transfer artifact org.apache.maven.wagon:wagon-ssh:pom:2.1 from/to central (http://repo.maven.apache.org/maven2):

Failed to transfer file: http://repo.maven.apache.org/maven2/org/apache/maven/wagon/wagon-ssh/2.1/wagon-ssh-2.1.pom.

Return code is: 501, ReasonPhrase:HTTPS Required. -> [Help 2]

Waiting for Jenkins to finish collecting data[ERROR]

Plugin org.apache.maven.plugins:maven-clean-plugin:2.4.1 or one of its dependencies could not be resolved:

Failed to read artifact descriptor for org.apache.maven.plugins:maven-clean-plugin:jar:2.4.1:

Could not transfer artifact org.apache.maven.plugins:maven-clean-plugin:pom:2.4.1 from/to central (http://repo.maven.apache.org/maven2):

Failed to transfer file: http://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-clean-plugin/2.4.1/maven-clean-plugin-2.4.1.pom.

Return code is: 501 , ReasonPhrase:HTTPS Required. -> [Help 1]

答:
If you are using Netbeans older version, you have to make changes in maven to use https over http

Open C:\Program Files\NetBeans8.0.2\java\maven\conf\settings.xml
and paste below code in between mirrors tag

```<code><mirror>
<id>maven-mirror</id>
<name>Maven Mirror</name>
<url>https://repo.maven.apache.org/maven2</url>
<mirrorOf>central</mirrorOf>
</mirror>
</code>```

It will force maven to use https://repo.maven.apache.org/maven2 url.

Body:
If you are using Netbeans older version, you have to make changes in maven to use https over http

Open C:\Program Files\NetBeans8.0.2\java\maven\conf\settings.xml
and paste below code in between mirrors tag

<mirror>
<id>maven-mirror</id>
<name>Maven Mirror</name>
<url>https://repo.maven.apache.org/maven2</url>
<mirrorOf>central</mirrorOf>
</mirror>

It will force maven to use https://repo.maven.apache.org/maven2 url.


问:
What is Java String interning?
What is String Interning in Java, when I should use it, and why?

答:
```<code>Java interning() method basically makes sure that if String object is present in SCP, If yes then it returns that object and if not then creates that objects in SCP and return its references

for eg: String s1=new String("abc");
        String s2="abc";
        String s3="abc";

s1==s2// false, because 1 object of s1 is stored in heap and other in scp(but this objects doesn't have explicit reference) and s2 in scp
s2==s3// true

now if we do intern on s1
s1=s1.intern()

//JVM checks if there is any string in the pool with value “abc” is present? Since there is a string object in the pool with value “abc”, its reference is returned.
Notice that we are calling s1 = s1.intern(), so the s1 is now referring to the string pool object having value “abc”.
At this point, all the three string objects are referring to the same object in the string pool. Hence s1==s2 is returning true now.
</code>```

Title: What is Java String interning?


问:
The located assembly's manifest definition does not match the assembly reference
I am trying to run some unit tests in a C# Windows Forms application (Visual Studio 2005), and I get the following error:

System.IO.FileLoadException: Could not load file or assembly 'Utility, Version=1.2.0.200, Culture=neutral, PublicKeyToken=764d581291d764f7' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)**

at x.Foo.FooGO()

at x.Foo.Foo2(String groupName_) in Foo.cs:line 123

at x.Foo.UnitTests.FooTests.TestFoo() in FooTests.cs:line 98**

System.IO.FileLoadException: Could not load file or assembly 'Utility, Version=1.2.0.203, Culture=neutral, PublicKeyToken=764d581291d764f7' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

I look in my references, and I only have a reference to Utility version 1.2.0.203 (the other one is old).

Any suggestions on how I figure out what is trying to reference this old version of this DLL file?

Besides, I don't think I even have this old assembly on my hard drive.
Is there any tool to search for this old versioned assembly?

答:
I got stumped with this for a while. I could build and run in release, couldn't in debug due to a reference that didn't match match the manifest. I must have checked the references a hundred times, and deleted all dll's. I noticed that the generated manifest in debug and release were different. </p>

<p>I deleted the app.manifest in my project/properties and it fixed the problem. This didn't include mention of the offending referenced dll's - so I don't know why this was causing a problem.  </p>

OwnerDisplayName: akantro

LastEditorDisplayName: Adam Bellaire

Body:
I got stumped with this for a while. I could build and run in release, couldn't in debug due to a reference that didn't match match the manifest. I must have checked the references a hundred times, and deleted all dll's. I noticed that the generated manifest in debug and release were different.

I deleted the app.manifest in my project/properties and it fixed the problem. This didn't include mention of the offending referenced dll's - so I don't know why this was causing a problem.


问:
problem comparing two dates in mysql
I m using below query from c# to compare current date with date stored in database as string.but it do not show the proper output even though it is not showing any error.

```<code>Select * from tblconcertdetail
WHERE STR_TO_DATE(Concert_Date,'%m/%d/%Y')>="+DateTime.Now.ToString("yyyy-MM-dd")+";
</code>```

first argument shows as: 2011-06-10
second shows ; 2011-06-02

it shows all rows of table

答:
Are you sure the first argument returns as you said YYYY-MM-DD???? Make sure the value for "Concert_Date" should look like "04/22/2011".

Try the following:

```<code>Select * from tblconcertdetail where date(Concert_Date) >= "+DateTime.Now.ToString("yyyy-MM-dd")+";
</code>```

I think Concert_Date is of datatype "date" or "datetime" or "timestamp".

Title: problem comparing two dates in mysql

Body:
I m using below query from c# to compare current date with date stored in database as string.but it do not show the proper output even though it is not showing any error.

Select * from tblconcertdetail
WHERE STR_TO_DATE(Concert_Date,'%m/%d/%Y')>="+DateTime.Now.ToString("yyyy-MM-dd")+";

first argument shows as: 2011-06-10
second shows ; 2011-06-02

it shows all rows of table

Body:
Are you sure the first argument returns as you said YYYY-MM-DD???? Make sure the value for "Concert_Date" should look like "04/22/2011".

Try the following:

Select * from tblconcertdetail where date(Concert_Date) >= "+DateTime.Now.ToString("yyyy-MM-dd")+";

I think Concert_Date is of datatype "date" or "datetime" or "timestamp".


问:
How to order by "Month" using a column that has "Date format" in my sql?
I have a table that has a session name and session date, ex:

```<code>Name: Football game, date: 2020-05-31.
</code>```

Is there a way to display these results in a group by date as in months?? ex:

Date X

1  (month 1) ...

2  (month 2)  ...

...

```<code>SELECT Date(?) , count(*) nb from Session group by Date(?)
</code>```

答:
If you want to group by month, you can use date functions:</p>

```<code>select year(date), month(date), count(*)
from t
group by year(date), month(date);
</code>```

Body:
I have a table that has a session name and session date, ex:

Name: Football game, date: 2020-05-31.

Is there a way to display these results in a group by date as in months?? ex:

Date X

1  (month 1) ...

2  (month 2)  ...

...

SELECT Date(?) , count(*) nb from Session group by Date(?)

Body:
If you want to group by month, you can use date functions:

select year(date), month(date), count(*)
from t
group by year(date), month(date);


问:
Displaying map in tabular format which has object as key and Arraylist as value in jsp
```<code>MapKey mapKey = new MapKey(reqId, name, status);
LinkedHashMap<Object, List<Dashboard>> map = new LinkedHashMap<>();
</code>```

Mapkey Class:

```<code>public class MapKey {
      private Integer id;
      private String name;
      private Integer status;

       public MapKey(Integer id, String name,Integer status) {
        this.id = id;
        this.name = name;
        this.status=status;
      }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }
 //All getters and setters
</code>```

POJO CLASS:

```<code>public class Dashboard {
    int requestId;
    String loginUser;
    int price;
    int status;
    public int getrequestId() {
        return requestId;
    }
    public void setrequestId(int requestId) {
        requestId= requestId;
    }
     //All getters and setters
</code>```

JSP code:

```<code><TABLE BORDER="1" CELLPADDING="3" CELLSPACING="1" style="text-align: center;">
 <TR>
  <c:forEach var="entry" items="${map}">
     <TH>${entry.key}</TH>
  </c:forEach>
 </TR>
 //iterate again
 <c:forEach var="entry" items="${map}">
   //entry.value is ArrayList so we can iterate with c:forEach
  <c:forEach var="headers" items="${entry.value}">
   <TR>
      <TD>${headers}</TD>
   </TR>
  </c:forEach>
</c:forEach>
</TABLE>
</code>```

Input:

```<code>MapKey [reqid=123, name=A,status=1]:[Dashboard [reqid=123, NAME=A, PRICE=5,STATUS=2],Dashboard [reqid=123, NAME=A, PRICE=10,STATUS=3],...,..]
MapKey [reqid=456, name=B,status=2]:[Dashboard [reqid=456, NAME=B, PRICE=20,STATUS=3],Dashboard [reqid=456, NAME=B, PRICE=25,STATUS=2],...,..]
</code>```

Expected Output:

```<code>123  A   1   ///Table header
123 A   5  2
123 A  10  3
//N no of rows

456 B 2    ///Table header
456 B  20  3
456 B  25  2
//N no of rows
</code>```

I have a Map where key is an Object and value is List.Arraylist comprises of rows of each unique reqid as objects. In the map, keys are my table header and the value in the map is the table data for that header.Keys depends on the data from sql.It can be vary as per data.I want to display each key as table header and all its related data as rows of the table.I have written code in jsp to create table for each key.I am newbie in java development,so that is is what I could write.I need help to achieve the expected output.

答:
Given below is a Minimal, Verifiable Example:

Dashboard.java:

```<code>package beans;

public class Dashboard {
    int requestId;
    String loginUser;
    int price;
    int status;
    public Dashboard(int requestId, String loginUser, int price, int status) {
        this.requestId = requestId;
        this.loginUser = loginUser;
        this.price = price;
        this.status = status;
    }
    public int getRequestId() {
        return requestId;
    }
    public String getLoginUser() {
        return loginUser;
    }
    public int getPrice() {
        return price;
    }
    public int getStatus() {
        return status;
    }
}
</code>```

MapKey.java:

```<code>package beans;

public class MapKey {
    private Integer id;
    private String name;
    private Integer status;

    public MapKey(Integer id, String name, Integer status) {
        this.id = id;
        this.name = name;
        this.status = status;
    }

    public Integer getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public Integer getStatus() {
        return status;
    }
}
</code>```

AppController.java:

```<code>package servlets;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import beans.Dashboard;
import beans.MapKey;

@WebServlet("/Report")
public class AppController extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        populateData(request, response);
        RequestDispatcher view = request.getRequestDispatcher("my_page.jsp");
        view.forward(request, response);
    }

    public void populateData(HttpServletRequest request, HttpServletResponse response) {
        Map<MapKey, List<Dashboard>> map = new LinkedHashMap<>();
        map.put(new MapKey(123, "A", 1), List.of(new Dashboard(123, "A", 5, 2), new Dashboard(123, "A", 10, 3)));
        map.put(new MapKey(456, "B", 2), List.of(new Dashboard(456, "B", 20, 3), new Dashboard(456, "B", 25, 2)));
        request.setAttribute("reportMap", map);
    }
}
</code>```

my_page.jsp:

```<code><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
    <head>
        <title>Applicant Information</title>
    </head>
    <body>
        <table border="1">
            <c:forEach var="map" items="${reportMap}">
                <tr>
                    <td>
                        <table border="1">
                            <tr>
                                <th>${map.key.id}</th><th>${map.key.name}</th><th>${map.key.status}</th>
                            </tr>
                        </table>
                    </td>
                    <td>
                        <table border="1">
                            <c:forEach var="item" items="${map.value}">
                                <tr>
                                    <td>${item.requestId}</td><td>${item.loginUser}</td><td>${item.price}</td><td>${item.status}</td>
                                </tr>
                            </c:forEach>
                        </table>
                    </td>
                </tr>
            </c:forEach>
        </table>
    </body>
</html>
</code>```

Output:

Body:
MapKey mapKey = new MapKey(reqId, name, status);
LinkedHashMap<Object, List<Dashboard>> map = new LinkedHashMap<>();

Mapkey Class:

public class MapKey {
      private Integer id;
      private String name;
      private Integer status;

       public MapKey(Integer id, String name,Integer status) {
        this.id = id;
        this.name = name;
        this.status=status;
      }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }
 //All getters and setters

POJO CLASS:

public class Dashboard {
    int requestId;
    String loginUser;
    int price;
    int status;
    public int getrequestId() {
        return requestId;
    }
    public void setrequestId(int requestId) {
        requestId= requestId;
    }
     //All getters and setters

JSP code:

  <c:forEach var="entry" items="${map}">
     ${entry.key}
  </c:forEach>

 //iterate again
 <c:forEach var="entry" items="${map}">
   //entry.value is ArrayList so we can iterate with c:forEach
  <c:forEach var="headers" items="${entry.value}">

      ${headers}

  </c:forEach>
</c:forEach>

Input:

MapKey [reqid=123, name=A,status=1]:[Dashboard [reqid=123, NAME=A, PRICE=5,STATUS=2],Dashboard [reqid=123, NAME=A, PRICE=10,STATUS=3],...,..]
MapKey [reqid=456, name=B,status=2]:[Dashboard [reqid=456, NAME=B, PRICE=20,STATUS=3],Dashboard [reqid=456, NAME=B, PRICE=25,STATUS=2],...,..]

Expected Output:

123  A   1   ///Table header
123 A   5  2
123 A  10  3
//N no of rows

456 B 2    ///Table header
456 B  20  3
456 B  25  2
//N no of rows

I have a Map where key is an Object and value is List.Arraylist comprises of rows of each unique reqid as objects. In the map, keys are my table header and the value in the map is the table data for that header.Keys depends on the data from sql.It can be vary as per data.I want to display each key as table header and all its related data as rows of the table.I have written code in jsp to create table for each key.I am newbie in java development,so that is is what I could write.I need help to achieve the expected output.

Body:
Given below is a Minimal, Verifiable Example:

Dashboard.java:

package beans;

public class Dashboard {
    int requestId;
    String loginUser;
    int price;
    int status;
    public Dashboard(int requestId, String loginUser, int price, int status) {
        this.requestId = requestId;
        this.loginUser = loginUser;
        this.price = price;
        this.status = status;
    }
    public int getRequestId() {
        return requestId;
    }
    public String getLoginUser() {
        return loginUser;
    }
    public int getPrice() {
        return price;
    }
    public int getStatus() {
        return status;
    }
}

MapKey.java:

package beans;

public class MapKey {
    private Integer id;
    private String name;
    private Integer status;

    public MapKey(Integer id, String name, Integer status) {
        this.id = id;
        this.name = name;
        this.status = status;
    }

    public Integer getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public Integer getStatus() {
        return status;
    }
}

AppController.java:

package servlets;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import beans.Dashboard;
import beans.MapKey;

@WebServlet("/Report")
public class AppController extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        populateData(request, response);
        RequestDispatcher view = request.getRequestDispatcher("my_page.jsp");
        view.forward(request, response);
    }

    public void populateData(HttpServletRequest request, HttpServletResponse response) {
        Map<MapKey, List<Dashboard>> map = new LinkedHashMap<>();
        map.put(new MapKey(123, "A", 1), List.of(new Dashboard(123, "A", 5, 2), new Dashboard(123, "A", 10, 3)));
        map.put(new MapKey(456, "B", 2), List.of(new Dashboard(456, "B", 20, 3), new Dashboard(456, "B", 25, 2)));
        request.setAttribute("reportMap", map);
    }
}

my_page.jsp:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
    <head>
        <title>Applicant Information</title>
    </head>
    <body>
        <table border="1">
            <c:forEach var="map" items="${reportMap}">
                <tr>
                    <td>
                        <table border="1">
                            <tr>
                                <th>${map.key.id}</th><th>${map.key.name}</th><th>${map.key.status}</th>
                            </tr>
                        </table>
                    </td>
                    <td>
                        <table border="1">
                            <c:forEach var="item" items="${map.value}">
                                <tr>
                                    <td>${item.requestId}</td><td>${item.loginUser}</td><td>${item.price}</td><td>${item.status}</td>
                                </tr>
                            </c:forEach>
                        </table>
                    </td>
                </tr>
            </c:forEach>
        </table>
    </body>
</html>

Output:


问:
Write list to 2 different text files
Reading in the data text file,
Running loops to check criteria for valid and invalid student numbers.

Then trying to write 2 text files, one for the invalid student numbers and one for the valid student numbers

This far everything works accept no text files written and no data written to text files at the end

Here is the Script so far

```<code>inputList = []
outputList = []

def FileOpen(myList):
    #try:
        count=0
        INFILE=open("data.txt", "r")
        for line in INFILE:
            myList.append(line.rstrip())
            count+=1
        INFILE.close()
        return count
    #except:
    #    print("File could not be found")
    #    exit()

FileOpen(inputList)
print(FileOpen(inputList),"number of lines read from file")

def AnalyseStudents(rawStudents,totalStudents):
    for entry in rawStudents:

        amountOfDigits = len(entry)
        testOfDigits = entry.isdigit()

        def inValid1(val1,val2):
            answ = val1 != 8 and val2 != True
            return answ

        inValidResult1=(inValid1(amountOfDigits,testOfDigits))

        def Valid1(val1,val2):
            answ = val1 == 8 and val2 == True
            return answ

        validResult1=(Valid1(amountOfDigits,testOfDigits))

        if inValidResult1:
            print(entry, " is an INVALID student number")

        elif validResult1:
            a=entry[0]
            b=entry[1]
            c=entry[2]
            d=entry[3]
            e=entry[4]
            f=entry[5]
            g=entry[6]
            h=entry[7]
            sum = float((a*8)+(b*7)+(c*6)+(d*5)+(e*4)+(f*3)+(g*2)+(h*1))
            result = sum%11

            def inValid2 (val):
                answ = val != 0
                return answ

            inValidResult2=(inValid2(result))

            def Valid2 (val):
                answ = val == 0
                return answ

            validResult2=(Valid2(result))

            if validResult2:
                print(entry, " is an VALID student number")

            elif inValidResult2:
                print(entry, " is an INVALID student number")

        totalStudents

AnalyseStudents(inputList,outputList)

def Write(outList):
    if outList == (" is an VALID student number"):
        OUTFILE1=open("ValidNumbers.txt","w")
        for validResult in outList:
            OUTFILE1.write(validResult+"\n")
        OUTFILE1.close()
    elif outList == (" is an INVALID student number"):
        OUTFILE2=open("InvalidNumbers.txt","w")
        for inValidResults in outList:
            OUTFILE2.write(inValidResults+"\n")
        OUTFILE2.close()

Write(outputList)
print("See output files for more details")
</code>```

答:
I'm still working my way through this, but for the first function, you can use list comprehension and a couple of other Python functions.  Commentary is included.

```<code>inputList = []
outputList = []

# Change parameter to the name of the file you want to open.
# Here, we can just make the parameter optional and pass your
# text file name by default.
def FileOpen(filename="data.txt"):

    # Using with keeps the open file in context until it's finished
    # it will then close automatically.
    with open(filename, "r") as INFILE:
        # Reach all the data at once and then try to decode it.
        data = INFILE.read()
        try:
            data = data.decode("utf-8")

        # If data can't be decoded, then it doesn't have that attribute.
        # Catch that exception
        except AttributeError:
            pass

    # Python 3 has a string method called .splitlines() that makes
    # splitting lines a little simpler.
    myList = [line for line in data.splitlines()]

    # We'll return two values: The length (or count) of the list
    # and the actual list.
    return len(myList), myList

# We set up two variables for intake of our count and list results.
count, myList = FileOpen()
print("{} number of lines read from file".format(count))
</code>```

EDIT: I don't know what the last part of your code is aiming to do. Maybe compare student count to valid entries?  Here's the middle part.  I moved the function outside and made it evaluate either valid or invalid in one fell swoop.

```<code>def is_valid(entry_value):
    """Validate current entry."""
    if len(entry_value) != 8 and entry_value.isnumeric():
        return False
    return True

def AnalyseStudents(rawStudents, totalStudents):

    for entry in rawStudents:

        # Our new function will return True if the entry is valid
        # So we can rework our function to run through the True condition
        # first.
        if is_valid(entry):
            entry_sum = entry[0] * 8
            entry_sum += entry[1] * 7
            entry_sum += entry[2] * 6
            entry_sum += entry[3] * 5
            entry_sum += entry[4] * 4
            entry_sum += entry[5] * 3
            entry_sum += entry[6] * 2
            entry_sum += entry[7] * 1

            if entry_sum % 11 == 0:
                print(entry, " is an VALID student number")

            else:
                print(entry, " is an INVALID student number")

        else:
            print(entry, " is an INVALID student number")

AnalyseStudents(inputList, outputList)
</code>```

Title: Write list to 2 different text files

Body:
Reading in the data text file,
Running loops to check criteria for valid and invalid student numbers.

Then trying to write 2 text files, one for the invalid student numbers and one for the valid student numbers

This far everything works accept no text files written and no data written to text files at the end

Here is the Script so far

inputList = []
outputList = []

def FileOpen(myList):
    #try:
        count=0
        INFILE=open("data.txt", "r")
        for line in INFILE:
            myList.append(line.rstrip())
            count+=1
        INFILE.close()
        return count
    #except:
    #    print("File could not be found")
    #    exit()

FileOpen(inputList)
print(FileOpen(inputList),"number of lines read from file")

def AnalyseStudents(rawStudents,totalStudents):
    for entry in rawStudents:

        amountOfDigits = len(entry)
        testOfDigits = entry.isdigit()

        def inValid1(val1,val2):
            answ = val1 != 8 and val2 != True
            return answ

        inValidResult1=(inValid1(amountOfDigits,testOfDigits))

        def Valid1(val1,val2):
            answ = val1 == 8 and val2 == True
            return answ

        validResult1=(Valid1(amountOfDigits,testOfDigits))

        if inValidResult1:
            print(entry, " is an INVALID student number")

        elif validResult1:
            a=entry[0]
            b=entry[1]
            c=entry[2]
            d=entry[3]
            e=entry[4]
            f=entry[5]
            g=entry[6]
            h=entry[7]
            sum = float((a*8)+(b*7)+(c*6)+(d*5)+(e*4)+(f*3)+(g*2)+(h*1))
            result = sum%11

            def inValid2 (val):
                answ = val != 0
                return answ

            inValidResult2=(inValid2(result))

            def Valid2 (val):
                answ = val == 0
                return answ

            validResult2=(Valid2(result))

            if validResult2:
                print(entry, " is an VALID student number")

            elif inValidResult2:
                print(entry, " is an INVALID student number")

        totalStudents

AnalyseStudents(inputList,outputList)

def Write(outList):
    if outList == (" is an VALID student number"):
        OUTFILE1=open("ValidNumbers.txt","w")
        for validResult in outList:
            OUTFILE1.write(validResult+"\n")
        OUTFILE1.close()
    elif outList == (" is an INVALID student number"):
        OUTFILE2=open("InvalidNumbers.txt","w")
        for inValidResults in outList:
            OUTFILE2.write(inValidResults+"\n")
        OUTFILE2.close()

Write(outputList)
print("See output files for more details")

Body:
I'm still working my way through this, but for the first function, you can use list comprehension and a couple of other Python functions.  Commentary is included.

inputList = []
outputList = []

# Change parameter to the name of the file you want to open.
# Here, we can just make the parameter optional and pass your
# text file name by default.
def FileOpen(filename="data.txt"):

    # Using with keeps the open file in context until it's finished
    # it will then close automatically.
    with open(filename, "r") as INFILE:
        # Reach all the data at once and then try to decode it.
        data = INFILE.read()
        try:
            data = data.decode("utf-8")

        # If data can't be decoded, then it doesn't have that attribute.
        # Catch that exception
        except AttributeError:
            pass

    # Python 3 has a string method called .splitlines() that makes
    # splitting lines a little simpler.
    myList = [line for line in data.splitlines()]

    # We'll return two values: The length (or count) of the list
    # and the actual list.
    return len(myList), myList

# We set up two variables for intake of our count and list results.
count, myList = FileOpen()
print("{} number of lines read from file".format(count))

EDIT: I don't know what the last part of your code is aiming to do. Maybe compare student count to valid entries?  Here's the middle part.  I moved the function outside and made it evaluate either valid or invalid in one fell swoop.

def is_valid(entry_value):
    """Validate current entry."""
    if len(entry_value) != 8 and entry_value.isnumeric():
        return False
    return True

def AnalyseStudents(rawStudents, totalStudents):

    for entry in rawStudents:

        # Our new function will return True if the entry is valid
        # So we can rework our function to run through the True condition
        # first.
        if is_valid(entry):
            entry_sum = entry[0] * 8
            entry_sum += entry[1] * 7
            entry_sum += entry[2] * 6
            entry_sum += entry[3] * 5
            entry_sum += entry[4] * 4
            entry_sum += entry[5] * 3
            entry_sum += entry[6] * 2
            entry_sum += entry[7] * 1

            if entry_sum % 11 == 0:
                print(entry, " is an VALID student number")

            else:
                print(entry, " is an INVALID student number")

        else:
            print(entry, " is an INVALID student number")

AnalyseStudents(inputList, outputList)


问:
Sending data from Android
I want to sent the data from an Android device to PHP. I have tried but where I am wrong I don't know. How do I correct this?

This is the Android code that I have done.

```<code>public class php_connect extends Activity {
    InputStream is;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main1);
        JSONObject json = new JSONObject();
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://10.0.2.2/food/food.php");
            json.put("id",1);
            json.put("name","john");
            Log.i("jason Object", json.toString());
            httppost.setHeader("json", json.toString());

            StringEntity se = new StringEntity(json.toString());
            se.setContentEncoding("UTF-8");
            se.setContentType("application/json");
            httppost.setEntity(se);
            HttpResponse response = httpclient.execute(httppost);
            int statusCode = response.getStatusLine().getStatusCode();
            Toast.makeText(getApplicationContext(),String.valueOf(statusCode), Toast.LENGTH_SHORT).show();
            is = se.getContent();
            Log.e("log_tag", "connection success ");
            Toast.makeText(getApplicationContext(), "Successfully Connected", Toast.LENGTH_SHORT).show();
        }
        catch(Exception e){
            Log.e("log_tag", "Error in http connection "+e.toString());
            Toast.makeText(getApplicationContext(), "Fail to Connect", Toast.LENGTH_SHORT).show();
        }
    }
}
</code>```

I get response as 200 and connected successfully but cannot see data in PHP.

And my PHP code is:

```<code><?php
    $data = file_get_contents('php://input');
    $json = json_decode($data,true);
    var_dump($json);
    $id=$json['id'];
    echo $id;
?>
</code>```

I always get the null result.

答:
From the PHP manual:

In case of POST requests, it preferrable to $HTTP_RAW_POST_DATA as it does not depend on special php.ini directives. Moreover, for those cases where $HTTP_RAW_POST_DATA is not populated by default, it is a potentially less memory intensive alternative to activating always_populate_raw_post_data. php://input is not available with enctype="multipart/form-data"

I think it will be even easier to encode your JSON as a form parameter and use the normal PHP $_POST function to read it:

```<code>List parameters = new ArrayList();
parameters.add(new BasicNameValuePair("jsonParam", json.toString())
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters)
httppost.setContentType("multipart/form-data");
httppost.setEntity(formEntity);
</code>```

On the PHP side you can simply do

```<code>Got <?php echo $_POST["jsonParam"]; ?>!<br />
</code>```

Note: I have not tested the above code.

Title: Sending data from Android

Body:
I want to sent the data from an Android device to PHP. I have tried but where I am wrong I don't know. How do I correct this?

This is the Android code that I have done.

public class php_connect extends Activity {
    InputStream is;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main1);
        JSONObject json = new JSONObject();
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://10.0.2.2/food/food.php");
            json.put("id",1);
            json.put("name","john");
            Log.i("jason Object", json.toString());
            httppost.setHeader("json", json.toString());

            StringEntity se = new StringEntity(json.toString());
            se.setContentEncoding("UTF-8");
            se.setContentType("application/json");
            httppost.setEntity(se);
            HttpResponse response = httpclient.execute(httppost);
            int statusCode = response.getStatusLine().getStatusCode();
            Toast.makeText(getApplicationContext(),String.valueOf(statusCode), Toast.LENGTH_SHORT).show();
            is = se.getContent();
            Log.e("log_tag", "connection success ");
            Toast.makeText(getApplicationContext(), "Successfully Connected", Toast.LENGTH_SHORT).show();
        }
        catch(Exception e){
            Log.e("log_tag", "Error in http connection "+e.toString());
            Toast.makeText(getApplicationContext(), "Fail to Connect", Toast.LENGTH_SHORT).show();
        }
    }
}

I get response as 200 and connected successfully but cannot see data in PHP.

And my PHP code is:

<?php
    $data = file_get_contents('php://input');
    $json = json_decode($data,true);
    var_dump($json);
    $id=$json['id'];
    echo $id;
?>

I always get the null result.

Body:
From the PHP manual:

In case of POST requests, it preferrable to $HTTP_RAW_POST_DATA as it does not depend on special php.ini directives. Moreover, for those cases where $HTTP_RAW_POST_DATA is not populated by default, it is a potentially less memory intensive alternative to activating always_populate_raw_post_data. php://input is not available with enctype="multipart/form-data"

I think it will be even easier to encode your JSON as a form parameter and use the normal PHP $_POST function to read it:

List parameters = new ArrayList();
parameters.add(new BasicNameValuePair("jsonParam", json.toString())
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters)
httppost.setContentType("multipart/form-data");
httppost.setEntity(formEntity);

On the PHP side you can simply do

Got <?php echo $_POST["jsonParam"]; ?>!<br />

Note: I have not tested the above code.


问:
Pin version with go get
I 'd like to pin the version of one package, so whenever I run

```<code>go get -u ./...
</code>```

..this package would stay unchanged (but the rest refreshed normally).

答:
Use go modules. It was specifically designed to handle precise version control.

In your package's go.mod you can pin any dependencies to a fixed version e.g.

```<code>module example.com/hello
go 1.12
require (
    golang.org/x/text v0.3.0 // indirect
    rsc.io/quote v1.5.2
    rsc.io/quote/v3 v3.0.0
    rsc.io/sampler v1.3.1 // indirect
)
</code>```

You can update individual package versions e.g.:

```<code>go get rsc.io/quote/v3@master
</code>```

Will pull the latest commit version (beyond even any semver tagged version).
You can also hand edit go.mod for extra precision.

P.S. you need go version 1.11 or later for go modules. go 1.13 has modules turned on by default. Earlier versions you have to explicitly enable it via the env var GO111MODULE=ON.

Title: Pin version with go get

Body:
I 'd like to pin the version of one package, so whenever I run

go get -u ./...

..this package would stay unchanged (but the rest refreshed normally).

Body:
Use go modules. It was specifically designed to handle precise version control.

In your package's go.mod you can pin any dependencies to a fixed version e.g.

module example.com/hello
go 1.12
require (
    golang.org/x/text v0.3.0 // indirect
    rsc.io/quote v1.5.2
    rsc.io/quote/v3 v3.0.0
    rsc.io/sampler v1.3.1 // indirect
)

You can update individual package versions e.g.:

go get rsc.io/quote/v3@master

Will pull the latest commit version (beyond even any semver tagged version).
You can also hand edit go.mod for extra precision.

P.S. you need go version 1.11 or later for go modules. go 1.13 has modules turned on by default. Earlier versions you have to explicitly enable it via the env var GO111MODULE=ON.


问:
cs50 pset2 caesar---validating the key
I'm going through cs50 and I'm stuck on pset2 caesar. I'm taking it step-by-step as instructed and I got past the part about validating the key--making sure the command-line argument is only a number (./caesar 20) and if not (./caesar 20x or ./caesar xyz) to print out Usage: ./caesar key\n. But once I add the next lines to prompt the user for plaintext and then print back the ciphertext it doesnt seem to register the former lines that validate the key. I am aware of Harvard's academic integrity policy so I'm more asking for hints/help/explaination with this. I've posted my code below and any help is greatly appreciated. </p>

```<code>int main(int argc, string argv[])
{

        int i = 0;
        if(isalpha(argv[1][i]))
        {
            printf("Usage: ./caesar key\n");
            return 1;
        }
        else
        {
            int key = atoi(argv[1]);
            string text = get_string("plaintext: ");
            printf("ciphertext: ");
            int n = strlen(text);
            for(i = 0; i < n; i++)
            {
                if(isupper(text[i]))
                {
                    printf("%c", (((text[i] - 65) + key) % 26) + 65);
                }
                else if(islower(text[i]))
                {
                    printf("%c", (((text[i] - 97) + key) % 26) + 97);
                }
                else
                {
                    printf("%c", text[i]);
                }
            }
    }
    printf("\n");
    return 0;
}
</code>```

答:
You have to check 2 things in the command-line argument.
1. Check if you have 2 arguments. (This is not checked in your program)
2. Check if it is not an alphabet... Since the second argument is automatically a string (due to string argv[]), you must convert it first to integers. ---- this breeds sub-problems that you must take care of by:
2.A. Check the string one-by-one (per CHARACTER) and all must be an integer.
2.B. If at least one is a character then return false...

2.A. and 2.B. should be a nested in a separate function that would return a boolean value(T/F), then from that boolean value, enclose those two boolean expressions in the while loop.

2 months late on my answer but since I just finished this problem, I thought maybe someone might be experiencing the same difficulty I had with this so hope someone can read this and help them out. :)

Title: cs50 pset2 caesar---validating the key

Body:
I'm going through cs50 and I'm stuck on pset2 caesar. I'm taking it step-by-step as instructed and I got past the part about validating the key--making sure the command-line argument is only a number (./caesar 20) and if not (./caesar 20x or ./caesar xyz) to print out Usage: ./caesar key\n. But once I add the next lines to prompt the user for plaintext and then print back the ciphertext it doesnt seem to register the former lines that validate the key. I am aware of Harvard's academic integrity policy so I'm more asking for hints/help/explaination with this. I've posted my code below and any help is greatly appreciated.

int main(int argc, string argv[])
{

        int i = 0;
        if(isalpha(argv[1][i]))
        {
            printf("Usage: ./caesar key\n");
            return 1;
        }
        else
        {
            int key = atoi(argv[1]);
            string text = get_string("plaintext: ");
            printf("ciphertext: ");
            int n = strlen(text);
            for(i = 0; i < n; i++)
            {
                if(isupper(text[i]))
                {
                    printf("%c", (((text[i] - 65) + key) % 26) + 65);
                }
                else if(islower(text[i]))
                {
                    printf("%c", (((text[i] - 97) + key) % 26) + 97);
                }
                else
                {
                    printf("%c", text[i]);
                }
            }
    }
    printf("\n");
    return 0;
}


问:
How to toggle dark mode in Angular
I am trying to toggle the dark mode when a user toggles the switch, which is in the header component. See image below:

```<code><nav class="navbar navbar-expand-lg navbar-light bg-light">
    <a class="navbar-brand" href="#">Navbar</a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
      <div class="navbar-nav">
        <a class="nav-item nav-link active" href="/">Home <span class="sr-only">(current)</span></a>
        <a class="nav-item nav-link" href="/about">About</a>
        <a class="nav-item nav-link" href="/contact">Contact</a>
        <a class="nav-item nav-link" href="/resume">Resume</a>
      </div>
    </div>
    <div class="custom-control custom-switch">
        <input (change)="onChangeToggle()" type="checkbox" class="custom-control-input" id="toggleTheme">
        <label class="custom-control-label" for="toggleTheme">Dark Mode</label>
      </div>
  </nav>
</code>```

My header component ts file holds a boolean value called setDark which is triggered in an event emitter through the Output decorator :

```<code>// header.component.ts

import { Component, OnInit , Output, EventEmitter} from '@angular/core';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {

  @Output() mode = new EventEmitter<boolean>();

  setDark = false;

  constructor() { }

  ngOnInit(): void {

  }

  onChangeToggle() {
    this.setDark = !this.setDark;
    this.mode.emit(this.setDark);
    console.log(this.setDark);
  }

}
</code>```

Then in the app.comoonent.html receive boolean

```<code> <app-header (mode)="receiveMode($event)"></app-header>

  <router-outlet></router-outlet>

// app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  setMode = false;

  receiveMode($event) {
    this.setMode = $event;
    console.log("MODEEEE", this.setMode);
  }

  title = 'about-me';
}
</code>```

I have tried to wrap the div around the app-header and router-outlet like so:

```<code><app-header (mode)="receiveMode($event)"></app-header>
<div class="darkTheme">
  <router-outlet></router-outlet>
</code>```

and using ngClass:

```<code><div [ngClass]="{
  darkTheme: setMode
}">
</div>
</code>```

But it doesn't work. I did check to see whether or not the boolean is being logged into the console when toggling the switch. It is.

答:
Have a look at this stackblitz: https://stackblitz.com/edit/angular-rubaka?file=src/app/toolbar-multirow-example.html

it toggles the class "dark-theme" on the #container:ElementRef:

The styles.scss defines two different theme's on line 28 (default theme)...

```<code>// Include the default theme styles.
@include angular-material-theme($candy-app-theme);
</code>```

and on line 39 (dark theme)...

```<code>.dark-theme {
  @include angular-material-theme($dark-theme)
};
</code>```

Hope this helps.

Title: How to toggle dark mode in Angular

Body:
I am trying to toggle the dark mode when a user toggles the switch, which is in the header component. See image below:

    Navbar
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">

    </button>

        Home (current)
        About
        Contact
        Resume

        <input (change)="onChangeToggle()" type="checkbox" class="custom-control-input" id="toggleTheme">
        Dark Mode

My header component ts file holds a boolean value called setDark which is triggered in an event emitter through the Output decorator :

// header.component.ts

import { Component, OnInit , Output, EventEmitter} from '@angular/core';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {

  @Output() mode = new EventEmitter<boolean>();

  setDark = false;

  constructor() { }

  ngOnInit(): void {

  }

  onChangeToggle() {
    this.setDark = !this.setDark;
    this.mode.emit(this.setDark);
    console.log(this.setDark);
  }

}

Then in the app.comoonent.html receive boolean

 <app-header (mode)="receiveMode($event)"></app-header>

  <router-outlet></router-outlet>

// app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  setMode = false;

  receiveMode($event) {
    this.setMode = $event;
    console.log("MODEEEE", this.setMode);
  }

  title = 'about-me';
}

I have tried to wrap the div around the app-header and router-outlet like so:

<app-header (mode)="receiveMode($event)"></app-header>

  <router-outlet></router-outlet>

and using ngClass:

But it doesn't work. I did check to see whether or not the boolean is being logged into the console when toggling the switch. It is.

Body:
Have a look at this stackblitz: https://stackblitz.com/edit/angular-rubaka?file=src/app/toolbar-multirow-example.html

it toggles the class "dark-theme" on the #container:ElementRef:

<div #container style="padding: 4rem;" class="mat-typography dark-theme">

The styles.scss defines two different theme's on line 28 (default theme)...

// Include the default theme styles.
@include angular-material-theme($candy-app-theme);

and on line 39 (dark theme)...

.dark-theme {
  @include angular-material-theme($dark-theme)
};

Hope this helps.


问:
How do I test the Asp.Net Core controller which has Db Context and Logger?
I have a controller with two parameters and need to test them via unit tests. Want to test 4 parameters, ViewBug, etc. But how I can make fake DB context and logger? I'm stuck at this moment:

```<code>        [Fact]
    public void IndexReturnsAViewResultWithAListOfUsers()
    {
        // Arrange
        var mock = new Mock<AircraftsController>();
        var controller = new AircraftsController(/*params*/);

        // Act

        // Assert
    }
</code>```

This is my controller:

```<code> public class AircraftsController : Controller
{
    #region DbContext, Logger
    public AppDbContext Context { get; }
    private readonly ILogger<AircraftsController> _logger;

    public AircraftsController(AppDbContext context, ILogger<AircraftsController> logger)
    {
        Context = context;
        _logger = logger;
        _logger.LogDebug(1, "NLog injected into Controller");
    }
    #endregion

    [HttpGet]
    public IActionResult Compare(int vehicle1, int vehicle2, int vehicle3, int vehicle4)
    {
        var planesFromDb = Context.Planes.OrderBy(x => x.BR).ToList();
        planesFromDb.Insert(0, new Plane { Image = "~/images/EmptyPlane.png", Nation = "EmptyFlag", Name = "Select aircraft", VehicleId=0 });
        var selectedPlanes = new List<Plane>();
        ViewBag.AllPlanesSelected = planesFromDb;

        selectedPlanes.Add(planesFromDb.FirstOrDefault(p => p.VehicleId == vehicle1));
        selectedPlanes.Add(planesFromDb.FirstOrDefault(p => p.VehicleId == vehicle2));
        selectedPlanes.Add(planesFromDb.FirstOrDefault(p => p.VehicleId == vehicle3));
        selectedPlanes.Add(planesFromDb.FirstOrDefault(p => p.VehicleId == vehicle4));

        _logger.LogInformation("Log Message");

        return View(selectedPlanes);
    }

}
</code>```

答:
In .NET Core, you can take advantage of in-memory databases for unit tests.  There are two options, EF In-Memory database, and SQLite In-Memory database.  I prefer SQLite In-Memory because it gives you all the advantages of handling relational data, unlike EF In-Memory.

Testing with the EF In-Memory Database

SQLite In-Memory Database

Below is a simple implementation for unit tests using SQLite In-Memory database:

```<code>    public YourContext GetDbContext()
    {
        var connection = new SqliteConnection("DataSource=:memory:");
        connection.Open();

        var option = new DbContextOptionsBuilder<YourContext>()
            .UseSqlite(connection,
            s => {
                s.UseNetTopologySuite();
                s.MigrationsHistoryTable("__MigrationHistory");
            }).Options;

        var dbContext = new YourContext(option);

        //Added to recreate database and run migration for each test.
        if (dbContext != null)
        {
            dbContext.Database.EnsureDeleted();
            dbContext.Database.EnsureCreated();
        }

        return dbContext;
    }
</code>```

And then in unit test:

```<code>var context = GetDbContext();
</code>```

Alternatively, you can place the GetDbContext method in a fixture, so that you are only re-creating the database one time per test class.  Have a dispose method in the fixture to run the dbContext.Database.EnsureDeleted() to clean up the data between test classes.

Shared context between Tests - Class Fixtures

Body:
I have a controller with two parameters and need to test them via unit tests. Want to test 4 parameters, ViewBug, etc. But how I can make fake DB context and logger? I'm stuck at this moment:

        [Fact]
    public void IndexReturnsAViewResultWithAListOfUsers()
    {
        // Arrange
        var mock = new Mock<AircraftsController>();
        var controller = new AircraftsController(/*params*/);

        // Act

        // Assert
    }

This is my controller:

 public class AircraftsController : Controller
{
    #region DbContext, Logger
    public AppDbContext Context { get; }
    private readonly ILogger<AircraftsController> _logger;

    public AircraftsController(AppDbContext context, ILogger<AircraftsController> logger)
    {
        Context = context;
        _logger = logger;
        _logger.LogDebug(1, "NLog injected into Controller");
    }
    #endregion

    [HttpGet]
    public IActionResult Compare(int vehicle1, int vehicle2, int vehicle3, int vehicle4)
    {
        var planesFromDb = Context.Planes.OrderBy(x => x.BR).ToList();
        planesFromDb.Insert(0, new Plane { Image = "~/images/EmptyPlane.png", Nation = "EmptyFlag", Name = "Select aircraft", VehicleId=0 });
        var selectedPlanes = new List<Plane>();
        ViewBag.AllPlanesSelected = planesFromDb;

        selectedPlanes.Add(planesFromDb.FirstOrDefault(p => p.VehicleId == vehicle1));
        selectedPlanes.Add(planesFromDb.FirstOrDefault(p => p.VehicleId == vehicle2));
        selectedPlanes.Add(planesFromDb.FirstOrDefault(p => p.VehicleId == vehicle3));
        selectedPlanes.Add(planesFromDb.FirstOrDefault(p => p.VehicleId == vehicle4));

        _logger.LogInformation("Log Message");

        return View(selectedPlanes);
    }

}

Body:
In .NET Core, you can take advantage of in-memory databases for unit tests.  There are two options, EF In-Memory database, and SQLite In-Memory database.  I prefer SQLite In-Memory because it gives you all the advantages of handling relational data, unlike EF In-Memory.

Testing with the EF In-Memory Database

SQLite In-Memory Database

Below is a simple implementation for unit tests using SQLite In-Memory database:

    public YourContext GetDbContext()
    {
        var connection = new SqliteConnection("DataSource=:memory:");
        connection.Open();

        var option = new DbContextOptionsBuilder<YourContext>()
            .UseSqlite(connection,
            s => {
                s.UseNetTopologySuite();
                s.MigrationsHistoryTable("__MigrationHistory");
            }).Options;

        var dbContext = new YourContext(option);

        //Added to recreate database and run migration for each test.
        if (dbContext != null)
        {
            dbContext.Database.EnsureDeleted();
            dbContext.Database.EnsureCreated();
        }

        return dbContext;
    }

And then in unit test:

var context = GetDbContext();

Alternatively, you can place the GetDbContext method in a fixture, so that you are only re-creating the database one time per test class.  Have a dispose method in the fixture to run the dbContext.Database.EnsureDeleted() to clean up the data between test classes.

Shared context between Tests - Class Fixtures