问:
azure-webapp-maven-plugin happens error "Socket operation on nonsocket: configureBlocking" while deploying maven app to azure server
when I execute mvn azure-webapp:deploy in cmd, a socket error happens.

```<code>情報: I/O exception (java.net.SocketException) caught when processing request to {s}->https://dc.services.visualstudio.com:443: --Socket operation on nonsocket: configureBlocking
2 15, 2020 6:42:46 午後 com.microsoft.applicationinsights.core.dependencies.http.impl.execchain.RetryExec execute
</code>```

I run this goal at a cloud server, windows 2016.
  It seems maven cannot connect with azure server to start to deploy.
  I have tried in my local machine with same command, it runs well.
  Can anybody help me what the issue is in my cloud server, please?

execution logs:

```<code>mvn  azure-webapp:deploy
[INFO] Scanning for projects...
[INFO]
[INFO] -------------------------< housecom.co.jp:hcm >-------------------------
[INFO] Building hcm 1.0
[INFO] --------------------------------[ war ]---------------------------------
[INFO]
[INFO] --- azure-webapp-maven-plugin:1.9.0:deploy (default-cli) @ hcm ---
[WARNING] You are using an old way of authentication which will be deprecated in future versions, please change your configurations.
[INFO] Authenticate with ServerId: azure-auth
[INFO] [Correlation ID: d45c8e88-35ea-43cd-8e63-7cb343e9ffcb] Instance discovery was successful
[ERROR] [Correlation ID: d45c8e88-35ea-43cd-8e63-7cb343e9ffcb] Execution of class com.microsoft.aad.adal4j.AcquireTokenCallable failed.
java.net.ConnectException: Connection timed out: connect
    at java.net.DualStackPlainSocketImpl.connect0 (Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect (DualStackPlainSocketImpl.java:79)
    at java.net.AbstractPlainSocketImpl.doConnect (AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress (AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect (AbstractPlainSocketImpl.java:188)
    at java.net.PlainSocketImpl.connect (PlainSocketImpl.java:172)
    at java.net.SocksSocketImpl.connect (SocksSocketImpl.java:392)
    at java.net.Socket.connect (Socket.java:589)
    at sun.security.ssl.SSLSocketImpl.connect (SSLSocketImpl.java:666)
    at sun.security.ssl.BaseSSLSocketImpl.connect (BaseSSLSocketImpl.java:173)
    at sun.net.NetworkClient.doConnect (NetworkClient.java:180)
    at sun.net.www.http.HttpClient.openServer (HttpClient.java:463)
    at sun.net.www.http.HttpClient.openServer (HttpClient.java:558)
    at sun.net.www.protocol.https.HttpsClient.<init> (HttpsClient.java:264)
    at sun.net.www.protocol.https.HttpsClient.New (HttpsClient.java:367)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient (AbstractDelegateHttpsURLConnection.java:191)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect0 (HttpURLConnection.java:1162)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect (HttpURLConnection.java:1056)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect (AbstractDelegateHttpsURLConnection.java:177)
    at sun.net.www.protocol.http.HttpURLConnection.getOutputStream0 (HttpURLConnection.java:1340)
    at sun.net.www.protocol.http.HttpURLConnection.getOutputStream (HttpURLConnection.java:1315)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream (HttpsURLConnectionImpl.java:264)
    at com.microsoft.aad.adal4j.AdalOAuthRequest.configureHeaderAndExecuteOAuthCall (AdalOAuthRequest.java:145)
    at com.microsoft.aad.adal4j.AdalOAuthRequest.send (AdalOAuthRequest.java:83)
    at com.microsoft.aad.adal4j.AdalTokenRequest.executeOAuthRequestAndProcessResponse (AdalTokenRequest.java:87)
    at com.microsoft.aad.adal4j.AuthenticationContext.acquireTokenCommon (AuthenticationContext.java:930)
    at com.microsoft.aad.adal4j.AcquireTokenCallable.execute (AcquireTokenCallable.java:70)
    at com.microsoft.aad.adal4j.AcquireTokenCallable.execute (AcquireTokenCallable.java:38)
    at com.microsoft.aad.adal4j.AdalCallable.call (AdalCallable.java:47)
    at java.util.concurrent.FutureTask.run (FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java:624)
    at java.lang.Thread.run (Thread.java:748)
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
2 15, 2020 6:42:46 午後 com.microsoft.applicationinsights.core.dependencies.http.impl.execchain.RetryExec execute
情報: I/O exception (java.net.SocketException) caught when processing request to {s}->https://rt.services.visualstudio.com:443: [Socket operation on nonsocket: connect
INFO] ------------------------------2 15, 2020 6:42:46 午後 com.microsoft.applicationinsights.core.dependencies.http.impl.execchain.RetryExec execute
情報: I/O exception (java.net.SocketException) caught when processing request to {s}->https://dc.services.visualstudio.com:443: --Socket operation on nonsocket: configureBlocking
2 15, 2020 6:42:46 午後 com.microsoft.applicationinsights.core.dependencies.http.impl.execchain.RetryExec execute
情報: Retrying request to {s}->https://rt.services.visualstudio.com:443
2 15, 2020 6:42:46 午後 com.microsoft.applicationinsights.core.dependencies.http.impl.execchain.RetryExec execute
情報: Retrying request to {s}->https://dc.services.visualstudio.com:443
----------------------------------------
[INFO] Total time:  33.361 s
[INFO] Finished at: 2020-02-15T18:42:46+09:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal com.microsoft.azure:azure-webapp-maven-plugin:1.9.0:deploy (default-cli) on project hcm: java.io.IOException: java.net.ConnectException: Connection timed out: connect -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException

</code>```

cloud env:

```<code>Apache Maven 3.6.0 (97c98ec64a1fdfee7767ce5ffb20918da4f719f3; 2018-10-25T03:41:47+09:00)
Maven home: C:\work\maven\bin\..
Java version: 1.8.0_221, vendor: Oracle Corporation, runtime: C:\Program Files\Java\jdk1.8.0_221\jre
Default locale: ja_JP, platform encoding: MS932
OS name: "windows server 2016", version: "10.0", arch: "amd64", family: "windows"

</code>```

the right process in my local machine:

```<code>mvn azure-webapp:deploy
[INFO] Scanning for projects...
[INFO]
[INFO] -------------------------< housecom.co.jp:hcm >-------------------------
[INFO] Building hcm 1.0
[INFO] --------------------------------[ war ]---------------------------------
[INFO]
[INFO] --- azure-webapp-maven-plugin:1.9.0:deploy (default-cli) @ hcm ---
[WARNING] You are using an old way of authentication which will be deprecated in future versions, please change your configurations.
[INFO] Authenticate with ServerId: azure-auth
[INFO] [Correlation ID: 88a3f90c-4396-49c9-8487-0ec3f040a578] Instance discovery was successful
[INFO] Updating App Service Plan...
[INFO] Updating target Web App...
[INFO] Successfully updated Web App.
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 1 resource to E:\testworkspace\hcm-dev\target\azure-webapp\HC-2-PsdOC0dd1-27f80ebb-ca1b-4cb9-b59c-bb970337311a
[INFO] Trying to deploy artifact to HC-WEBAPP-PO2C56...
[INFO] Deploying the war file hcm-1.0.war...
[INFO] Successfully deployed the artifact to https://hc-wx-pocasdf01.azurddewebsites.net2
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  01:25 min
[INFO] Finished at: 2020-02-15T17:27:16+09:00
[INFO] ------------------------------------------------------------------------

</code>```

答:
solved, refer to the post HttpsURLConnection: Connection Timed out error.

I finally found my cloud computer is offline to internet, and browse with a proxy server!!

Body:
when I execute mvn azure-webapp:deploy in cmd, a socket error happens.

情報: I/O exception (java.net.SocketException) caught when processing request to {s}->https://dc.services.visualstudio.com:443: --Socket operation on nonsocket: configureBlocking
2 15, 2020 6:42:46 午後 com.microsoft.applicationinsights.core.dependencies.http.impl.execchain.RetryExec execute

I run this goal at a cloud server, windows 2016.
  It seems maven cannot connect with azure server to start to deploy.
  I have tried in my local machine with same command, it runs well.
  Can anybody help me what the issue is in my cloud server, please?

execution logs:

mvn  azure-webapp:deploy
[INFO] Scanning for projects...
[INFO]
[INFO] -------------------------< housecom.co.jp:hcm >-------------------------
[INFO] Building hcm 1.0
[INFO] --------------------------------[ war ]---------------------------------
[INFO]
[INFO] --- azure-webapp-maven-plugin:1.9.0:deploy (default-cli) @ hcm ---
[WARNING] You are using an old way of authentication which will be deprecated in future versions, please change your configurations.
[INFO] Authenticate with ServerId: azure-auth
[INFO] [Correlation ID: d45c8e88-35ea-43cd-8e63-7cb343e9ffcb] Instance discovery was successful
[ERROR] [Correlation ID: d45c8e88-35ea-43cd-8e63-7cb343e9ffcb] Execution of class com.microsoft.aad.adal4j.AcquireTokenCallable failed.
java.net.ConnectException: Connection timed out: connect
    at java.net.DualStackPlainSocketImpl.connect0 (Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect (DualStackPlainSocketImpl.java:79)
    at java.net.AbstractPlainSocketImpl.doConnect (AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress (AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect (AbstractPlainSocketImpl.java:188)
    at java.net.PlainSocketImpl.connect (PlainSocketImpl.java:172)
    at java.net.SocksSocketImpl.connect (SocksSocketImpl.java:392)
    at java.net.Socket.connect (Socket.java:589)
    at sun.security.ssl.SSLSocketImpl.connect (SSLSocketImpl.java:666)
    at sun.security.ssl.BaseSSLSocketImpl.connect (BaseSSLSocketImpl.java:173)
    at sun.net.NetworkClient.doConnect (NetworkClient.java:180)
    at sun.net.www.http.HttpClient.openServer (HttpClient.java:463)
    at sun.net.www.http.HttpClient.openServer (HttpClient.java:558)
    at sun.net.www.protocol.https.HttpsClient.<init> (HttpsClient.java:264)
    at sun.net.www.protocol.https.HttpsClient.New (HttpsClient.java:367)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient (AbstractDelegateHttpsURLConnection.java:191)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect0 (HttpURLConnection.java:1162)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect (HttpURLConnection.java:1056)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect (AbstractDelegateHttpsURLConnection.java:177)
    at sun.net.www.protocol.http.HttpURLConnection.getOutputStream0 (HttpURLConnection.java:1340)
    at sun.net.www.protocol.http.HttpURLConnection.getOutputStream (HttpURLConnection.java:1315)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream (HttpsURLConnectionImpl.java:264)
    at com.microsoft.aad.adal4j.AdalOAuthRequest.configureHeaderAndExecuteOAuthCall (AdalOAuthRequest.java:145)
    at com.microsoft.aad.adal4j.AdalOAuthRequest.send (AdalOAuthRequest.java:83)
    at com.microsoft.aad.adal4j.AdalTokenRequest.executeOAuthRequestAndProcessResponse (AdalTokenRequest.java:87)
    at com.microsoft.aad.adal4j.AuthenticationContext.acquireTokenCommon (AuthenticationContext.java:930)
    at com.microsoft.aad.adal4j.AcquireTokenCallable.execute (AcquireTokenCallable.java:70)
    at com.microsoft.aad.adal4j.AcquireTokenCallable.execute (AcquireTokenCallable.java:38)
    at com.microsoft.aad.adal4j.AdalCallable.call (AdalCallable.java:47)
    at java.util.concurrent.FutureTask.run (FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java:624)
    at java.lang.Thread.run (Thread.java:748)
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
2 15, 2020 6:42:46 午後 com.microsoft.applicationinsights.core.dependencies.http.impl.execchain.RetryExec execute
情報: I/O exception (java.net.SocketException) caught when processing request to {s}->https://rt.services.visualstudio.com:443: [Socket operation on nonsocket: connect
INFO] ------------------------------2 15, 2020 6:42:46 午後 com.microsoft.applicationinsights.core.dependencies.http.impl.execchain.RetryExec execute
情報: I/O exception (java.net.SocketException) caught when processing request to {s}->https://dc.services.visualstudio.com:443: --Socket operation on nonsocket: configureBlocking
2 15, 2020 6:42:46 午後 com.microsoft.applicationinsights.core.dependencies.http.impl.execchain.RetryExec execute
情報: Retrying request to {s}->https://rt.services.visualstudio.com:443
2 15, 2020 6:42:46 午後 com.microsoft.applicationinsights.core.dependencies.http.impl.execchain.RetryExec execute
情報: Retrying request to {s}->https://dc.services.visualstudio.com:443
----------------------------------------
[INFO] Total time:  33.361 s
[INFO] Finished at: 2020-02-15T18:42:46+09:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal com.microsoft.azure:azure-webapp-maven-plugin:1.9.0:deploy (default-cli) on project hcm: java.io.IOException: java.net.ConnectException: Connection timed out: connect -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException

cloud env:

Apache Maven 3.6.0 (97c98ec64a1fdfee7767ce5ffb20918da4f719f3; 2018-10-25T03:41:47+09:00)
Maven home: C:\work\maven\bin\..
Java version: 1.8.0_221, vendor: Oracle Corporation, runtime: C:\Program Files\Java\jdk1.8.0_221\jre
Default locale: ja_JP, platform encoding: MS932
OS name: "windows server 2016", version: "10.0", arch: "amd64", family: "windows"

the right process in my local machine:

mvn azure-webapp:deploy
[INFO] Scanning for projects...
[INFO]
[INFO] -------------------------< housecom.co.jp:hcm >-------------------------
[INFO] Building hcm 1.0
[INFO] --------------------------------[ war ]---------------------------------
[INFO]
[INFO] --- azure-webapp-maven-plugin:1.9.0:deploy (default-cli) @ hcm ---
[WARNING] You are using an old way of authentication which will be deprecated in future versions, please change your configurations.
[INFO] Authenticate with ServerId: azure-auth
[INFO] [Correlation ID: 88a3f90c-4396-49c9-8487-0ec3f040a578] Instance discovery was successful
[INFO] Updating App Service Plan...
[INFO] Updating target Web App...
[INFO] Successfully updated Web App.
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 1 resource to E:\testworkspace\hcm-dev\target\azure-webapp\HC-2-PsdOC0dd1-27f80ebb-ca1b-4cb9-b59c-bb970337311a
[INFO] Trying to deploy artifact to HC-WEBAPP-PO2C56...
[INFO] Deploying the war file hcm-1.0.war...
[INFO] Successfully deployed the artifact to https://hc-wx-pocasdf01.azurddewebsites.net2
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  01:25 min
[INFO] Finished at: 2020-02-15T17:27:16+09:00
[INFO] ------------------------------------------------------------------------


来源: stackexchange

问:
RSpec let with string and hash - syntax error
I'm trying to have let which in result I'll have:

```<code>("project = TSW-123 AND status != Done AND status != Closed AND status != Cancelled AND status != Followup", {:max_results=>1000, :start_at=>0})
</code>```

My let:

```<code>  let(:jql_options) do
   "project = TSW-123 AND
    status != Done AND
    status != Closed AND
    status != Cancelled AND
    status != Followup",
    {
      start_at => 0,
      max_results => 1000
    }
  end
</code>```

With error:

```<code>syntax error, unexpected ',', expecting keyword_end
      status != Followup",
</code>```

答:
You want the let to return an array:

```<code>let(:jql_options) do
  [
    "project = TSW-123 AND status != Done AND status != Closed AND status != Cancelled AND status != Followup",
    {
      start_at => 0,
      max_results => 1000
    }
  ]
end
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to have let which in result I'll have:

("project = TSW-123 AND status != Done AND status != Closed AND status != Cancelled AND status != Followup", {:max_results=>1000, :start_at=>0})

My let:

  let(:jql_options) do
   "project = TSW-123 AND
    status != Done AND
    status != Closed AND
    status != Cancelled AND
    status != Followup",
    {
      start_at => 0,
      max_results => 1000
    }
  end

With error:

syntax error, unexpected ',', expecting keyword_end
      status != Followup",

Body:
You want the let to return an array:

let(:jql_options) do
  [
    "project = TSW-123 AND status != Done AND status != Closed AND status != Cancelled AND status != Followup",
    {
      start_at => 0,
      max_results => 1000
    }
  ]
end


问:
ContentView's content isn't shown if it isn't visible at the beginning?
I have a problem to show the content of an overlay when a Task is running. I did a very simple Xamarin.Forms shared project that reproduces the problem (at this moment I'm only running it in an Android emulator). I have 2 main elements in the page: an StackLayout with a Button (to show the overlay) and a ContentView with another Button (to hide the overlay):

OverlayPage.xaml:

```<code><?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="OverlayTest.Pages.OverlayPage">
    <AbsoluteLayout>
    <StackLayout AbsoluteLayout.LayoutBounds="0, 0, 1, 1" AbsoluteLayout.LayoutFlags="All">
      <Button x:Name="showOverlayButton" Text="Show overlay" Clicked="ShowOverlayButtonClicked"/>
    </StackLayout>
    <ContentView x:Name="overlay" AbsoluteLayout.LayoutBounds="0, 0, 1, 1" AbsoluteLayout.LayoutFlags="All"
                 IsVisible="False" BackgroundColor="#C0808080" Padding="10, 0">
      <Button x:Name="hideOverlayButton" Text="Hide overlay" Clicked="HideOverlayButtonClicked"/>
    </ContentView>
  </AbsoluteLayout>
</ContentPage>
</code>```

OverlayPage.xaml.cs:

```<code>using System;
using Xamarin.Forms;

namespace OverlayTest.Pages
{
    public partial class OverlayPage : ContentPage
    {
        public OverlayPage()
        {
            InitializeComponent();
        }

        private void ShowOverlayButtonClicked(object sender, EventArgs e)
        {
            this.overlay.IsVisible = true;
        }

        private void HideOverlayButtonClicked(object sender, EventArgs e)
        {
            this.overlay.IsVisible = false;
        }
    }
}
</code>```

App.cs:

```<code>using OverlayTest.Pages;
using Xamarin.Forms;

namespace OverlayTest
{
    public class App : Application
    {
        public App()
        {
            // The root page of your application
            this.MainPage = new NavigationPage(new OverlayPage());
        }
    }
}
</code>```

When I run the app, when I click on showOverlayButton the grey layer is shown, but it's content (hideOverlayButton button) is not visible. If I change the xaml setting overlay's IsVisible property to True:

```<code><ContentView x:Name="overlay" AbsoluteLayout.LayoutBounds="0, 0, 1, 1" AbsoluteLayout.LayoutFlags="All"
             IsVisible="True" BackgroundColor="#C0808080" Padding="10, 0">
</code>```

and I run the app, then I can see the grey layer with a big hideOverlayButton button. In this case I can hide the overlay, and show it again, and hide, show, hide...

It seems that the ContentView's content have to be visible at the beginning... How can I solve this problem?

答:
Sometimes Xamarin.Forms misses re-rendering of the content. In this case you can explicitly trigger the re-render process of the view by calling ForceLayout() function on the parent view.
In your case, you'd have to call :

```<code>overlay.ForceLayout();
</code>```

after changing its visiblity.

ContentLicense: CC BY-SA 3.0

Body:
I have a problem to show the content of an overlay when a Task is running. I did a very simple Xamarin.Forms shared project that reproduces the problem (at this moment I'm only running it in an Android emulator). I have 2 main elements in the page: an StackLayout with a Button (to show the overlay) and a ContentView with another Button (to hide the overlay):

OverlayPage.xaml:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="OverlayTest.Pages.OverlayPage">
    <AbsoluteLayout>
    <StackLayout AbsoluteLayout.LayoutBounds="0, 0, 1, 1" AbsoluteLayout.LayoutFlags="All">
      <Button x:Name="showOverlayButton" Text="Show overlay" Clicked="ShowOverlayButtonClicked"/>
    </StackLayout>
    <ContentView x:Name="overlay" AbsoluteLayout.LayoutBounds="0, 0, 1, 1" AbsoluteLayout.LayoutFlags="All"
                 IsVisible="False" BackgroundColor="#C0808080" Padding="10, 0">
      <Button x:Name="hideOverlayButton" Text="Hide overlay" Clicked="HideOverlayButtonClicked"/>
    </ContentView>
  </AbsoluteLayout>
</ContentPage>

OverlayPage.xaml.cs:

using System;
using Xamarin.Forms;

namespace OverlayTest.Pages
{
    public partial class OverlayPage : ContentPage
    {
        public OverlayPage()
        {
            InitializeComponent();
        }

        private void ShowOverlayButtonClicked(object sender, EventArgs e)
        {
            this.overlay.IsVisible = true;
        }

        private void HideOverlayButtonClicked(object sender, EventArgs e)
        {
            this.overlay.IsVisible = false;
        }
    }
}

App.cs:

using OverlayTest.Pages;
using Xamarin.Forms;

namespace OverlayTest
{
    public class App : Application
    {
        public App()
        {
            // The root page of your application
            this.MainPage = new NavigationPage(new OverlayPage());
        }
    }
}

When I run the app, when I click on showOverlayButton the grey layer is shown, but it's content (hideOverlayButton button) is not visible. If I change the xaml setting overlay's IsVisible property to True:

<ContentView x:Name="overlay" AbsoluteLayout.LayoutBounds="0, 0, 1, 1" AbsoluteLayout.LayoutFlags="All"
             IsVisible="True" BackgroundColor="#C0808080" Padding="10, 0">

and I run the app, then I can see the grey layer with a big hideOverlayButton button. In this case I can hide the overlay, and show it again, and hide, show, hide...

It seems that the ContentView's content have to be visible at the beginning... How can I solve this problem?

Body:
Sometimes Xamarin.Forms misses re-rendering of the content. In this case you can explicitly trigger the re-render process of the view by calling ForceLayout() function on the parent view.
In your case, you'd have to call :

overlay.ForceLayout();

after changing its visiblity.


问:
How to restore the permissions of files and directories within git if they have been modified?
I have a git checkout. All the file permissions are different than what git thinks they should be therefore they all show up as modified.

Without touching the content of the files (just want to modify the permissions) how do I set all the files permissions to what git thinks they should be?

答:
I use git from cygwin on Windows, the git apply solution doesn't work for me. Here is my solution, run chmod on every file to reset its permissions.

```<code>#!/bin/bash
IFS=$'\n'
for c in `git diff -p |sed -n '/diff --git/{N;s/diff --git//g;s/\n/ /g;s# a/.* b/##g;s/old mode //g;s/\(.*\) 100\(.*\)/chmod \2 \1/g;p}'`
do
        eval $c
done
unset IFS

</code>```

Body:
I use git from cygwin on Windows, the git apply solution doesn't work for me. Here is my solution, run chmod on every file to reset its permissions.

#!/bin/bash
IFS=$'\n'
for c in `git diff -p |sed -n '/diff --git/{N;s/diff --git//g;s/\n/ /g;s# a/.* b/##g;s/old mode //g;s/\(.*\) 100\(.*\)/chmod \2 \1/g;p}'`
do
        eval $c
done
unset IFS


问:
Function running when it shouldn't
I have the following snippets of code:

```<code>struct TreeNode *allocate_node(char *value) {
  struct TreeNode *new_node = malloc(sizeof(struct TreeNode));
  new_node->value = value;
  new_node->sibling = NULL;
  new_node->child = NULL;
  return new_node;
}
</code>```

```<code>void tree_insert(struct TreeNode *root, char **values) {

  struct TreeNode *prev = root;
  struct TreeNode *curr = prev->child;

  for (int i = 0; i < 4; i++) {
    if (!curr) {
      prev->child = allocate_node(values[i]);

      prev = prev->child;
      curr = prev->child;
    }
  }
}
</code>```

```<code>int main(void) {
  struct TreeNode root;
  root.value = "";
  root.child = NULL;
  root.sibling = NULL;

  char *command1[] = {"a", "b", "c", "d"};
  char *command2[] = {"e", "f", "g", "h"};

  tree_insert(&root, command1);
  tree_insert(&root, command2);

  printf("Printing current tree values: \n");
  struct TreeNode *curr = root.child;
  while (curr) {
    printf("%s ", curr->value);
    curr = curr->child;
  }
}
</code>```

Expected output:

```<code>Current tree values:
a b c d
</code>```

Actual output:

```<code>Current tree values:
e f g h
</code>```

After the first tree_insert is run my tree is linked like this:
(root) -> a -> b -> c -> d

But when the second tree_insert runs my old tree seems to have been replaced even though tree_insert shouldn't even run. New tree is as such:
(root) -> e -> f -> g -> h

Since in the second tree_insert curr is no longer NULL, how come it's still running and overwriting my tree? I'm pretty new to C so I might be missing something really obvious

edit:
TreeNode is defined as such:

```<code>struct TreeNode {
    char *value;
  struct TreeNode *sibling;
  struct TreeNode *child;
};
</code>```

答:
```<code>new_node->value = value;
</code>```

This line leads me to believe that you are storing the pointer value in the structure.

The problem here is that the pointer is stored in the struct. This pointer points to some other location, usually in the stack. When this variable is changed, the data in the structure also changes.

You can store the data in the structure in the form of an array or you can use dynamic memory allocation to store the data.

For Dynamic memory allocation, the function allocate_node is changed as below.

```<code>struct TreeNode *allocate_node(char *value) {
  struct TreeNode *new_node = malloc(sizeof(struct TreeNode));
  int len = strlen(value);
  new_node->value = malloc(len +1);
  strcpy(new_node->value, value);
  new_node->sibling = NULL;
  new_node->child = NULL;
  return new_node;
}
</code>```

To store in an array, you need to know the maximum length of value in advance. In this case the following changes are required.

```<code>struct TreeNode {
  char value[MAXLEN + 1];
  struct TreeNode *sibling;
  struct TreeNode *child;
};

struct TreeNode *allocate_node(char *value) {
  struct TreeNode *new_node = malloc(sizeof(struct TreeNode));
  strcpy(new_node->value,value);
  new_node->sibling = NULL;
  new_node->child = NULL;
  return new_node;
}
</code>```

Title: Function running when it shouldn't

Body:
I have the following snippets of code:

struct TreeNode *allocate_node(char *value) {
  struct TreeNode *new_node = malloc(sizeof(struct TreeNode));
  new_node->value = value;
  new_node->sibling = NULL;
  new_node->child = NULL;
  return new_node;
}

void tree_insert(struct TreeNode *root, char **values) {

  struct TreeNode *prev = root;
  struct TreeNode *curr = prev->child;

  for (int i = 0; i < 4; i++) {
    if (!curr) {
      prev->child = allocate_node(values[i]);

      prev = prev->child;
      curr = prev->child;
    }
  }
}

int main(void) {
  struct TreeNode root;
  root.value = "";
  root.child = NULL;
  root.sibling = NULL;

  char *command1[] = {"a", "b", "c", "d"};
  char *command2[] = {"e", "f", "g", "h"};

  tree_insert(&root, command1);
  tree_insert(&root, command2);

  printf("Printing current tree values: \n");
  struct TreeNode *curr = root.child;
  while (curr) {
    printf("%s ", curr->value);
    curr = curr->child;
  }
}

Expected output:

Current tree values:
a b c d

Actual output:

Current tree values:
e f g h

After the first tree_insert is run my tree is linked like this:
(root) -> a -> b -> c -> d

But when the second tree_insert runs my old tree seems to have been replaced even though tree_insert shouldn't even run. New tree is as such:
(root) -> e -> f -> g -> h

Since in the second tree_insert curr is no longer NULL, how come it's still running and overwriting my tree? I'm pretty new to C so I might be missing something really obvious

edit:
TreeNode is defined as such:

struct TreeNode {
    char *value;
  struct TreeNode *sibling;
  struct TreeNode *child;
};

Body:
new_node->value = value;

This line leads me to believe that you are storing the pointer value in the structure.

The problem here is that the pointer is stored in the struct. This pointer points to some other location, usually in the stack. When this variable is changed, the data in the structure also changes.

You can store the data in the structure in the form of an array or you can use dynamic memory allocation to store the data.

For Dynamic memory allocation, the function allocate_node is changed as below.

struct TreeNode *allocate_node(char *value) {
  struct TreeNode *new_node = malloc(sizeof(struct TreeNode));
  int len = strlen(value);
  new_node->value = malloc(len +1);
  strcpy(new_node->value, value);
  new_node->sibling = NULL;
  new_node->child = NULL;
  return new_node;
}

To store in an array, you need to know the maximum length of value in advance. In this case the following changes are required.

struct TreeNode {
  char value[MAXLEN + 1];
  struct TreeNode *sibling;
  struct TreeNode *child;
};

struct TreeNode *allocate_node(char *value) {
  struct TreeNode *new_node = malloc(sizeof(struct TreeNode));
  strcpy(new_node->value,value);
  new_node->sibling = NULL;
  new_node->child = NULL;
  return new_node;
}


答:
You can try this.

```<code>In [18]: for d in total:
    ...:     for k,v in d.items():
    ...:         if k not in new:
    ...:             new[k]=v
    ...:         else:
    ...:             new[k].update(v)
</code>```

output

```<code>{'9940542': {'Invalid Adjust(Platform Fee)': '-1.00',
  'Invalid Adjust(Media Fee)': '-2.00'},
 '10315065': {'Invalid Adjust(Platform Fee)': '-1.00',
  'Invalid Adjust(Media Fee)': '-3.00'},
 '11211744': {'Invalid Adjust(Platform Fee)': '-290.00',
  'Invalid Adjust(Media Fee)': '-3403.00'},
 '11309685': {'Invalid Adjust(Platform Fee)': '-57.00',
  'Invalid Adjust(Media Fee)': '-670.00'},
 '12103490': {'Media Fee': '709472.00',
  'Platform Fee': '22703.00',
  'Invalid Adjust(Platform Fee)': '-30.00',
  'TrueView Budget Adjust (Platofrm Fee)': '-301.00',
  'Invalid Adjust(Media Fee)': '-348.00',
  'TrueView Budget Adjust (Media Fee)': '-9376.00'},
 '12160150': {'Media Fee': '549173.00', 'Platform Fee': '17573.00'}}
</code>```

Title: Merge List of nested dictionaries

Body:
I have 3 lists as below, which are extracted from a PDF file,

adID = ['9940542', '9940542', '10315065', '10315065', '11211744', '11211744', '11309685', '11309685', '12103490', '12103490', '12103490', '12103490', '12103490', '12103490', '12160150', '12160150']

description = ['Invalid Adjust(Platform Fee)', 'Invalid Adjust(Media Fee)', 'Invalid Adjust(Platform Fee)', 'Invalid Adjust(Media Fee)', 'Invalid Adjust(Platform Fee)', 'Invalid Adjust(Media Fee)', 'Invalid Adjust(Platform Fee)', 'Invalid Adjust(Media Fee)', 'Media Fee', 'Platform Fee', 'Invalid Adjust(Platform Fee)', 'TrueView Budget Adjust (Platofrm Fee)', 'Invalid Adjust(Media Fee)', 'TrueView Budget Adjust (Media Fee)', 'Media Fee', 'Platform Fee']

spendItem = ['-1.00', '-2.00', '-1.00', '-3.00', '-290.00', '-3403.00', '-57.00', '-670.00', '709472.00', '22703.00', '-30.00', '-301.00', '-348.00', '-9376.00', '549173.00', '17573.00']

And I've converted these lists into a list of dictionaries as below

total= [{'9940542': {'Invalid Adjust(Platform Fee)': '-1.00'}},
        {'9940542': {'Invalid Adjust(Media Fee)': '-2.00'}},
        {'10315065': {'Invalid Adjust(Platform Fee)': '-1.00'}},
        {'10315065': {'Invalid Adjust(Media Fee)': '-3.00'}},
        {'11211744': {'Invalid Adjust(Platform Fee)': '-290.00'}},
        {'11211744': {'Invalid Adjust(Media Fee)': '-3403.00'}},
        {'11309685': {'Invalid Adjust(Platform Fee)': '-57.00'}},
        {'11309685': {'Invalid Adjust(Media Fee)': '-670.00'}},
        {'12103490': {'Media Fee': '709472.00'}},
        {'12103490': {'Platform Fee': '22703.00'}},
        {'12103490': {'Invalid Adjust(Platform Fee)': '-30.00'}},
        {'12103490': {'TrueView Budget Adjust (Platofrm Fee)': '-301.00'}},
        {'12103490': {'Invalid Adjust(Media Fee)': '-348.00'}},
        {'12103490': {'TrueView Budget Adjust (Media Fee)': '-9376.00'}},
        {'12160150': {'Media Fee': '549173.00'}},
        {'12160150': {'Platform Fee': '17573.00'}}]

Is there any way to iterate over this list to merge keys and values based on adID. Such as

Expected_result= {'12103490': {'Invalid Adjust(Platform Fee)': '-30.00',TrueView Budget Adjust (Platofrm Fee)': '-301.00','Invalid Adjust(Media Fee)': '-348.00','TrueView Budget Adjust (Media Fee)': '-9376.00'}}

Or is there any better way to merge such data?

Body:
You can try this.

In [18]: for d in total:
    ...:     for k,v in d.items():
    ...:         if k not in new:
    ...:             new[k]=v
    ...:         else:
    ...:             new[k].update(v)

output

{'9940542': {'Invalid Adjust(Platform Fee)': '-1.00',
  'Invalid Adjust(Media Fee)': '-2.00'},
 '10315065': {'Invalid Adjust(Platform Fee)': '-1.00',
  'Invalid Adjust(Media Fee)': '-3.00'},
 '11211744': {'Invalid Adjust(Platform Fee)': '-290.00',
  'Invalid Adjust(Media Fee)': '-3403.00'},
 '11309685': {'Invalid Adjust(Platform Fee)': '-57.00',
  'Invalid Adjust(Media Fee)': '-670.00'},
 '12103490': {'Media Fee': '709472.00',
  'Platform Fee': '22703.00',
  'Invalid Adjust(Platform Fee)': '-30.00',
  'TrueView Budget Adjust (Platofrm Fee)': '-301.00',
  'Invalid Adjust(Media Fee)': '-348.00',
  'TrueView Budget Adjust (Media Fee)': '-9376.00'},
 '12160150': {'Media Fee': '549173.00', 'Platform Fee': '17573.00'}}


问:
Form's Apps Script returning Cannot read property 'value' of undefined error
I have a simple script to generate a doc and PDF upon form submission. I checked all of my code and have submitted a test form to test it out but I kept getting the error of 'values' being undefined when the script is trying to read from the spreadsheet result from the form.

I also tried adding the script in spreadsheet that stores the form submissioon result instead of the form, but I got the same error.

Can anybody points out what have I done wrong?

I set a trigger to execute the script upon form submission:

Here's my code:

function myFunction(e) {
  //e.values is an array of form values
  var timestamp = e.values[0];
  var firstName = e.values[1];
  var lastName = e.values[2];
  var title = e.values[3];
  Logger.log(e.values[0]);

  //file is the template file, and you get it by ID
  var file = DriveApp.getFileById('google-doc-template-file-id');

  //We can make a copy of the template, name it, and optionally tell it what folder to live in
  //file.makeCopy will return a Google Drive file object
  var folder = DriveApp.getFolderById('my-drive-folder-id')
  var copy = file.makeCopy(lastName + ',' + firstName, folder);

  //Once we've got the new file created, we need to open it as a document by using its ID
  var doc = DocumentApp.openById(copy.getId());

  //Since everything we need to change is in the body, we need to get that
  var body = doc.getBody();

  //Then we call all of our replaceText methods
  body.replaceText('{{First name}}', firstName);
  body.replaceText('{{Last name}}', lastName);
  body.replaceText('{{Company}}', company);

  doc.getAs(pdf);
  //Lastly we save and close the document to persist our changes
  doc.saveAndClose();
}
```

The error occured at line 3 - var timestamp = e.values[0];.

答:
In your situation, the container-bound script of Google Form is used.

The OnSubmit event trigger is installed to the function of myFunction.

You want to retrieve 3 response values of firstName, lastName, title from the 4 questions.

You want to also retrieve timestamp.

If my understanding is correct, how about this modification? Please think of this as just one of several possible answers.

Modification points:

From the image you provided, it is found that the script is the container-bound script of Google Form.

Unfortunately, the event object of the OnSubmit event trigger has no property of values for the container-bound script of Google Form. Ref

In this case, it is required to retrieve the response values with e.response.getItemResponses().

In the case that values is included in the event object, it is required to be the container-bound script of Spreadsheet. When the container-bound script of Spreadsheet is used, you can retrieve the response values using e.values from myFunction(e). Ref

And also, in order to retrieve the time stamp, getTimestamp() is used.

When above points are reflected to your script, it becomes as follows.

Modified script:

From:

```<code>//e.values is an array of form values
var timestamp = e.values[0];
var firstName = e.values[1];
var lastName = e.values[2];
var title = e.values[3];
Logger.log(e.values[0]);
</code>```

To:

```<code>var response = e.response;
var timestamp = response.getTimestamp();
var [firstName, lastName, title] = response.getItemResponses().map(function(f) {return f.getResponse()});
</code>```

References:

Form submit of Event Objects

getTimestamp()

getItemResponses()

How to get form values in the submit event handler?

I thought that this thread might be useful.

Body:
I have a simple script to generate a doc and PDF upon form submission. I checked all of my code and have submitted a test form to test it out but I kept getting the error of 'values' being undefined when the script is trying to read from the spreadsheet result from the form.

I also tried adding the script in spreadsheet that stores the form submissioon result instead of the form, but I got the same error.

Can anybody points out what have I done wrong?

I set a trigger to execute the script upon form submission:

Here's my code:

function myFunction(e) {
  //e.values is an array of form values
  var timestamp = e.values[0];
  var firstName = e.values[1];
  var lastName = e.values[2];
  var title = e.values[3];
  Logger.log(e.values[0]);

  //file is the template file, and you get it by ID
  var file = DriveApp.getFileById('google-doc-template-file-id');

  //We can make a copy of the template, name it, and optionally tell it what folder to live in
  //file.makeCopy will return a Google Drive file object
  var folder = DriveApp.getFolderById('my-drive-folder-id')
  var copy = file.makeCopy(lastName + ',' + firstName, folder);

  //Once we've got the new file created, we need to open it as a document by using its ID
  var doc = DocumentApp.openById(copy.getId());

  //Since everything we need to change is in the body, we need to get that
  var body = doc.getBody();

  //Then we call all of our replaceText methods
  body.replaceText('{{First name}}', firstName);
  body.replaceText('{{Last name}}', lastName);
  body.replaceText('{{Company}}', company);

  doc.getAs(pdf);
  //Lastly we save and close the document to persist our changes
  doc.saveAndClose();
}

The error occured at line 3 - var timestamp = e.values[0];.

Body:
In your situation, the container-bound script of Google Form is used.

The OnSubmit event trigger is installed to the function of myFunction.

You want to retrieve 3 response values of firstName, lastName, title from the 4 questions.

You want to also retrieve timestamp.

If my understanding is correct, how about this modification? Please think of this as just one of several possible answers.

Modification points:

From the image you provided, it is found that the script is the container-bound script of Google Form.

Unfortunately, the event object of the OnSubmit event trigger has no property of values for the container-bound script of Google Form. Ref

In this case, it is required to retrieve the response values with e.response.getItemResponses().

In the case that values is included in the event object, it is required to be the container-bound script of Spreadsheet. When the container-bound script of Spreadsheet is used, you can retrieve the response values using e.values from myFunction(e). Ref

And also, in order to retrieve the time stamp, getTimestamp() is used.

When above points are reflected to your script, it becomes as follows.

Modified script:

From:

//e.values is an array of form values
var timestamp = e.values[0];
var firstName = e.values[1];
var lastName = e.values[2];
var title = e.values[3];
Logger.log(e.values[0]);

To:

var response = e.response;
var timestamp = response.getTimestamp();
var [firstName, lastName, title] = response.getItemResponses().map(function(f) {return f.getResponse()});

References:

Form submit of Event Objects

getTimestamp()

getItemResponses()

How to get form values in the submit event handler?

I thought that this thread might be useful.


问:
Finding index of recurring objects in an ArrayList in Java
```<code>public class NewMain {
    public static void main(String[] args) {
        ArrayList<String> array = new ArrayList<>();
        array.add("Ace of Hearts");
        array.add("King of Clubs");
        array.add("Three of Spade");
        array.add("Ace of Hearts");
        array.add("Ten of Clubs");
        for(String s: array)
            System.out.println(s+"at postion: "+array.indexOf(s));
    }
}
</code>```

IndexOf() returns the first occurence of the object in an ArrayList.
Assuming my code is the hand of a poker player, and I want to know the indices of the cards he is holding. Ace of Hearts is at positon 1 and 4. But IndexOf() returns as position 1 and 1 for both occurences of Ace of Hearts.

Question:

1)Is there any other way of getting the value?

2)Should I use someother Data Structure like HashMap or something else?

