问:
WebClient.DownloadString with HTTPS "The authentication or decryption has failed"
I am creating a game using the Unity Engine(2017.2.0f3) on Windows 10 in which I am trying to get the HTML from a webpage. To my knowledge, Unity uses the "Mono" C# compiler and runtime v2.0 (according to the results of running mono --version in Unity\Editor\Data\Mono\bin), but also v5.0.1 (according to the results of running mono --version in Unity\Editor\Data\MonoBleedingEdge\bin). I am currently using the HTML Agility Pack for parsing. When attempting to access an HTTP secured website, such as dictionary.com, everything works as expected, but no matter what I do, I cannot access an HTTPS secured website, such as urbandictionary.com(Edit: Apparently, the problem is specific to this site, because after importing certificates using mozroots, github.com can be accessed), and always receive the exception: TlsException: The authentication or decryption has failed. I am aware that the HTML Agility Pack does not support HTTPS, and have wrote my code according to this answer. I've tried the solution described here and here, but to no avail. I've tried running mozroots, which I located in PathTo/Unity/Editor/Data/MonoBleedingEdge/lib/mono/4.5/mozroots, with the --import, --sync, and --quiet flags, but the same exception is thrown (if this did work, I'm skeptical about its portability, but perhaps I could implement my own version of mozroots, as suggested by the comments). Also, I've been informed that the version of Mono that Unity uses does not support TLS 1.2, which is problematic. If there is no solution to this problem, are there any workarounds?

Note: abridged for clarity

```<code>class MyWebClient : WebClient
{
    protected override WebRequest GetWebRequest(Uri address)
    {
        HttpWebRequest request = base.GetWebRequest(address) as HttpWebRequest;
        request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
        return request;
    }
}

class GetHtml
{
    public static void Get(string url)
    {
        string documentString = new MyWebClient().DownloadString(url);
        ...
    }
}

class CallingClass
{
     public void CallingMethod()
     {
         ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
         //With or without the above line ^, the same TlsException is thrown.
         GetHtml.Get("https://www.urbandictionary.com/define.php?term=example");
         //HTTP works properly, but HTTPS, as in this example, does not.
     }
}
</code>```

The log is as follows:

```<code>TlsException: The authentication or decryption has failed.
Mono.Security.Protocol.Tls.RecordProtocol.ProcessAlert (AlertLevel alertLevel, AlertDescription alertDesc)
Mono.Security.Protocol.Tls.RecordProtocol.InternalReceiveRecordCallback (IAsyncResult asyncResult)
Rethrow as IOException: The authentication or decryption has failed.
Mono.Security.Protocol.Tls.SslStreamBase.AsyncHandshakeCallback (IAsyncResult asyncResult)
Rethrow as WebException: Error getting response stream (Write: The authentication or decryption has failed.): SendFailure
System.Net.HttpWebRequest.EndGetResponse (IAsyncResult asyncResult)
System.Net.HttpWebRequest.GetResponse ()
System.Net.WebClient.GetWebResponse (System.Net.WebRequest request)
System.Net.WebClient.DownloadDataCore (System.Uri address, System.Object userToken)
</code>```

Edit: I've tried updating the runtime version. The only option was to change from .Net 3.5 to 4.6 in the Project Settings->Player menu, which is experimental. I still get an exception when the code is run, but the output log is a little different.

```<code>TlsException: The authentication or decryption has failed.
Mono.Security.Protocol.Tls.RecordProtocol.EndReceiveRecord (System.IAsyncResult asyncResult) (at <eb1224ae7b184cd09343d47f8a05481b>:0)
Mono.Security.Protocol.Tls.SslClientStream.SafeEndReceiveRecord (System.IAsyncResult ar, System.Boolean ignoreEmpty) (at <eb1224ae7b184cd09343d47f8a05481b>:0)
Mono.Security.Protocol.Tls.SslClientStream.NegotiateAsyncWorker (System.IAsyncResult result) (at <eb1224ae7b184cd09343d47f8a05481b>:0)
Rethrow as IOException: The authentication or decryption has failed.
Mono.Security.Protocol.Tls.SslClientStream.EndNegotiateHandshake (System.IAsyncResult result) (at <eb1224ae7b184cd09343d47f8a05481b>:0)
Mono.Security.Protocol.Tls.SslStreamBase.AsyncHandshakeCallback (System.IAsyncResult asyncResult) (at <eb1224ae7b184cd09343d47f8a05481b>:0)
Rethrow as IOException: The authentication or decryption has failed.
Mono.Security.Protocol.Tls.SslStreamBase.EndRead (System.IAsyncResult asyncResult) (at <eb1224ae7b184cd09343d47f8a05481b>:0)
Mono.Net.Security.Private.LegacySslStream.EndAuthenticateAsClient (System.IAsyncResult asyncResult) (at <344dc4d3f1ad41809df78607b6121a41>:0)
Mono.Net.Security.Private.LegacySslStream.AuthenticateAsClient (System.String targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection clientCertificates, System.Security.Authentication.SslProtocols enabledSslProtocols, System.Boolean checkCertificateRevocation) (at <344dc4d3f1ad41809df78607b6121a41>:0)
Mono.Net.Security.MonoTlsStream.CreateStream (System.Byte[] buffer) (at <344dc4d3f1ad41809df78607b6121a41>:0)
System.Net.WebConnection.CreateStream (System.Net.HttpWebRequest request) (at <344dc4d3f1ad41809df78607b6121a41>:0)
Rethrow as WebException: Error: SecureChannelFailure (The authentication or decryption has failed.)
System.Net.WebClient.DownloadDataInternal (System.Uri address, System.Net.WebRequest& request) (at <344dc4d3f1ad41809df78607b6121a41>:0)
System.Net.WebClient.DownloadString (System.Uri address) (at <344dc4d3f1ad41809df78607b6121a41>:0)
System.Net.WebClient.DownloadString (System.String address) (at <344dc4d3f1ad41809df78607b6121a41>:0)
</code>```

答:
After some rigorous research it turns out that the version of Mono that Unity(2017.2.0f3) currently uses does not support TLS 1.2, as explained by a developer here. Also, a careful examination of the exception log shows that internally, the legacy backend is being used:  Mono.Net.Security.Private.LegacySslStream as opposed to Mono.Net.Security.Private.SslStream. As of right now, the only solution would involve third-party libraries, or workarounds.

Thanks to @Evk for pointing me in the right direction.

Body:
I am creating a game using the Unity Engine(2017.2.0f3) on Windows 10 in which I am trying to get the HTML from a webpage. To my knowledge, Unity uses the "Mono" C# compiler and runtime v2.0 (according to the results of running mono --version in Unity\Editor\Data\Mono\bin), but also v5.0.1 (according to the results of running mono --version in Unity\Editor\Data\MonoBleedingEdge\bin). I am currently using the HTML Agility Pack for parsing. When attempting to access an HTTP secured website, such as dictionary.com, everything works as expected, but no matter what I do, I cannot access an HTTPS secured website, such as urbandictionary.com(Edit: Apparently, the problem is specific to this site, because after importing certificates using mozroots, github.com can be accessed), and always receive the exception: TlsException: The authentication or decryption has failed. I am aware that the HTML Agility Pack does not support HTTPS, and have wrote my code according to this answer. I've tried the solution described here and here, but to no avail. I've tried running mozroots, which I located in PathTo/Unity/Editor/Data/MonoBleedingEdge/lib/mono/4.5/mozroots, with the --import, --sync, and --quiet flags, but the same exception is thrown (if this did work, I'm skeptical about its portability, but perhaps I could implement my own version of mozroots, as suggested by the comments). Also, I've been informed that the version of Mono that Unity uses does not support TLS 1.2, which is problematic. If there is no solution to this problem, are there any workarounds?

Note: abridged for clarity

class MyWebClient : WebClient
{
    protected override WebRequest GetWebRequest(Uri address)
    {
        HttpWebRequest request = base.GetWebRequest(address) as HttpWebRequest;
        request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
        return request;
    }
}

class GetHtml
{
    public static void Get(string url)
    {
        string documentString = new MyWebClient().DownloadString(url);
        ...
    }
}

class CallingClass
{
     public void CallingMethod()
     {
         ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
         //With or without the above line ^, the same TlsException is thrown.
         GetHtml.Get("https://www.urbandictionary.com/define.php?term=example");
         //HTTP works properly, but HTTPS, as in this example, does not.
     }
}

The log is as follows:

TlsException: The authentication or decryption has failed.
Mono.Security.Protocol.Tls.RecordProtocol.ProcessAlert (AlertLevel alertLevel, AlertDescription alertDesc)
Mono.Security.Protocol.Tls.RecordProtocol.InternalReceiveRecordCallback (IAsyncResult asyncResult)
Rethrow as IOException: The authentication or decryption has failed.
Mono.Security.Protocol.Tls.SslStreamBase.AsyncHandshakeCallback (IAsyncResult asyncResult)
Rethrow as WebException: Error getting response stream (Write: The authentication or decryption has failed.): SendFailure
System.Net.HttpWebRequest.EndGetResponse (IAsyncResult asyncResult)
System.Net.HttpWebRequest.GetResponse ()
System.Net.WebClient.GetWebResponse (System.Net.WebRequest request)
System.Net.WebClient.DownloadDataCore (System.Uri address, System.Object userToken)

Edit: I've tried updating the runtime version. The only option was to change from .Net 3.5 to 4.6 in the Project Settings->Player menu, which is experimental. I still get an exception when the code is run, but the output log is a little different.

TlsException: The authentication or decryption has failed.
Mono.Security.Protocol.Tls.RecordProtocol.EndReceiveRecord (System.IAsyncResult asyncResult) (at <eb1224ae7b184cd09343d47f8a05481b>:0)
Mono.Security.Protocol.Tls.SslClientStream.SafeEndReceiveRecord (System.IAsyncResult ar, System.Boolean ignoreEmpty) (at <eb1224ae7b184cd09343d47f8a05481b>:0)
Mono.Security.Protocol.Tls.SslClientStream.NegotiateAsyncWorker (System.IAsyncResult result) (at <eb1224ae7b184cd09343d47f8a05481b>:0)
Rethrow as IOException: The authentication or decryption has failed.
Mono.Security.Protocol.Tls.SslClientStream.EndNegotiateHandshake (System.IAsyncResult result) (at <eb1224ae7b184cd09343d47f8a05481b>:0)
Mono.Security.Protocol.Tls.SslStreamBase.AsyncHandshakeCallback (System.IAsyncResult asyncResult) (at <eb1224ae7b184cd09343d47f8a05481b>:0)
Rethrow as IOException: The authentication or decryption has failed.
Mono.Security.Protocol.Tls.SslStreamBase.EndRead (System.IAsyncResult asyncResult) (at <eb1224ae7b184cd09343d47f8a05481b>:0)
Mono.Net.Security.Private.LegacySslStream.EndAuthenticateAsClient (System.IAsyncResult asyncResult) (at <344dc4d3f1ad41809df78607b6121a41>:0)
Mono.Net.Security.Private.LegacySslStream.AuthenticateAsClient (System.String targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection clientCertificates, System.Security.Authentication.SslProtocols enabledSslProtocols, System.Boolean checkCertificateRevocation) (at <344dc4d3f1ad41809df78607b6121a41>:0)
Mono.Net.Security.MonoTlsStream.CreateStream (System.Byte[] buffer) (at <344dc4d3f1ad41809df78607b6121a41>:0)
System.Net.WebConnection.CreateStream (System.Net.HttpWebRequest request) (at <344dc4d3f1ad41809df78607b6121a41>:0)
Rethrow as WebException: Error: SecureChannelFailure (The authentication or decryption has failed.)
System.Net.WebClient.DownloadDataInternal (System.Uri address, System.Net.WebRequest& request) (at <344dc4d3f1ad41809df78607b6121a41>:0)
System.Net.WebClient.DownloadString (System.Uri address) (at <344dc4d3f1ad41809df78607b6121a41>:0)
System.Net.WebClient.DownloadString (System.String address) (at <344dc4d3f1ad41809df78607b6121a41>:0)


