答:
I would suggest that you put your header on a master page and have a couple of content pages. You can still put it into a user control.

If you want to keep your user control and just reload the content, it get's a bit complicated. You will have to use JavaScript to achieve this goal. In ASP.NET you could use an UpdatePanel.

```<code><asp:UpdatePanel ID=”UpdatePanel1” runat=”server”>
  <ContentTemplate>
    <!-- this content can be refreshed on post backs -->
  </ContentTemplate>
</asp:UpdatePanel>
</code>```

To have separate panels for logged in Users, you can use login view:

```<code><asp:LoginView ID="HeadLoginView" runat="server" EnableViewState="false">
   <AnonymousTemplate>
   </AnonymousTemplate>
   <LoggedInTemplate>
         Welcome <span class="bold"><asp:LoginName ID="HeadLoginName" runat="server" /></span>!
          [ <asp:LoginStatus ID="HeadLoginStatus" runat="server" LogoutAction="Redirect" LogoutText="Log Out" LogoutPageUrl="~/"/> ]
   </LoggedInTemplate>
</asp:LoginView>
</code>```

Title: How to make user control header load only one time?

Body:
I'm implementing a user control in an asp.net website.  The user control will be used as a header in all pages.  How can load the user control content depends on the user (logged in, logged out, user name).

How can i load my user control only one time?  For example, when the user is logged in like quora.  To have an idea of what i mean, log into quora, you will notice: every time,i open a page of a question,the quora header is not reloaded.only the main content changes.

How that is achieved?

Body:
I would suggest that you put your header on a master page and have a couple of content pages. You can still put it into a user control.

If you want to keep your user control and just reload the content, it get's a bit complicated. You will have to use JavaScript to achieve this goal. In ASP.NET you could use an UpdatePanel.

<asp:UpdatePanel ID=”UpdatePanel1” runat=”server”>
  <ContentTemplate>
    <!-- this content can be refreshed on post backs -->
  </ContentTemplate>
</asp:UpdatePanel>

To have separate panels for logged in Users, you can use login view:

<asp:LoginView ID="HeadLoginView" runat="server" EnableViewState="false">
   <AnonymousTemplate>
   </AnonymousTemplate>
   <LoggedInTemplate>
         Welcome <span class="bold"><asp:LoginName ID="HeadLoginName" runat="server" /></span>!
          [ <asp:LoginStatus ID="HeadLoginStatus" runat="server" LogoutAction="Redirect" LogoutText="Log Out" LogoutPageUrl="~/"/> ]
   </LoggedInTemplate>
</asp:LoginView>


来源: stackexchange

问:
Spring Security SAML2 multiple IDPs configuration
I am trying to configure multiple idps via RelyingPartyRegistrationRepository using spring security 5.3
This is my application.yaml config

```<code>spring:
  security:
    saml2:
      relyingparty:
        registration:
          idpokta:
            identityprovider:
              entity-id: http://<url>
              sso-url: https://<url>
              verification:
                credentials:
                  - certificate-location: "classpath:saml/okta.cert"
              signing:
                credentials:
                  certificate: |
                    -----BEGIN CERTIFICATE-----
                    MIIDpDCC...
                    -----END CERTIFICATE-----
                  private-key: |
                    -----BEGIN PRIVATE KEY-----
                    MIIEvQIBA....

                    -----END PRIVATE KEY-----

          idponelogin:
            identityprovider:
              entity-id: https://<url>
              sso-url: https://<url>
              verification:
                credentials:
                  - certificate-location: "classpath:saml/onelogin.cert"
            signing:
              credentials:
                certificate: |
                  -----BEGIN CERTIFICATE-----
                  MIID/z...
                  -----END CERTIFICATE-----
                private-key: |
                  -----BEGIN PRIVATE KEY-----
                  MIpoi...

                  -----END PRIVATE KEY-----
</code>```

my login controller is defined as follows:

```<code>@Controller
public class LoginController {
    private final RelyingPartyRegistrationRepository relyingParties;

    // ...

   @GetMapping("/login")
  public void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String registrationId = request.getParameter("idp");
    RelyingPartyRegistration relyingParty = this.relyingParties
            .findByRegistrationId(registrationId);
    if (relyingParty == null) {
      response.setStatus(401);
    } else {
      response.sendRedirect("/saml2/authenticate/" + registrationId);
    }
}
</code>```

PROBLEM
my relyingParty has the provider details but I think the fact that my assertionConsumerServiceUrl is defaulting to {baseUrl}/login/saml2/sso/{registrationId} and my localEntityIdTemplate = {baseUrl}/saml2/service-provider-metadata/{registrationId}` is causing it the problem. How do I add the sp info in my yaml file? or Am I doing this completely wrong?

Screenshot

答:
I've been trying to do the same thing. The API doesn't seem to be well thought through. If you try to use auto configuration spring boot feature the only way I found is to exclude this configuration

```<code>Saml2RelyingPartyRegistrationConfiguration
</code>```

and provide your own class for that.

Since all of that is package local, you have to bring pretty much entire package

```<code>org.springframework.boot.autoconfigure.security.saml2
</code>```

to your own application first disabling the one from spring altogether.

You will end up with

```<code>CustomRegistrationConfiguredCondition
CustomSaml2LoginConfiguration
CustomSaml2RelyingPartyAutoConfiguration
CustomSaml2RelyingPartyRegistrationConfiguration
</code>```

at the very least.
Make sure the references between the classes are updated too.

Now, you need to update the following method in the CustomSaml2RelyingPartyRegistrationConfiguration:

```<code>    private RelyingPartyRegistration asRegistration(String id, Registration properties) {
        RelyingPartyRegistration.Builder builder = RelyingPartyRegistration.withRegistrationId(id);
        builder.assertionConsumerServiceUrlTemplate(
                "{baseUrl}" + Saml2WebSsoAuthenticationFilter.DEFAULT_FILTER_PROCESSES_URI);
        builder.idpWebSsoUrl(properties.getIdentityprovider().getSsoUrl());
        builder.remoteIdpEntityId(properties.getIdentityprovider().getEntityId());
        builder.localEntityIdTemplate("template_you_like");
        builder.credentials((credentials) -> credentials.addAll(asCredentials(properties)));
        return builder.build();
    }
</code>```

Alternatively, you can also copy Saml2RelyingPartyProperties to your project and add all necessary fields there. This way you'll be able to set properties in yaml or properties file. Don't forget to use those values in asRegistration method mentioned above.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to configure multiple idps via RelyingPartyRegistrationRepository using spring security 5.3
This is my application.yaml config

spring:
  security:
    saml2:
      relyingparty:
        registration:
          idpokta:
            identityprovider:
              entity-id: http://<url>
              sso-url: https://<url>
              verification:
                credentials:
                  - certificate-location: "classpath:saml/okta.cert"
              signing:
                credentials:
                  certificate: |
                    -----BEGIN CERTIFICATE-----
                    MIIDpDCC...
                    -----END CERTIFICATE-----
                  private-key: |
                    -----BEGIN PRIVATE KEY-----
                    MIIEvQIBA....

                    -----END PRIVATE KEY-----

          idponelogin:
            identityprovider:
              entity-id: https://<url>
              sso-url: https://<url>
              verification:
                credentials:
                  - certificate-location: "classpath:saml/onelogin.cert"
            signing:
              credentials:
                certificate: |
                  -----BEGIN CERTIFICATE-----
                  MIID/z...
                  -----END CERTIFICATE-----
                private-key: |
                  -----BEGIN PRIVATE KEY-----
                  MIpoi...

                  -----END PRIVATE KEY-----

my login controller is defined as follows:

@Controller
public class LoginController {
    private final RelyingPartyRegistrationRepository relyingParties;

    // ...

   @GetMapping("/login")
  public void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String registrationId = request.getParameter("idp");
    RelyingPartyRegistration relyingParty = this.relyingParties
            .findByRegistrationId(registrationId);
    if (relyingParty == null) {
      response.setStatus(401);
    } else {
      response.sendRedirect("/saml2/authenticate/" + registrationId);
    }
}

PROBLEM
my relyingParty has the provider details but I think the fact that my assertionConsumerServiceUrl is defaulting to {baseUrl}/login/saml2/sso/{registrationId} and my localEntityIdTemplate = {baseUrl}/saml2/service-provider-metadata/{registrationId}` is causing it the problem. How do I add the sp info in my yaml file? or Am I doing this completely wrong?

Screenshot

Body:
I've been trying to do the same thing. The API doesn't seem to be well thought through. If you try to use auto configuration spring boot feature the only way I found is to exclude this configuration

Saml2RelyingPartyRegistrationConfiguration

and provide your own class for that.

Since all of that is package local, you have to bring pretty much entire package

org.springframework.boot.autoconfigure.security.saml2

to your own application first disabling the one from spring altogether.

You will end up with

CustomRegistrationConfiguredCondition
CustomSaml2LoginConfiguration
CustomSaml2RelyingPartyAutoConfiguration
CustomSaml2RelyingPartyRegistrationConfiguration

at the very least.
Make sure the references between the classes are updated too.

Now, you need to update the following method in the CustomSaml2RelyingPartyRegistrationConfiguration:

    private RelyingPartyRegistration asRegistration(String id, Registration properties) {
        RelyingPartyRegistration.Builder builder = RelyingPartyRegistration.withRegistrationId(id);
        builder.assertionConsumerServiceUrlTemplate(
                "{baseUrl}" + Saml2WebSsoAuthenticationFilter.DEFAULT_FILTER_PROCESSES_URI);
        builder.idpWebSsoUrl(properties.getIdentityprovider().getSsoUrl());
        builder.remoteIdpEntityId(properties.getIdentityprovider().getEntityId());
        builder.localEntityIdTemplate("template_you_like");
        builder.credentials((credentials) -> credentials.addAll(asCredentials(properties)));
        return builder.build();
    }

Alternatively, you can also copy Saml2RelyingPartyProperties to your project and add all necessary fields there. This way you'll be able to set properties in yaml or properties file. Don't forget to use those values in asRegistration method mentioned above.


问:
docx4j: Generated word document is says there are problems with the contents
I am using docx4j version: '8.1.4'.