答:
The List.indesOf() method will return the first occurrence of the list. But your requirement can fulfill as following way.  </p>

```<code>    import java.util.ArrayList;

    public class NewMain {
        public static void main(String[] args) {
            ArrayList<String> array = new ArrayList<>();
            array.add("Ace of Hearts");
            array.add("King of Clubs");
            array.add("Three of Spade");
            array.add("Ace of Hearts");
            array.add("Ten of Clubs");
            for(int i =0;i<array.size();i++)
                System.out.println(array.get(i)+"at postion: "+i);
        }
    }
</code>```

Body:
public class NewMain {
    public static void main(String[] args) {
        ArrayList<String> array = new ArrayList<>();
        array.add("Ace of Hearts");
        array.add("King of Clubs");
        array.add("Three of Spade");
        array.add("Ace of Hearts");
        array.add("Ten of Clubs");
        for(String s: array)
            System.out.println(s+"at postion: "+array.indexOf(s));
    }
}

IndexOf() returns the first occurence of the object in an ArrayList.
Assuming my code is the hand of a poker player, and I want to know the indices of the cards he is holding. Ace of Hearts is at positon 1 and 4. But IndexOf() returns as position 1 and 1 for both occurences of Ace of Hearts.

Question:

1)Is there any other way of getting the value?