来源: stackexchange

问:
Changing the geom order in a stacked ggplot legend
I am trying to change the order in which my legend displays the points and lines using ggplot for my graph.

Currently I have my graph itself displaying dots first then lines on top of the dots which is what I want. Here is a reproducible example:

```<code>ggplot(iris, aes(Sepal.Width, Petal.Width, linetype = Species)) +
  geom_point(aes(colour = Species, shape = Species)) +
  geom_smooth()
</code>```

As you can see from the legend, it has overlayed the values in the order plotted, but I would like to reverse this. I know that I could overlay the points on top of the plot as follows:

```<code>ggplot(iris, aes(Sepal.Width, Petal.Width, linetype = Species)) +
  geom_smooth() +
  geom_point(aes(colour = Species, shape = Species))
</code>```

I have searched and found the function guides(fill = guide_legend(reverse = TRUE)) from here, but this is having no effect.

Any help much appreciated

答:
From what I have read in the ggplot descriptions, I don't believe this is possible to set the order of overlaying ggplot legends. Within the guides function, you can set the order of the separate guides using the order argument, which it explains:

"positive integer less that 99 that specifies the order of this guide among multiple guides. This controls the order in which multiple guides are displayed, not the contents of the guide itself. If 0 (default), the order is determined by a secret algorithm."

It seems easiest to me to achieve what you want through a combination of:

Using legend=FALSE to suppress certain legends

Plotting some layers multiple times.

In the example below, the geom_smooth is plotted twice. Once to create the legend background, and then second to overlay the data. The second time it is plotted, the legend isn't shown:

```<code>ggplot(iris, aes(Sepal.Width, Petal.Width, linetype = Species)) +
  geom_smooth() +
  geom_point(aes(colour = Species, shape = Species)) +
  geom_smooth(show.legend = FALSE)
</code>```

Another approach would be to make the line colour change with each dataset. This requires less playing around and is clearer to understand, so I would probably go with this:

```<code>ggplot(iris, aes(Sepal.Width, Petal.Width, colour = Species, shape = Species, linetype = Species)) +
  geom_point(aes())  +
  geom_smooth(aes())
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to change the order in which my legend displays the points and lines using ggplot for my graph.

Currently I have my graph itself displaying dots first then lines on top of the dots which is what I want. Here is a reproducible example:

ggplot(iris, aes(Sepal.Width, Petal.Width, linetype = Species)) +
  geom_point(aes(colour = Species, shape = Species)) +
  geom_smooth()

As you can see from the legend, it has overlayed the values in the order plotted, but I would like to reverse this. I know that I could overlay the points on top of the plot as follows:

ggplot(iris, aes(Sepal.Width, Petal.Width, linetype = Species)) +
  geom_smooth() +
  geom_point(aes(colour = Species, shape = Species))

I have searched and found the function guides(fill = guide_legend(reverse = TRUE)) from here, but this is having no effect.

Any help much appreciated

Body:
From what I have read in the ggplot descriptions, I don't believe this is possible to set the order of overlaying ggplot legends. Within the guides function, you can set the order of the separate guides using the order argument, which it explains:

"positive integer less that 99 that specifies the order of this guide among multiple guides. This controls the order in which multiple guides are displayed, not the contents of the guide itself. If 0 (default), the order is determined by a secret algorithm."

It seems easiest to me to achieve what you want through a combination of:

Using legend=FALSE to suppress certain legends

Plotting some layers multiple times.

In the example below, the geom_smooth is plotted twice. Once to create the legend background, and then second to overlay the data. The second time it is plotted, the legend isn't shown:

ggplot(iris, aes(Sepal.Width, Petal.Width, linetype = Species)) +
  geom_smooth() +
  geom_point(aes(colour = Species, shape = Species)) +
  geom_smooth(show.legend = FALSE)

Another approach would be to make the line colour change with each dataset. This requires less playing around and is clearer to understand, so I would probably go with this:

ggplot(iris, aes(Sepal.Width, Petal.Width, colour = Species, shape = Species, linetype = Species)) +
  geom_point(aes())  +
  geom_smooth(aes())


问:
converting String YYYY-MM to Date YYYY-MM-DD
I have a set of data below and they are all in string.

```<code>EndDate
--------
2017-04

2017-02
2017-01
2017-03

2017-06
</code>```

I would like to add the last date of the month into it.

```<code>EndDate
--------
2017-04-30

2017-02-28
2017-01-31
2017-03-31

2017-06-30
</code>```

I'm thinking to convert them to date first and use EOMONTH syntax to give the last date of the month. However I have tried to convert the data to date using convert(datetime, EndDate) and it fails.

I tried a the syntax below from a post in stackoverflow however it gives me error message as well.

```<code>EOMONTH(CONVERT(VARCHAR(max),CAST(EndDate + '01' AS DATETIME),120))
</code>```

FYI, the blank value should remain in the column.

I'm using SQL Server 2012

Thanks all for your help.

答:
I think this should do it :</p>

```<code>CASE WHEN ISNULL(EndDate, '') <> '' THEN EOMONTH(CAST(EndDate + '-01' AS DATETIME)) ELSE EndDate END
</code>```

Body:
I have a set of data below and they are all in string.

EndDate
--------
2017-04

2017-02
2017-01
2017-03

2017-06

I would like to add the last date of the month into it.

EndDate
--------
2017-04-30

2017-02-28
2017-01-31
2017-03-31

2017-06-30

I'm thinking to convert them to date first and use EOMONTH syntax to give the last date of the month. However I have tried to convert the data to date using convert(datetime, EndDate) and it fails.

I tried a the syntax below from a post in stackoverflow however it gives me error message as well.

EOMONTH(CONVERT(VARCHAR(max),CAST(EndDate + '01' AS DATETIME),120))

FYI, the blank value should remain in the column.

I'm using SQL Server 2012

Thanks all for your help.

Body:
I think this should do it :

CASE WHEN ISNULL(EndDate, '') <> '' THEN EOMONTH(CAST(EndDate + '-01' AS DATETIME)) ELSE EndDate END


问:
lapply function using a numericInput parameter around an observeEvent in RShiny
I would like to create many multiple selectize inputs which are connected with each other. In other words : if an item is selected in one of the selectizeinputs i would like that it disappears from the other selectizeinputs' choices. In addition, i would like that the number of selectize inputs corresponds to the number selected in a numericinput.

The example below is working. The only question I have left is on the following line  :

```<code>  X = 1:100, ####### QUESTION HERE
</code>```

Instead of 1:100, i would like to put something like 1:input$ui_number but I have the following error in R :

```<code> Error in .getReactiveEnvironment()$currentContext() :  Operation not allowed without an active reactive context.
</code>```

And if I put a "reactive" or an "observe" function around the lapply, the observeEvent does not work anymore. Any trick for me ?

Thank you for your help !

```<code> modalities <- LETTERS[1:10]

 library(shiny)

 app <- shinyApp(
   ui = tabPanel("Change modalities",
            numericInput("ui_number", label="Number of modalities",min = 1, max = 4, value=3),
            uiOutput("renderui")
   ),

   server = function(input, output, session) {

     output$renderui <- renderUI({
       output = tagList()
       for(i in 1:input$ui_number){
         output[[i]] = tagList()
         output[[i]][[1]] = selectizeInput(paste0("ui_mod_choose",i), label=paste0("Modality ",i),choices=modalities, multiple = TRUE)
  }
  return(output)
})

 lapply(
  X = 1:100, ####### QUESTION HERE
  FUN = function(j){
    observeEvent({
      input[[paste0("ui_mod_choose",j)]]
    },
    {
      sapply(1:input$ui_number,function(i){
        vecteur <- do.call(c,lapply((1:input$ui_number)[-i],function(i){input[[paste0("ui_mod_choose",i)]]}))
        updateSelectizeInput(session,paste0("ui_mod_choose",i),choices=  modalities[!modalities %in% vecteur],selected = input[[paste0("ui_mod_choose",i)]])
      })
    },
    ignoreNULL = FALSE)

  }
)

observeEvent({
  input$ui_num
},
{
  sapply(1:nput$ui_num,function(i){
    updateSelectizeInput(session,paste0("ui_mod_choose",i),choice= modalities,selected=NULL)
       })
     }
     )

   }

 )
 runApp(app)
</code>```

答:
You could have a single observe() instead of multiple observeEvent():

```<code>library(shiny)

modalities <- LETTERS[1:10]

ui = tabPanel("Change modalities",
              numericInput("ui_number", label = "Number of modalities",
                           min = 1, max = 4, value = 3),
              uiOutput("renderui"))

server = function(input, output, session) {

  # Generate modalities select lists
  output$renderui <- renderUI({
    output = tagList()
    for (i in seq_len(input$ui_number)) {
      output[[i]] = selectizeInput(paste0("ui_mod_choose", i),
                                   label = paste0("Modality ", i),
                                   choices = modalities, multiple = TRUE)
    }
    return(output)
  })

  # Remove selected modalities from other select lists
  observe({
    n <- isolate(input$ui_number)
    for (i in seq_len(n)) {
      vecteur <- unlist(lapply((1:n)[-i], function(i)
        input[[paste0("ui_mod_choose",i)]]))
      updateSelectizeInput(session, paste0("ui_mod_choose",i),
                           choices = setdiff(modalities, vecteur),
                           selected = input[[paste0("ui_mod_choose",i)]])
    }
  })

}