I have update to 8.1.4 recently and after update generated document says below while opening.
It says "Only a default namespace can have an empty URI"

Document.xml is as below..

'''?xml version="1.0" encoding="UTF-8"?
w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math" xmlns:sl="http://schemas.openxmlformats.org/schemaLibrary/2006/main" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:ns0="" xmlns:wp14="http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing" xmlns:w16se="http://schemas.microsoft.com/office/word/2015/wordml/symex" xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml" xmlns:w15="http://schemas.microsoft.com/office/word/2012/wordml" xmlns:w16cid="http://schemas.microsoft.com/office/word/2016/wordml/cid" mc:Ignorable="w14 w15 w16se w16cid w16 w16cex wp14"
   w:body!-- Modified by docx4j 8.1.4 (Apache licensed) using ECLIPSELINK_MOXy JAXB in Oracle Java 11.0.2 on Windows 10 '''

Please help me in understanding what might be going wrong here..

old document element:

w:document xmlns:wpc="http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas" xmlns:cx="http://schemas.microsoft.com/office/drawing/2014/chartex" xmlns:cx1="http://schemas.microsoft.com/office/drawing/2015/9/8/chartex" xmlns:cx2="http://schemas.microsoft.com/office/drawing/2015/10/21/chartex" xmlns:cx3="http://schemas.microsoft.com/office/drawing/2016/5/9/chartex" xmlns:cx4="http://schemas.microsoft.com/office/drawing/2016/5/10/chartex" xmlns:cx5="http://schemas.microsoft.com/office/drawing/2016/5/11/chartex" xmlns:cx6="http://schemas.microsoft.com/office/drawing/2016/5/12/chartex" xmlns:cx7="http://schemas.microsoft.com/office/drawing/2016/5/13/chartex" xmlns:cx8="http://schemas.microsoft.com/office/drawing/2016/5/14/chartex" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:aink="http://schemas.microsoft.com/office/drawing/2016/ink" xmlns:am3d="http://schemas.microsoft.com/office/drawing/2017/model3d" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:wp14="http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:w10="urn:schemas-microsoft-com:office:word" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml" xmlns:w15="http://schemas.microsoft.com/office/word/2012/wordml" xmlns:w16cid="http://schemas.microsoft.com/office/word/2016/wordml/cid" xmlns:w16se="http://schemas.microsoft.com/office/word/2015/wordml/symex" xmlns:wpg="http://schemas.microsoft.com/office/word/2010/wordprocessingGroup" xmlns:wpi="http://schemas.microsoft.com/office/word/2010/wordprocessingInk" xmlns:wne="http://schemas.microsoft.com/office/word/2006/wordml" xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape" mc:Ignorable="w14 w15 w16se w16cid wp14"

new document element:

w:document xmlns:wpc="http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas" xmlns:cx="http://schemas.microsoft.com/office/drawing/2014/chartex" xmlns:cx1="http://schemas.microsoft.com/office/drawing/2015/9/8/chartex" xmlns:cx2="http://schemas.microsoft.com/office/drawing/2015/10/21/chartex" xmlns:cx3="http://schemas.microsoft.com/office/drawing/2016/5/9/chartex" xmlns:cx4="http://schemas.microsoft.com/office/drawing/2016/5/10/chartex" xmlns:cx5="http://schemas.microsoft.com/office/drawing/2016/5/11/chartex" xmlns:cx6="http://schemas.microsoft.com/office/drawing/2016/5/12/chartex" xmlns:cx7="http://schemas.microsoft.com/office/drawing/2016/5/13/chartex" xmlns:cx8="http://schemas.microsoft.com/office/drawing/2016/5/14/chartex" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:aink="http://schemas.microsoft.com/office/drawing/2016/ink" xmlns:am3d="http://schemas.microsoft.com/office/drawing/2017/model3d" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:wp14="http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:w10="urn:schemas-microsoft-com:office:word" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml" xmlns:w15="http://schemas.microsoft.com/office/word/2012/wordml" xmlns:w16cex="http://schemas.microsoft.com/office/word/2018/wordml/cex" xmlns:w16cid="http://schemas.microsoft.com/office/word/2016/wordml/cid" xmlns:w16="http://schemas.microsoft.com/office/word/2018/wordml" xmlns:w16se="http://schemas.microsoft.com/office/word/2015/wordml/symex" xmlns:wpg="http://schemas.microsoft.com/office/word/2010/wordprocessingGroup" xmlns:wpi="http://schemas.microsoft.com/office/word/2010/wordprocessingInk" xmlns:wne="http://schemas.microsoft.com/office/word/2006/wordml" xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape" mc:Ignorable="w14 w15 w16se w16cid w16 w16cex wp14"

答:
It seems docx4j-JAXB-MOXy-8.1.4 might write xmlns:ns0=""

Fixed by docx4j-JAXB-MOXy-8.1.5 (current release is 8.1.7).


问:
Xamarin.iOS native linking error MTOUCH MT5210 undefined symbol std::string
My Xamarion.iOS binding project has the links to all the required native video SDK libraries and native OS frameworks.  I have set the required frameworks using Frameworks attribute. Other settings include SmartLink=true, ForceLoad=true, IsCxx=true, LinkerFlags="-lc++". It can be built into a C# DLL. In iOS project, the DLL is referenced and used.  However there are native linking errors.

```<code>MTOUCH: Error MT5210: Native linking failed, undefined symbol: std::string::_Rep::_M_destroy(std::allocator<char> const&). Please verify that all the necessary frameworks have been referenced and native libraries are properly linked in.
</code>```

The details in build log:

```<code>> Undefined symbols for architecture arm64:
>       "std::string::_Rep::_M_destroy(std::allocator<char> const&)", referenced from:
>           HPR_UTF82A(char const*) in libHCCore.a(HPR_Utils.o)
>           HPR_A2UTF8(char const*) in libHCCore.a(HPR_Utils.o)
>       "std::string::_Rep::_S_empty_rep_storage", referenced from:
>           HPR_UTF82A(char const*) in libHCCore.a(HPR_Utils.o)
>           HPR_A2UTF8(char const*) in libHCCore.a(HPR_Utils.o)
>       "std::string::assign(char const*, unsigned long)", referenced from:
>           HPR_UTF82A(char const*) in libHCCore.a(HPR_Utils.o)
>           HPR_A2UTF8(char const*) in libHCCore.a(HPR_Utils.o)
>       "std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(char const*, std::allocator<char>
> const&)", referenced from:
>           HPR_A2UTF8(char const*) in libHCCore.a(HPR_Utils.o)
>       "std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(std::string const&)", referenced
> from:
>           HPR_A2UTF8(char const*) in libHCCore.a(HPR_Utils.o)
>     ld: symbol(s) not found for architecture arm64
>     clang : error : linker command failed with exit code 1 (use -v to see invocation)
</code>```

The wrap errors:

```<code>MTOUCH: Warning MT5215: References to 'System' might require additional -framework=XXX or -lXXX instructions to the native linker (MT5215)

Error MT5201: Native linking failed. Please review the build log and the user flags provided to gcc: -ObjC (MT5201)

MTOUCH: Error MT5202: Native linking failed. Please review the build log. (MT5202)

clang: Error: linker command failed with exit code 1 (use -v to see invocation)
</code>```

Please shed light. Thanks.

No such native linking error in Xcode. The build settings:

答:
Managed linking and native linking may remove code. Link All may remove more code. So need to solve the problem instead of making the issues disappear using Link All. When using Link All, need to use Preserve attribute to preserve code.

I added all native references, set the linking options correctly. Also I set the linker flags to include all the required OS platform frameworks correctly. After adding reference to a native dynamic framework, the error disappeared. Then instead of getting undefined symbols, I got duplicate symbols. I had to remove a reference to a native library.

Although the iOS project is linked and built after referencing dynamic frameworks, there is a runtime issue. Our SDK provider confirmed that we must not use their dynamic frameworks. The dynamic frameworks are provided for other customers for a different target SimpleDemo_Dy in Xcode. They are older versions SDK. We should just use the static libraries.

I have re-examined the Xcode build log. No dynamic frameworks are used for target SimpleDemo in Xcode. The question is why Xcode project builds without using any dynamic frameworks, but Visual Studio for Mac build fails with a native linking error?

I’ve created a sample iOS app which only uses static libraries. It builds and runs OK. I've shared the sample iOS app with you. The link is https://drive.google.com/file/d/10QXkaZE7lURN6IF96NIrTGY2lmn88ctF/view?usp=sharing.

I haven’t been able to achieve the same in our product app with identical binding project settings. I even tried to swap the binding project from the sample app. It didn't help. Also I compared the iOS project settings from project options UI and WinMerge. I still couldn't find what's wrong. I have tried clean and rebuild many times. I have tried to check out to a fresh workspace. It still has undefined symbol error.

I think the issue is one of the native libraries libHCCore.a is compiled with libstdc++ which caused the error undefined symbol std::string while the rest are libc++.

Adding Linker Flags -lstdc++ to the native reference didn't help. How to used additional Mtouch arguments in iOS project or additional btouch arguments in binding project to resolve the issue?

Body:
My Xamarion.iOS binding project has the links to all the required native video SDK libraries and native OS frameworks.  I have set the required frameworks using Frameworks attribute. Other settings include SmartLink=true, ForceLoad=true, IsCxx=true, LinkerFlags="-lc++". It can be built into a C# DLL. In iOS project, the DLL is referenced and used.  However there are native linking errors.

MTOUCH: Error MT5210: Native linking failed, undefined symbol: std::string::_Rep::_M_destroy(std::allocator<char> const&). Please verify that all the necessary frameworks have been referenced and native libraries are properly linked in.

The details in build log:

> Undefined symbols for architecture arm64:
>       "std::string::_Rep::_M_destroy(std::allocator<char> const&)", referenced from:
>           HPR_UTF82A(char const*) in libHCCore.a(HPR_Utils.o)
>           HPR_A2UTF8(char const*) in libHCCore.a(HPR_Utils.o)
>       "std::string::_Rep::_S_empty_rep_storage", referenced from:
>           HPR_UTF82A(char const*) in libHCCore.a(HPR_Utils.o)
>           HPR_A2UTF8(char const*) in libHCCore.a(HPR_Utils.o)
>       "std::string::assign(char const*, unsigned long)", referenced from:
>           HPR_UTF82A(char const*) in libHCCore.a(HPR_Utils.o)
>           HPR_A2UTF8(char const*) in libHCCore.a(HPR_Utils.o)
>       "std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(char const*, std::allocator<char>
> const&)", referenced from:
>           HPR_A2UTF8(char const*) in libHCCore.a(HPR_Utils.o)
>       "std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(std::string const&)", referenced
> from:
>           HPR_A2UTF8(char const*) in libHCCore.a(HPR_Utils.o)
>     ld: symbol(s) not found for architecture arm64
>     clang : error : linker command failed with exit code 1 (use -v to see invocation)

The wrap errors:

MTOUCH: Warning MT5215: References to 'System' might require additional -framework=XXX or -lXXX instructions to the native linker (MT5215)

Error MT5201: Native linking failed. Please review the build log and the user flags provided to gcc: -ObjC (MT5201)

MTOUCH: Error MT5202: Native linking failed. Please review the build log. (MT5202)

clang: Error: linker command failed with exit code 1 (use -v to see invocation)

Please shed light. Thanks.

No such native linking error in Xcode. The build settings:


问:
How can I provide users option to add search results, with click of button, to database model in Django?
I am a django beginner and am creating a simple app where users can search players from a model and then be given option to add those players as their favorite player, which is stored in a different model. I have created a search view as shown below:

```<code>```def search(request):
try:
    q = request.GET.get('q')
except:
    q = None
if q:
    Players = Player.objects.filter(First_Name__icontains=q)
    context = {'query': q,
               'Players': Players}
    template = 'home/results.html'
else:
    template = 'home/index.html'
    context = {}
return render(request,template,context)```
</code>```

The search view shows redirects users to home/results.html where results are displayed. I would like for users to be able to click a button next to each of results and add that player to favorites database. I have tried to use Django ModelForms in forms.py as follows:

```<code>   from django import forms
   from .models import favoritePlayer

   class favoritePlayerForm(forms.ModelForm):
   class Meta:
      model = favoritePlayer
      fields = ['First_Name',]
</code>```

The following is the view function I have wrote to add player into favorites database:

```<code>def favorite_create_view (request):
form = favoritePlayerForm(request.POST or None)
if form.is_valid():
    form.save()
context = {'form':form}
template = 'home/results.html'
return render(request,template,context)
</code>```

Finally, below is the results.html file:

```<code><!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
  <h1>Searched for {{ query }}</h1>
  {% for Player in Players %}
  <form method="POST"> {% csrf_token %}
  <a href = "/{{ Player.id }}/">{{ Player.First_Name}}</a>
      {{ form.as_p }}
      <input type="submit" value="Save" />
  </form>
 {% endfor %}
</body>
</html>
</code>```

I cannot get this to work. I would prefer not to use AJAX or Javascript. Any help would be appreciated.

答:
```<code>def search(request):
    query = request.GET.get('q', None)
    user = None   #if no
    if request.user.is_authenticated:
        user = request.user
    context =  {"query": query}
    if query is not None:
       Player.objects.create(user=user, query=query)
       Players = Player.objects.search(query=query)

        context['Players '] = Players
    return render(request, 'home/index.html',context)
</code>```

Body:
I am a django beginner and am creating a simple app where users can search players from a model and then be given option to add those players as their favorite player, which is stored in a different model. I have created a search view as shown below:

```def search(request):
try:
    q = request.GET.get('q')
except:
    q = None
if q:
    Players = Player.objects.filter(First_Name__icontains=q)
    context = {'query': q,
               'Players': Players}
    template = 'home/results.html'
else:
    template = 'home/index.html'
    context = {}
return render(request,template,context)```

The search view shows redirects users to home/results.html where results are displayed. I would like for users to be able to click a button next to each of results and add that player to favorites database. I have tried to use Django ModelForms in forms.py as follows:

   from django import forms
   from .models import favoritePlayer

   class favoritePlayerForm(forms.ModelForm):
   class Meta:
      model = favoritePlayer
      fields = ['First_Name',]

The following is the view function I have wrote to add player into favorites database:

def favorite_create_view (request):
form = favoritePlayerForm(request.POST or None)
if form.is_valid():
    form.save()
context = {'form':form}
template = 'home/results.html'
return render(request,template,context)

Finally, below is the results.html file:

<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Title</title>

Searched for {{ query }}

  {% for Player in Players %}
  <form method="POST"> {% csrf_token %}
  {{ Player.First_Name}}
      {{ form.as_p }}
      <input type="submit" value="Save" />
  </form>
 {% endfor %}

I cannot get this to work. I would prefer not to use AJAX or Javascript. Any help would be appreciated.


问:
Expand flex container respective to its children with flex grow
I have a container that has fixed width and inside that I have a flexible menu with display: flex

I want the menu-list to grow upto max-width: 420px, and if it reaches max-width it should wrap and display in next line, so I can't use  white-space: nowrap which makes my menu-list scrollable if it exceeds 420px. How can I make the parent menu expand proportionally with menu-list. The red background should expand 420px in the example below.

.container {
  display: block;
  padding: 10px;
  width: 180px;
}

.menu {
  background-color: red;
  display: inline-flex;
}