2)Should I use someother Data Structure like HashMap or something else?

Body:
The List.indesOf() method will return the first occurrence of the list. But your requirement can fulfill as following way.

    import java.util.ArrayList;

    public class NewMain {
        public static void main(String[] args) {
            ArrayList<String> array = new ArrayList<>();
            array.add("Ace of Hearts");
            array.add("King of Clubs");
            array.add("Three of Spade");
            array.add("Ace of Hearts");
            array.add("Ten of Clubs");
            for(int i =0;i<array.size();i++)
                System.out.println(array.get(i)+"at postion: "+i);
        }
    }


问:
Old files remain in new docker container
I have a basic Hyperledger Fabric network where the nodes uses docker containers.

Inside each node I have done some file creation and editing. However, I now want to restart the network with clean containers.

I have tried to shut down all containers, images and networks, then run the docker prune command.
I have also tried to delete all volumes.

However, once I re-create the Fabric network, when bashing into a container the old files that I custom created are still there. I never created those files on host machine, only inside that container. But I do not understand how it is possible that those files still exists. I even tried to delete the images.

System is Ubuntu 18.4

Can anybody spot the potential fix to this?

答:
Delete the volumes of the containers after stopping and removing the containers by below commands,

docker kill $(docker ps -aq)

docker rm $(docker ps -aq)

Then remove the volumes of the containers by below command.

docker system prune --volumes -f

This removes all the unused networks and volumes .

Hope this helps.


问:
how can I prevent my widget from running if there is no internet connection?
I am making a weather widget. If I install the widget on the home screen, app configuration starts automatically. I'd like to prevent the configuration from running if there is no wifi or 3g. I used ConnectivityManager in the instance of AppWidgetProvider, but it didn't work. And I used ConnectivityManager in the java class of widget configuration, but it still didn't work with error messages "..stopped unexpectedly." Anyone who can help me? </p>

答: Did you add uses-permissions to your manifest file to access the network state? If not you should add them.</p>


问:
Add leading zero to numbers between special tags
I know it is not complicated to add leading zero to numbers. However, I am looking for an optimal solution to add leading zero only to values between <SpecialTag>0</SpecialTag> to make them 5 digits.

```<code><?xml version="1.0" encoding="ISO-8859-1" standalone="yes" ?>
<Root>
    <Row>
        <Tag1>0</Tag1>
        <SpecialTag>0</SpecialTag>
        <Tag2>0</Tag2>
    </Row>
    <Row>
        <Tag1>0</Tag1>
        <SpecialTag>12</SpecialTag>
        <Tag2>0</Tag2>
    </Row>
    <Row>
        <Tag1>0</Tag1>
        <SpecialTag>12345</SpecialTag>
        <Tag2>0</Tag2>
    </Row>
    <Row>
        <Tag1>0</Tag1>
        <SpecialTag>1234</SpecialTag>
        <Tag2>0</Tag2>
    </Row>
</Root>
</code>```

Expected results should be like below:

```<code><?xml version="1.0" encoding="ISO-8859-1" standalone="yes" ?>
<Root>
    <Row>
        <Tag1>0</Tag1>
        <SpecialTag>00000</SpecialTag>
        <Tag2>0</Tag2>
    </Row>
    <Row>
        <Tag1>0</Tag1>
        <SpecialTag>00012</SpecialTag>
        <Tag2>0</Tag2>
    </Row>
    <Row>
        <Tag1>0</Tag1>
        <SpecialTag>12345</SpecialTag>
        <Tag2>0</Tag2>
    </Row>
    <Row>
        <Tag1>0</Tag1>
        <SpecialTag>01234</SpecialTag>
        <Tag2>0</Tag2>
    </Row>
</Root>
</code>```

答:
Using xsltproc (Suggested solution!):

Having XLST file transform.xsl:

```<code><?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <!-- Matches the SpecialTag -->
    <xsl:template match="SpecialTag">
        <xsl:copy>
            <!-- The number is available using node() and format-number() applies the 0-padding -->
            <xsl:value-of select="format-number(node(), '00000')" />
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>
</code>```

Run the following, provided that input.xml contains your XML:

```<code>$ xsltproc transform.xml input.xml
</code>```

Unsafe solutions:

Those rely on the fact that opening tag <SpecialTag> and closing tag </SpecialTag> are on the same line and that there is only one of them per line.

The solutions below are only mentioned because the author explicitly tagged the question with sed/bash/shell. Those are not the right tools to achieve the job!

They all work with regular expressions to catch <SpecialTag>, followed by several numbers then </SpecialTag> and transform the numbers caught with a 0-padded version of those numbers.

Using sed:

```<code>sed --regexp-extended 's@<SpecialTag>([0-9]+)</SpecialTag>@<SpecialTag>0000000\1</SpecialTag>@;s@0*([0-9]{5,})@\1@'
</code>```

Using perl:

```<code>perl -pe 's@<SpecialTag>([0-9]+)</SpecialTag>@sprintf("<SpecialTag>%05d</SpecialTag>",$1)@e'
</code>```

Using awk:

```<code>awk '{gsub( /<SpecialTag>[0-9]+<\/SpecialTag>/, sprintf("<SpecialTag>%05d</SpecialTag>", gensub(/[^0-9]/, "","g"))); print}'
</code>```

Body:
I know it is not complicated to add leading zero to numbers. However, I am looking for an optimal solution to add leading zero only to values between <SpecialTag>0</SpecialTag> to make them 5 digits.

<?xml version="1.0" encoding="ISO-8859-1" standalone="yes" ?>
<Root>
    <Row>
        <Tag1>0</Tag1>
        <SpecialTag>0</SpecialTag>
        <Tag2>0</Tag2>
    </Row>
    <Row>
        <Tag1>0</Tag1>
        <SpecialTag>12</SpecialTag>
        <Tag2>0</Tag2>
    </Row>
    <Row>
        <Tag1>0</Tag1>
        <SpecialTag>12345</SpecialTag>
        <Tag2>0</Tag2>
    </Row>
    <Row>
        <Tag1>0</Tag1>
        <SpecialTag>1234</SpecialTag>
        <Tag2>0</Tag2>
    </Row>
</Root>

Expected results should be like below:

<?xml version="1.0" encoding="ISO-8859-1" standalone="yes" ?>
<Root>
    <Row>
        <Tag1>0</Tag1>
        <SpecialTag>00000</SpecialTag>
        <Tag2>0</Tag2>
    </Row>
    <Row>
        <Tag1>0</Tag1>
        <SpecialTag>00012</SpecialTag>
        <Tag2>0</Tag2>
    </Row>
    <Row>
        <Tag1>0</Tag1>
        <SpecialTag>12345</SpecialTag>
        <Tag2>0</Tag2>
    </Row>
    <Row>
        <Tag1>0</Tag1>
        <SpecialTag>01234</SpecialTag>
        <Tag2>0</Tag2>
    </Row>
</Root>

Body:
Using xsltproc (Suggested solution!):

Having XLST file transform.xsl:

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <!-- Matches the SpecialTag -->
    <xsl:template match="SpecialTag">
        <xsl:copy>
            <!-- The number is available using node() and format-number() applies the 0-padding -->
            <xsl:value-of select="format-number(node(), '00000')" />
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>

Run the following, provided that input.xml contains your XML:

$ xsltproc transform.xml input.xml

Unsafe solutions:

Those rely on the fact that opening tag <SpecialTag> and closing tag </SpecialTag> are on the same line and that there is only one of them per line.

The solutions below are only mentioned because the author explicitly tagged the question with sed/bash/shell. Those are not the right tools to achieve the job!

They all work with regular expressions to catch <SpecialTag>, followed by several numbers then </SpecialTag> and transform the numbers caught with a 0-padded version of those numbers.

Using sed:

sed --regexp-extended 's@<SpecialTag>([0-9]+)</SpecialTag>@<SpecialTag>0000000\1</SpecialTag>@;s@0*([0-9]{5,})@\1@'

Using perl:

perl -pe 's@<SpecialTag>([0-9]+)</SpecialTag>@sprintf("<SpecialTag>%05d</SpecialTag>",$1)@e'

Using awk:

awk '{gsub( /<SpecialTag>[0-9]+<\/SpecialTag>/, sprintf("<SpecialTag>%05d</SpecialTag>", gensub(/[^0-9]/, "","g"))); print}'


问:
Fastify response schema with $merge-keyword throws FST_ERR_SCH_BUILD
When adding a response schema to a fastify resource that leverages the $merge keyword, an error

```<code>FST_ERR_SCH_BUILD: Failed building the schema for GET: /, due error undefined unsupported
</code>```

is thrown.

Schema looks like the following, but the same error is thrown using the examples from ajv or fastify.

response: {
        200: {
            $merge: {
                source: {
                    type: 'object',
                    properties: {
                        foo: { type: 'string' }
                    }
                },
                with: {
                    type: 'object',
                    properties: {
                        bar: { type: 'string' }
                    }
                }
            }
        }
    }
```

workaround described in own answer

答:
The serializer doesn't implement the ajv's schema customization (as it is $merge). Under the hood fast-json-stringify is used by default.

You should use standard JSON schema and its combining keywords.

In fastify v2 the serializer that uses the schemas is not customizable, so you should write your own serializer and set up it using setReplySerializer.

Body:
When adding a response schema to a fastify resource that leverages the $merge keyword, an error

FST_ERR_SCH_BUILD: Failed building the schema for GET: /, due error undefined unsupported

is thrown.

Schema looks like the following, but the same error is thrown using the examples from ajv or fastify.

response: {
        200: {
            $merge: {
                source: {
                    type: 'object',
                    properties: {
                        foo: { type: 'string' }
                    }
                },
                with: {
                    type: 'object',
                    properties: {
                        bar: { type: 'string' }
                    }
                }
            }
        }
    }

workaround described in own answer


问:
Can anyone tell me why I get IndexError: list index out of range?
Trying to replicate this repository: https://github.com/sujiongming/UCF-101_video_classification. I get the following error when I run the CNN_train_UCF101.py file.

```<code>Traceback (most recent call last):
  File "CNN_train_UCF101.py", line 18, in <module>
    data = DataSet()
  File "D:\Clones\UCF-101_video_classification-master\UCFdata.py", line 32, in __init__
    self.classes = self.get_classes()
  File "D:\Clones\UCF-101_video_classification-master\UCFdata.py", line 64, in get_classes
    if item[1] not in classes:
IndexError: list index out of range
</code>```

part of the code referenced is as follows:

```<code>def get_data():
        """Load our data from file."""
        with open('./data/data_file.csv', 'r') as fin:
            reader = csv.reader(fin)
            data = list(reader)
def clean_data(self):
        """Limit samples to greater than the sequence length and fewer
        than N frames. Also limit it to classes we want to use."""
        data_clean = []
        for item in self.data:
            if int(item[3]) >= self.seq_length and int(item[3]) <= self.max_frames \
                    and item[1] in self.classes:
                data_clean.append(item)

        return data_clean

    def get_classes(self):
        """Extract the classes from our data. If we want to limit them,
        only return the classes we need."""
        classes = []
        for item in self.data:
            if item[1] not in classes:
                classes.append(item[1])

        # Sort them.
        classes = sorted(classes)

        # Return.
        if self.class_limit is not None:
            return classes[:self.class_limit]
        else:
            return classes
</code>```

I have updated the question to give clarity on data.
When I do print (self.data) I get something like this:
['train', 'UnevenBars', 'v_UnevenBars_g22_c04', '126'], [] for each image in the dataset.

Can anyone please show me what I'm doing wrong. Thanks in advance.

```<code>Window 10
Python 3.7.6
</code>```

答:
You have a blank line in the CSV file, which is resulting in an empty list at the end of self.data.

You should skip empty items.

```<code>for item in self.data:
    if len(item) < 2:
        continue
    if item[1] not in classes:
        classes.append(item[1])
</code>```

Body:
Trying to replicate this repository: https://github.com/sujiongming/UCF-101_video_classification. I get the following error when I run the CNN_train_UCF101.py file.

Traceback (most recent call last):
  File "CNN_train_UCF101.py", line 18, in <module>
    data = DataSet()
  File "D:\Clones\UCF-101_video_classification-master\UCFdata.py", line 32, in __init__
    self.classes = self.get_classes()
  File "D:\Clones\UCF-101_video_classification-master\UCFdata.py", line 64, in get_classes
    if item[1] not in classes:
IndexError: list index out of range

part of the code referenced is as follows:

def get_data():
        """Load our data from file."""
        with open('./data/data_file.csv', 'r') as fin:
            reader = csv.reader(fin)
            data = list(reader)
def clean_data(self):
        """Limit samples to greater than the sequence length and fewer
        than N frames. Also limit it to classes we want to use."""
        data_clean = []
        for item in self.data:
            if int(item[3]) >= self.seq_length and int(item[3]) <= self.max_frames \
                    and item[1] in self.classes:
                data_clean.append(item)

        return data_clean

    def get_classes(self):
        """Extract the classes from our data. If we want to limit them,
        only return the classes we need."""
        classes = []
        for item in self.data:
            if item[1] not in classes:
                classes.append(item[1])

        # Sort them.
        classes = sorted(classes)

        # Return.
        if self.class_limit is not None:
            return classes[:self.class_limit]
        else:
            return classes

I have updated the question to give clarity on data.
When I do print (self.data) I get something like this:
['train', 'UnevenBars', 'v_UnevenBars_g22_c04', '126'], [] for each image in the dataset.

Can anyone please show me what I'm doing wrong. Thanks in advance.

Window 10
Python 3.7.6

Body:
You have a blank line in the CSV file, which is resulting in an empty list at the end of self.data.

You should skip empty items.

for item in self.data:
    if len(item) < 2:
        continue
    if item[1] not in classes:
        classes.append(item[1])


问:
Is there a possibility to group coincident lines to evaluate line "density"?

Objective

Starting from a line soup with many overlying lines. Group these coincident lines and sum the number of lines. Divide this sum to the highest sum in the assembly to get the relative amount. Use this relative amount as a measurement for the line density.

State of work

One possibility that comes to my mind is to create a "Line" Class (or use shapely LineString) to calculate the distance between line pairs. In a coincident case, P_1 and P_2 of line_i are on line_j. For the application, a small tolerance for the coincidence would be required.
In this brute force approach, many many loops have to be done which can cause performance issues (I guess) for larger assemblies. Target number range of lines is 50.000 - 150.000.

Problem

Currently, a smart approach is missing to do this task, either to

Identify coincident line pairs

And to build a smart structure containing this information to reduce the number of lines to the most significant ones with a measured density value

The resulting reduced set of lines shall be used for constructing polygons.

Unfortunately, I do not have an exemplary data set since I am already theoretically struggling. As soon as I have built an exemplary data set, I will put it online here.

Below, there is an example of a segment of the process. I have an approximated polygon represented by multiple lines. I only want to get the most "important" ones to rebuild the "most important" polygon from it. In the figure, one can see that l6 and l7 are there only once, so l8/l2 are preferred.

答:
Represent lines using rho-theta equation.

```<code>dx = x2 - x1
dy = y2 - y1
L = Sqrt(dx*dx+dy*dy)
Dis = dx*y1 - dy*x1
SD = Sign(Dis)
rho = SD * Dis / L   // always poitive
theta = atan2(-SD*dx, SD*dy)
</code>```

Fill 2D table containing some discrete set of angles and rho's like Hough Transform accumulator.

For example, make angle step 1°, so 360 rows and some hundred columns for reasonable rho range. For every line increment value of A[theta][rho] using rounding to the closest integer indices.

Then check what cell has the largest amount of votes - in describes a set of close lines.

Note that this method is much faster than Hough transform because it works with ready-to-use lines, it is linear against number of lines and cell count depends on needed precision, while Hough works with points and fills the whole trajectory in rho-theta space for every point.

Body:
Represent lines using rho-theta equation.

dx = x2 - x1
dy = y2 - y1
L = Sqrt(dx*dx+dy*dy)
Dis = dx*y1 - dy*x1
SD = Sign(Dis)
rho = SD * Dis / L   // always poitive
theta = atan2(-SD*dx, SD*dy)

Fill 2D table containing some discrete set of angles and rho's like Hough Transform accumulator.

For example, make angle step 1°, so 360 rows and some hundred columns for reasonable rho range. For every line increment value of A[theta][rho] using rounding to the closest integer indices.

Then check what cell has the largest amount of votes - in describes a set of close lines.

Note that this method is much faster than Hough transform because it works with ready-to-use lines, it is linear against number of lines and cell count depends on needed precision, while Hough works with points and fills the whole trajectory in rho-theta space for every point.


问:
Can't get access to data sent from a server as POST AJAX in JSON
I have a form on a page. I send an ajax json POST request which I want to parse on a server. I'm using no Go frameworks.

```<code>type data1 struct {
  email string
  fullName string `json:full_name`
  body string
}

  //[...............]
  var d1 data1
  err := json.NewDecoder(r.Body).Decode(&d1)
  if err != nil {
    log.Print("error#1")
    http.Error(w, err.Error(), http.StatusBadRequest)
    return
  }

  log.Printf("data#1: %+v", d1)