runApp(shinyApp(ui, server))
</code>```

Body:
I would like to create many multiple selectize inputs which are connected with each other. In other words : if an item is selected in one of the selectizeinputs i would like that it disappears from the other selectizeinputs' choices. In addition, i would like that the number of selectize inputs corresponds to the number selected in a numericinput.

The example below is working. The only question I have left is on the following line  :

  X = 1:100, ####### QUESTION HERE

Instead of 1:100, i would like to put something like 1:input$ui_number but I have the following error in R :

 Error in .getReactiveEnvironment()$currentContext() :  Operation not allowed without an active reactive context.

And if I put a "reactive" or an "observe" function around the lapply, the observeEvent does not work anymore. Any trick for me ?

Thank you for your help !

 modalities <- LETTERS[1:10]

 library(shiny)

 app <- shinyApp(
   ui = tabPanel("Change modalities",
            numericInput("ui_number", label="Number of modalities",min = 1, max = 4, value=3),
            uiOutput("renderui")
   ),

   server = function(input, output, session) {

     output$renderui <- renderUI({
       output = tagList()
       for(i in 1:input$ui_number){
         output[[i]] = tagList()
         output[[i]][[1]] = selectizeInput(paste0("ui_mod_choose",i), label=paste0("Modality ",i),choices=modalities, multiple = TRUE)
  }
  return(output)
})

 lapply(
  X = 1:100, ####### QUESTION HERE
  FUN = function(j){
    observeEvent({
      input[[paste0("ui_mod_choose",j)]]
    },
    {
      sapply(1:input$ui_number,function(i){
        vecteur <- do.call(c,lapply((1:input$ui_number)[-i],function(i){input[[paste0("ui_mod_choose",i)]]}))
        updateSelectizeInput(session,paste0("ui_mod_choose",i),choices=  modalities[!modalities %in% vecteur],selected = input[[paste0("ui_mod_choose",i)]])
      })
    },
    ignoreNULL = FALSE)

  }
)

observeEvent({
  input$ui_num
},
{
  sapply(1:nput$ui_num,function(i){
    updateSelectizeInput(session,paste0("ui_mod_choose",i),choice= modalities,selected=NULL)
       })
     }
     )

   }

 )
 runApp(app)

Body:
You could have a single observe() instead of multiple observeEvent():

library(shiny)

modalities <- LETTERS[1:10]

ui = tabPanel("Change modalities",
              numericInput("ui_number", label = "Number of modalities",
                           min = 1, max = 4, value = 3),
              uiOutput("renderui"))

server = function(input, output, session) {

  # Generate modalities select lists
  output$renderui <- renderUI({
    output = tagList()
    for (i in seq_len(input$ui_number)) {
      output[[i]] = selectizeInput(paste0("ui_mod_choose", i),
                                   label = paste0("Modality ", i),
                                   choices = modalities, multiple = TRUE)
    }
    return(output)
  })

  # Remove selected modalities from other select lists
  observe({
    n <- isolate(input$ui_number)
    for (i in seq_len(n)) {
      vecteur <- unlist(lapply((1:n)[-i], function(i)
        input[[paste0("ui_mod_choose",i)]]))
      updateSelectizeInput(session, paste0("ui_mod_choose",i),
                           choices = setdiff(modalities, vecteur),
                           selected = input[[paste0("ui_mod_choose",i)]])
    }
  })

}

runApp(shinyApp(ui, server))


问:
Sys.argv python error list index out of range
I'm new user of stackoverflow, besides I'm not an English guy, so I'm sorry for my english.

I was programming in python 'til I got a mistake tho I'm not able to figure out what's wrong...

```<code>#!/usr/bin/env python2.7

from random import choice
import sys

def help():
    print ("Please, you need to introduce a Int in this way: PWrand 10")

def PWrand(insert_by_user):
    chars = 'ABCDEFGHIJKLMNOPQRSTUWXYZabcdefghijklmnopqrstuwxyz0123456789!-_:.,;&)('

    for password in range(insert_by_user):
        sys.stdout.write(choice(chars))

 #Command Line

if __name__ == '__main__':

    if len(sys.argv) < 2 or len(sys.argv) > 2:
        help()

    elif (type(sys.argv[2]) != int):
        print("It need to be an Int!")

    else:
        insert_by_user = (sys.argv[2])
        print(PWrand(insert_by_user))
</code>```

So, this is what I take.

```<code>Traceback (most recent call last):
  File "./passwordrandom.py", line 24, in <module>
    elif (type(sys.argv[2]) != int):
IndexError: list index out of range
</code>```

Thank you all!

答:
You have two issues here. The first is that you're a little confused about list indexes. Lists in python are "zero-indexed" meaning that to get the first element of a list named L you need to do L[0]. Similarly, to get the second, like you need, you do L[1].

The other issue is that all elements from sys.argv are going to be strings, so checking the type won't work. You should try to cast the piece of user input as an int inside a try block and catch a ValueError. It'd look something like this:

```<code>if __name__ == '__main__':

    if len(sys.argv) < 2 or len(sys.argv) > 2:
        help()

    else:
        try:
            insert_by_user = int(sys.argv[1])
            print(PWrand(insert_by_user))
        except ValueError:
            print("It need to be an Int!")
</code>```

The code inside the except ValueError: block will only be executed if the user's input cannot be properly cast to an integer.

Body:
I'm new user of stackoverflow, besides I'm not an English guy, so I'm sorry for my english.

I was programming in python 'til I got a mistake tho I'm not able to figure out what's wrong...

#!/usr/bin/env python2.7

from random import choice
import sys

def help():
    print ("Please, you need to introduce a Int in this way: PWrand 10")

def PWrand(insert_by_user):
    chars = 'ABCDEFGHIJKLMNOPQRSTUWXYZabcdefghijklmnopqrstuwxyz0123456789!-_:.,;&)('

    for password in range(insert_by_user):
        sys.stdout.write(choice(chars))

 #Command Line

if __name__ == '__main__':

    if len(sys.argv) < 2 or len(sys.argv) > 2:
        help()

    elif (type(sys.argv[2]) != int):
        print("It need to be an Int!")

    else:
        insert_by_user = (sys.argv[2])
        print(PWrand(insert_by_user))

So, this is what I take.

Traceback (most recent call last):
  File "./passwordrandom.py", line 24, in <module>
    elif (type(sys.argv[2]) != int):
IndexError: list index out of range

Thank you all!

Body:
You have two issues here. The first is that you're a little confused about list indexes. Lists in python are "zero-indexed" meaning that to get the first element of a list named L you need to do L[0]. Similarly, to get the second, like you need, you do L[1].

The other issue is that all elements from sys.argv are going to be strings, so checking the type won't work. You should try to cast the piece of user input as an int inside a try block and catch a ValueError. It'd look something like this:

if __name__ == '__main__':

    if len(sys.argv) < 2 or len(sys.argv) > 2:
        help()

    else:
        try:
            insert_by_user = int(sys.argv[1])
            print(PWrand(insert_by_user))
        except ValueError:
            print("It need to be an Int!")

The code inside the except ValueError: block will only be executed if the user's input cannot be properly cast to an integer.


问:
How to impose order on a dictionary?
I wrote a program and then regretted not making certain objects earlier on OrderedDicts instead of dicts. So to fix this after the fact, the one dictionary was converted into an OrderedDict, but I needed to convert the second dictionary also to become an OrderedDict, but with its keys in the same order as the first.

A dict often displays in a way that looks deceivingly ordered, I almost made a mistake. There's a few questions about this apparent ordering here and here. Anyway, however ordered it may look to the eye, one needs to remember:

```<code>{'a':5,'b':7, 'c':3, 'd':9} == {'d':9,'b':7,'a':5, 'c':3}
>> True
</code>```

So if there are two Python dictionaries:

a = {'a':5, 'b':7, 'c':3, 'd':9}
b = {'c':2, 'b':1, 'd':17, 'a':8}

I can fix the order of a like this:

```<code>c = OrderedDict(a)
print (c)
>> OrderedDict([('a', 5), ('b', 7), ('c', 3), ('d', 9)])
</code>```

How do you impose order on dictionary b, convert it into an OrderedDict with its keys in the same order as a?

In my exact use case, both dictionaries have the same keys, but I would be interested to know how you can do this in general, say instead your two dictionaries were:

```<code>a = {'a':5, 'b':7, 'c':3, 'd':9}
b = {'f':3, 'c':2, 'd':17, 'a':8, 'e':9, 'b':1}
</code>```

How do you convert a and b to OrderedDict's but make sure that whatever keys b has in common with a, they end up in the same order as those keys in a

答:
I assume you want it in sorted order. Try this</p>

```<code>c = OrderedDict(sorted(a.items()))
</code>```

Title: How to impose order on a dictionary?

Body:
I wrote a program and then regretted not making certain objects earlier on OrderedDicts instead of dicts. So to fix this after the fact, the one dictionary was converted into an OrderedDict, but I needed to convert the second dictionary also to become an OrderedDict, but with its keys in the same order as the first.

A dict often displays in a way that looks deceivingly ordered, I almost made a mistake. There's a few questions about this apparent ordering here and here. Anyway, however ordered it may look to the eye, one needs to remember:

{'a':5,'b':7, 'c':3, 'd':9} == {'d':9,'b':7,'a':5, 'c':3}
>> True

So if there are two Python dictionaries:

a = {'a':5, 'b':7, 'c':3, 'd':9}
b = {'c':2, 'b':1, 'd':17, 'a':8}

I can fix the order of a like this:

c = OrderedDict(a)
print (c)
>> OrderedDict([('a', 5), ('b', 7), ('c', 3), ('d', 9)])

How do you impose order on dictionary b, convert it into an OrderedDict with its keys in the same order as a?

In my exact use case, both dictionaries have the same keys, but I would be interested to know how you can do this in general, say instead your two dictionaries were:

a = {'a':5, 'b':7, 'c':3, 'd':9}
b = {'f':3, 'c':2, 'd':17, 'a':8, 'e':9, 'b':1}

How do you convert a and b to OrderedDict's but make sure that whatever keys b has in common with a, they end up in the same order as those keys in a

Body:
I assume you want it in sorted order. Try this

c = OrderedDict(sorted(a.items()))


答:
It's because the first if catch every list that has less than 2 elements or everything that has more than 2 elements, so the elif is catching everything that has exactly 2 elements, which will be stored in the position 0 and 1.

```<code>if len(sys.argv) is not 2:
    help()

else:
   user_input = sys.argv[1].decode()
   if not user_input.isnumeric():
      print("It need to be an Int!")
   else:
       user_input = int(user_input)
</code>```

should fix it.

Title: Sys.argv python error list index out of range

Body:
It's because the first if catch every list that has less than 2 elements or everything that has more than 2 elements, so the elif is catching everything that has exactly 2 elements, which will be stored in the position 0 and 1.

if len(sys.argv) is not 2:
    help()

else:
   user_input = sys.argv[1].decode()
   if not user_input.isnumeric():
      print("It need to be an Int!")
   else:
       user_input = int(user_input)

should fix it.


问:
SecurityException: Failed to find provider null for user 0; on ActiveAndroid on Android 8.0
I have an app that is using ActiveAndroid and it's been working fine.  However; now when I try to save a model to the database I'm getting a SecurityException.

The stack is:

```<code>Error saving model java.lang.SecurityException: Failed to find provider null for user 0; expected to find a valid ContentProvider for this authority
at android.os.Parcel.readException(Parcel.java:1942)
at android.os.Parcel.readException(Parcel.java:1888)
at android.content.IContentService$Stub$Proxy.notifyChange(IContentService.java:801)
at android.content.ContentResolver.notifyChange(ContentResolver.java:2046)
at android.content.ContentResolver.notifyChange(ContentResolver.java:1997)
at android.content.ContentResolver.notifyChange(ContentResolver.java:1967)
at com.activeandroid.Model.save(Model.java:162)
[.... local stack removed]
</code>```

Has anyone else experienced this?  Do we need to specify the Content Provider in the AndroidManifest.xml?

Sorry but I do not have an isolated example of this yet.  I will work to put something together.

Thanks in advance

答:
As pointed out by @GeigerGeek security changes on Android 26 and above require you to specify the content provider in your manifest.

For ActiveAndroid you can add the below to your Manifest and change your package name.

```<code><provider
  android:name="com.activeandroid.content.ContentProvider"
  android:authorities="<your.package.name>"
  android:enabled="true"
  android:exported="false">