.menu-list {
  margin: 10px;
  flex: 1 0 auto;
  max-width: 420px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="menu">
    <div class="menu-list">
      <div class="option">1. The quick brown fox jumps over the lazy dog</div>
      <div class="option">2. The quick brown fox jumps over the lazy dog</div>
      <div class="option">3. The quick brown fox jumps over the lazy dog</div>
      <div class="option">4. The quick brown fox jumps over the lazy dog</div>
    </div>
  </div>
</div></code>```

答:
If the .menu-list has a maximum width of 420px, then why not just give .menu the same maximum?

Then make the top level wrapper a flex container and disable shrinking on .menu.

.container {
  display: flex;
  max-width: 180px;
  border: 2px dashed black;
}

.menu {
  flex-shrink: 0;
  max-width: 420px;
  border: 2px solid green;
}

.menu-list {}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="menu">
    <div class="menu-list">
      <div class="option">1. The quick brown fox jumps over the lazy dog</div>
      <div class="option">2. The quick brown fox jumps over the lazy dog The quick brown fox jumps over the lazy dogThe quick brown fox jumps over the lazy dogThe quick brown fox jumps over the lazy dog</div>
    </div>
  </div>
</div></code>```

Body:
I have a container that has fixed width and inside that I have a flexible menu with display: flex

I want the menu-list to grow upto max-width: 420px, and if it reaches max-width it should wrap and display in next line, so I can't use  white-space: nowrap which makes my menu-list scrollable if it exceeds 420px. How can I make the parent menu expand proportionally with menu-list. The red background should expand 420px in the example below.

.container {
  display: block;
  padding: 10px;
  width: 180px;
}

.menu {
  background-color: red;
  display: inline-flex;
}

.menu-list {
  margin: 10px;
  flex: 1 0 auto;
  max-width: 420px;
}

1. The quick brown fox jumps over the lazy dog

2. The quick brown fox jumps over the lazy dog

3. The quick brown fox jumps over the lazy dog

4. The quick brown fox jumps over the lazy dog

Body:
If the .menu-list has a maximum width of 420px, then why not just give .menu the same maximum?

Then make the top level wrapper a flex container and disable shrinking on .menu.

.container {
  display: flex;
  max-width: 180px;
  border: 2px dashed black;
}

.menu {
  flex-shrink: 0;
  max-width: 420px;
  border: 2px solid green;
}

.menu-list {}

<div class="container">
  <div class="menu">
    <div class="menu-list">
      <div class="option">1. The quick brown fox jumps over the lazy dog</div>
      <div class="option">2. The quick brown fox jumps over the lazy dog The quick brown fox jumps over the lazy dogThe quick brown fox jumps over the lazy dogThe quick brown fox jumps over the lazy dog</div>
    </div>
  </div>
</div>


问:
Listen for Browser Events in Protractor
Is there a way to attach event listeners to browser events in a Protractor test?

I know Protractor is running as a Node program, but I'm curious if anyone has done this with a Node package like browserevent.

Looking for any examples if so.

答:
I know this an old question but I just want to add some information here, maybe it was not there when this question was asked. As it seems  in question and comments that it is for Javascript implementation of webdriver , which is webdriverjs . Protractor is a wrapper around Webdriverjs , so it should be valid here.

You should be able to use addEventListener command to add any browser supported events

Note, this is only supported in chrome currently

Also, this is an experimental feature in webdriver.js so  one has to add

```<code>var client = WebdriverJS.remote({
    logLevel: 'verbose',
    experimental: true, // <-- enables browser side eventhandling
    desiredCapabilities: {
        browserName: 'chrome'
    }
});
</code>```

And then register events like

```<code>client
    .url('http://google.com')
    .addEventListener('dblclick','#hplogo', function(e) {
        console.log(e.target); // -> 'id("hplogo")'
        console.log(e.type); // -> 'dblclick'
        console.log(e.clientX, e.clientY); // -> 239 524
    })
    .doubleClick('#hplogo') // triggers event
    .end();
</code>```

You can use removeEventListener to unregister any registered listeners

Evenhandling in Node.js environment is also supported as implied by this

WebdriverJS inherits several function from the NodeJS EventEmitter object

ContentLicense: CC BY-SA 3.0

Title: Listen for Browser Events in Protractor

Body:
I know this an old question but I just want to add some information here, maybe it was not there when this question was asked. As it seems  in question and comments that it is for Javascript implementation of webdriver , which is webdriverjs . Protractor is a wrapper around Webdriverjs , so it should be valid here.

You should be able to use addEventListener command to add any browser supported events

Note, this is only supported in chrome currently

Also, this is an experimental feature in webdriver.js so  one has to add

var client = WebdriverJS.remote({
    logLevel: 'verbose',
    experimental: true, // <-- enables browser side eventhandling
    desiredCapabilities: {
        browserName: 'chrome'
    }
});

And then register events like

client
    .url('http://google.com')
    .addEventListener('dblclick','#hplogo', function(e) {
        console.log(e.target); // -> 'id("hplogo")'
        console.log(e.type); // -> 'dblclick'
        console.log(e.clientX, e.clientY); // -> 239 524
    })
    .doubleClick('#hplogo') // triggers event
    .end();

You can use removeEventListener to unregister any registered listeners

Evenhandling in Node.js environment is also supported as implied by this

WebdriverJS inherits several function from the NodeJS EventEmitter object


问:
Removing duplicate dictionaries in list of dicts based on value uniqueness for a given key
I have a dictionary:

```<code>dicts = [
{'id': 'item1', 'type': 'foo', 'metaId': 'metaId1'},
{'id': 'item2', 'type': 'foo', 'metaId': 'metaId2'},
{'id': 'item3', 'type': 'foo3', 'metaId': 'metaId3'},
{'id': 'item4', 'type': 'foo2', 'metaId': 'metaId2'},
{'id': 'item5', 'type': 'foo3', 'metaId': 'metaId3'},
{'id': 'item6', 'type': 'foo2', 'metaId': 'metaId2'},
{'id': 'item7', 'type': 'foo3', 'metaId': 'metaId3'},
{'id': 'item8', 'type': 'foo2', 'metaId': 'metaId2'},
{'id': 'item9', 'type': 'foo3', 'metaId': 'metaId3'}]
</code>```

I want to loop through the list and create a new list, that contains dictionaries with unique values for key 'type'. I don't care which dictionaries stay, first instance with that key: value  stays, the rest is omitted. So in the end I'd like to see:

```<code>expected = [
{'id': 'item1', 'type': 'foo', 'metaId': 'metaId1'},
{'id': 'item3', 'type': 'foo3', 'metaId': 'metaId3'},
{'id': 'item4', 'type': 'foo2', 'metaId': 'metaId2'}
]
</code>```

Here is what I tried, definitely not what I need as it returns an empty list. I think I struggle with checking for a value in new sublist of dictionaries to make it excluded

```<code>keys_to_keep = set()
expected = []
for d in dicts:
    for key, value in d.items():
        if value not in expected:
            keys_to_keep.add(key)
remove_keys = set(d) - keys_to_keep

for d in dicts:
    for k in remove_keys:
        del d[k]
dicts = expected
print(dicts)
</code>```

答:
You can create a temporary dictionary to hold the first dictionary when a particular type is first encountered, and then use the values that end up in it to create the an updated list with one additional line of code.</p>

```<code>dicts = [{'id': 'item1', 'type': 'foo', 'metaId': 'metaId1'},
         {'id': 'item2', 'type': 'foo', 'metaId': 'metaId2'},
         {'id': 'item3', 'type': 'foo3', 'metaId': 'metaId3'},
         {'id': 'item4', 'type': 'foo2', 'metaId': 'metaId2'},
         {'id': 'item5', 'type': 'foo3', 'metaId': 'metaId3'},
         {'id': 'item6', 'type': 'foo2', 'metaId': 'metaId2'},
         {'id': 'item7', 'type': 'foo3', 'metaId': 'metaId3'},
         {'id': 'item8', 'type': 'foo2', 'metaId': 'metaId2'},
         {'id': 'item9', 'type': 'foo3', 'metaId': 'metaId3'}]

temp = {}
for d in dicts:
    if d['type'] not in temp:
        temp[d['type']] = d

dicts = list(temp.values())  # Update list.

for d in dicts:
    print(d)
</code>```

Body:
I have a dictionary:

dicts = [
{'id': 'item1', 'type': 'foo', 'metaId': 'metaId1'},
{'id': 'item2', 'type': 'foo', 'metaId': 'metaId2'},
{'id': 'item3', 'type': 'foo3', 'metaId': 'metaId3'},
{'id': 'item4', 'type': 'foo2', 'metaId': 'metaId2'},
{'id': 'item5', 'type': 'foo3', 'metaId': 'metaId3'},
{'id': 'item6', 'type': 'foo2', 'metaId': 'metaId2'},
{'id': 'item7', 'type': 'foo3', 'metaId': 'metaId3'},
{'id': 'item8', 'type': 'foo2', 'metaId': 'metaId2'},
{'id': 'item9', 'type': 'foo3', 'metaId': 'metaId3'}]

I want to loop through the list and create a new list, that contains dictionaries with unique values for key 'type'. I don't care which dictionaries stay, first instance with that key: value  stays, the rest is omitted. So in the end I'd like to see:

expected = [
{'id': 'item1', 'type': 'foo', 'metaId': 'metaId1'},
{'id': 'item3', 'type': 'foo3', 'metaId': 'metaId3'},
{'id': 'item4', 'type': 'foo2', 'metaId': 'metaId2'}
]

Here is what I tried, definitely not what I need as it returns an empty list. I think I struggle with checking for a value in new sublist of dictionaries to make it excluded

keys_to_keep = set()
expected = []
for d in dicts:
    for key, value in d.items():
        if value not in expected:
            keys_to_keep.add(key)
remove_keys = set(d) - keys_to_keep

for d in dicts:
    for k in remove_keys:
        del d[k]
dicts = expected
print(dicts)

Body:
You can create a temporary dictionary to hold the first dictionary when a particular type is first encountered, and then use the values that end up in it to create the an updated list with one additional line of code.

dicts = [{'id': 'item1', 'type': 'foo', 'metaId': 'metaId1'},
         {'id': 'item2', 'type': 'foo', 'metaId': 'metaId2'},
         {'id': 'item3', 'type': 'foo3', 'metaId': 'metaId3'},
         {'id': 'item4', 'type': 'foo2', 'metaId': 'metaId2'},
         {'id': 'item5', 'type': 'foo3', 'metaId': 'metaId3'},
         {'id': 'item6', 'type': 'foo2', 'metaId': 'metaId2'},
         {'id': 'item7', 'type': 'foo3', 'metaId': 'metaId3'},
         {'id': 'item8', 'type': 'foo2', 'metaId': 'metaId2'},
         {'id': 'item9', 'type': 'foo3', 'metaId': 'metaId3'}]

temp = {}
for d in dicts:
    if d['type'] not in temp:
        temp[d['type']] = d

dicts = list(temp.values())  # Update list.

for d in dicts:
    print(d)


问:
Decode QR Code Image from Camera Roll React Native
I'm trying to implement a feature in my app where I the user can select a picture from their camera roll and the app will decode a QR code in the image is detected.

I'm currently using react-native-camera-roll-picker: https://github.com/jeanpan/react-native-camera-roll-picker
and react-native-qrcode-local-image: https://github.com/remobile/react-native-qrcode-local-image

The problem is the local QR code image library wants me to pass a local path and isn't compatible with the native uri provided by react-native-camera-roll-picker. I would use another library for decoding the image QR code but this one appears to be the only one that works on iOS and Android and scans from existing images rather than from the actual camera.

I've also tried implementing react-native-fetch-blob in order to temporarily save the camera roll image locally, but that's been giving me trouble as well: https://github.com/wkh237/react-native-fetch-blob

This is my current attempt in a function that I call in the "callback" prop for react-native-camera-roll-picker (with previous attempts commented out):

```<code>_pickedImage(array,currentImg) {
console.log(currentImg)
var path = RNFS.DocumentDirectoryPath + '/pickedqr';
let rnfbURI = RNFetchBlob.wrap(RNFetchBlob.fs.asset(currentImg.uri))
const Blob = RNFetchBlob.polyfill.Blob
Blob.build(rnfbURI, {type:'image/jpg'}).then((b) => {
  tmpBlob = b;
  RNFetchBlob.fs.readFile(tmpBlob, 'base64').then((data) => {
    console.log("Base64", data)
    QRDecoder.decode(`data:image/gif;base64,${data}`, (error, result)=>{
      console.log("Code", result)
      console.log("Error", error)
    });
  });
})
/*fullPath = currentImg.uri.replace("assets-library://", "cdvfile://localhost/assets-library/")
QRDecoder.decode(fullPath, (error, result)=>{
  console.log("Code", result)
  console.log("Error", error)
});*/
/*let blb = Blob.build( rnfbURI, { type: 'image/jpg'})
console.log(blb)*/
/*RNFetchBlob.fs.readFile(rnfbURI, 'base64').then((data) => {
  console.log("Base64", data)
  QRDecoder.decode(`data:image/gif;base64,${data}`, (error, result)=>{
    console.log("Code", result)
    console.log("Error", error)
  });
})*/
}
</code>```

I'm at a total loss at the moment so any methods or insight would be much appreciated.

答:
This answer solved it for me.
Created native method to covert uri in path, here is my code:

```<code>    @ReactMethod
    public void getRealPathFromURI(String contentUriString, Promise promise) {
        Uri contentUri = Uri.parse(contentUriString);
        Cursor cursor = null;
        try {
            String wholeID = DocumentsContract.getDocumentId(contentUri);
            String id = wholeID.split(":")[1];

            String[] column = { MediaStore.Images.Media.DATA };

            String sel = MediaStore.Images.Media._ID + "=?";

            cursor = reactContext.getContentResolver().
                    query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                            column, sel, new String[]{ id }, null);

            int columnIndex = cursor.getColumnIndex(column[0]);

            String filePath = "";
            if (cursor.moveToFirst()) {
                filePath = cursor.getString(columnIndex);
            }
            promise.resolve(filePath);
        } catch (Throwable e) {
            promise.reject(e);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }
</code>```

And js:

```<code>DocumentPicker.pick({ type }).then((document: DocumentPickerResponse) => {
    MyNativeModule.getRealPathFromURI(document.uri).then((path) => {
        QRCodeLocalImage.decode(path, (err, res) => {
            callback(err, { qrData: res });
        });
    });
});
</code>```

Body:
I'm trying to implement a feature in my app where I the user can select a picture from their camera roll and the app will decode a QR code in the image is detected.

I'm currently using react-native-camera-roll-picker: https://github.com/jeanpan/react-native-camera-roll-picker
and react-native-qrcode-local-image: https://github.com/remobile/react-native-qrcode-local-image

The problem is the local QR code image library wants me to pass a local path and isn't compatible with the native uri provided by react-native-camera-roll-picker. I would use another library for decoding the image QR code but this one appears to be the only one that works on iOS and Android and scans from existing images rather than from the actual camera.

I've also tried implementing react-native-fetch-blob in order to temporarily save the camera roll image locally, but that's been giving me trouble as well: https://github.com/wkh237/react-native-fetch-blob

This is my current attempt in a function that I call in the "callback" prop for react-native-camera-roll-picker (with previous attempts commented out):

_pickedImage(array,currentImg) {
console.log(currentImg)
var path = RNFS.DocumentDirectoryPath + '/pickedqr';
let rnfbURI = RNFetchBlob.wrap(RNFetchBlob.fs.asset(currentImg.uri))
const Blob = RNFetchBlob.polyfill.Blob
Blob.build(rnfbURI, {type:'image/jpg'}).then((b) => {
  tmpBlob = b;
  RNFetchBlob.fs.readFile(tmpBlob, 'base64').then((data) => {
    console.log("Base64", data)
    QRDecoder.decode(`data:image/gif;base64,${data}`, (error, result)=>{
      console.log("Code", result)
      console.log("Error", error)
    });
  });
})
/*fullPath = currentImg.uri.replace("assets-library://", "cdvfile://localhost/assets-library/")
QRDecoder.decode(fullPath, (error, result)=>{
  console.log("Code", result)
  console.log("Error", error)
});*/
/*let blb = Blob.build( rnfbURI, { type: 'image/jpg'})
console.log(blb)*/
/*RNFetchBlob.fs.readFile(rnfbURI, 'base64').then((data) => {
  console.log("Base64", data)
  QRDecoder.decode(`data:image/gif;base64,${data}`, (error, result)=>{
    console.log("Code", result)
    console.log("Error", error)
  });
})*/
}

I'm at a total loss at the moment so any methods or insight would be much appreciated.

Body:
This answer solved it for me.
Created native method to covert uri in path, here is my code:

    @ReactMethod
    public void getRealPathFromURI(String contentUriString, Promise promise) {
        Uri contentUri = Uri.parse(contentUriString);
        Cursor cursor = null;
        try {
            String wholeID = DocumentsContract.getDocumentId(contentUri);
            String id = wholeID.split(":")[1];

            String[] column = { MediaStore.Images.Media.DATA };

            String sel = MediaStore.Images.Media._ID + "=?";

            cursor = reactContext.getContentResolver().
                    query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                            column, sel, new String[]{ id }, null);

            int columnIndex = cursor.getColumnIndex(column[0]);

            String filePath = "";
            if (cursor.moveToFirst()) {
                filePath = cursor.getString(columnIndex);
            }
            promise.resolve(filePath);
        } catch (Throwable e) {
            promise.reject(e);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }

And js:

DocumentPicker.pick({ type }).then((document: DocumentPickerResponse) => {
    MyNativeModule.getRealPathFromURI(document.uri).then((path) => {
        QRCodeLocalImage.decode(path, (err, res) => {
            callback(err, { qrData: res });
        });
    });
});


问:
Delete item from subcollection array in Firestore Firebase
I am trying to delete item from array in  profile collection named items subcollection. Function should be triggered whenever item is deleted from main items collection. Problem with below function is that when triggered it deletes all items from profile instead of deleted one only. How I could iterate over items array and perform check of deleted item id.

exports.updateDeletedItemOnProfile = functions.firestore
.document('items/{itemId}')
.onDelete((snap, context) => {
    const { itemId } = context.params
    const deletedItem = snap.data()

    if(deletedItem){
      db.collection('profiles')
        .doc(deletedItem.user.id)
        .update({
          items: admin.firestore.FieldValue.delete({
              id: itemId,
              title: deletedItem.title,
              price: deletedItem.price,
              image: deletedItem.image
          })
        })
      }
    return true
})```

答:
I 've also tried onUpdate trigger for deleting data along with onWrite trigger to listen for any change when data is changed, however in both cases it does not give me any result for part referring to deleting data. Items subcollection in profiles collection remains unchanged. I am not sure where error in function lies, function execution does not show any error, finishes with status Ok....

exports.updateDeletedItemOnProfile = functions.firestore
.document('items/{itemId}')
.onUpdate((change, context) => {
  const { itemId } = context.params
  const beforeItem = change.before.data()
  const updatedItem = change.after.data()

    if (updatedItem === null) {

    return db.collection('profiles')
      .doc(beforeItem.user.id)
      .delete({
        items: admin.firestore.FieldValue.arrayRemove({
          id: itemId,
          title: beforeItem.title,
          price: beforeItem.price,
          image: beforeItem.image,
          status: beforeItem.status,
        })
      })
    }
    return true

})```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>exports.updateDeletedItemOnProfile = functions.firestore
.document('items/{itemId}')
.onUpdate((change, context) => {
  const { itemId } = context.params
  const beforeItem = change.before.data()
  const updatedItem = change.after.data()

    if (updatedItem === null) {

    return db.collection('profiles')
      .doc(beforeItem.user.id)
      .update({
        items: admin.firestore.FieldValue.delete({
          id: itemId,
          title: beforeItem.title,
          price: beforeItem.price,
          image: beforeItem.image,
          status: beforeItem.status,
        })
      })
    }
    return true

})</code>```

Body:
I 've also tried onUpdate trigger for deleting data along with onWrite trigger to listen for any change when data is changed, however in both cases it does not give me any result for part referring to deleting data. Items subcollection in profiles collection remains unchanged. I am not sure where error in function lies, function execution does not show any error, finishes with status Ok....

exports.updateDeletedItemOnProfile = functions.firestore
.document('items/{itemId}')
.onUpdate((change, context) => {
  const { itemId } = context.params
  const beforeItem = change.before.data()
  const updatedItem = change.after.data()

    if (updatedItem === null) {

    return db.collection('profiles')
      .doc(beforeItem.user.id)
      .delete({
        items: admin.firestore.FieldValue.arrayRemove({
          id: itemId,
          title: beforeItem.title,
          price: beforeItem.price,
          image: beforeItem.image,
          status: beforeItem.status,
        })
      })
    }
    return true

})

exports.updateDeletedItemOnProfile = functions.firestore
.document('items/{itemId}')
.onUpdate((change, context) => {
  const { itemId } = context.params
  const beforeItem = change.before.data()
  const updatedItem = change.after.data()

    if (updatedItem === null) {

    return db.collection('profiles')
      .doc(beforeItem.user.id)
      .update({
        items: admin.firestore.FieldValue.delete({
          id: itemId,
          title: beforeItem.title,
          price: beforeItem.price,
          image: beforeItem.image,
          status: beforeItem.status,
        })
      })
    }
    return true

})


问:
Radiobuttonlist event not always firing
I have a radiobuttonlist with a selectedindexchanged event that updates a search function.  One of the items is specified in the aspx, and the others are appended databound items.  No matter what I set as the default, that item will not fire the event.  All other items will fire the event.  Also, it seems that after the "dead" item is selected, the event won't fire at all.

How can I track down the error and correct?  Here is current code.

EDIT: Sorry if the short version was misleading.  I wasn't sure what to include.  Here is the whole page.

All aspx:

```<code>     <%@ Page Language="C#" MasterPageFile="~/MSDS/MSDS.master" EnableEventValidation="false"
    AutoEventWireup="true" CodeFile="SearchMSDS.aspx.cs" Inherits="MSDS_ByDept" Title="NCLWeb - Search MSDS" %>

<%@ Register Assembly="SqlWhereBuilder" Namespace="UNLV.IAP.WebControls" TagPrefix="cc1" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc2" %>
<asp:Content ID="Content1" ContentPlaceHolderID="PageContent" runat="Server">
    <h2>
        <asp:Label ID="lblTitle" runat="server">Search Active MSDS</asp:Label></h2>
    <table class="style1">
        <tr>
            <td style="width: 435px" valign="top">
                <asp:Panel runat="server" ID="pnlSearch" DefaultButton="btnSearch">
                    <asp:TextBox ID="txtSimpleSearch" runat="server" Width="262px"></asp:TextBox>
                    <asp:Button ID="btnSearch" runat="server" Text="Search" Width="96px" OnClick="btnSearch_Click" />
                    <br />
                    <asp:LinkButton ID="btnAdvSearch" runat="server" OnClick="btnAdvSearch_Click" Font-Size="Small">Show Advanced Search</asp:LinkButton>
                </asp:Panel>
                <asp:Panel ID="pnlAdvSearch" runat="server" Width="635px" DefaultButton="btnRunAdvSearch">
                    <asp:Button ID="btnRunAdvSearch" runat="server" OnClick="btnRunAdvSearch_Click" Text="Advanced Search" />
                    <cc1:SqlWhereBuilder ID="SqlWhereBuilder1" runat="server" ClientCodeLocation="../JavaScripts/SqlWhereBuilder.js"
                        FieldsFile="../ConfigFiles/SearchMSDS.config" OperatorListsFile="../ConfigFiles/SearchMSDS.config"
                        ValueEntryFile="../ConfigFiles/SearchMSDS.config">
                    </cc1:SqlWhereBuilder>
                    <br />
                    <br />
                </asp:Panel>
                <cc2:CollapsiblePanelExtender ID="pnlAdvSearch_CollapsiblePanelExtender" runat="server"
                    CollapseControlID="btnAdvSearch" Collapsed="True" Enabled="True" ExpandControlID="btnAdvSearch"
                    TargetControlID="pnlAdvSearch">
                </cc2:CollapsiblePanelExtender>
            </td>
            <td valign="top">
                <asp:Panel ID="pnlStatus" runat="server">
                    <asp:RadioButtonList ID="rblStatus" runat="server" AppendDataBoundItems="True"
                        AutoPostBack="True" DataSourceID="SqlDataSource1" DataTextField="DisplayValue"
                        DataValueField="Value" OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged"
                        RepeatDirection="Horizontal" CellPadding="3" CellSpacing="3"
                        CausesValidation="True" Visible="True">
                        <asp:ListItem Selected="True">All</asp:ListItem>
                    </asp:RadioButtonList>
                </asp:Panel>
                <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NCLWebConnectionString %>"
                    SelectCommand="getOptionList" SelectCommandType="StoredProcedure">
                    <SelectParameters>
                        <asp:Parameter DefaultValue="msds_Status" Name="ListName" Type="String" />
                    </SelectParameters>
                </asp:SqlDataSource>
                <asp:UpdatePanel runat="server" ID="upd2">
                    <ContentTemplate>
                        <asp:Button ID="btnExport" runat="server" Text="Export Results"
                            OnClick="btnExport_Click1" UseSubmitBehavior="False" />
                    </ContentTemplate>
                </asp:UpdatePanel>
            </td>
        </tr>
    </table>
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <asp:UpdateProgress ID="UpdateProgress1" runat="server" DisplayAfter="100" DynamicLayout="False">
                <ProgressTemplate>
                    <img src="../images/loading.gif" alt="Loading..." style="text-align: center" />
                    <asp:Label ID="lblProgress" runat="server"></asp:Label></ProgressTemplate>
            </asp:UpdateProgress>
            <asp:GridView ID="gridResults" runat="server" DataSourceID="sqlMSDS" OnRowDataBound="GridView1_RowDataBound"
                AllowPaging="True" PageSize="25" AllowSorting="True" OnSelectedIndexChanged="gridResults_SelectedIndexChanged"
                AutoGenerateColumns="False" EmptyDataText="No matching MSDS Sheets." OnSorted="gridResults_Sorted">
                <Columns>
                    <asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" Visible="false"
                        ReadOnly="True" SortExpression="ID" />
                    <asp:BoundField DataField="ChemicalTitle" HeaderText="ChemicalTitle" SortExpression="ChemicalTitle" />
                    <asp:BoundField DataField="Manufacturer" HeaderText="Manufacturer" SortExpression="Manufacturer" />
                    <asp:BoundField DataField="UsageDept" HeaderText="UsageDept" SortExpression="UsageDept" />
                    <asp:BoundField DataField="Notes" HeaderText="Notes" SortExpression="Notes" />
                    <asp:BoundField DataField="Health" HeaderText="Health" visible="false" SortExpression="Health" />
                    <asp:BoundField DataField="Fire" HeaderText="Fire"  visible="false" SortExpression="Fire" />
                    <asp:BoundField DataField="Reactivity" HeaderText="Reactivity"  visible="false" SortExpression="Reactivity" />
                    <asp:BoundField DataField="DateUpdated" HeaderText="DateUpdated" SortExpression="DateUpdated" />
                </Columns>
                <SelectedRowStyle BackColor="Yellow" />
            </asp:GridView>
            <asp:SqlDataSource ID="sqlMSDS" OnSelected="sqlMSDS_OnSelected" runat="server" ConnectionString="<%$ ConnectionStrings:NCLWebConnectionString %>"
                SelectCommand="SELECT [ID]
                                      ,[ChemicalTitle]
                                      ,[Manufacturer]
                                      ,[UsageDept]
                                      ,[Notes]
                                      ,[Health]
                                      ,[Fire]
                                      ,[Reactivity]
                                      ,[DateUpdated]
                                      FROM [msds_Sheets]" OnSelecting="sqlMSDS_Selecting"></asp:SqlDataSource>
        </ContentTemplate>
        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="btnSearch" EventName="Click" />
            <asp:AsyncPostBackTrigger ControlID="btnRunAdvSearch" EventName="Click" />
            <asp:AsyncPostBackTrigger ControlID="rblStatus" EventName="SelectedIndexChanged" />
            <asp:AsyncPostBackTrigger ControlID="btnExport" EventName="Click" />
        </Triggers>
    </asp:UpdatePanel>
    <br />
</asp:Content>
</code>```

And code-behind:

```<code>    List<String> safeWords = new List<String>();

protected void Page_Load(object sender, EventArgs e)
{
    pnlStatus.Visible = User.IsInRole("msds_Admin");

    gridResults.DataKeyNames = new String[] { "id" };

    txtSimpleSearch.Focus();

    if (!IsPostBack)
    {
        safeWords.Add("delete");
        safeWords.Add("insert");
        safeWords.Add("update");
        safeWords.Add("set");
        safeWords.Add("exec");
        safeWords.Add("N'");

        sqlMSDS.SelectCommand += " Where status = 0 ";

        Session["Sql"] = sqlMSDS.SelectCommand;

        try
        {
            Session["OriginalSQL"] = sqlMSDS.SelectCommand.Remove(sqlMSDS.SelectCommand.IndexOf("Where"));
        }
        catch (Exception)
        {
            Session["OriginalSQL"] = sqlMSDS.SelectCommand;
        }
    }
}

protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            ((Label)UpdateProgress1.FindControl("lblProgress")).Text = "Searching...";

            if (btnSearch.Visible)
            {
                btnSearch_Click(null, null);

                if (RadioButtonList1.SelectedValue != "All")
                {
                    sqlMSDS.SelectCommand += " And Status = " + RadioButtonList1.SelectedValue;
                }
                else
                {
                    //Somehow force the grid to research using no status parameter
                    sqlMSDS.SelectCommand = Session["Sql"].ToString();
                }
            }
            else
            {
                btnRunAdvSearch_Click(null, null);

                if (RadioButtonList1.SelectedValue != "All")
                {
                    if (sqlMSDS.SelectCommand.Contains("Where"))
                    {
                        sqlMSDS.SelectCommand += " And Status = " + RadioButtonList1.SelectedValue;
                    }
                    else
                    {
                        sqlMSDS.SelectCommand += " Where Status = " + RadioButtonList1.SelectedValue;
                    }
                }
                else
                {
                    //Somehow force the grid to research using no status parameter
                    sqlMSDS.SelectCommand = Session["Sql"].ToString();
                }
            }
        }