</code>```

I always get this in the log:

```<code>  data#1: {email: fullName: body:}
</code>```

From a server a requect gets sent correctly -- I see that in Chrome dev tools.

Why and how to fix it?

答:
In the data1 struct the fields are not exported. They must be exported to use in json decoder. Also, your json tag is not written in valid syntax.

You can change the data1 struct like following:

type data1 struct {
  Email string
  FullName string `json:"full_name"`
  Body string
}
```

Go PlayGround Link

Body:
I have a form on a page. I send an ajax json POST request which I want to parse on a server. I'm using no Go frameworks.

type data1 struct {
  email string
  fullName string `json:full_name`
  body string
}

  //[...............]
  var d1 data1
  err := json.NewDecoder(r.Body).Decode(&d1)
  if err != nil {
    log.Print("error#1")
    http.Error(w, err.Error(), http.StatusBadRequest)
    return
  }

  log.Printf("data#1: %+v", d1)

I always get this in the log:

  data#1: {email: fullName: body:}

From a server a requect gets sent correctly -- I see that in Chrome dev tools.

Why and how to fix it?

Body:
In the data1 struct the fields are not exported. They must be exported to use in json decoder. Also, your json tag is not written in valid syntax.

You can change the data1 struct like following:

type data1 struct {
  Email string
  FullName string `json:"full_name"`
  Body string
}

Go PlayGround Link


问:
How do pull images from a wordpress post to display it on the screen?
I am trying to display something like a thumbnail for my post. Is there any wordpress function that can do that? I read about wordpress featured images but I dont see the option to set one on the wordpress admin page.

I also tried using the_post_thumbnail() but it didnt work.

this is what my div looks like at the moment:

```<code><div class="card" style="width: 22rem;">
          <img src="<?php the_post_thumbnail(); ?>" class="card-img-top" alt="...">
          <div class="card-body">
            <h5 class="card-title"><?php the_title() ?></h5>
            <p class="card-text">Random Card content</p>
          </div>
</div>
</code>```

答:
the_post_thumbnail(); directly output the image.So please don't use echo</p>

```<code>the_post_thumbnail( $size, $attr );
the_post_thumbnail( 'thumbnail' );

<div class="card" style="width: 22rem;">
   <?php the_post_thumbnail('thumbnail'); ?>
          <div class="card-body">
            <h5 class="card-title"><?php the_title() ?></h5>
            <p class="card-text">Random Card content</p>
          </div>
</div>
</code>```

Body:
I am trying to display something like a thumbnail for my post. Is there any wordpress function that can do that? I read about wordpress featured images but I dont see the option to set one on the wordpress admin page.

I also tried using the_post_thumbnail() but it didnt work.

this is what my div looks like at the moment:

          <img src="<?php the_post_thumbnail(); ?>" class="card-img-top" alt="...">

<?php the_title() ?>

Random Card content

Body:
the_post_thumbnail(); directly output the image.So please don't use echo

the_post_thumbnail( $size, $attr );
the_post_thumbnail( 'thumbnail' );

<div class="card" style="width: 22rem;">
   <?php the_post_thumbnail('thumbnail'); ?>
          <div class="card-body">
            <h5 class="card-title"><?php the_title() ?></h5>
            <p class="card-text">Random Card content</p>
          </div>
</div>


问:
Pubsub publish multiple events Apollo Server
I am using Apollo Server and I want to publish 2 events in the row from same resolver. Both subscriptions are working fine but only if I dispatch only one event. If I try to dispatch both, second subscription resolver never gets called. If I comment out the first event dispatch second works normally.

const publishMessageNotification = async (message, me, action) => {
  const notification = await models.Notification.create({
    ownerId: message.userId,
    messageId: message.id,
    userId: me.id,
    action,
  });

 // if I comment out this one, second pubsub.publish starts firing
  pubsub.publish(EVENTS.NOTIFICATION.CREATED, {
    notificationCreated: { notification },
  });

  const unseenNotificationsCount = await models.Notification.find({
    ownerId: notification.ownerId,
    isSeen: false,
  }).countDocuments();

  console.log('unseenNotificationsCount', unseenNotificationsCount);// logs correct value

  // this one is not working if first one is present
  pubsub.publish(EVENTS.NOTIFICATION.NOT_SEEN_UPDATED, {
    notSeenUpdated: unseenNotificationsCount,
  });
};
```

<p>I am using default pubsub implementation. There are no errors in the console.</p>

<pre class="lang-js prettyprint-override"><code>import { PubSub } from 'apollo-server';

import * as MESSAGE_EVENTS from './message';
import * as NOTIFICATION_EVENTS from './notification';

export const EVENTS = {
  MESSAGE: MESSAGE_EVENTS,
  NOTIFICATION: NOTIFICATION_EVENTS,
};

export default new PubSub();
</code>```

答:
Make sure, that you use pubsub from context of apollo server, for example:

Server:

```<code>const server = new ApolloServer({
  schema: schemaWithMiddleware,
  subscriptions: {
    path: PATH,
    ...subscriptionOptions,
  },
  context: http => ({
    http,
    pubsub,
    redisCache,
  }),
  engine: {
    apiKey: ENGINE_API_KEY,
    schemaTag: process.env.NODE_ENV,
  },
  playground: process.env.NODE_ENV === 'DEV',
  tracing: process.env.NODE_ENV === 'DEV',
  debug: process.env.NODE_ENV === 'DEV',
});
</code>```

and example use in resolver, by context:

```<code>...
const Mutation = {
  async createOrder(parent, { input }, context) {
    ...
    try {
       ...
        context.pubsub.publish(CHANNEL_NAME, {
          newMessage: {
            messageCount: 0,
          },
          participants,
        });
        dialog.lastMessage = `{ "orderID": ${parentID}, "text": "created" }`;
        context.pubsub.publish(NOTIFICATION_CHANNEL_NAME, {
          notification: { messageCount: 0, dialogID: dialog.id },
          participants,
        });
        ...
      }
      return result;
    } catch (err) {
      log.error(err);
      return sendError(err);
    }
  },
};
...
</code>```

Body:
I am using Apollo Server and I want to publish 2 events in the row from same resolver. Both subscriptions are working fine but only if I dispatch only one event. If I try to dispatch both, second subscription resolver never gets called. If I comment out the first event dispatch second works normally.

const publishMessageNotification = async (message, me, action) => {
  const notification = await models.Notification.create({
    ownerId: message.userId,
    messageId: message.id,
    userId: me.id,
    action,
  });

 // if I comment out this one, second pubsub.publish starts firing
  pubsub.publish(EVENTS.NOTIFICATION.CREATED, {
    notificationCreated: { notification },
  });

  const unseenNotificationsCount = await models.Notification.find({
    ownerId: notification.ownerId,
    isSeen: false,
  }).countDocuments();

  console.log('unseenNotificationsCount', unseenNotificationsCount);// logs correct value

  // this one is not working if first one is present
  pubsub.publish(EVENTS.NOTIFICATION.NOT_SEEN_UPDATED, {
    notSeenUpdated: unseenNotificationsCount,
  });
};

I am using default pubsub implementation. There are no errors in the console.

import { PubSub } from 'apollo-server';

import * as MESSAGE_EVENTS from './message';
import * as NOTIFICATION_EVENTS from './notification';

export const EVENTS = {
  MESSAGE: MESSAGE_EVENTS,
  NOTIFICATION: NOTIFICATION_EVENTS,
};

export default new PubSub();

Body:
Make sure, that you use pubsub from context of apollo server, for example:

Server:

const server = new ApolloServer({
  schema: schemaWithMiddleware,
  subscriptions: {
    path: PATH,
    ...subscriptionOptions,
  },
  context: http => ({
    http,
    pubsub,
    redisCache,
  }),
  engine: {
    apiKey: ENGINE_API_KEY,
    schemaTag: process.env.NODE_ENV,
  },
  playground: process.env.NODE_ENV === 'DEV',
  tracing: process.env.NODE_ENV === 'DEV',
  debug: process.env.NODE_ENV === 'DEV',
});

and example use in resolver, by context:

...
const Mutation = {
  async createOrder(parent, { input }, context) {
    ...
    try {
       ...
        context.pubsub.publish(CHANNEL_NAME, {
          newMessage: {
            messageCount: 0,
          },
          participants,
        });
        dialog.lastMessage = `{ "orderID": ${parentID}, "text": "created" }`;
        context.pubsub.publish(NOTIFICATION_CHANNEL_NAME, {
          notification: { messageCount: 0, dialogID: dialog.id },
          participants,
        });
        ...
      }
      return result;
    } catch (err) {
      log.error(err);
      return sendError(err);
    }
  },
};
...


问:
Catching Warnings in Function skimage.img_as_uint
I tried both warnings.catch_warnings() and the input parameter force_copy
both failed to catch conversion warnings

```<code>import numpy as np
import skimage
import warnings

mm = np.ones([55,55],dtype=np.float32)
with warnings.catch_warnings():
     dd = skimage.img_as_uint(mm,force_copy=True)
</code>```

gives

```<code>XXX/lib/python2.7/site-packages/skimage/util/dtype.py:130: UserWarning: Possible precision loss
when converting from float32 to uint16.format(dtypeobj_in, dtypeobj_out))

</code>```

答:
You need to add a line, warnings.simplefilter('ignore'):

import numpy as np
import skimage
import warnings

mm = np.ones([55,55],dtype=np.float32)
with warnings.catch_warnings():
    warnings.simplefilter('ignore')
    dd = skimage.img_as_uint(mm,force_copy=True)
```

See the Python documentation for "temporarily suppressing warnings" for more information.

Body:
I tried both warnings.catch_warnings() and the input parameter force_copy
both failed to catch conversion warnings

import numpy as np
import skimage
import warnings

mm = np.ones([55,55],dtype=np.float32)
with warnings.catch_warnings():
     dd = skimage.img_as_uint(mm,force_copy=True)

gives

XXX/lib/python2.7/site-packages/skimage/util/dtype.py:130: UserWarning: Possible precision loss
when converting from float32 to uint16.format(dtypeobj_in, dtypeobj_out))

Body:
You need to add a line, warnings.simplefilter('ignore'):

import numpy as np
import skimage
import warnings

mm = np.ones([55,55],dtype=np.float32)
with warnings.catch_warnings():
    warnings.simplefilter('ignore')
    dd = skimage.img_as_uint(mm,force_copy=True)

See the Python documentation for "temporarily suppressing warnings" for more information.


问:
how to set initialRouteName dynamically in the react-native
how to give dynamic initial route name in the react-navigation? if the unit exists we have to redirect to another route or else we have to take user another route.

Note: I'm creating a bottom tab navigator in which I have to set an initial route to that particular bottom tab navigator.

(Not the authentication flow)

```<code>import React, {Component} from 'react';
import {createAppContainer} from 'react-navigation';
import {createMaterialBottomTabNavigator} from 'react-navigation-material-bottom-tabs';
... imports
function getInitialScreen() {
  AsyncStorage.getItem('unit')
    .then(unit => {
      return unit ? 'Home' : 'secondTab';
    })
    .catch(err => {

    });
}