</provider>
</code>```

If using flavours on your build process you can use below instead:

```<code>android:authorities="${applicationId}"
</code>```

Using ${applicationId} will help in flavor based project structure where application package may be different for each flavors.

For more solutions or info this was taken from here.

Body:
I have an app that is using ActiveAndroid and it's been working fine.  However; now when I try to save a model to the database I'm getting a SecurityException.

The stack is:

Error saving model java.lang.SecurityException: Failed to find provider null for user 0; expected to find a valid ContentProvider for this authority
at android.os.Parcel.readException(Parcel.java:1942)
at android.os.Parcel.readException(Parcel.java:1888)
at android.content.IContentService$Stub$Proxy.notifyChange(IContentService.java:801)
at android.content.ContentResolver.notifyChange(ContentResolver.java:2046)
at android.content.ContentResolver.notifyChange(ContentResolver.java:1997)
at android.content.ContentResolver.notifyChange(ContentResolver.java:1967)
at com.activeandroid.Model.save(Model.java:162)
[.... local stack removed]

Has anyone else experienced this?  Do we need to specify the Content Provider in the AndroidManifest.xml?

Sorry but I do not have an isolated example of this yet.  I will work to put something together.

Thanks in advance

Body:
As pointed out by @GeigerGeek security changes on Android 26 and above require you to specify the content provider in your manifest.

For ActiveAndroid you can add the below to your Manifest and change your package name.

<provider
  android:name="com.activeandroid.content.ContentProvider"
  android:authorities="<your.package.name>"
  android:enabled="true"
  android:exported="false">
</provider>

If using flavours on your build process you can use below instead:

android:authorities="${applicationId}"

Using ${applicationId} will help in flavor based project structure where application package may be different for each flavors.

For more solutions or info this was taken from here.

ContentLicense: CC BY-SA 4.0


问:
How to deny s3 bucket access for an AWS account
I have an AWS account with ID 11111 and I would like to deny access to certain parts of an s3 bucket to the same account the bucket belongs to, even if the role accessing that object has full s3 access.

It is my understanding that setting a DENY rule on a s3 bucket policy should do that, so I tried the s3 policy below

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "",
            "Effect": "Deny",
            "Principal": {
                "AWS": "arn:aws:iam::111111:root"
            },
            "Action": [
                "s3:PutObject",
                "s3:GetObjectVersion",
                "s3:GetObject",
                "s3:DeleteObject"
            ],
            "Resource": [
                "arn:aws:s3:::mybucket/production/*"
            ]
        }
    ]
}

However an ec2 machine in the same account as the s3 bucket with an iam role to allow full access to the bucket (s3:*) is still able to write/read to mybucket/production/*

Am I missing something? Shouldn't the DENY bucket rule take precedence? How does one handle this situation? I want to avoid having to remove the full access from the ec2 role but rather be able to deny on top of that.

答:
See if this works. Since you are giving full access, you need to explicitly deny access. Below policy says deny access if user is not alloweduser or role is not allowedrole. This should also prevent non-authorized users/roles to delete bucket policy. I have not tested it yet.</p>

```<code>{
                "Id": "DenyAllAllowOnlyOne",
                "Statement": [
                        {
                                "Action": "s3:*",
                                "Effect": "Deny",
                                "NotPrincipal": {
                                        "AWS": [
                                    "arn:aws:iam::111111:user/alloweduser",
                                    "arn:aws:iam::111111:role/allowedrole"

                                        ]
                                },
                                "Resource": [
                                        "arn:aws:s3:::mybucket/production",
                                        "arn:aws:s3:::mybucket/production/*"
                                ]
                        }
                ],
                "Version": "2012-10-17"
        }
</code>```

Body:
See if this works. Since you are giving full access, you need to explicitly deny access. Below policy says deny access if user is not alloweduser or role is not allowedrole. This should also prevent non-authorized users/roles to delete bucket policy. I have not tested it yet.

{
                "Id": "DenyAllAllowOnlyOne",
                "Statement": [
                        {
                                "Action": "s3:*",
                                "Effect": "Deny",
                                "NotPrincipal": {
                                        "AWS": [
                                    "arn:aws:iam::111111:user/alloweduser",
                                    "arn:aws:iam::111111:role/allowedrole"

                                        ]
                                },
                                "Resource": [
                                        "arn:aws:s3:::mybucket/production",
                                        "arn:aws:s3:::mybucket/production/*"
                                ]
                        }
                ],
                "Version": "2012-10-17"
        }


Title: converting pandas dataframe to contain a dictionary or list of lists

Body:
      state      Year  Month  count
0       alabama  2017.0   10.0     31
1       alabama  2017.0   11.0     30
2       alabama  2017.0   12.0     31
3       alabama  2018.0    1.0     31
4       alabama  2018.0    2.0     28
5       alabama  2018.0    3.0     31
6       alabama  2018.0    4.0     30
7       alabama  2018.0    5.0     31
8       alabama  2018.0    6.0     30
9       alabama  2018.0    7.0     14
10     arkansas  2017.0   10.0     31
11     arkansas  2017.0   11.0     30
12     arkansas  2017.0   12.0     31

Can I convert dataframe above to:

                                                            Month
state
alabama         {2017:10.0, 2017:11.0, 2017:12.0, 2018:1.0, 2018:2.0, 2018:3.0, 2018:4.0, 2018:5.0, 2018:6.0, 2018:7.0}
arkansas        {2017:10.0, 2017:11.0, 2017:12.0}

related to converting pandas dataframe to contain a list

based on @Vaishali's comment below, since dictionary cannot contain duplicate keys, this should be ok too:

                                                            Month
state
alabama         [[2017,10.0], [2017,11.0], [2017,12.0], [2018,1.0], [2018,2.0], [2018,3.0], [2018,4.0], [2018,5.0], [2018,6.0], 2[018,7.0]]
arkansas        [[2017,10.0], [2017,11.0], [2017,12.0]]

Body:
Or also

df.groupby('state').apply(lambda x:x[['Year','Month']].values)

state
alabama     [[2017.0, 10.0], [2017.0, 11.0], [2017.0, 12.0...
arkansas     [[2017.0, 10.0], [2017.0, 11.0], [2017.0, 12.0]]


问:
Sometimes I get an invalid date from javascript date function
Really not sure where I'm going wrong here.

I have some JavaScript to sort a table by date value:

```<code>function sortByDate() {
    if (jQuery("#web-orders .data-table tbody").length > 0) {
        var tbody = document.querySelector("#web-orders .data-table tbody");
        var rows = [].slice.call(tbody.querySelectorAll("tr"));
    }
    if (jQuery("#store-orders .data-table tbody").length > 0) {
        var tbodyStore = document.querySelector("#store-orders .data-table tbody");
        var rowsStore = [].slice.call(tbodyStore.querySelectorAll("tr"));

        rowsStore.forEach(function (entry) {
            rows.push(entry);
        });
    }

    rows.sort(function (a, b) {
        console.log("a.cells[2].innerHTML = " + a.cells[2].innerHTML);
        console.log("b.cells[2].innerHTML = " + b.cells[2].innerHTML);

        a = new Date(Date.parse(a.cells[2].innerHTML));
        b = new Date(Date.parse(b.cells[2].innerHTML));

        console.log("a = " + a);
        console.log("b = " + b);

        return a - b;
    });

    rows.forEach(function (v) {
        tbody.appendChild(v); // note that .appendChild() *moves* elements
    });
}
</code>```

Now here is some of the console output with the invalid dates:

```<code>a.cells[2].innerHTML = 28/11/2017 1:49:37 PM
b.cells[2].innerHTML = 5/09/2017 6:27:35 AM
a = Invalid Date
b = Tue May 09 2017 06:27:35 GMT+0930 (Cen. Australia Standard Time)
a.cells[2].innerHTML = 28/11/2017 1:49:37 PM
b.cells[2].innerHTML = 24/09/2017 6:12:48 PM
a = Invalid Date
b = Invalid Date
</code>```

Does anyone know why this might be happening? It's got me stumped.

答:
Date.parse uses RFC 2822 formatting and doesn't allow to specify a custom format. Though, if your input is consistently in the DD/MM/YYYY h:m:s AM/PM format, then you can use split to do the parsing yourself and manually create a Date object.

```<code>parseDate(a.cells[2].innerHTML);
parseDate(b.cells[2].innerHTML);