</code>```

答:
```<code><asp:ListItem Selected="True">All</asp:ListItem>
</code>```

Clicking "All" doesn't change the selected index since that item was already selected, so the event does not fire.  Picking any other option changes the selected option and causes the event to fire.  I believe your goal is to display results for all statuses when you click on "All".  You should do one of the following:

Display those results when the page initially loads since "All" is already selected.

Add a "Search" button that initiates the post-back instead of using the radio button's AutoPostBack.

Replace the RadioButtonList with a DropDownList, and give it two initial ListItems: "Pick a Status" - whose value is an empty string, and "All" whose value is "All".  The "Pick a Status" dummy entry would look less out of place in a DropDownList than in a RadioButtonList.

Of the options listed above, I would personally prefer the "Search" button, because AutoPostBack annoys me as a user.  I hate AutoPostBack DropDownLists that make the web page go bonkers when I accidentally use my mouse wheel when the list has focus.

Title: Radiobuttonlist event not always firing

Body:
I have a radiobuttonlist with a selectedindexchanged event that updates a search function.  One of the items is specified in the aspx, and the others are appended databound items.  No matter what I set as the default, that item will not fire the event.  All other items will fire the event.  Also, it seems that after the "dead" item is selected, the event won't fire at all.

How can I track down the error and correct?  Here is current code.

EDIT: Sorry if the short version was misleading.  I wasn't sure what to include.  Here is the whole page.

All aspx:

     <%@ Page Language="C#" MasterPageFile="~/MSDS/MSDS.master" EnableEventValidation="false"
    AutoEventWireup="true" CodeFile="SearchMSDS.aspx.cs" Inherits="MSDS_ByDept" Title="NCLWeb - Search MSDS" %>

<%@ Register Assembly="SqlWhereBuilder" Namespace="UNLV.IAP.WebControls" TagPrefix="cc1" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc2" %>
<asp:Content ID="Content1" ContentPlaceHolderID="PageContent" runat="Server">

        <asp:Label ID="lblTitle" runat="server">Search Active MSDS</asp:Label>

                <asp:Panel runat="server" ID="pnlSearch" DefaultButton="btnSearch">
                    <asp:TextBox ID="txtSimpleSearch" runat="server" Width="262px"></asp:TextBox>
                    <asp:Button ID="btnSearch" runat="server" Text="Search" Width="96px" OnClick="btnSearch_Click" />

                    <asp:LinkButton ID="btnAdvSearch" runat="server" OnClick="btnAdvSearch_Click" Font-Size="Small">Show Advanced Search</asp:LinkButton>
                </asp:Panel>
                <asp:Panel ID="pnlAdvSearch" runat="server" Width="635px" DefaultButton="btnRunAdvSearch">
                    <asp:Button ID="btnRunAdvSearch" runat="server" OnClick="btnRunAdvSearch_Click" Text="Advanced Search" />
                    <cc1:SqlWhereBuilder ID="SqlWhereBuilder1" runat="server" ClientCodeLocation="../JavaScripts/SqlWhereBuilder.js"
                        FieldsFile="../ConfigFiles/SearchMSDS.config" OperatorListsFile="../ConfigFiles/SearchMSDS.config"
                        ValueEntryFile="../ConfigFiles/SearchMSDS.config">
                    </cc1:SqlWhereBuilder>

                </asp:Panel>
                <cc2:CollapsiblePanelExtender ID="pnlAdvSearch_CollapsiblePanelExtender" runat="server"
                    CollapseControlID="btnAdvSearch" Collapsed="True" Enabled="True" ExpandControlID="btnAdvSearch"
                    TargetControlID="pnlAdvSearch">
                </cc2:CollapsiblePanelExtender>

                <asp:Panel ID="pnlStatus" runat="server">
                    <asp:RadioButtonList ID="rblStatus" runat="server" AppendDataBoundItems="True"
                        AutoPostBack="True" DataSourceID="SqlDataSource1" DataTextField="DisplayValue"
                        DataValueField="Value" OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged"
                        RepeatDirection="Horizontal" CellPadding="3" CellSpacing="3"
                        CausesValidation="True" Visible="True">
                        <asp:ListItem Selected="True">All</asp:ListItem>
                    </asp:RadioButtonList>
                </asp:Panel>
                <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NCLWebConnectionString %>"
                    SelectCommand="getOptionList" SelectCommandType="StoredProcedure">
                    <SelectParameters>
                        <asp:Parameter DefaultValue="msds_Status" Name="ListName" Type="String" />
                    </SelectParameters>
                </asp:SqlDataSource>
                <asp:UpdatePanel runat="server" ID="upd2">
                    <ContentTemplate>
                        <asp:Button ID="btnExport" runat="server" Text="Export Results"
                            OnClick="btnExport_Click1" UseSubmitBehavior="False" />
                    </ContentTemplate>
                </asp:UpdatePanel>

    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <asp:UpdateProgress ID="UpdateProgress1" runat="server" DisplayAfter="100" DynamicLayout="False">
                <ProgressTemplate>

                    <asp:Label ID="lblProgress" runat="server"></asp:Label></ProgressTemplate>
            </asp:UpdateProgress>
            <asp:GridView ID="gridResults" runat="server" DataSourceID="sqlMSDS" OnRowDataBound="GridView1_RowDataBound"
                AllowPaging="True" PageSize="25" AllowSorting="True" OnSelectedIndexChanged="gridResults_SelectedIndexChanged"
                AutoGenerateColumns="False" EmptyDataText="No matching MSDS Sheets." OnSorted="gridResults_Sorted">
                <Columns>
                    <asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" Visible="false"
                        ReadOnly="True" SortExpression="ID" />
                    <asp:BoundField DataField="ChemicalTitle" HeaderText="ChemicalTitle" SortExpression="ChemicalTitle" />
                    <asp:BoundField DataField="Manufacturer" HeaderText="Manufacturer" SortExpression="Manufacturer" />
                    <asp:BoundField DataField="UsageDept" HeaderText="UsageDept" SortExpression="UsageDept" />
                    <asp:BoundField DataField="Notes" HeaderText="Notes" SortExpression="Notes" />
                    <asp:BoundField DataField="Health" HeaderText="Health" visible="false" SortExpression="Health" />
                    <asp:BoundField DataField="Fire" HeaderText="Fire"  visible="false" SortExpression="Fire" />
                    <asp:BoundField DataField="Reactivity" HeaderText="Reactivity"  visible="false" SortExpression="Reactivity" />
                    <asp:BoundField DataField="DateUpdated" HeaderText="DateUpdated" SortExpression="DateUpdated" />
                </Columns>
                <SelectedRowStyle BackColor="Yellow" />
            </asp:GridView>
            <asp:SqlDataSource ID="sqlMSDS" OnSelected="sqlMSDS_OnSelected" runat="server" ConnectionString="<%$ ConnectionStrings:NCLWebConnectionString %>"
                SelectCommand="SELECT [ID]
                                      ,[ChemicalTitle]
                                      ,[Manufacturer]
                                      ,[UsageDept]
                                      ,[Notes]
                                      ,[Health]
                                      ,[Fire]
                                      ,[Reactivity]
                                      ,[DateUpdated]
                                      FROM [msds_Sheets]" OnSelecting="sqlMSDS_Selecting"></asp:SqlDataSource>
        </ContentTemplate>
        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="btnSearch" EventName="Click" />
            <asp:AsyncPostBackTrigger ControlID="btnRunAdvSearch" EventName="Click" />
            <asp:AsyncPostBackTrigger ControlID="rblStatus" EventName="SelectedIndexChanged" />
            <asp:AsyncPostBackTrigger ControlID="btnExport" EventName="Click" />
        </Triggers>
    </asp:UpdatePanel>

</asp:Content>

And code-behind:

    List<String> safeWords = new List<String>();

protected void Page_Load(object sender, EventArgs e)
{
    pnlStatus.Visible = User.IsInRole("msds_Admin");

    gridResults.DataKeyNames = new String[] { "id" };

    txtSimpleSearch.Focus();

    if (!IsPostBack)
    {
        safeWords.Add("delete");
        safeWords.Add("insert");
        safeWords.Add("update");
        safeWords.Add("set");
        safeWords.Add("exec");
        safeWords.Add("N'");

        sqlMSDS.SelectCommand += " Where status = 0 ";

        Session["Sql"] = sqlMSDS.SelectCommand;

        try
        {
            Session["OriginalSQL"] = sqlMSDS.SelectCommand.Remove(sqlMSDS.SelectCommand.IndexOf("Where"));
        }
        catch (Exception)
        {
            Session["OriginalSQL"] = sqlMSDS.SelectCommand;
        }
    }
}

protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            ((Label)UpdateProgress1.FindControl("lblProgress")).Text = "Searching...";

            if (btnSearch.Visible)
            {
                btnSearch_Click(null, null);

                if (RadioButtonList1.SelectedValue != "All")
                {
                    sqlMSDS.SelectCommand += " And Status = " + RadioButtonList1.SelectedValue;
                }
                else
                {
                    //Somehow force the grid to research using no status parameter
                    sqlMSDS.SelectCommand = Session["Sql"].ToString();
                }
            }
            else
            {
                btnRunAdvSearch_Click(null, null);

                if (RadioButtonList1.SelectedValue != "All")
                {
                    if (sqlMSDS.SelectCommand.Contains("Where"))
                    {
                        sqlMSDS.SelectCommand += " And Status = " + RadioButtonList1.SelectedValue;
                    }
                    else
                    {
                        sqlMSDS.SelectCommand += " Where Status = " + RadioButtonList1.SelectedValue;
                    }
                }
                else
                {
                    //Somehow force the grid to research using no status parameter
                    sqlMSDS.SelectCommand = Session["Sql"].ToString();
                }
            }
        }

Body:
<asp:ListItem Selected="True">All</asp:ListItem>

Clicking "All" doesn't change the selected index since that item was already selected, so the event does not fire.  Picking any other option changes the selected option and causes the event to fire.  I believe your goal is to display results for all statuses when you click on "All".  You should do one of the following:

Display those results when the page initially loads since "All" is already selected.

Add a "Search" button that initiates the post-back instead of using the radio button's AutoPostBack.

Replace the RadioButtonList with a DropDownList, and give it two initial ListItems: "Pick a Status" - whose value is an empty string, and "All" whose value is "All".  The "Pick a Status" dummy entry would look less out of place in a DropDownList than in a RadioButtonList.

Of the options listed above, I would personally prefer the "Search" button, because AutoPostBack annoys me as a user.  I hate AutoPostBack DropDownLists that make the web page go bonkers when I accidentally use my mouse wheel when the list has focus.


问:
Flask and React routing
I'm building the Flask app with React, I ended up having a problem with routing.

The backend is responsible to be an API, hence some routes look like:

```<code>@app.route('/api/v1/do-something/', methods=["GET"])
def do_something():
    return something()