const TabNavigator = createMaterialBottomTabNavigator(
  {
    Home: {
       screen: HomeScreen,
       navigationOptions: {
        .....navigation options
       },
     },
    secondTab: {
      screen: secondTab,
    },
  },
  {
    initialRouteName: getInitialScreen(),
  },
);
export default createAppContainer(TabNavigator);
</code>```

答:
See according to the docs, initialRoute name should not be a async func .

So ideally what you should do is , anyways you need a splashscreen for your app right, where you display the logo and name of app. Make that page the initialRoute and in its componentDidMount, check for the async function and navigate to ddesired page.

Like what ive done :

```<code>createSwitchNavigator(
    {
      App: TabNavigator,
      Auth: AuthStack,
      SplashScreen: SplashScreen,
    },
    {
      initialRouteName: 'SplashScreen',
    },
  ),
</code>```

And inside SplashScreen im doing :

```<code>componentDidMount(){
 if (token) {
      this.props.navigation.navigate('App');
    } else {
      this.props.navigation.navigate('Auth');
    }

}
</code>```

Hope its clear. Feel free for doubts

Body:
how to give dynamic initial route name in the react-navigation? if the unit exists we have to redirect to another route or else we have to take user another route.

Note: I'm creating a bottom tab navigator in which I have to set an initial route to that particular bottom tab navigator.

(Not the authentication flow)

import React, {Component} from 'react';
import {createAppContainer} from 'react-navigation';
import {createMaterialBottomTabNavigator} from 'react-navigation-material-bottom-tabs';
... imports
function getInitialScreen() {
  AsyncStorage.getItem('unit')
    .then(unit => {
      return unit ? 'Home' : 'secondTab';
    })
    .catch(err => {

    });
}

const TabNavigator = createMaterialBottomTabNavigator(
  {
    Home: {
       screen: HomeScreen,
       navigationOptions: {
        .....navigation options
       },
     },
    secondTab: {
      screen: secondTab,
    },
  },
  {
    initialRouteName: getInitialScreen(),
  },
);
export default createAppContainer(TabNavigator);

Body:
See according to the docs, initialRoute name should not be a async func .

So ideally what you should do is , anyways you need a splashscreen for your app right, where you display the logo and name of app. Make that page the initialRoute and in its componentDidMount, check for the async function and navigate to ddesired page.

Like what ive done :

createSwitchNavigator(
    {
      App: TabNavigator,
      Auth: AuthStack,
      SplashScreen: SplashScreen,
    },
    {
      initialRouteName: 'SplashScreen',
    },
  ),

And inside SplashScreen im doing :

componentDidMount(){
 if (token) {
      this.props.navigation.navigate('App');
    } else {
      this.props.navigation.navigate('Auth');
    }

}

Hope its clear. Feel free for doubts


问:
react native how to check FLog on android?
I want to see and check Logs on android native codes using terminal or something. How can I do?

I know adb logcat -s ReactNative:V ReactNativeJS:V but this is warnings on js side, not native side.

```<code>    try {
      updateInstanceHandle(resolveView(tag), instanceHandle);
    } catch (IllegalViewOperationException e) {
      FLog.e(TAG, "Unable to update properties for view tag " + tag, e); // <------- I want to see this !!!!!!
    }
</code>```

I expect the logs on terminal but do not know how can I do that.

答:
You can set your own LoggingDelegate in your Application class using FLog.setLoggingDelegate(YourCustomLogger())

YourCustomLogger would implement LoggingDelegate and you could just use the normal Log for each override method. This will show all the RN logs for you.

Body:
I want to see and check Logs on android native codes using terminal or something. How can I do?

I know adb logcat -s ReactNative:V ReactNativeJS:V but this is warnings on js side, not native side.

    try {
      updateInstanceHandle(resolveView(tag), instanceHandle);
    } catch (IllegalViewOperationException e) {
      FLog.e(TAG, "Unable to update properties for view tag " + tag, e); // <------- I want to see this !!!!!!
    }

I expect the logs on terminal but do not know how can I do that.


问:
Form CCS Style Request
The form right at the top of this page was made with aweber. I want to create a form like this, but I cannot get the sign up part to the right of the email field as in the example page. (mean horizontal form)

Sample page: https://www.backlinko.com/

I want to be able to do the same form you see in the sample page. How can I change where?

<form method="post" class="af-form-wrapper" accept-charset="UTF-8" action="https://www.aweber.com/scripts/addlead.pl" target="_blank" >

<input type="hidden" name="meta_web_form_id" value="586791810" />
<input type="hidden" name="meta_split_id" value="" />
<input type="hidden" name="listname" value="awlist5545047" />
<input type="hidden" name="redirect" value="https://www.aweber.com/form/thankyou_vo.html" id="redirect_06888bc1326c8dabe3e277c31b9118ce" />

<input type="hidden" name="meta_adtracking" value="My Web Form" />
<input type="hidden" name="meta_message" value="1" />
<input type="hidden" name="meta_required" value="email" />
<input type="hidden" name="meta_forward_vars" value="1" />
<input type="hidden" name="meta_tooltip" value="" />

Email:

<input class="text" id="awf_field-105496004" type="text" name="email" value="" tabindex="500" onfocus=" if (this.value == '') { this.value = ''; }" onblur="if (this.value == '') { this.value='';} " />

<input name="submit" class="submit" type="submit" value="Abone Ol!" tabindex="501" />

</form>

```

thanks for helping

答:
Well you can achieve this with position absolute. In your example the button is over the input.

It's not a good idea as if you write a long email the text goes ' behind ' the button.
So what you can do is add a padding-right equal to the button width.

See below

TIP: Do not share unnecessary code. 90% of what you shared is not related to your question and therefor useless. Also, please FORMAT FORMAT FORMAT your code. When you post questions and also in your own project.

.buttonContainer {
  position: absolute;
  bottom:25px;
  right:60px;
  padding:0!important;
  }
.af-body.af-standards {
position: relative;
}
.af-body.af-standards input.text {
padding: 4px 130px 4px 2px!important;
box-sizing:border-box;
}
#af-form-586791810 .af-body .af-textWrap {
  width: 98%;
  display: block;
  float: none;
}

#af-form-586791810 .af-body input.text,
#af-form-586791810 .af-body textarea {
  background-color: #FFFFFF;
  border-color: #454545;
  border-width: 1px;
  border-style: solid;
  color: #454545;
  text-decoration: none;
  font-style: normal;
  font-weight: normal;
  font-size: 24px;
  font-family: Trebuchet MS, sans-serif;
}

#af-form-586791810 .af-body input.text:focus,
#af-form-586791810 .af-body textarea:focus {
  background-color: #FFFFFF;
  border-color: #454545;
  border-width: 1px;
  border-style: solid;
}

#af-form-586791810 .af-body label.previewLabel {
  display: block;
  float: none;
  text-align: left;
  width: auto;
  color: #454545;
  text-decoration: none;
  font-style: normal;
  font-weight: normal;
  font-size: 16px;
  font-family: Helvetica, sans-serif;
}

#af-form-586791810 .af-body {
  padding-bottom: 15px;
  padding-top: 15px;
  background-repeat: no-repeat;
  background-position: inherit;
  background-image: none;
  color: inherit;
  font-size: 16px;
  font-family: Helvetica, sans-serif;
}

#af-form-586791810 .af-quirksMode {
  padding-right: 60px;
  padding-left: 60px;
}

#af-form-586791810 .af-standards .af-element {
  padding-right: 60px;
  padding-left: 60px;
}

#af-form-586791810 .buttonContainer input.submit {
  background-image: none;
  background-color: #4D0B4D;
  color: #FFFFFF;
  text-decoration: none;
  font-style: normal;
  font-weight: normal;
  font-size: 16px;
  font-family: Trebuchet MS, sans-serif;
}

#af-form-586791810 .buttonContainer input.submit {
  width: auto;
}

#af-form-586791810 .buttonContainer {
  text-align: center;
}

#af-form-586791810 button,
#af-form-586791810 input,
#af-form-586791810 submit,
#af-form-586791810 textarea,
#af-form-586791810 select,
#af-form-586791810 label,
#af-form-586791810 optgroup,
#af-form-586791810 option {
  float: none;
  position: static;
  margin: 0;
}

#af-form-586791810 div {
  margin: 0;
}

#af-form-586791810 form,
#af-form-586791810 textarea,
.af-form-wrapper,
.af-form-close-button,
#af-form-586791810 img {
  float: none;
  color: inherit;
  position: static;
  background-color: none;
  border: none;
  margin: 0;
  padding: 0;
}

#af-form-586791810 input,
#af-form-586791810 button,
#af-form-586791810 textarea,
#af-form-586791810 select {
  font-size: 100%;
}

#af-form-586791810 select,
#af-form-586791810 label,
#af-form-586791810 optgroup,
#af-form-586791810 option {
  padding: 0;
}

#af-form-586791810,
#af-form-586791810 .quirksMode {
  width: 100%;
  max-width: 418px;
}

#af-form-586791810.af-quirksMode {
  overflow-x: hidden;
}

#af-form-586791810 {
  background-color: #FFFFFF;
  border-color: #454545;
  border-width: 1px;
  border-style: none;
}

#af-form-586791810 {
  display: block;
}

#af-form-586791810 {
  overflow: hidden;
}

.af-body .af-textWrap {
  text-align: left;
}

.af-body input.image {
  border: none !important;
}

.af-body input.submit,
.af-body input.image,
.af-form .af-element input.button {
  float: none !important;
}

.af-body input.submit {
  white-space: inherit;
}

.af-body input.text {
  width: 100%;
  float: none;
  padding: 2px !important;
}

.af-body.af-standards input.submit {
  padding: 4px 12px;
}

.af-clear {
  clear: both;
}

.af-element label {
  text-align: left;
  display: block;
  float: left;
}

.af-element {
  padding-bottom: 5px;
  padding-top: 5px;
}

.af-form-wrapper {
  text-indent: 0;
}

.af-form {
  box-sizing: border-box;
  text-align: left;
  margin: auto;
}

.af-quirksMode .af-element {
  padding-left: 0 !important;
  padding-right: 0 !important;
}

.lbl-right .af-element label {
  text-align: right;
}

body {}

#af-form-586791810 input.submit,
#af-form-586791810 #webFormSubmitButton {
  -webkit-appearance: none;
}

.af-form {
  border-radius: 12px;
}

.af-header {
  -webkit-clip-path: polygon(0 0, 100% 0, 100% 80%, 0% 100%);
  clip-path: polygon(0 0, 100% 0, 100% 80%, 0% 100%);
}

.af-header p {
  padding-top: 25px;
  padding-right: 50px;
  padding-bottom: 40px;
  padding-left: 50px;
}

.af-body input.text,
.af-body textarea {
  border-radius: 4px;
}

.af-element {
  padding-top: 10px;
  padding-bottom: 10px;
}

#af-form-586791810 select,
#af-form-586791810 label,
#af-form-586791810 optgroup,
#af-form-586791810 option {
  padding-bottom: 5px;
}

#af-form-586791810 p {
  margin: 0;
}