function parseDate(str) {
    // Split into date, time, and AM/PM
    var parts = str.split(" ");

    // Split and parse the day, month, and year
    var date = parts[0].split("/");
    var day = parseInt(date[0]);
    var month = parseInt(date[1]) - 1;
    var year = parseInt(date[2]);

    // Split and parse the hours, minutes, and seconds
    var time = parts[1].split(":");
    var hour = parseInt(time[0]);
    var minute = parseInt(time[1]);
    var second = parseInt(time[2]);

    // Add 12 hours to the time if it's in the afternoon
    if (parts[2] == "PM") { hour += 12; }

    // Build and return our Date object
    return new Date(year, month, day, hour, minute, second);
}
</code>```

As others have mentioned, you can also use Moment to make things easier.

Body:
Really not sure where I'm going wrong here.

I have some JavaScript to sort a table by date value:

function sortByDate() {
    if (jQuery("#web-orders .data-table tbody").length > 0) {
        var tbody = document.querySelector("#web-orders .data-table tbody");
        var rows = [].slice.call(tbody.querySelectorAll("tr"));
    }
    if (jQuery("#store-orders .data-table tbody").length > 0) {
        var tbodyStore = document.querySelector("#store-orders .data-table tbody");
        var rowsStore = [].slice.call(tbodyStore.querySelectorAll("tr"));

        rowsStore.forEach(function (entry) {
            rows.push(entry);
        });
    }

    rows.sort(function (a, b) {
        console.log("a.cells[2].innerHTML = " + a.cells[2].innerHTML);
        console.log("b.cells[2].innerHTML = " + b.cells[2].innerHTML);

        a = new Date(Date.parse(a.cells[2].innerHTML));
        b = new Date(Date.parse(b.cells[2].innerHTML));

        console.log("a = " + a);
        console.log("b = " + b);

        return a - b;
    });

    rows.forEach(function (v) {
        tbody.appendChild(v); // note that .appendChild() *moves* elements
    });
}

Now here is some of the console output with the invalid dates:

a.cells[2].innerHTML = 28/11/2017 1:49:37 PM
b.cells[2].innerHTML = 5/09/2017 6:27:35 AM
a = Invalid Date
b = Tue May 09 2017 06:27:35 GMT+0930 (Cen. Australia Standard Time)
a.cells[2].innerHTML = 28/11/2017 1:49:37 PM
b.cells[2].innerHTML = 24/09/2017 6:12:48 PM
a = Invalid Date
b = Invalid Date

Does anyone know why this might be happening? It's got me stumped.

Body:
Date.parse uses RFC 2822 formatting and doesn't allow to specify a custom format. Though, if your input is consistently in the DD/MM/YYYY h:m:s AM/PM format, then you can use split to do the parsing yourself and manually create a Date object.

parseDate(a.cells[2].innerHTML);
parseDate(b.cells[2].innerHTML);

function parseDate(str) {
    // Split into date, time, and AM/PM
    var parts = str.split(" ");

    // Split and parse the day, month, and year
    var date = parts[0].split("/");
    var day = parseInt(date[0]);
    var month = parseInt(date[1]) - 1;
    var year = parseInt(date[2]);

    // Split and parse the hours, minutes, and seconds
    var time = parts[1].split(":");
    var hour = parseInt(time[0]);
    var minute = parseInt(time[1]);
    var second = parseInt(time[2]);

    // Add 12 hours to the time if it's in the afternoon
    if (parts[2] == "PM") { hour += 12; }

    // Build and return our Date object
    return new Date(year, month, day, hour, minute, second);
}

As others have mentioned, you can also use Moment to make things easier.


问:
VSCode 1.18.1 doesn't install extensions from VSIX if offline?
I tend to use Visual Studio Code as a text editor on my development machine that doesn't have internet connection. However after updating to 1.18.1 I am unable to install extensions from downloaded VSIX files. If I try to use GUI nothing happens, no errors or warnings and the extension is not installed as the result. When I tried to install extension using command line I get:

```<code>code --install-extension ms-python.python-0.8.0.vsix
Error: getaddrinfo EAI_AGAIN marketplace.visualstudio.com:443
    at Object.exports._errnoException (util.js:1050:11)
    at errnoException (dns.js:33:15)
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:73:26)
</code>```

It seems it tries to connect to the internet, but extension is already downloaded.

答:
Sounds like you are running into this VS Code 1.18 bug: https://github.com/Microsoft/vscode/issues/37973

This should already be fixed in VS Code insiders and should also be fixed in VS Code 1.19 stable once that is released

Body:
I tend to use Visual Studio Code as a text editor on my development machine that doesn't have internet connection. However after updating to 1.18.1 I am unable to install extensions from downloaded VSIX files. If I try to use GUI nothing happens, no errors or warnings and the extension is not installed as the result. When I tried to install extension using command line I get:

code --install-extension ms-python.python-0.8.0.vsix
Error: getaddrinfo EAI_AGAIN marketplace.visualstudio.com:443
    at Object.exports._errnoException (util.js:1050:11)
    at errnoException (dns.js:33:15)
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:73:26)

It seems it tries to connect to the internet, but extension is already downloaded.


问:
SSIS reading data from a view
I have recently encountered this problem wherein when I am trying to load data from a view(view has join on 3 different tables) to a table, I see that the reading from source pauses for a minute and continues the load and after loading x number of records it again pauses for a while and then continues.
this are my settings of
Default BufferSize:104857600(100MB)
DefaultBufferMaxRows: 2700(my row size 39417 bytes based on dataTypes)

right now I am not loading any data to destination to check why reading goes into a pause state, I am using a rowcount transformation as destination.
in my case data reading happens continuously for 1024580 records pauses for approx 1min and then continues till 2067449 and then pauses for a 1min and then continues till 3110368 and this happens till the load is complete.
number of rows in input is approx 300Million.

答:
Check your local Temp folder (run %temp%) and see if SSIS creates temp files. If that's the case, you need to do some hack solution which breaks down rows by 8MB chuncks and then recreate it back together.<br>
This is old DTS model that does not process blob data well in memory (pretty much anything over 8MB) </p>

Title: SSIS reading data from a view

Body:
Check your local Temp folder (run %temp%) and see if SSIS creates temp files. If that's the case, you need to do some hack solution which breaks down rows by 8MB chuncks and then recreate it back together.

This is old DTS model that does not process blob data well in memory (pretty much anything over 8MB)


问:
What's the difference between var and _var in Rust?
Given this:

```<code>fn main() {
   let variable = [0; 15];
}
</code>```

The Rust compiler produces this warning:

= note: #[warn(unused_variables)] on by default
= note: to avoid this warning, consider using `_variable` instead
```

What's the difference between variable and _variable?

答:
The difference is an underscore at the front, which causes the Rust compiler to allow it to be unused. It is kind of a named version of the bare underscore _ which can be used to ignore a value.

However, _name acts differently than _. The plain underscore drops the value immediately while _name acts like any other variable and drops the value at the end of the scope.

An example of how it does not act exactly the same as a plain underscore:

```<code>struct Count(i32);

impl Drop for Count {
    fn drop(&mut self) {
        println!("dropping count {}", self.0);
    }
}

fn main() {
    {
        let _a = Count(3);
        let _ = Count(2);
        let _c = Count(1);
    }

    {
        let _a = Count(3);
        let _b = Count(2);
        let _c = Count(1);
    }
}
</code>```

prints the following (playground):

dropping count 2
dropping count 1
dropping count 3
dropping count 1
dropping count 2
dropping count 3
```

Body:
Given this:

fn main() {
   let variable = [0; 15];
}

The Rust compiler produces this warning:

= note: #[warn(unused_variables)] on by default
= note: to avoid this warning, consider using `_variable` instead

What's the difference between variable and _variable?

Body:
The difference is an underscore at the front, which causes the Rust compiler to allow it to be unused. It is kind of a named version of the bare underscore _ which can be used to ignore a value.

However, _name acts differently than _. The plain underscore drops the value immediately while _name acts like any other variable and drops the value at the end of the scope.

An example of how it does not act exactly the same as a plain underscore:

struct Count(i32);

impl Drop for Count {
    fn drop(&mut self) {
        println!("dropping count {}", self.0);
    }
}

fn main() {
    {
        let _a = Count(3);
        let _ = Count(2);
        let _c = Count(1);
    }

    {
        let _a = Count(3);
        let _b = Count(2);
        let _c = Count(1);
    }
}

prints the following (playground):

dropping count 2
dropping count 1
dropping count 3
dropping count 1
dropping count 2
dropping count 3


问:
Sending JMS message immediately disregarding current TX status
in short, I use super simple JMS configuration taken from spring Getting Started guide: https://spring.io/guides/gs/messaging-jms/.

My case is that I'd like to send JMS message from transactional method even if TX is failed, sth like (kotlin code) :

```<code>@Service
open class MyService(private val t: JmsTemplate) {
//
  @Transactional
  open fun go(sth: String) {
    val result = // some logic here
    t.convertAndSend("NeedsToBeDelivered", result)
    // more logic which might fail
  }
}
</code>```

Result is delivered only if TX is successful, if not - more logic section fails - the msg is lost.
I was trying to configure AMQ in many different ways, also tried several TX variants but none of the works for me.

I'm interested in
1/ delivery disregarding tx status
2/ immediate delivery (not postponed until current TX finishes).

Suggestions?

UPDATE

Yesterday I tried this one and works as expected.

```<code> @Transactional(propagation = NOT_SUPPORTED)
 fun sendNoTx(msg: String, destination: String) = try {
    val con = cf.createConnection() // cf stands for connection factory
    con.start()
    val session = con.createSession(false, AUTO_ACKNOWLEDGE)
    val producer = session.createProducer(session.createQueue(destination))
    producer.send(session.createTextMessage(msg))
    con.close()
 } catch (e: Exception) {
    LOG.warn("Failed to send NO TX message", e)
 }
</code>```

More elegant solution suggested by Gary is to feed JmsTemplate with another instance of CF - having it done this way we avoid all conn.close()-like mess and exception handling.

答:
You need to use 2 connection factories so that the JmsTemplate does not participate in the listener container's transaction.

The template does a lookup for a transactional resource (the session) keyed on the connection factory.

If it has a different connection factory it won't find it and will use its own session instead.

Body:
in short, I use super simple JMS configuration taken from spring Getting Started guide: https://spring.io/guides/gs/messaging-jms/.

My case is that I'd like to send JMS message from transactional method even if TX is failed, sth like (kotlin code) :

@Service
open class MyService(private val t: JmsTemplate) {
//
  @Transactional
  open fun go(sth: String) {
    val result = // some logic here
    t.convertAndSend("NeedsToBeDelivered", result)
    // more logic which might fail
  }
}

Result is delivered only if TX is successful, if not - more logic section fails - the msg is lost.
I was trying to configure AMQ in many different ways, also tried several TX variants but none of the works for me.

I'm interested in
1/ delivery disregarding tx status
2/ immediate delivery (not postponed until current TX finishes).

Suggestions?

UPDATE

Yesterday I tried this one and works as expected.

 @Transactional(propagation = NOT_SUPPORTED)
 fun sendNoTx(msg: String, destination: String) = try {
    val con = cf.createConnection() // cf stands for connection factory
    con.start()
    val session = con.createSession(false, AUTO_ACKNOWLEDGE)
    val producer = session.createProducer(session.createQueue(destination))
    producer.send(session.createTextMessage(msg))
    con.close()
 } catch (e: Exception) {
    LOG.warn("Failed to send NO TX message", e)
 }

More elegant solution suggested by Gary is to feed JmsTemplate with another instance of CF - having it done this way we avoid all conn.close()-like mess and exception handling.


问:
RecyclerView doesn't show items until scrolling
This question has been asked a few times but those answers doesn't apply to me. I would like a more general answer about what causes this issue generally.

I have a recyclerview in my activity layout. Rows of the recyclerview is a constraint layout with one imageview and textview:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:clickable="true">

    <ImageView
        android:id="@+id/file_icon"
        android:layout_width="50dp"
        android:layout_height="50dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

    <TextView
        android:text="File"
        android:id="@+id/file_name"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintLeft_toRightOf="@+id/file_icon"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintRight_toRightOf="parent"/>

</android.support.constraint.ConstraintLayout>
</code>```

I have several items to show in this row structure. I set up the adapter properly. However, when I run my application, textviews that are on the screen doesn't get shown, until I scroll-down and scroll-up again. Basically, in order for those textviews to be shown, they need to be discarded from display and enter again. Here is my adapter code:

```<code>public class FileViewAdapter extends RecyclerView.Adapter<FileViewAdapter.Viewholder> {

    private Context context;
    private List<File> files;

    public FileViewAdapter(Context context, List<File> files) {
        this.context = context;
        this.files = files;
    }

    public FileViewAdapter(Context context){

        this.context = context;
    }

    @Override
    public Viewholder onCreateViewHolder(ViewGroup viewGroup, int i) {
        LayoutInflater inflater = LayoutInflater.from(context);
        View layout = inflater.inflate(R.layout.file_list_item, viewGroup, false);
        return new Viewholder(layout);
    }

    @Override
    public void onBindViewHolder(Viewholder viewholder, int i) {
        File file = files.get(i);
        if (file.isDirectory()) {
            viewholder.fileIcon.setImageDrawable(
                    context.getResources().getDrawable(R.drawable.ic_folder_black_24dp));
            viewholder.wholeThing.setOnClickListener(null);
        } else {
            viewholder.fileIcon.setImageDrawable(
                    context.getResources().getDrawable(R.drawable.ic_insert_drive_file_black_24dp));
            viewholder.wholeThing.setOnClickListener(null);
        }
        viewholder.fileName.setText(file.getName());
    }

    @Override
    public int getItemCount() {
        return files.size();
    }

    public void clear() {
        files.clear();
        notifyDataSetChanged();
    }

    public void addAll(List<File> newFiles) {
        files.addAll(newFiles);
        notifyDataSetChanged();
    }

    class Viewholder extends RecyclerView.ViewHolder {
        View wholeThing;
        ImageView fileIcon;
        TextView fileName;

        public Viewholder(View itemView) {
            super(itemView);
            wholeThing = itemView;
            fileIcon = (ImageView) itemView.findViewById(R.id.file_icon);
            fileName = (TextView) itemView.findViewById(R.id.file_name);
        }
    }

}
</code>```