</code>```

and the main route which leads to the React:

```<code>@app.route('/')
def index():
    return render_template('index.html')
</code>```

I'm using react-router in the React app, everything works fine, react-router takes me to /something and I get the rendered view, but when I refresh the page on /something then Flask app takes care of this call and I get Not Found error.

What is the best solution? I was thinking about redirecting all calls which are not calling /api/v1/... to / it's not ideal as I will get back the home page of my app, not rendered React view.

答:
Just to inform handle error 404 and render_template works perfectly for me.</p>

```<code>@app.errorhandler(404)
def not_found(e):
    return render_template("index.html")
</code>```

Title: Flask and React routing

Body:
I'm building the Flask app with React, I ended up having a problem with routing.

The backend is responsible to be an API, hence some routes look like:

@app.route('/api/v1/do-something/', methods=["GET"])
def do_something():
    return something()

and the main route which leads to the React:

@app.route('/')
def index():
    return render_template('index.html')

I'm using react-router in the React app, everything works fine, react-router takes me to /something and I get the rendered view, but when I refresh the page on /something then Flask app takes care of this call and I get Not Found error.

What is the best solution? I was thinking about redirecting all calls which are not calling /api/v1/... to / it's not ideal as I will get back the home page of my app, not rendered React view.

Body:
Just to inform handle error 404 and render_template works perfectly for me.

@app.errorhandler(404)
def not_found(e):
    return render_template("index.html")


问:
Project Lombok Installation. [java.lang.OutOfMemoryError]
I am trying to install project Lombok from an executable jar for eclipse neon 3 .
But I am Receiving: java.lang.OutOfMemoryError Java Heap Space,
I am Using Lombok-1.16.10 jar.
outOfMemoryException image </p>

<p>Please suggest a solution.
Thanks </p>

答: Try with java -Xmx1G -jar lombok.jar, keep in mind that the latest version of lombok is 1.18.12

Body:
I am trying to install project Lombok from an executable jar for eclipse neon 3 .
But I am Receiving: java.lang.OutOfMemoryError Java Heap Space,
I am Using Lombok-1.16.10 jar.
outOfMemoryException image

Please suggest a solution.
Thanks


问:
how to append values to lists in dictionary?
I, have a dictionary say {0:[1,2,3],1[1,2,3],2:[1,2,3],3:[1,2,4],4:[1,2,4],5:[1,2,4]}. there are some duplicate values but the keys are different. when i append a value to list corresponding to key 0 python also adds the value to other duplicates what i don't need.

my code :-

```<code>for k, v in f.items():
    if k == 0:
        v.append(1)