#af-form-586791810 .af-body .privacyPolicy {
  font-size: 9px;
  padding-top: 20px;
  padding-bottom: 10px;
}

#af-form-586791810 .af-body .poweredBy {
  font-size: 9px;
  padding-top: 0;
  padding-bottom: 0;
}

#af-form #webFormSubmitButton,
.buttonContainer input.submit,
.af-body.af-standards input.submit {
  border: none;
  border-radius: 4px;
  padding: 10px 30px;
}

.bodyText p strong {
  letter-spacing: 0.03em;
  line-height: 1.25;
}

.af-form .af-element-radio {
  padding-bottom: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form method="post" class="af-form-wrapper" accept-charset="UTF-8" action="https://www.aweber.com/scripts/addlead.pl" target="_blank">
  <div style="display: none;">
    <input type="hidden" name="meta_web_form_id" value="586791810" />
    <input type="hidden" name="meta_split_id" value="" />
    <input type="hidden" name="listname" value="awlist5545047" />
    <input type="hidden" name="redirect" value="https://www.aweber.com/form/thankyou_vo.html" id="redirect_06888bc1326c8dabe3e277c31b9118ce" />

    <input type="hidden" name="meta_adtracking" value="My Web Form" />
    <input type="hidden" name="meta_message" value="1" />
    <input type="hidden" name="meta_required" value="email" />
    <input type="hidden" name="meta_forward_vars" value="1" />
    <input type="hidden" name="meta_tooltip" value="" />
  </div>
  <div id="af-form-586791810" class="af-form">
    <div id="af-body-586791810" class="af-body af-standards">
      <div class="af-element">
        <label class="previewLabel" for="awf_field-105496004">Email: </label>
        <div class="af-textWrap"><input class="text" id="awf_field-105496004" type="text" name="email" value="" tabindex="500" onfocus=" if (this.value == '') { this.value = ''; }" onblur="if (this.value == '') { this.value='';} " />
        </div>
        <div class="af-clear"></div>
      </div>
      <div class="af-element buttonContainer">
        <input name="submit" class="submit" type="submit" value="Abone Ol!" tabindex="501" />
        <div class="af-clear"></div>
      </div>
    </div>
  </div>
  <div style="display: none;"><img src="https://forms.aweber.com/form/displays.htm?id=rBxs7JyMHIwM" alt="" /></div>
</form></code>```

Title: Form CCS Style Request

Body:
The form right at the top of this page was made with aweber. I want to create a form like this, but I cannot get the sign up part to the right of the email field as in the example page. (mean horizontal form)

Sample page: https://www.backlinko.com/

I want to be able to do the same form you see in the sample page. How can I change where?

<form method="post" class="af-form-wrapper" accept-charset="UTF-8" action="https://www.aweber.com/scripts/addlead.pl" target="_blank" >

<input type="hidden" name="meta_web_form_id" value="586791810" />
<input type="hidden" name="meta_split_id" value="" />
<input type="hidden" name="listname" value="awlist5545047" />
<input type="hidden" name="redirect" value="https://www.aweber.com/form/thankyou_vo.html" id="redirect_06888bc1326c8dabe3e277c31b9118ce" />

<input type="hidden" name="meta_adtracking" value="My Web Form" />
<input type="hidden" name="meta_message" value="1" />
<input type="hidden" name="meta_required" value="email" />
<input type="hidden" name="meta_forward_vars" value="1" />
<input type="hidden" name="meta_tooltip" value="" />

Email:

<input class="text" id="awf_field-105496004" type="text" name="email" value="" tabindex="500" onfocus=" if (this.value == '') { this.value = ''; }" onblur="if (this.value == '') { this.value='';} " />

<input name="submit" class="submit" type="submit" value="Abone Ol!" tabindex="501" />

</form>

thanks for helping

Body:
Well you can achieve this with position absolute. In your example the button is over the input.

It's not a good idea as if you write a long email the text goes ' behind ' the button.
So what you can do is add a padding-right equal to the button width.

See below

TIP: Do not share unnecessary code. 90% of what you shared is not related to your question and therefor useless. Also, please FORMAT FORMAT FORMAT your code. When you post questions and also in your own project.

.buttonContainer {
  position: absolute;
  bottom:25px;
  right:60px;
  padding:0!important;
  }
.af-body.af-standards {
position: relative;
}
.af-body.af-standards input.text {
padding: 4px 130px 4px 2px!important;
box-sizing:border-box;
}
#af-form-586791810 .af-body .af-textWrap {
  width: 98%;
  display: block;
  float: none;
}

#af-form-586791810 .af-body input.text,
#af-form-586791810 .af-body textarea {
  background-color: #FFFFFF;
  border-color: #454545;
  border-width: 1px;
  border-style: solid;
  color: #454545;
  text-decoration: none;
  font-style: normal;
  font-weight: normal;
  font-size: 24px;
  font-family: Trebuchet MS, sans-serif;
}

#af-form-586791810 .af-body input.text:focus,
#af-form-586791810 .af-body textarea:focus {
  background-color: #FFFFFF;
  border-color: #454545;
  border-width: 1px;
  border-style: solid;
}

#af-form-586791810 .af-body label.previewLabel {
  display: block;
  float: none;
  text-align: left;
  width: auto;
  color: #454545;
  text-decoration: none;
  font-style: normal;
  font-weight: normal;
  font-size: 16px;
  font-family: Helvetica, sans-serif;
}

#af-form-586791810 .af-body {
  padding-bottom: 15px;
  padding-top: 15px;
  background-repeat: no-repeat;
  background-position: inherit;
  background-image: none;
  color: inherit;
  font-size: 16px;
  font-family: Helvetica, sans-serif;
}

#af-form-586791810 .af-quirksMode {
  padding-right: 60px;
  padding-left: 60px;
}

#af-form-586791810 .af-standards .af-element {
  padding-right: 60px;
  padding-left: 60px;
}

#af-form-586791810 .buttonContainer input.submit {
  background-image: none;
  background-color: #4D0B4D;
  color: #FFFFFF;
  text-decoration: none;
  font-style: normal;
  font-weight: normal;
  font-size: 16px;
  font-family: Trebuchet MS, sans-serif;
}

#af-form-586791810 .buttonContainer input.submit {
  width: auto;
}

#af-form-586791810 .buttonContainer {
  text-align: center;
}

#af-form-586791810 button,
#af-form-586791810 input,
#af-form-586791810 submit,
#af-form-586791810 textarea,
#af-form-586791810 select,
#af-form-586791810 label,
#af-form-586791810 optgroup,
#af-form-586791810 option {
  float: none;
  position: static;
  margin: 0;
}

#af-form-586791810 div {
  margin: 0;
}

#af-form-586791810 form,
#af-form-586791810 textarea,
.af-form-wrapper,
.af-form-close-button,
#af-form-586791810 img {
  float: none;
  color: inherit;
  position: static;
  background-color: none;
  border: none;
  margin: 0;
  padding: 0;
}

#af-form-586791810 input,
#af-form-586791810 button,
#af-form-586791810 textarea,
#af-form-586791810 select {
  font-size: 100%;
}

#af-form-586791810 select,
#af-form-586791810 label,
#af-form-586791810 optgroup,
#af-form-586791810 option {
  padding: 0;
}

#af-form-586791810,
#af-form-586791810 .quirksMode {
  width: 100%;
  max-width: 418px;
}

#af-form-586791810.af-quirksMode {
  overflow-x: hidden;
}

#af-form-586791810 {
  background-color: #FFFFFF;
  border-color: #454545;
  border-width: 1px;
  border-style: none;
}

#af-form-586791810 {
  display: block;
}

#af-form-586791810 {
  overflow: hidden;
}

.af-body .af-textWrap {
  text-align: left;
}

.af-body input.image {
  border: none !important;
}

.af-body input.submit,
.af-body input.image,
.af-form .af-element input.button {
  float: none !important;
}

.af-body input.submit {
  white-space: inherit;
}

.af-body input.text {
  width: 100%;
  float: none;
  padding: 2px !important;
}

.af-body.af-standards input.submit {
  padding: 4px 12px;
}

.af-clear {
  clear: both;
}

.af-element label {
  text-align: left;
  display: block;
  float: left;
}

.af-element {
  padding-bottom: 5px;
  padding-top: 5px;
}

.af-form-wrapper {
  text-indent: 0;
}

.af-form {
  box-sizing: border-box;
  text-align: left;
  margin: auto;
}

.af-quirksMode .af-element {
  padding-left: 0 !important;
  padding-right: 0 !important;
}

.lbl-right .af-element label {
  text-align: right;
}

body {}

#af-form-586791810 input.submit,
#af-form-586791810 #webFormSubmitButton {
  -webkit-appearance: none;
}

.af-form {
  border-radius: 12px;
}

.af-header {
  -webkit-clip-path: polygon(0 0, 100% 0, 100% 80%, 0% 100%);
  clip-path: polygon(0 0, 100% 0, 100% 80%, 0% 100%);
}

.af-header p {
  padding-top: 25px;
  padding-right: 50px;
  padding-bottom: 40px;
  padding-left: 50px;
}

.af-body input.text,
.af-body textarea {
  border-radius: 4px;
}

.af-element {
  padding-top: 10px;
  padding-bottom: 10px;
}

#af-form-586791810 select,
#af-form-586791810 label,
#af-form-586791810 optgroup,
#af-form-586791810 option {
  padding-bottom: 5px;
}

#af-form-586791810 p {
  margin: 0;
}

#af-form-586791810 .af-body .privacyPolicy {
  font-size: 9px;
  padding-top: 20px;
  padding-bottom: 10px;
}

#af-form-586791810 .af-body .poweredBy {
  font-size: 9px;
  padding-top: 0;
  padding-bottom: 0;
}

#af-form #webFormSubmitButton,
.buttonContainer input.submit,
.af-body.af-standards input.submit {
  border: none;
  border-radius: 4px;
  padding: 10px 30px;
}

.bodyText p strong {
  letter-spacing: 0.03em;
  line-height: 1.25;
}

.af-form .af-element-radio {
  padding-bottom: 5px;
}

<form method="post" class="af-form-wrapper" accept-charset="UTF-8" action="https://www.aweber.com/scripts/addlead.pl" target="_blank">
  <div style="display: none;">
    <input type="hidden" name="meta_web_form_id" value="586791810" />
    <input type="hidden" name="meta_split_id" value="" />
    <input type="hidden" name="listname" value="awlist5545047" />
    <input type="hidden" name="redirect" value="https://www.aweber.com/form/thankyou_vo.html" id="redirect_06888bc1326c8dabe3e277c31b9118ce" />

    <input type="hidden" name="meta_adtracking" value="My Web Form" />
    <input type="hidden" name="meta_message" value="1" />
    <input type="hidden" name="meta_required" value="email" />
    <input type="hidden" name="meta_forward_vars" value="1" />
    <input type="hidden" name="meta_tooltip" value="" />
  </div>
  <div id="af-form-586791810" class="af-form">
    <div id="af-body-586791810" class="af-body af-standards">
      <div class="af-element">
        <label class="previewLabel" for="awf_field-105496004">Email: </label>
        <div class="af-textWrap"><input class="text" id="awf_field-105496004" type="text" name="email" value="" tabindex="500" onfocus=" if (this.value == '') { this.value = ''; }" onblur="if (this.value == '') { this.value='';} " />
        </div>
        <div class="af-clear"></div>
      </div>
      <div class="af-element buttonContainer">
        <input name="submit" class="submit" type="submit" value="Abone Ol!" tabindex="501" />
        <div class="af-clear"></div>
      </div>
    </div>
  </div>
  <div style="display: none;"><img src="https://forms.aweber.com/form/displays.htm?id=rBxs7JyMHIwM" alt="" /></div>
</form>