EDIT: How I am calling the constructor of adapter on activity.

```<code>@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_file_viewer);
    recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
}

@Override
public void onResume() {
     adapter = new Adapter(this, /*A list of File items*/);
     recyclerView.setAdapter(adapter);
     recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
</code>```

答:
The problem from what i see is that the notifyDataSetChanged doesnt ocurr in the UiThread so if run ur setData method like this it will work.</p>

```<code> this.runOnUiThread(new Runnable() {
        public void run() {
            mAdapter.setNewData(newDataListForAdapter);
            mAdapter.notifyDataSetChanged();

        }
    });
</code>```

Body:
This question has been asked a few times but those answers doesn't apply to me. I would like a more general answer about what causes this issue generally.

I have a recyclerview in my activity layout. Rows of the recyclerview is a constraint layout with one imageview and textview:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:clickable="true">

    <ImageView
        android:id="@+id/file_icon"
        android:layout_width="50dp"
        android:layout_height="50dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

    <TextView
        android:text="File"
        android:id="@+id/file_name"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintLeft_toRightOf="@+id/file_icon"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintRight_toRightOf="parent"/>

</android.support.constraint.ConstraintLayout>

I have several items to show in this row structure. I set up the adapter properly. However, when I run my application, textviews that are on the screen doesn't get shown, until I scroll-down and scroll-up again. Basically, in order for those textviews to be shown, they need to be discarded from display and enter again. Here is my adapter code:

public class FileViewAdapter extends RecyclerView.Adapter<FileViewAdapter.Viewholder> {

    private Context context;
    private List<File> files;

    public FileViewAdapter(Context context, List<File> files) {
        this.context = context;
        this.files = files;
    }

    public FileViewAdapter(Context context){

        this.context = context;
    }

    @Override
    public Viewholder onCreateViewHolder(ViewGroup viewGroup, int i) {
        LayoutInflater inflater = LayoutInflater.from(context);
        View layout = inflater.inflate(R.layout.file_list_item, viewGroup, false);
        return new Viewholder(layout);
    }

    @Override
    public void onBindViewHolder(Viewholder viewholder, int i) {
        File file = files.get(i);
        if (file.isDirectory()) {
            viewholder.fileIcon.setImageDrawable(
                    context.getResources().getDrawable(R.drawable.ic_folder_black_24dp));
            viewholder.wholeThing.setOnClickListener(null);
        } else {
            viewholder.fileIcon.setImageDrawable(
                    context.getResources().getDrawable(R.drawable.ic_insert_drive_file_black_24dp));
            viewholder.wholeThing.setOnClickListener(null);
        }
        viewholder.fileName.setText(file.getName());
    }

    @Override
    public int getItemCount() {
        return files.size();
    }

    public void clear() {
        files.clear();
        notifyDataSetChanged();
    }

    public void addAll(List<File> newFiles) {
        files.addAll(newFiles);
        notifyDataSetChanged();
    }

    class Viewholder extends RecyclerView.ViewHolder {
        View wholeThing;
        ImageView fileIcon;
        TextView fileName;

        public Viewholder(View itemView) {
            super(itemView);
            wholeThing = itemView;
            fileIcon = (ImageView) itemView.findViewById(R.id.file_icon);
            fileName = (TextView) itemView.findViewById(R.id.file_name);
        }
    }

}

EDIT: How I am calling the constructor of adapter on activity.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_file_viewer);
    recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
}

@Override
public void onResume() {
     adapter = new Adapter(this, /*A list of File items*/);
     recyclerView.setAdapter(adapter);
     recyclerView.setLayoutManager(new LinearLayoutManager(this));
}

Body:
The problem from what i see is that the notifyDataSetChanged doesnt ocurr in the UiThread so if run ur setData method like this it will work.

 this.runOnUiThread(new Runnable() {
        public void run() {
            mAdapter.setNewData(newDataListForAdapter);
            mAdapter.notifyDataSetChanged();

        }
    });


问:
dplyr tidyeval equivalent of underscore function versions
Rencent versions of dplyr deprecate underscore versions of functions, such as filter_, in favour of tidy evaluation.

What is expected new form of the underscore forms with the new way? How do I write avoiding undefined symbols with R CMD check?

```<code>library(dplyr)

df <- data_frame(id = rep(c("a","b"), 3), val = 1:6)
df %>% filter_(~id == "a")

# want to avoid this, because it references column id in a variable-style
df %>% filter( id == "a" )

# option A
df %>% filter( UQ(rlang::sym("id")) == "a" )
# option B
df %>% filter( UQ(as.name("id")) == "a" )
# option C
df %>% filter( .data$id == "a" )
</code>```

Is there a preferred or more conside form? Option C is shortest but is slower on some of my real-world larger datasets and more complex dplyr constructs:

```<code>microbenchmark(
sym = dsPClosest %>%
  group_by(!!sym(dateVarName), !!sym("depth")) %>%
  summarise(temperature = mean(!!sym("temperature"), na.rm = TRUE)
            , moisture = mean(!!sym("moisture"), na.rm = TRUE)) %>%
  ungroup()
,data = dsPClosest %>%
    group_by(!!sym(dateVarName), .data$depth ) %>%
    summarise(temperature = mean(.data$temperature , na.rm = TRUE)
              , moisture = mean(.data$moisture , na.rm = TRUE)) %>%
    ungroup()
,times=10
)
#Unit: milliseconds
# expr        min         lq      mean     median        uq       max neval
#  sym   80.05512   84.97267  122.7513   94.79805  100.9679  392.1375    10
# data 4652.83104 4741.99165 5371.5448 5039.63307 5471.9261 7926.7648    10
</code>```

There is another answer for mutate_ using even more complex syntax.

答:
Based on your comment, I guess it would be:

```<code>df %>% filter(!!as.name("id") == "a")
</code>```

rlang is unnecessary, as you can do this with !! and as.name instead of UQ and sym.

But maybe a better option is a scoped filter, which avoids quosure-related issues:

```<code>df %>% filter_at(vars("id"), all_vars(. == "a"))
</code>```

In the code above vars() determines to which columns we're going to apply the  filtering statement (in the help for filter_at, the filtering statement is called the "predicate". In this case, vars("id") means the filtering statement is applied only to the id column. The filtering statement can be either an all_vars() or any_vars() statement, though they're equivalent in this case. all_vars(. == "a") means that all of the columns in vars("id") must equal "a". Yes, it's a bit confusing.

Timings for data similar to your example: In this case, we use group_by_at and summarise_at, which are scoped versions of those functions:

```<code>set.seed(2)
df <- data_frame(group = sample(1:100,1e4*52,replace=TRUE),
                 id = rep(c(letters,LETTERS), 1e4),
                 val = sample(1:50,1e4*52,replace=TRUE))

microbenchmark(
quosure=df %>% group_by(!!as.name("group"), !!as.name("id")) %>%
  summarise(val = mean(!!as.name("val"))),
data=df %>% group_by(.data$group, .data$id) %>%
  summarise(val = mean(.data$val)),
scoped_group_by = df %>% group_by_at(vars("group","id")) %>%
  summarise_at("val", mean), times=10)
</code>```

```<code>Unit: milliseconds
            expr       min        lq      mean    median        uq       max neval cld
         quosure  59.29157  61.03928  64.39405  62.60126  67.93810  72.47615    10  a
            data 391.22784 394.65636 419.24201 413.74683 425.11709 498.42660    10   b
 scoped_group_by  69.57573  71.21068  78.26388  76.67216  82.89914  91.45061    10  a
</code>```

Original Answer

I think this is a case where you would enter the filter variable as a bare name and then use enquo and !! (the equivalent of UQ) to use the filter variable. For example:

```<code>library(dplyr)

fnc = function(data, filter_var, filter_value) {
  filter_var=enquo(filter_var)
  data %>% filter(!!filter_var == filter_value)
}

fnc(df, id, "a")
</code>```

```<code>     id   val
1     a     1
2     a     3
3     a     5
</code>```

```<code>fnc(mtcars, carb, 3)
</code>```

```<code>   mpg cyl  disp  hp drat   wt qsec vs am gear carb
1 16.4   8 275.8 180 3.07 4.07 17.4  0  0    3    3
2 17.3   8 275.8 180 3.07 3.73 17.6  0  0    3    3
3 15.2   8 275.8 180 3.07 3.78 18.0  0  0    3    3
</code>```

Body:
Rencent versions of dplyr deprecate underscore versions of functions, such as filter_, in favour of tidy evaluation.

What is expected new form of the underscore forms with the new way? How do I write avoiding undefined symbols with R CMD check?

library(dplyr)

df <- data_frame(id = rep(c("a","b"), 3), val = 1:6)
df %>% filter_(~id == "a")

# want to avoid this, because it references column id in a variable-style
df %>% filter( id == "a" )

# option A
df %>% filter( UQ(rlang::sym("id")) == "a" )
# option B
df %>% filter( UQ(as.name("id")) == "a" )
# option C
df %>% filter( .data$id == "a" )

Is there a preferred or more conside form? Option C is shortest but is slower on some of my real-world larger datasets and more complex dplyr constructs:

microbenchmark(
sym = dsPClosest %>%
  group_by(!!sym(dateVarName), !!sym("depth")) %>%
  summarise(temperature = mean(!!sym("temperature"), na.rm = TRUE)
            , moisture = mean(!!sym("moisture"), na.rm = TRUE)) %>%
  ungroup()
,data = dsPClosest %>%
    group_by(!!sym(dateVarName), .data$depth ) %>%
    summarise(temperature = mean(.data$temperature , na.rm = TRUE)
              , moisture = mean(.data$moisture , na.rm = TRUE)) %>%
    ungroup()
,times=10
)
#Unit: milliseconds
# expr        min         lq      mean     median        uq       max neval
#  sym   80.05512   84.97267  122.7513   94.79805  100.9679  392.1375    10
# data 4652.83104 4741.99165 5371.5448 5039.63307 5471.9261 7926.7648    10

There is another answer for mutate_ using even more complex syntax.

Body:
Based on your comment, I guess it would be:

df %>% filter(!!as.name("id") == "a")

rlang is unnecessary, as you can do this with !! and as.name instead of UQ and sym.

But maybe a better option is a scoped filter, which avoids quosure-related issues:

df %>% filter_at(vars("id"), all_vars(. == "a"))

In the code above vars() determines to which columns we're going to apply the  filtering statement (in the help for filter_at, the filtering statement is called the "predicate". In this case, vars("id") means the filtering statement is applied only to the id column. The filtering statement can be either an all_vars() or any_vars() statement, though they're equivalent in this case. all_vars(. == "a") means that all of the columns in vars("id") must equal "a". Yes, it's a bit confusing.

Timings for data similar to your example: In this case, we use group_by_at and summarise_at, which are scoped versions of those functions:

set.seed(2)
df <- data_frame(group = sample(1:100,1e4*52,replace=TRUE),
                 id = rep(c(letters,LETTERS), 1e4),
                 val = sample(1:50,1e4*52,replace=TRUE))

microbenchmark(
quosure=df %>% group_by(!!as.name("group"), !!as.name("id")) %>%
  summarise(val = mean(!!as.name("val"))),
data=df %>% group_by(.data$group, .data$id) %>%
  summarise(val = mean(.data$val)),
scoped_group_by = df %>% group_by_at(vars("group","id")) %>%
  summarise_at("val", mean), times=10)