</code>```

result:-

```<code>{0:[1,2,3,1],1[1,2,3,1],2:[1,2,3,1],3:[1,2,4],4:[1,2,4],5:[1,2,4]}
</code>```

what i want is :-

```<code>{0:[1,2,3,1],1[1,2,3],2:[1,2,3],3:[1,2,4],4:[1,2,4],5:[1,2,4]}
</code>```

Body:
I, have a dictionary say {0:[1,2,3],1[1,2,3],2:[1,2,3],3:[1,2,4],4:[1,2,4],5:[1,2,4]}. there are some duplicate values but the keys are different. when i append a value to list corresponding to key 0 python also adds the value to other duplicates what i don't need.

my code :-

for k, v in f.items():
    if k == 0:
        v.append(1)

result:-

{0:[1,2,3,1],1[1,2,3,1],2:[1,2,3,1],3:[1,2,4],4:[1,2,4],5:[1,2,4]}

what i want is :-

{0:[1,2,3,1],1[1,2,3],2:[1,2,3],3:[1,2,4],4:[1,2,4],5:[1,2,4]}

Body:
I guess your dictionary is faulty. It should be like this:

f={0:[1,2,3],1:[1,2,3],2:[1,2,3],3:[1,2,4],4:[1,2,4],5:[1,2,4]}

for k,v in f.items():
    if k==0:
        v.append(1)

print(f)

Output: {0: [1, 2, 3, 1], 1: [1, 2, 3], 2: [1, 2, 3], 3: [1, 2, 4], 4: [1, 2, 4], 5: [1, 2, 4]}

Isn't it what you want?


问:
Change color of FontAwsome Glyph
I'm using FontAwesome Glyphs in a button and want to change the color in a method. Does anyone know how to do this? I also tried "-fx-fill: black;". Both don't work.</p>

```<code>import de.jensd.fx.glyphs.fontawesome.FontAwesomeIcon;
public FontAwesomeIcon close;
close.setStyle("-fx-fill: black;");
</code>```

答:
```<code>import de.jensd.fx.glyphs.fontawesome.FontAwesomeIconView;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage stage) {

        VBox vBox = new VBox();

        FontAwesomeIconView closeIcon = new FontAwesomeIconView();
        closeIcon.setStyle("-glyph-name: CLOSE;");

        Button button = new Button("change icon color to red");
        button.setOnAction(event -> closeIcon.setStyle("-glyph-name: CLOSE; -fx-fill: red;"));

        vBox.getChildren().addAll(closeIcon, button);
        stage.setScene(new Scene(vBox));
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
</code>```

Title: Change color of FontAwsome Glyph

Body:
I'm using FontAwesome Glyphs in a button and want to change the color in a method. Does anyone know how to do this? I also tried "-fx-fill: black;". Both don't work.

import de.jensd.fx.glyphs.fontawesome.FontAwesomeIcon;
public FontAwesomeIcon close;
close.setStyle("-fx-fill: black;");


问:
Lua require mpack twice in different files fails
Given the following (fully complete) Lua file:

-- test/file1_spec.lua
local mpack = require('mpack')
print(mpack)
```

<p>It works without a problem if I execute the file with busted: <code>busted test</code>.</p>

<p>And if I update the file to load <code>mpack</code> twice:</p>

<pre class="lang-lua prettyprint-override"><code>-- test/file1_spec.lua
local mpack = require('mpack')
print(mpack)
local mpack2 = require('mpack')
print(mpack2)
</code>```

It still works. But if I add a second file (additionally to the one above) with:

-- test/file2_spec.lua
local mpack = require('mpack')
print(mpack)
```

<p>Then loading <code>mpack</code> on this second file fails with the following error:</p>

```test/file2_spec.lua:1: attempt to index a mpack.NIL value
```

How does require work? How can I require mpack in different Lua files?

答:
There is something wrong with mpack module itself, it cannot be loaded twice for some reason:

```<code>-- demo.lua
require('mpack')
-- remove the loaded package from a cache, otherwise the package will not be reloaded
package.loaded['mpack'] = nil
require('mpack')
</code>```
```<code>$ lua demo.lua
lua: attempt to index a mpack.NIL value
</code>```

It also happens with busted because busted flushes the package cache between tests:

Test environment insulation saves the global table _G and any currently loaded packages package.loaded, restoring them to their original state at the completion of the insulate block.

By default each test file runs in a separate insulate block, which can be disabled with the --no-auto-insulate flag.

So, you have several options:

Use busted --no-auto-insulate flag. I wouldn't recommend doing that because it disables isolation at all.

Use busted -e 'require("mpack")'. An expression passed with -e argument is executed before any tests, so an insulation mechanism will not remove an already cached package.

Use expose block:

```<code>-- spec/__init_spec.lua
-- The name of this file is started with underscores to ensure that it will be processed
-- before any other spec file. I don't know how to do it in a proper way (if it's possible).
expose('preload mpack module', function()
    require('mpack')
end)
</code>```

See https://olivinelabs.com/busted/#defining-tests, “Describe: Insulate & Expose blocks” section for details.

I'll check mpack source code later and maybe I can fix this issue.

UPD: A qoute from Lua reference manual about package.loaded:

A table used by require to control which modules are already loaded. When you require a module modname and package.loaded[modname] is not false, require simply returns the value stored there.

https://www.lua.org/manual/5.3/manual.html#pdf-package.loaded

Body:
Given the following (fully complete) Lua file:

-- test/file1_spec.lua
local mpack = require('mpack')
print(mpack)

It works without a problem if I execute the file with busted: busted test.

And if I update the file to load mpack twice:

-- test/file1_spec.lua
local mpack = require('mpack')
print(mpack)
local mpack2 = require('mpack')
print(mpack2)

It still works. But if I add a second file (additionally to the one above) with:

-- test/file2_spec.lua
local mpack = require('mpack')
print(mpack)

Then loading mpack on this second file fails with the following error:

test/file2_spec.lua:1: attempt to index a mpack.NIL value

How does require work? How can I require mpack in different Lua files?

Body:
There is something wrong with mpack module itself, it cannot be loaded twice for some reason:

-- demo.lua
require('mpack')
-- remove the loaded package from a cache, otherwise the package will not be reloaded
package.loaded['mpack'] = nil
require('mpack')

$ lua demo.lua
lua: attempt to index a mpack.NIL value

It also happens with busted because busted flushes the package cache between tests:

Test environment insulation saves the global table _G and any currently loaded packages package.loaded, restoring them to their original state at the completion of the insulate block.

By default each test file runs in a separate insulate block, which can be disabled with the --no-auto-insulate flag.

So, you have several options:

Use busted --no-auto-insulate flag. I wouldn't recommend doing that because it disables isolation at all.

Use busted -e 'require("mpack")'. An expression passed with -e argument is executed before any tests, so an insulation mechanism will not remove an already cached package.

Use expose block:

-- spec/__init_spec.lua
-- The name of this file is started with underscores to ensure that it will be processed
-- before any other spec file. I don't know how to do it in a proper way (if it's possible).
expose('preload mpack module', function()
    require('mpack')
end)