Unit: milliseconds
            expr       min        lq      mean    median        uq       max neval cld
         quosure  59.29157  61.03928  64.39405  62.60126  67.93810  72.47615    10  a
            data 391.22784 394.65636 419.24201 413.74683 425.11709 498.42660    10   b
 scoped_group_by  69.57573  71.21068  78.26388  76.67216  82.89914  91.45061    10  a

Original Answer

I think this is a case where you would enter the filter variable as a bare name and then use enquo and !! (the equivalent of UQ) to use the filter variable. For example:

library(dplyr)

fnc = function(data, filter_var, filter_value) {
  filter_var=enquo(filter_var)
  data %>% filter(!!filter_var == filter_value)
}

fnc(df, id, "a")

     id   val
1     a     1
2     a     3
3     a     5

fnc(mtcars, carb, 3)

   mpg cyl  disp  hp drat   wt qsec vs am gear carb
1 16.4   8 275.8 180 3.07 4.07 17.4  0  0    3    3
2 17.3   8 275.8 180 3.07 3.73 17.6  0  0    3    3
3 15.2   8 275.8 180 3.07 3.78 18.0  0  0    3    3


问:
In Rails 3 how can you access the user_id of the last user in the database in your model?
Edit See Below:

```<code>class Post < ActiveRecord::Base
  last_user_id = User.last.id
  validates_inclusion_of :user_id, :in => 0..last_user_id
end
</code>```

The above solution works but as vojlo explains, once in production the code will only be executed once and the model will then validate against an incorrect range of users.

I'm working on a tutorial (rails 3.0.3) and have tried for the last half hour to figure out how to tell rails that one of the classes in my model should make sure the :user_id is within the range zero to the user_id of the last user in the database.

I know I need to be using:

```<code>validates_inclusion_of :user_id, :in 0..(can't figure out this piece)
</code>```

I was able to easily ensure the number entered for User_ID in numeric with:

```<code>validates_numericality_of :user_id
</code>```

I'm looking for information on where to research this, I took a good look at the ActiveRecord Validators documentation and didn't find much there.

答:
Range from zero to last user id? The only way is writing a new validator. </p>

<p>I don't understand your purpose, but check out validates_associated. </p>

ContentLicense: CC BY-SA 2.5

Body:
Edit See Below:

class Post < ActiveRecord::Base
  last_user_id = User.last.id
  validates_inclusion_of :user_id, :in => 0..last_user_id
end

The above solution works but as vojlo explains, once in production the code will only be executed once and the model will then validate against an incorrect range of users.

I'm working on a tutorial (rails 3.0.3) and have tried for the last half hour to figure out how to tell rails that one of the classes in my model should make sure the :user_id is within the range zero to the user_id of the last user in the database.

I know I need to be using:

validates_inclusion_of :user_id, :in 0..(can't figure out this piece)

I was able to easily ensure the number entered for User_ID in numeric with:

validates_numericality_of :user_id

I'm looking for information on where to research this, I took a good look at the ActiveRecord Validators documentation and didn't find much there.

Body:
Range from zero to last user id? The only way is writing a new validator.

I don't understand your purpose, but check out validates_associated.


问:
Having issues with a program that skips the If Else part of the code
I am creating a text-based game and, so far, I have gotten the if and the else statements to work. However, the else if does not work. I've gone through several sites and several pages and even talked with a  fellow coder. I've done what I can, such as replacing == with "?".equals(Call#)) then changing to Call#.equals("?"). I had the else if as a nested if but that also failed.

```<code>public static void FirstRoom(){
    System.out.println("You are in a room filled with\ndarkness and no memory of your\npast. There are several objects\nscattered on the ground and a\nlantern in your hand. You find\na lighter in your pocket.");
    System.out.println("\n ----- \n");
    Scanner console = new Scanner(System.in);
    String Call = console.next();
    if (Call.equals("Inspect")) {
        System.out.println("\nYou can only see darkness");
        System.out.println("\n ----- \n");
    } else if(Call.equals("Light Lantern")){
        System.out.println("\nYou pull the lighter from your pocket and,\nturning the knob, raise the\nlantern's wick and light it.");
    System.out.println("\n ----- \n");
    }else{
        System.out.println("\nWhat do you mean?");
        System.out.println("\n ----- \n");
    FirstRoom();
   }
   String Call2 = console.next();
   if(Call.equals("Inspect")) {
       System.out.println("You see a large sword to your\nright and a bag to the left.\nThere is a door in front\n of you and a door behind.");
       System.out.println("\n ----- \n");
   }
}
</code>```

When I type in Light Lantern, I expect it to say You pull the lighter from your pocket and, turning the knob, raise the lantern's wick and light it. Instead, it skips to the second statement (supposed to also wait for you to input for the second) and says You see a large sword to your right and a bag to your left. There is a door in front of you and a door behind.

Inspect

You can only see
darkness

Light Lantern
You see a large sword to your
right and a bag to your left.
There is a door in front
 of you and a door behind.

答:
You need to use console.nextLine() not console.next()

```<code>String Call /*bad name*/ = console.next();
</code>```

Will only take the first word "Light"

```<code>String call = console.nextLine(); //using normal JAVA naming conventions
</code>```

Will take everything up to the the end of line character which means you will be able to input multiple words like "Light Lantern"

For more information on the difference between next() and nextLine() you can check out this post

Body:
I am creating a text-based game and, so far, I have gotten the if and the else statements to work. However, the else if does not work. I've gone through several sites and several pages and even talked with a  fellow coder. I've done what I can, such as replacing == with "?".equals(Call#)) then changing to Call#.equals("?"). I had the else if as a nested if but that also failed.

public static void FirstRoom(){
    System.out.println("You are in a room filled with\ndarkness and no memory of your\npast. There are several objects\nscattered on the ground and a\nlantern in your hand. You find\na lighter in your pocket.");
    System.out.println("\n ----- \n");
    Scanner console = new Scanner(System.in);
    String Call = console.next();
    if (Call.equals("Inspect")) {
        System.out.println("\nYou can only see darkness");
        System.out.println("\n ----- \n");
    } else if(Call.equals("Light Lantern")){
        System.out.println("\nYou pull the lighter from your pocket and,\nturning the knob, raise the\nlantern's wick and light it.");
    System.out.println("\n ----- \n");
    }else{
        System.out.println("\nWhat do you mean?");
        System.out.println("\n ----- \n");
    FirstRoom();
   }
   String Call2 = console.next();
   if(Call.equals("Inspect")) {
       System.out.println("You see a large sword to your\nright and a bag to the left.\nThere is a door in front\n of you and a door behind.");
       System.out.println("\n ----- \n");
   }
}

When I type in Light Lantern, I expect it to say You pull the lighter from your pocket and, turning the knob, raise the lantern's wick and light it. Instead, it skips to the second statement (supposed to also wait for you to input for the second) and says You see a large sword to your right and a bag to your left. There is a door in front of you and a door behind.

Inspect

You can only see
darkness

Light Lantern
You see a large sword to your
right and a bag to your left.
There is a door in front
 of you and a door behind.

Body:
You need to use console.nextLine() not console.next()

String Call /*bad name*/ = console.next();

Will only take the first word "Light"

String call = console.nextLine(); //using normal JAVA naming conventions

Will take everything up to the the end of line character which means you will be able to input multiple words like "Light Lantern"

For more information on the difference between next() and nextLine() you can check out this post


问:
I am trying to access my mysql server from the command line by typing in this: mysql -u root -p
I am trying to access my MySQL server from the command prompt. I typed in this command:

```<code>c:\Program Files\MySQL\MySQL Server 5.7\bin>mysql -u root -p
</code>```

Then I entered my password when prompted and got this error message:

```<code>ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)
</code>```

I'm not too experienced with MySQL or the command line interface so I'm not sure what this error message means. I've tried watching some youtube videos on different ways to do this but I keep on getting the same error. Any help on this would be appreciated. Thanks!

答:
It means your attempt to get authenticated failed.

That is probably because you are using the wrong password for the "root" user in your mysql instance. When you say "entered my password" do you mean you entered the password you set for root when you installed mysql, or do you mean the password you have for your user account on that computer?

It needs to be the mysql password for the user in mysql named "root". Note that this has nothing to do with any users in the operating system that is running this instance of mysql.

Check your choice of password and make sure you use the mysql "root" user password. Or if you have the credentials (that is, the user name and password) for a different user in the mysql instance, use those instead.

Body:
I am trying to access my MySQL server from the command prompt. I typed in this command:

c:\Program Files\MySQL\MySQL Server 5.7\bin>mysql -u root -p

Then I entered my password when prompted and got this error message:

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)

I'm not too experienced with MySQL or the command line interface so I'm not sure what this error message means. I've tried watching some youtube videos on different ways to do this but I keep on getting the same error. Any help on this would be appreciated. Thanks!


问:
Why doesn't the website default to index.html by default?
I'm unable to put in the domain name to observe the landing page:

```<code>http://some_url.com
</code>```

Error:

Could not find file 'E:\index.html'.

However, the following works:

http://some_url.com/index.html

FYI:
This website was built with Elm, Giraffe, and .Net Core.

答:
If you're running Giraffe, then you're running F# which means there's a good chance you're using IApplicationBuilder for configuring your server. You should be able to call UseDefaultFiles, then UseStaticFiles to use index.html as a default document.

```<code>let configureApp (app : IApplicationBuilder) =
    app.UseGiraffeErrorHandler errorHandler
    app.UseDefaultFiles() |> ignore
    app.UseStaticFiles() |> ignore
    app.UseGiraffe webApp
</code>```

From Serving Static Files:

UseDefaultFiles must be called before UseStaticFiles to serve the default file. UseDefaultFiles is a URL re-writer that doesn't actually serve the file. You must enable the static file middleware (UseStaticFiles) to serve the file.

Body:
I'm unable to put in the domain name to observe the landing page:

http://some_url.com

Error:

Could not find file 'E:\index.html'.

However, the following works:

http://some_url.com/index.html

FYI:
This website was built with Elm, Giraffe, and .Net Core.

Body:
If you're running Giraffe, then you're running F# which means there's a good chance you're using IApplicationBuilder for configuring your server. You should be able to call UseDefaultFiles, then UseStaticFiles to use index.html as a default document.

let configureApp (app : IApplicationBuilder) =
    app.UseGiraffeErrorHandler errorHandler
    app.UseDefaultFiles() |> ignore
    app.UseStaticFiles() |> ignore
    app.UseGiraffe webApp

From Serving Static Files:

UseDefaultFiles must be called before UseStaticFiles to serve the default file. UseDefaultFiles is a URL re-writer that doesn't actually serve the file. You must enable the static file middleware (UseStaticFiles) to serve the file.


问:
Python: strptime() format-timezone field not working as expected
I'm trying to parse a given string of custom format date into epoch time with the following code:

```<code>time_tuple = time.strptime('Tue Dec 05 13:01:48 PST 2017', '%a %b %d %X %Z %Y')
time_epoch = time.mktime(time_tuple)
</code>```

The given date format is as shown in the code. The problem I'm facing is when the code is compile I keep getting error saying:

```<code> ValueError: time data 'Tue Dec 05 13:01:48 PST 2017' does not match format '%a %b %d %X %Z %Y'
</code>```

From what I can see, the format seems to be exactly as specified according to: https://docs.python.org/3/library/datetime.html

What seem's to be wrong?

Edit:
I have tried using datetime instead of time as well, but didn't work

```<code>time_tuple = datetime.strptime('Tue Dec 05 13:01:48 PST 2017', '%a %b %d %X %Z %Y')
</code>```

Based on the comments below, it seems like the timezone field(%Z) is causing the problem. It seems like that field is based on the timezone the code is ran, and not the timezone the input string gives.

答:
You are using a different time zone than those described in the docs, however, if you change the time zone, you can try this:</p>

```<code>import time
time_tuple = time.strptime('Tue Dec 05 13:01:48 EST 2017', '%a %b %d %X %Z %Y')
time_epoch = time.mktime(time_tuple)
</code>```

Body:
I'm trying to parse a given string of custom format date into epoch time with the following code:

time_tuple = time.strptime('Tue Dec 05 13:01:48 PST 2017', '%a %b %d %X %Z %Y')
time_epoch = time.mktime(time_tuple)

The given date format is as shown in the code. The problem I'm facing is when the code is compile I keep getting error saying:

 ValueError: time data 'Tue Dec 05 13:01:48 PST 2017' does not match format '%a %b %d %X %Z %Y'

From what I can see, the format seems to be exactly as specified according to: https://docs.python.org/3/library/datetime.html

What seem's to be wrong?

Edit:
I have tried using datetime instead of time as well, but didn't work

time_tuple = datetime.strptime('Tue Dec 05 13:01:48 PST 2017', '%a %b %d %X %Z %Y')

Based on the comments below, it seems like the timezone field(%Z) is causing the problem. It seems like that field is based on the timezone the code is ran, and not the timezone the input string gives.

Body:
You are using a different time zone than those described in the docs, however, if you change the time zone, you can try this:

import time
time_tuple = time.strptime('Tue Dec 05 13:01:48 EST 2017', '%a %b %d %X %Z %Y')
time_epoch = time.mktime(time_tuple)


问:
Why angular4 calls two times oauth/token?
I have problem but didn't see what make that problem. I made one laravel+passport project and try with other angular4 project to "talk" with laravel project. This is start angular4 project. But am stack. AS you can see in picture below  when I click login it calls two times oauth/token to laravel project. Firstable time he have Request method: Options, and second one is OK and have Request method: POST. First one didn't return nothing and the other one return valid results with token and reset token. I don't see where is that first one triggered but second one is triggered after finished first request. Code where is placed click on login button is here.

Hope that someone can tell me what is the problem.

答: That first request options is part of CORS. This is normal. See this page if you want more details: https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS</p>


问:
EF Code First self rating by DataAnnotations or fluent API
I have one class:

```<code>[Table(nameof(User), Schema = "Administration")]
public class User : IBaseModel
{
    [Key]
    public int UserId { get; set; }

    #region IBaseModel

    public int AddedBy { get; set; }
    [ForeignKey("AddedBy")]
    public virtual User UserAddedBy { get; set; }

    public int ModifiedBy { get; set; }
    [ForeignKey("ModifiedBy")]
    public virtual User UserModifiedBy { get; set; }

    #endregion
}
</code>```

I try create self relation for this table (who AddedBy and who ModifiedBy item)

When my class look like above and I try use Add-Migration init on Package Manager Console it returns error:

Unable to determine the principal end of an association between the
  types 'abc.Administration.User' and 'abc.Administration.User'.
  The principal end of this association must be explicitly configured
  using either the relationship fluent API or data annotations.

after this error I try use fluent API and on method OnModelCreating (in my context) I wrote:

```<code>    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Administration.User>().HasOptional(e => e.UserAddedBy).WithMany().HasForeignKey(m => m.AddedBy);
        modelBuilder.Entity<Administration.User>().HasOptional(e => e.UserModifiedBy).WithMany().HasForeignKey(m => m.ModifiedBy);
    }
</code>```

and again try Add-Migration init but again I saw error message:

One or more validation errors were detected during model generation:

abc.User_UserAddedBy: : Multiplicity conflicts with the referential
  constraint in Role 'User_UserAddedBy_Target' in relationship
  'User_UserAddedBy'. Because all of the properties in the Dependent
  Role are non-nullable, multiplicity of the Principal Role must be '1'.
  abc.User_UserModifiedBy: : Multiplicity conflicts with the referential
  constraint in Role 'User_UserModifiedBy_Target' in relationship
  'User_UserModifiedBy'. Because all of the properties in the Dependent
  Role are non-nullable, multiplicity of the Principal Role must be '1'.

I found information to add Required to attribute before virtual properites but it did not help.

答:
Based on the clarifications provided, you can do the following:

Disable enforcing the Foreign Key(FK)

Add a dummy user, you could use a name like "System", give it an imposible id like -1.

Make system be it's own UserAddedBy and UserModifiedBy

Enable enforcing FK.
Now you can add users with System as their UserModifiedBy and UserAddedBy.

This way the only "cheated" in user will be System, which, in my humble opinion, is an OK trade-off.

Body:
I have one class:

[Table(nameof(User), Schema = "Administration")]
public class User : IBaseModel
{
    [Key]
    public int UserId { get; set; }

    #region IBaseModel

    public int AddedBy { get; set; }
    [ForeignKey("AddedBy")]
    public virtual User UserAddedBy { get; set; }

    public int ModifiedBy { get; set; }
    [ForeignKey("ModifiedBy")]
    public virtual User UserModifiedBy { get; set; }

    #endregion
}

I try create self relation for this table (who AddedBy and who ModifiedBy item)

When my class look like above and I try use Add-Migration init on Package Manager Console it returns error:

Unable to determine the principal end of an association between the
  types 'abc.Administration.User' and 'abc.Administration.User'.
  The principal end of this association must be explicitly configured
  using either the relationship fluent API or data annotations.

after this error I try use fluent API and on method OnModelCreating (in my context) I wrote:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Administration.User>().HasOptional(e => e.UserAddedBy).WithMany().HasForeignKey(m => m.AddedBy);
        modelBuilder.Entity<Administration.User>().HasOptional(e => e.UserModifiedBy).WithMany().HasForeignKey(m => m.ModifiedBy);
    }

and again try Add-Migration init but again I saw error message:

One or more validation errors were detected during model generation:

abc.User_UserAddedBy: : Multiplicity conflicts with the referential
  constraint in Role 'User_UserAddedBy_Target' in relationship
  'User_UserAddedBy'. Because all of the properties in the Dependent
  Role are non-nullable, multiplicity of the Principal Role must be '1'.
  abc.User_UserModifiedBy: : Multiplicity conflicts with the referential
  constraint in Role 'User_UserModifiedBy_Target' in relationship
  'User_UserModifiedBy'. Because all of the properties in the Dependent
  Role are non-nullable, multiplicity of the Principal Role must be '1'.

I found information to add Required to attribute before virtual properites but it did not help.


问:
Python 2.7, How to convert (ord>128) string into unicode
I am trying to convert a standard string containing >128 chars into Unicode.
For example,

```<code>a='en métro'
b=u'en métro'
c = whatToDoWith(a)
</code>```

so that I can get c exactly equals to b, in both types and values.

In my real program I got the following error when txt = 'en métro'

```<code> utxt = txt.decode('utf8')
 File "C:\Python27\lib\encodings\utf_8.py", line 16, in decode
 return codecs.utf_8_decode(input, errors, True)
 UnicodeDecodeError: 'utf8' codec can't decode byte 0xe9 in position 3: invalid continuation byte
</code>```

To investigate, I also have the following test code:

```<code># -*- coding: utf-8 -*-

c='en métro'
print type(c)
print c
d=c.decode('utf8')
print type(d)
print d
a='中文'
print type(a)
print a
b=a.decode('utf8')
print type(b)
print b
</code>```

and this time result is expected:

```<code><type 'str'>
en mÃ©tro
<type 'unicode'>
en métro
<type 'str'>
ä¸æ–‡
<type 'unicode'>
中文
</code>```

I cannot tell what's the different with my real program.  I also have the
# -*- coding: utf-8 -*- line in it.

Can someone point out possible problems?

答:
str.decode() should most definitely work in your case:

```<code># coding=utf-8

a = "en métro"
b = u"en métro"
c = a.decode("utf-8")

print(type(a))  # <type 'str'>
print(type(b))  # <type 'unicode'>
print(type(c))  # <type 'unicode'>

if b == c:
    print("b equals c!")  # hooray they are equal in value

if type(b) == type(c):
    print("b is the same type as c!")  # hooray they are of equal type
</code>```

Body:
I am trying to convert a standard string containing >128 chars into Unicode.
For example,

a='en métro'
b=u'en métro'
c = whatToDoWith(a)

so that I can get c exactly equals to b, in both types and values.

In my real program I got the following error when txt = 'en métro'

 utxt = txt.decode('utf8')
 File "C:\Python27\lib\encodings\utf_8.py", line 16, in decode
 return codecs.utf_8_decode(input, errors, True)
 UnicodeDecodeError: 'utf8' codec can't decode byte 0xe9 in position 3: invalid continuation byte

To investigate, I also have the following test code:

# -*- coding: utf-8 -*-

c='en métro'
print type(c)
print c
d=c.decode('utf8')
print type(d)
print d
a='中文'
print type(a)
print a
b=a.decode('utf8')
print type(b)
print b

and this time result is expected:

<type 'str'>
en mÃ©tro
<type 'unicode'>
en métro
<type 'str'>
ä¸æ–‡
<type 'unicode'>
中文

I cannot tell what's the different with my real program.  I also have the
# -*- coding: utf-8 -*- line in it.

Can someone point out possible problems?

Body:
str.decode() should most definitely work in your case:

# coding=utf-8

a = "en métro"
b = u"en métro"
c = a.decode("utf-8")

print(type(a))  # <type 'str'>
print(type(b))  # <type 'unicode'>
print(type(c))  # <type 'unicode'>

if b == c:
    print("b equals c!")  # hooray they are equal in value

if type(b) == type(c):
    print("b is the same type as c!")  # hooray they are of equal type


问:
What verb would describe the relationship between a C# class and its Attribute?
Considering the following:

```<code>[Export]
public class BudgetView : ViewBase, IView
{
    // Members Galore
}
</code>```

It is clear that you would say BudgetView extends ViewBase, and it implements IView, but what does it to to poor old Export?

Perhaps BudgetView uses Export?
Or BudgetView applies Export?

I need this for my documentation.  I'm need to be very formal and very detailed.

Edit:

My UML tool is very restrictive about what I can and cannot do.  I cannot make custom stereotypes for instance.

答:
A dotnet attribute is similar to a uml stereotype</p>

```<code><<Export>>
BudgetView
</code>```

Body:
Considering the following:

[Export]
public class BudgetView : ViewBase, IView
{
    // Members Galore
}

It is clear that you would say BudgetView extends ViewBase, and it implements IView, but what does it to to poor old Export?

Perhaps BudgetView uses Export?
Or BudgetView applies Export?

I need this for my documentation.  I'm need to be very formal and very detailed.

Edit:

My UML tool is very restrictive about what I can and cannot do.  I cannot make custom stereotypes for instance.

Body:
A dotnet attribute is similar to a uml stereotype

<<Export>>
BudgetView