See https://olivinelabs.com/busted/#defining-tests, “Describe: Insulate & Expose blocks” section for details.

I'll check mpack source code later and maybe I can fix this issue.

UPD: A qoute from Lua reference manual about package.loaded:

A table used by require to control which modules are already loaded. When you require a module modname and package.loaded[modname] is not false, require simply returns the value stored there.

https://www.lua.org/manual/5.3/manual.html#pdf-package.loaded


问:
Is there a way to get a difference report on two Jet (.mdb) databases?
I have code that depends a relatively small MS Jet (created in Access) database. Our source control process is far from all that it could/should be (which is a problem that needs to be solved immediately) and we have ended up with two versions of the same database. The person who edited the "other" version is no longer around to give me hints about what he changed. What is the best way to find the differences of the actual data contained in two versions of a database?</p>

答: Take a look at this http://www.download.com/StarInix-Database-Compare/3000-10254_4-10614062.html </p>

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: MarlonRibunal


问:
How can I find an unused TCP port in Dart?
I'm trying to launch a process and tell it to use an unused TCP port. Unfortunately, the binary I'm starting won't probe for an unused port. Is there a decent way for me to probe ports in Dart so I can use that as an argument to my process?

The best I can think of is to create a ServerSocket with a port of 0, and then close the socket and use it's port, but this seems hacky to me.

Anyone have a better way?

答:
The above is racy since another process can reclaim the port once the socket is closed. Use the pattern in https://chromium.googlesource.com/external/github.com/dart-lang/test/+/master/pkgs/test_core/lib/src/util/io.dart#147</p>

```<code>Future<T> getUnusedPort<T>(FutureOr<T> Function(int port) tryPort) async {
  T value;
  await Future.doWhile(() async {
    value = await tryPort(await getUnsafeUnusedPort());
    return value == null;
  });
  return value;
}
</code>```

Body:
The above is racy since another process can reclaim the port once the socket is closed. Use the pattern in https://chromium.googlesource.com/external/github.com/dart-lang/test/+/master/pkgs/test_core/lib/src/util/io.dart#147

Future<T> getUnusedPort<T>(FutureOr<T> Function(int port) tryPort) async {
  T value;
  await Future.doWhile(() async {
    value = await tryPort(await getUnsafeUnusedPort());
    return value == null;
  });
  return value;
}


问:
React return component onclick
I'm trying to return a component when I click on a button.
(a delete button with a confirmation popup) I've tried some examples I found online but none really worked for me.

Here is my code:

```<code>class DeleteTask extends React.Component {
  handleClick() {
        return <TaskDeleteModal />
    }
  render() {
    return (
        <div>
            <button type="button" className={styles.deletetask} onClick={() => this.handleClick()}>Verwijderen</button>;
        </div>
    )
  }
}
</code>```

Thanks for reading, I hope you can assist me.

答:
It did not work because the return <TaskDeleteModal /> of handleClick does not add <TaskDeleteModal /> to your render function.
You need to add <TaskDeleteModal /> to render function and control it visibility by a state:
Try the following code:

class DeleteTask extends React.Component {
  this.state = {
    showModal: false
  }
  handleClick() {
        this.setState({showModal: true})
    }
  render() {
    return (

            <button type="button" className={styles.deletetask} onClick={() => this.handleClick()}>Verwijderen</button>;
            {/* In TaskDeleteModal you might have a button, when you click on that button call this.setState({showModal: false}) to hide the modal */}
         {this.state.showModal && <TaskDeleteModal />}

    )
  }
}```

Title: React return component onclick

Body:
I'm trying to return a component when I click on a button.
(a delete button with a confirmation popup) I've tried some examples I found online but none really worked for me.

Here is my code:

class DeleteTask extends React.Component {
  handleClick() {
        return <TaskDeleteModal />
    }
  render() {
    return (

            <button type="button" className={styles.deletetask} onClick={() => this.handleClick()}>Verwijderen</button>;

    )
  }
}

Thanks for reading, I hope you can assist me.

Body:
It did not work because the return <TaskDeleteModal /> of handleClick does not add <TaskDeleteModal /> to your render function.
You need to add <TaskDeleteModal /> to render function and control it visibility by a state:
Try the following code:

class DeleteTask extends React.Component {
  this.state = {
    showModal: false
  }
  handleClick() {
        this.setState({showModal: true})
    }
  render() {
    return (
        <div>
            <button type="button" className={styles.deletetask} onClick={() => this.handleClick()}>Verwijderen</button>;
            {/* In TaskDeleteModal you might have a button, when you click on that button call this.setState({showModal: false}) to hide the modal */}
         {this.state.showModal && <TaskDeleteModal />}
        </div>
    )
  }
}