问:
Error overriding get method in Django Rest
I am new to Django Rest Framework. In my work I was suggested to work in an existing project and learn the Rest Framework on the fly. So I was writing an api to display the vehicle-list with both the get_queryset method and the get method. I could make the get_queryset() method work, but the get() method isn't working (I'm assuming some kind of syntax error).

The working code :

```<code>class VehicleList(ListAPIView):
    permission_classes = (AllowAny,)
    serializer_class = FleetVehicleSerializer

    def get_queryset(self):
        domain = self.request.META.get('HTTP_DOMAIN', None)
        if domain is None:
            raise Exception("Domain is missing in request header")
        qs = FleetVehicle.objects.using(domain).all()
        return qs
</code>```

Not working code:

```<code>class VehicleList(ListAPIView):
    permission_classes = (AllowAny,)
    serializer_class = FleetVehicleSerializer

  def get(self, request):
        domain = self.request.META.get('HTTP_DOMAIN', None)
        if domain is None:
            raise Exception("Domain is missing in request header")
        vehicles = FleetVehicle.objects.using(domain).all()
        return Response({'a': vehicles},status=status.HTTP_200_OK, content_type = 'application/json' )
</code>```

The output is supposed to be a json, I am testing the api in postman. Can anyone help me with the possible syntax error?

答:
You need to override list method for ListAPIView. You can do it like this:

```<code>class VehicleList(ListAPIView):
    permission_classes = (AllowAny,)
    serializer_class = FleetVehicleSerializer

  def list(self, request, *args, **kwargs):
        domain = self.request.META.get('HTTP_DOMAIN', None)
        if domain is None:
            raise Exception("Domain is missing in request header")
        vehicles = FleetVehicle.objects.using(domain).all()
        data = self.get_serializer(vehicles, many=True).data
        return Response({'a': data},status=status.HTTP_200_OK, content_type = 'application/json' )
</code>```

Body:
I am new to Django Rest Framework. In my work I was suggested to work in an existing project and learn the Rest Framework on the fly. So I was writing an api to display the vehicle-list with both the get_queryset method and the get method. I could make the get_queryset() method work, but the get() method isn't working (I'm assuming some kind of syntax error).

The working code :

class VehicleList(ListAPIView):
    permission_classes = (AllowAny,)
    serializer_class = FleetVehicleSerializer

    def get_queryset(self):
        domain = self.request.META.get('HTTP_DOMAIN', None)
        if domain is None:
            raise Exception("Domain is missing in request header")
        qs = FleetVehicle.objects.using(domain).all()
        return qs

Not working code:

class VehicleList(ListAPIView):
    permission_classes = (AllowAny,)
    serializer_class = FleetVehicleSerializer

  def get(self, request):
        domain = self.request.META.get('HTTP_DOMAIN', None)
        if domain is None:
            raise Exception("Domain is missing in request header")
        vehicles = FleetVehicle.objects.using(domain).all()
        return Response({'a': vehicles},status=status.HTTP_200_OK, content_type = 'application/json' )

The output is supposed to be a json, I am testing the api in postman. Can anyone help me with the possible syntax error?

Body:
You need to override list method for ListAPIView. You can do it like this:

class VehicleList(ListAPIView):
    permission_classes = (AllowAny,)
    serializer_class = FleetVehicleSerializer

  def list(self, request, *args, **kwargs):
        domain = self.request.META.get('HTTP_DOMAIN', None)
        if domain is None:
            raise Exception("Domain is missing in request header")
        vehicles = FleetVehicle.objects.using(domain).all()
        data = self.get_serializer(vehicles, many=True).data
        return Response({'a': data},status=status.HTTP_200_OK, content_type = 'application/json' )


来源: stackexchange

问:
How to Pause AnimationTimer for a Set Number of Seconds?
I'm currently working on a game made with JavaFX, and I was wondering how to pause AnimationTimer's for a set number of seconds? I tried using Thread.sleep, but it causes the entire window to freeze. Any help would be appreciated, I can provide code if needed.</p>

答:
You could create a PauseTransition that starts your timer after a certain amount of time has passed.

```<code>void pauseTimerForDuration(AnimationTimer timer, Duration duration) {
    PauseTransition pt = new PauseTransition(duration);
    pt.setOnFinished(event -> timer.start());

    timer.stop();
    pt.play();
}
</code>```

Note: This uses javafx.util.Duration, not java.time.Duration.

If you want something you can reuse, then you can try a Timeline.

```<code>Timeline createPauseTimerTimeline(AnimationTimer timer, Duration duration) {
    return new Timeline(
            new KeyFrame(Duration.ZERO, event -> timer.stop()),
            new KeyFrame(duration, event -> timer.play())
    );
}
</code>```

Then store the Timeline somewhere and call playFromStart() when you want to pause your timer.

ContentLicense: CC BY-SA 4.0

Body:
You could create a PauseTransition that starts your timer after a certain amount of time has passed.

void pauseTimerForDuration(AnimationTimer timer, Duration duration) {
    PauseTransition pt = new PauseTransition(duration);
    pt.setOnFinished(event -> timer.start());

    timer.stop();
    pt.play();
}

Note: This uses javafx.util.Duration, not java.time.Duration.

If you want something you can reuse, then you can try a Timeline.

Timeline createPauseTimerTimeline(AnimationTimer timer, Duration duration) {
    return new Timeline(
            new KeyFrame(Duration.ZERO, event -> timer.stop()),
            new KeyFrame(duration, event -> timer.play())
    );
}

Then store the Timeline somewhere and call playFromStart() when you want to pause your timer.


问:
Is there any tool to optimize MySQL Queries?
I am  undergoing the performance test on MySQL and i need your guidance.If there is any tool available to optimize the MySQL Queries.Please let me know.The tool i am  seeking for is one which would be useful to identify the query which causing the memory leak.

Thanks,

答: User wampserver, it provides a mysql gui.</p>

ContentLicense: CC BY-SA 3.0


问:
Calculate sentence from row to row in .txt file using vs code
I am doing the sentiment analysis. The initial code is just for a string. However, I want to make the program run and process the sentiment analysis for each sentence in a .csv file. The program is run using vs code.

Here is how I modified my code:

fp = open('C:/Users/User/Desktop/hj.txt',encoding='utf-8' ,errors='ignore' ) # Open file on read mode
    lines = fp.read().split("\n") # Create a list containing all lines
    fp.close() # Close file
    print(lines)
    print("----------------------------------------------------\n")

    # simple example to tokenize paragraph into sentences for VADER
    from nltk import tokenize

    sentence_list = tokenize.sent_tokenize(lines)
    paragraphSentiments = 0.0
    for sentence in sentence_list:
        vs = analyzer.polarity_scores(sentence)

        print("{:-<69} {}".format(sentence, str(vs["compound"])))
        paragraphSentiments += vs["compound"]
    print("AVERAGE SENTIMENT FOR PARAGRAPH: \t" + str(round(paragraphSentiments / len(sentence_list), 4)))
    print("----------------------------------------------------")
```

<p>I expect the output is sentiment analysis for each sentence in the .csv file. The errors I got are :</p>

``` File "C:\Users\User\Anaconda3\lib\site-packages\nltk\tokenize\__init__.py", line 95, in sent_tokenize
    return tokenizer.tokenize(text)
  File "C:\Users\User\Anaconda3\lib\site-packages\nltk\tokenize\punkt.py", line 1237, in tokenize
    return list(self.sentences_from_text(text, realign_boundaries))
  File "C:\Users\User\Anaconda3\lib\site-packages\nltk\tokenize\punkt.py", line 1285, in sentences_from_text
    return [text[s:e] for s, e in self.span_tokenize(text, realign_boundaries)]
  File "C:\Users\User\Anaconda3\lib\site-packages\nltk\tokenize\punkt.py", line 1276, in span_tokenize
    return [(sl.start, sl.stop) for sl in slices]
  File "C:\Users\User\Anaconda3\lib\site-packages\nltk\tokenize\punkt.py", line 1276, in <listcomp>
    return [(sl.start, sl.stop) for sl in slices]
  File "C:\Users\User\Anaconda3\lib\site-packages\nltk\tokenize\punkt.py", line 1316, in _realign_boundaries
    for sl1, sl2 in _pair_iter(slices):
  File "C:\Users\User\Anaconda3\lib\site-packages\nltk\tokenize\punkt.py", line 312, in _pair_iter
    prev = next(it)
  File "C:\Users\User\Anaconda3\lib\site-packages\nltk\tokenize\punkt.py", line 1289, in _slices_from_text
    for match in self._lang_vars.period_context_re().finditer(text):
TypeError: expected string or bytes-like object
```

答:
The initial code is this:

```<code>paragraph = "It was one of the worst movies I've seen, despite good reviews. Unbelievably bad acting!! Poor direction. VERY poor production. The movie was bad. Very bad movie. VERY BAD movie!"

    from nltk import tokenize

    sentence_list = tokenize.sent_tokenize(paragraph)
    paragraphSentiments = 0.0
    for sentence in sentence_list:
        vs = analyzer.polarity_scores(sentence)
        print("{:-<69} {}".format(sentence, str(vs["compound"])))
        paragraphSentiments += vs["compound"]
    print("AVERAGE SENTIMENT FOR PARAGRAPH: \t" + str(round(paragraphSentiments / len(sentence_list), 4)))

print("{:-<69} {}".format(lines, str(vs["compound"])))
    paragraphSentiments += vs["compound"]
    print("AVERAGE SENTIMENT FOR PARAGRAPH: \t" + str(round(paragraphSentiments / len(sent_list), 4)))
</code>```

I changed the code so it can read and do the sentiment analysis for each of the sentence in the .csv file. However, I hit with error. The modified code is as below:

```<code>    fp = open('C:/Users/User/Desktop/hj.txt',encoding='utf-8' ,errors='ignore' ) # Open file on read mode
    lines = fp.read().split("\n") # Create a list containing all lines
    fp.close() # Close file
    print(lines)

    from nltk import tokenize

    for line in lines:
        sent_list = tokenize.sent_tokenize(lines)
        paragraphSentiments = 0.0
    for sent in sent_list:

  sentence_list = tokenize.sent_tokenize(lines)
   paragraphSentiments = 0.0
   for sentence in sentence_list:
        vs = analyzer.polarity_scores(sentence)

       print("{:-<69} {}".format(sentence, str(vs["compound"])))
    #  paragraphSentiments += vs["compound"]
  print("AVERAGE SENTIMENT FOR PARAGRAPH: \t" + str(round(paragraphSentiments / len(sentence_list), 4)))
</code>```

Anyone knows whats the issue here?

Body:
I am doing the sentiment analysis. The initial code is just for a string. However, I want to make the program run and process the sentiment analysis for each sentence in a .csv file. The program is run using vs code.

Here is how I modified my code:

fp = open('C:/Users/User/Desktop/hj.txt',encoding='utf-8' ,errors='ignore' ) # Open file on read mode
    lines = fp.read().split("\n") # Create a list containing all lines
    fp.close() # Close file
    print(lines)
    print("----------------------------------------------------\n")

    # simple example to tokenize paragraph into sentences for VADER
    from nltk import tokenize

    sentence_list = tokenize.sent_tokenize(lines)
    paragraphSentiments = 0.0
    for sentence in sentence_list:
        vs = analyzer.polarity_scores(sentence)

        print("{:-<69} {}".format(sentence, str(vs["compound"])))
        paragraphSentiments += vs["compound"]
    print("AVERAGE SENTIMENT FOR PARAGRAPH: \t" + str(round(paragraphSentiments / len(sentence_list), 4)))
    print("----------------------------------------------------")

I expect the output is sentiment analysis for each sentence in the .csv file. The errors I got are :

 File "C:\Users\User\Anaconda3\lib\site-packages\nltk\tokenize\__init__.py", line 95, in sent_tokenize
    return tokenizer.tokenize(text)
  File "C:\Users\User\Anaconda3\lib\site-packages\nltk\tokenize\punkt.py", line 1237, in tokenize
    return list(self.sentences_from_text(text, realign_boundaries))
  File "C:\Users\User\Anaconda3\lib\site-packages\nltk\tokenize\punkt.py", line 1285, in sentences_from_text
    return [text[s:e] for s, e in self.span_tokenize(text, realign_boundaries)]
  File "C:\Users\User\Anaconda3\lib\site-packages\nltk\tokenize\punkt.py", line 1276, in span_tokenize
    return [(sl.start, sl.stop) for sl in slices]
  File "C:\Users\User\Anaconda3\lib\site-packages\nltk\tokenize\punkt.py", line 1276, in <listcomp>
    return [(sl.start, sl.stop) for sl in slices]
  File "C:\Users\User\Anaconda3\lib\site-packages\nltk\tokenize\punkt.py", line 1316, in _realign_boundaries
    for sl1, sl2 in _pair_iter(slices):
  File "C:\Users\User\Anaconda3\lib\site-packages\nltk\tokenize\punkt.py", line 312, in _pair_iter
    prev = next(it)
  File "C:\Users\User\Anaconda3\lib\site-packages\nltk\tokenize\punkt.py", line 1289, in _slices_from_text
    for match in self._lang_vars.period_context_re().finditer(text):
TypeError: expected string or bytes-like object

Body:
The initial code is this:

paragraph = "It was one of the worst movies I've seen, despite good reviews. Unbelievably bad acting!! Poor direction. VERY poor production. The movie was bad. Very bad movie. VERY BAD movie!"

    from nltk import tokenize

    sentence_list = tokenize.sent_tokenize(paragraph)
    paragraphSentiments = 0.0
    for sentence in sentence_list:
        vs = analyzer.polarity_scores(sentence)
        print("{:-<69} {}".format(sentence, str(vs["compound"])))
        paragraphSentiments += vs["compound"]
    print("AVERAGE SENTIMENT FOR PARAGRAPH: \t" + str(round(paragraphSentiments / len(sentence_list), 4)))

print("{:-<69} {}".format(lines, str(vs["compound"])))
    paragraphSentiments += vs["compound"]
    print("AVERAGE SENTIMENT FOR PARAGRAPH: \t" + str(round(paragraphSentiments / len(sent_list), 4)))

I changed the code so it can read and do the sentiment analysis for each of the sentence in the .csv file. However, I hit with error. The modified code is as below:

    fp = open('C:/Users/User/Desktop/hj.txt',encoding='utf-8' ,errors='ignore' ) # Open file on read mode
    lines = fp.read().split("\n") # Create a list containing all lines
    fp.close() # Close file
    print(lines)

    from nltk import tokenize

    for line in lines:
        sent_list = tokenize.sent_tokenize(lines)
        paragraphSentiments = 0.0
    for sent in sent_list:

  sentence_list = tokenize.sent_tokenize(lines)
   paragraphSentiments = 0.0
   for sentence in sentence_list:
        vs = analyzer.polarity_scores(sentence)

       print("{:-<69} {}".format(sentence, str(vs["compound"])))
    #  paragraphSentiments += vs["compound"]
  print("AVERAGE SENTIMENT FOR PARAGRAPH: \t" + str(round(paragraphSentiments / len(sentence_list), 4)))

Anyone knows whats the issue here?


问:
How to ignore SSL validation in .net core 2.1
I am trying to call a web service that is deployed on a Linux Server that has a self-signed certificate from an application developed in .net core and deployed on an IIS server (Windows server 2012).

But when I try to call the endpoint the next error is thrown:

"Message": "The SSL connection could not be established, see inner
  exception.",
      "Description": "InnerError : System.Security.Authentication.AuthenticationException: Authentication
  failed, see inner exception. --->
  System.ComponentModel.Win32Exception: Mensaje recibido inesperado, o
  bien su formato es incorrecto\r\n   --- End of inner exception stack
  trace ---\r\n   at
  System.Net.Security.SslState.StartSendAuthResetSignal(ProtocolToken
  message, AsyncProtocolRequest asyncRequest, ExceptionDispatchInfo
  exception)\r\n   at
  System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken
  message, AsyncProtocolRequest asyncRequest)\r\n   at
  System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32
  count, AsyncProtocolRequest asyncRequest)\r\n   at
  System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32
  count, AsyncProtocolRequest asyncRequest)\r\n   at
  System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32
  readBytes, AsyncProtocolRequest asyncRequest)\r\n   at
  System.Net.Security.SslState.PartialFrameCallback(AsyncProtocolRequest
  asyncRequest)\r\n--- End of stack trace from previous location where
  exception was thrown ---\r\n   at
  System.Net.Security.SslState.ThrowIfExceptional()\r\n   at
  System.Net.Security.SslState.InternalEndProcessAuthentication(LazyAsyncResult
  lazyResult)\r\n   at
  System.Net.Security.SslState.EndProcessAuthentication(IAsyncResult
  result)\r\n   at
  System.Net.Security.SslStream.EndAuthenticateAsClient(IAsyncResult
  asyncResult)\r\n   at
  System.Net.Security.SslStream.<>c.b__47_1(IAsyncResult
  iar)\r\n   at
  System.Threading.Tasks.TaskFactory1.FromAsyncCoreLogic(IAsyncResult
  iar, Func2 endFunction, Action1 endAction, Task1 promise, Boolean
  requiresSynchronization)\r\n--- End of stack trace from previous
  location where exception was thrown ---\r\n   at
  System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Stream
  stream, SslClientAuthenticationOptions sslOptions, CancellationToken
  cancellationToken) | stackTrace :    at
  System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Stream
  stream, SslClientAuthenticationOptions sslOptions, CancellationToken
  cancellationToken)\r\n   at
  System.Threading.Tasks.ValueTask1.get_Result()\r\n   at
  System.Net.Http.HttpConnectionPool.CreateConnectionAsync(HttpRequestMessage
  request, CancellationToken cancellationToken)\r\n   at
  System.Threading.Tasks.ValueTask1.get_Result()\r\n   at
  System.Net.Http.HttpConnectionPool.WaitForCreatedConnectionAsync(ValueTask1
  creationTask)\r\n   at
  System.Threading.Tasks.ValueTask1.get_Result()\r\n   at
  System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage
  request, Boolean doRequestAuth, CancellationToken
  cancellationToken)\r\n   at
  System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request,
  CancellationToken cancellationToken)\r\n   at
  System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask,
  HttpRequestMessage request, CancellationTokenSource cts, Boolean
  disposeCts)\r\n   at
  ReservasProxy.Data.APIConnection.CallXMLFormDataApiPostAsyc(String
  body) in
  C:\gitProjects\ResevasProxy\ReservasProxy\ReservasProxy\Data\APIConnection.cs:line
  181\r\n

I already try the next solutions but they didn´t work.

Solution 1 :

```<code>          using (var httpClientHandler = new HttpClientHandler())
        {
            httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; };
            // Make your request...
            //send request
            using (var httpClient = new HttpClient(httpClientHandler))
            {

                var content = new StringContent(body, Encoding.UTF8, "application/soap+xml");
                HttpResponseMessage response = await httpClient.PostAsync(_url, content);
                //var res = await response.Content.ReadAsAsync<T>();

            }

        }
</code>```

Solution 2:

```<code>            //send request
        using (var httpClient = new HttpClient())
        {
             ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
            ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
            var content = new StringContent(body, Encoding.UTF8, "application/soap+xml");
            HttpResponseMessage response = await httpClient.PostAsync(_url, content);

        }
</code>```

Solution 3:
Trying to import the certificate and then make the call but still not working.

```<code>const string certPath = @"C:\soaProdcer.cer";
var handler = new HttpClientHandler
            {
                ClientCertificateOptions = ClientCertificateOption.Manual,
                SslProtocols = System.Security.Authentication.SslProtocols.Tls
            };
            handler.ClientCertificates.Add(new System.Security.Cryptography.X509Certificates.X509Certificate(certPath));

            //send request
            using (var httpClient = new HttpClient(handler))
            {
                var content = new StringContent(body, Encoding.UTF8, "application/soap+xml");
                HttpResponseMessage response = await httpClient.PostAsync(_url, content);

            }
</code>```

I got the certificate using OpenSSL

```<code>>openssl s_client -showcerts -connect serversoa:443

No client certificate CA names sent
---
SSL handshake has read 774 bytes and written 493 bytes
---
New, TLSv1/SSLv3, Cipher is RC4-SHA
Server public key is 1024 bit
Secure Renegotiation IS supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
SSL-Session:
    Protocol  : TLSv1
    Cipher    : RC4-SHA
    Session-ID: 4E0F69C75B8F041101562F7E9B3EA349
    Session-ID-ctx:
    Master-Key: 61A916A9B8AF26281B5F7A0138DF5E4C2A4B83995E0B3FDD2274BAD0D8E3C2B5E98AA7CCB48A6543F6814C2540B18848
    Key-Arg   : None
    PSK identity: None
    PSK identity hint: None
    SRP username: None
    Start Time: 1558979896
    Timeout   : 300 (sec)
    Verify return code: 18 (self signed certificate)
</code>```

I imported the certificate into the IIS server into the trusted root certification authorities.

答:
The error does not indicate a trouble with the certificate CA authority, but rather a response from a server that is not expected for the TLS to be established.

As the author has figured out the client supported 1.2 and the server 1.0 and it caused the trouble.

P.S. I would recommend using only TLS 1.2 if that is the option with browser support that you need to handle. (only old versions do not support 1.2.)

Body:
I am trying to call a web service that is deployed on a Linux Server that has a self-signed certificate from an application developed in .net core and deployed on an IIS server (Windows server 2012).

But when I try to call the endpoint the next error is thrown:

"Message": "The SSL connection could not be established, see inner
  exception.",
      "Description": "InnerError : System.Security.Authentication.AuthenticationException: Authentication
  failed, see inner exception. --->
  System.ComponentModel.Win32Exception: Mensaje recibido inesperado, o
  bien su formato es incorrecto\r\n   --- End of inner exception stack
  trace ---\r\n   at
  System.Net.Security.SslState.StartSendAuthResetSignal(ProtocolToken
  message, AsyncProtocolRequest asyncRequest, ExceptionDispatchInfo
  exception)\r\n   at
  System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken
  message, AsyncProtocolRequest asyncRequest)\r\n   at
  System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32
  count, AsyncProtocolRequest asyncRequest)\r\n   at
  System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32
  count, AsyncProtocolRequest asyncRequest)\r\n   at
  System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32
  readBytes, AsyncProtocolRequest asyncRequest)\r\n   at
  System.Net.Security.SslState.PartialFrameCallback(AsyncProtocolRequest
  asyncRequest)\r\n--- End of stack trace from previous location where
  exception was thrown ---\r\n   at
  System.Net.Security.SslState.ThrowIfExceptional()\r\n   at
  System.Net.Security.SslState.InternalEndProcessAuthentication(LazyAsyncResult
  lazyResult)\r\n   at
  System.Net.Security.SslState.EndProcessAuthentication(IAsyncResult
  result)\r\n   at
  System.Net.Security.SslStream.EndAuthenticateAsClient(IAsyncResult
  asyncResult)\r\n   at
  System.Net.Security.SslStream.<>c.b__47_1(IAsyncResult
  iar)\r\n   at
  System.Threading.Tasks.TaskFactory1.FromAsyncCoreLogic(IAsyncResult
  iar, Func2 endFunction, Action1 endAction, Task1 promise, Boolean
  requiresSynchronization)\r\n--- End of stack trace from previous
  location where exception was thrown ---\r\n   at
  System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Stream
  stream, SslClientAuthenticationOptions sslOptions, CancellationToken
  cancellationToken) | stackTrace :    at
  System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Stream
  stream, SslClientAuthenticationOptions sslOptions, CancellationToken
  cancellationToken)\r\n   at
  System.Threading.Tasks.ValueTask1.get_Result()\r\n   at
  System.Net.Http.HttpConnectionPool.CreateConnectionAsync(HttpRequestMessage
  request, CancellationToken cancellationToken)\r\n   at
  System.Threading.Tasks.ValueTask1.get_Result()\r\n   at
  System.Net.Http.HttpConnectionPool.WaitForCreatedConnectionAsync(ValueTask1
  creationTask)\r\n   at
  System.Threading.Tasks.ValueTask1.get_Result()\r\n   at
  System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage
  request, Boolean doRequestAuth, CancellationToken
  cancellationToken)\r\n   at
  System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request,
  CancellationToken cancellationToken)\r\n   at
  System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask,
  HttpRequestMessage request, CancellationTokenSource cts, Boolean
  disposeCts)\r\n   at
  ReservasProxy.Data.APIConnection.CallXMLFormDataApiPostAsyc(String
  body) in
  C:\gitProjects\ResevasProxy\ReservasProxy\ReservasProxy\Data\APIConnection.cs:line
  181\r\n

I already try the next solutions but they didn´t work.

Solution 1 :

          using (var httpClientHandler = new HttpClientHandler())
        {
            httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; };
            // Make your request...
            //send request
            using (var httpClient = new HttpClient(httpClientHandler))
            {

                var content = new StringContent(body, Encoding.UTF8, "application/soap+xml");
                HttpResponseMessage response = await httpClient.PostAsync(_url, content);
                //var res = await response.Content.ReadAsAsync<T>();

            }

        }

Solution 2:

            //send request
        using (var httpClient = new HttpClient())
        {
             ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
            ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
            var content = new StringContent(body, Encoding.UTF8, "application/soap+xml");
            HttpResponseMessage response = await httpClient.PostAsync(_url, content);

        }

Solution 3:
Trying to import the certificate and then make the call but still not working.

const string certPath = @"C:\soaProdcer.cer";
var handler = new HttpClientHandler
            {
                ClientCertificateOptions = ClientCertificateOption.Manual,
                SslProtocols = System.Security.Authentication.SslProtocols.Tls
            };
            handler.ClientCertificates.Add(new System.Security.Cryptography.X509Certificates.X509Certificate(certPath));

            //send request
            using (var httpClient = new HttpClient(handler))
            {
                var content = new StringContent(body, Encoding.UTF8, "application/soap+xml");
                HttpResponseMessage response = await httpClient.PostAsync(_url, content);

            }

I got the certificate using OpenSSL

>openssl s_client -showcerts -connect serversoa:443

No client certificate CA names sent
---
SSL handshake has read 774 bytes and written 493 bytes
---
New, TLSv1/SSLv3, Cipher is RC4-SHA
Server public key is 1024 bit
Secure Renegotiation IS supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
SSL-Session:
    Protocol  : TLSv1
    Cipher    : RC4-SHA
    Session-ID: 4E0F69C75B8F041101562F7E9B3EA349
    Session-ID-ctx:
    Master-Key: 61A916A9B8AF26281B5F7A0138DF5E4C2A4B83995E0B3FDD2274BAD0D8E3C2B5E98AA7CCB48A6543F6814C2540B18848
    Key-Arg   : None
    PSK identity: None
    PSK identity hint: None
    SRP username: None
    Start Time: 1558979896
    Timeout   : 300 (sec)
    Verify return code: 18 (self signed certificate)

I imported the certificate into the IIS server into the trusted root certification authorities.


问:
How to create OLAP cube using azure data lake store?
I have 3 csv data sets. I want to create an OLAP cube so that it creates a schema joining all the 3 data sets. How can we do it in Azure? Can we use Azure data lake for this?</p>

答:
In Azure, data held in OLTP systems such as Azure SQL Database is copied into the OLAP system, such as Azure Analysis Services.

In Azure, all of the following data stores will meet the core requirements for OLAP:

SQL Server with Columnstore indexes

Azure Analysis Services SQL

Server Analysis Services (SSAS)

For more details, refer “OLAP in Azure” and "Defining and Deploying a Cube".

Hope this helps.


问:
Spring boot Request Mapping URI Patterns
There is a request mapping like this:

```<code>@DeleteMapping(value = "/{version:.+}")
</code>```

I not sure what is the .+ does, but from what i know, this delete mapping can accept a value and match to path variable version, something like:

```<code>DELETE
/abc
</code>```

Value abc will map to path variable version

Why the .+ is needed?

Edited Question:
What is the difference with just /{version}, is there any special case that requires .+?

答:
@DeleteMapping(value = "/{version:.+}")

.+ means "one or more of any characters" - thats standard regex/

version: means - put that match in path variable named version.

Body:
There is a request mapping like this:

@DeleteMapping(value = "/{version:.+}")

I not sure what is the .+ does, but from what i know, this delete mapping can accept a value and match to path variable version, something like:

DELETE
/abc

Value abc will map to path variable version

Why the .+ is needed?

Edited Question:
What is the difference with just /{version}, is there any special case that requires .+?


问:
How to run iPhone emulator WITHOUT starting Xcode?
On my old Mac running Snow Leopard, I could type "ios" into spotlight and it would start up the iPhone/iPad emulator by itself.

I have since had to get a new machine running Lion. I have installed Xcode for Lion, I have installed the developer tool options from the preferences panel.

But the "ios" option is no longer there :(  The only way now seems to be to run Xcode, create an empty project and then launch emulator with the run option.

I have searched and searched the internet and the Facebook, but nothing helps.

Does anyone know how to run only the emulator on Lion?

Update:
In response to @ike_love thread below.
that answer is not assured to work on all Yosemite machines.

答:
The easiest way is to use Spotlight Search. Just click CMD+Space and type in search Simulator. Just like this:

And in few seconds emulated device will be loaded:

To switch to another device you can use menu under Hardware -> Device

There are few different cool instruments you can use under Hardware menu, such as orientation change, gestures, buttons, FaceID, keyboard or audio inputs.


问:
How to find the maximum element in the matrix using function?
```<code> #include<stdio.h>
 int findMax(int **a,int r,int c);
 int main()
 {
  int a[10][10],i,j,max,r,c;
  printf("Enter the number of rows in the matrix\n");
  scanf("%d",&r);
  printf("Enter the number of columns in the matrix\n");
  scanf("%d",&c);
  printf("Enter the elements in the matrix\n");
  for(i=1;i<=r;i++)
  {  for(j=1;j<=c;j++)
     scanf("%d",&[i][j]);
  }
  printf("The matrix is\n");
  for(i=1;i<=r;i++)
  { for(j=1;j<=c;j++)
    scanf("%d",&a[i][j]);
  }printf("\n");}
  max=findMax((int **)a,r,c);
  printf("The maximum elements in the matrix is %d\n",max);
  return 0;
  }
  int findMax(int **a,int r,int c)
  {
    int t,i,j;
    t=a[1][1];
    for(i=1;i<r;i++)
    { for(j=1;j<c;j++)
    { if(a[i][j]>t)
        t=a[i][j];
    }
    }
   return (t);
  }
</code>```

Here I attached my coding, I need to find the maximum element present in the matrix using function, I am doing the coding, calling function is not executed, I don't know why, Help me to figure it out.

答:
```<code>#include<stdio.h>
#include<stdlib.h>
int findMax(int **a,int m,int n)
{
    int i,j,larg;
    larg=a[0][0];
    for(i=0;i<m;i++)
    {
        for(j=0;j<n;j++)
        {
            if(larg<a[i][j])
                larg=a[i][j];
        }
    }
    return larg;
}
int main()
{
    int m,n,i,j,larg;
    printf("Enter the number of rows in the matrix\n");
    scanf("%d",&m);
    printf("Enter the number of columns in the matrix\n");
    scanf("%d",&n);
    printf("Enter the elements in the matrix\n");
    int **a=(int**)malloc(m*sizeof(int *));
    for(i=0;i<m;i++)
        a[i]=(int *)malloc(n*sizeof(int));
    for(i=0;i<m;i++)
        for(j=0;j<n;j++)
            scanf("%d\n",&a[i][j]);
    larg=findMax(a,m,n);
    printf("The matrix is\n");
    for(i=0;i<m;i++)
    {
        for(j=0;j<n;j++)
        {
            printf("%d ",a[i][j]);
        }
        printf("\n");
    }
    printf("The maximum element in the matrix is %d\n",larg);
    return 0;
}
</code>```

Body:
 #include<stdio.h>
 int findMax(int **a,int r,int c);
 int main()
 {
  int a[10][10],i,j,max,r,c;
  printf("Enter the number of rows in the matrix\n");
  scanf("%d",&r);
  printf("Enter the number of columns in the matrix\n");
  scanf("%d",&c);
  printf("Enter the elements in the matrix\n");
  for(i=1;i<=r;i++)
  {  for(j=1;j<=c;j++)
     scanf("%d",&[i][j]);
  }
  printf("The matrix is\n");
  for(i=1;i<=r;i++)
  { for(j=1;j<=c;j++)
    scanf("%d",&a[i][j]);
  }printf("\n");}
  max=findMax((int **)a,r,c);
  printf("The maximum elements in the matrix is %d\n",max);
  return 0;
  }
  int findMax(int **a,int r,int c)
  {
    int t,i,j;
    t=a[1][1];
    for(i=1;i<r;i++)
    { for(j=1;j<c;j++)
    { if(a[i][j]>t)
        t=a[i][j];
    }
    }
   return (t);
  }

Here I attached my coding, I need to find the maximum element present in the matrix using function, I am doing the coding, calling function is not executed, I don't know why, Help me to figure it out.


问:
Confused about Typescript object types {} []
I have never worked with lists, object lists etc in Typescript and im not sure how they work. The below code doesnt do much except create a few objects and create some temp values for them through a loop, but i want the console log to print out the second objects name ("image1") followed by the second objects height (21).

What is wrong with the below code? Since undefined is being printed out.

```<code>import { Component, OnInit } from '@angular/core';

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

  image = {};
  images = [this.image];

  constructor() {
  }

  ngOnInit() {
    for (let i = 0; i < 3; i++) {
      this.image = {name: "image"+i, height: 20+i};
      this.images[i] = this.image;
    }

    console.log(this.images[1][0]);
    console.log(this.images[1][1]);
  }

}
</code>```

答:
You're trying to access this.image[1] with an index [0] while the saved image is an object with name and height properties

You should access images by pointing the index of this.images then using property as a key instead of a second index

```<code>for (let i = 0; i < 3; i++) {
   const image = {name: "image"+i, height: 20+i};
   this.images[i] = image;
 }

 console.log(this.images[0].name);
 console.log(this.images[1].name);
 console.log(this.images[2].height);
...
</code>```

Body:
I have never worked with lists, object lists etc in Typescript and im not sure how they work. The below code doesnt do much except create a few objects and create some temp values for them through a loop, but i want the console log to print out the second objects name ("image1") followed by the second objects height (21).

What is wrong with the below code? Since undefined is being printed out.

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

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

  image = {};
  images = [this.image];

  constructor() {
  }

  ngOnInit() {
    for (let i = 0; i < 3; i++) {
      this.image = {name: "image"+i, height: 20+i};
      this.images[i] = this.image;
    }

    console.log(this.images[1][0]);
    console.log(this.images[1][1]);
  }

}

Body:
You're trying to access this.image[1] with an index [0] while the saved image is an object with name and height properties

You should access images by pointing the index of this.images then using property as a key instead of a second index

for (let i = 0; i < 3; i++) {
   const image = {name: "image"+i, height: 20+i};
   this.images[i] = image;
 }

 console.log(this.images[0].name);
 console.log(this.images[1].name);
 console.log(this.images[2].height);
...


问:
Multiply all values in a pandas df by max value within group
I am trying to return the max value within a pandas df for each specific group. I then want to use this max value to multiply separate values and return in a separate column.

For example, using the df below, the max value for each group in Item is:

```<code>X = 5
Y = 2
</code>```

I want to use these values to multiply all other values as a separate column.
import pandas as pd

```<code>d = ({
    'Item' : ['X','X','X','Y','Y','Y','Y'],
    'Count' : [0,2,5,3,1,2,1],
    })

df = pd.DataFrame(data = d)
</code>```

This is my attempt:

```<code>df['Mult_max'] = df.groupby('Item').apply(lambda x: x['Count'].max() * x['Count'])
</code>```

Intended Output:

```<code>  Group  Value  Mult_max
0     X      0         0
1     X      2        10
2     X      5        25
3     Y      3         9
4     Y      1         3
5     Y      2         6
6     Y      1         3
</code>```

答:
Use GroupBy.transform for Series with same size like original DataFrame filled by max values:

```<code>df['Mult_max'] = df.groupby('Item')['Count'].transform('max') * df['Count']
print (df)
  Item  Count  Mult_max
0    X      0         0
1    X      2        10
2    X      5        25
3    Y      3         9
4    Y      1         3
5    Y      2         6
6    Y      1         3
</code>```

Body:
I am trying to return the max value within a pandas df for each specific group. I then want to use this max value to multiply separate values and return in a separate column.

For example, using the df below, the max value for each group in Item is:

X = 5
Y = 2

I want to use these values to multiply all other values as a separate column.
import pandas as pd

d = ({
    'Item' : ['X','X','X','Y','Y','Y','Y'],
    'Count' : [0,2,5,3,1,2,1],
    })

df = pd.DataFrame(data = d)

This is my attempt:

df['Mult_max'] = df.groupby('Item').apply(lambda x: x['Count'].max() * x['Count'])

Intended Output:

  Group  Value  Mult_max
0     X      0         0
1     X      2        10
2     X      5        25
3     Y      3         9
4     Y      1         3
5     Y      2         6
6     Y      1         3

Body:
Use GroupBy.transform for Series with same size like original DataFrame filled by max values:

df['Mult_max'] = df.groupby('Item')['Count'].transform('max') * df['Count']
print (df)
  Item  Count  Mult_max
0    X      0         0
1    X      2        10
2    X      5        25
3    Y      3         9
4    Y      1         3
5    Y      2         6
6    Y      1         3


答:
You can find details or URL matching on this link

URL matching

REGEX: .+ means one or more.

‘*’ Matches 0 or More Characters

'+' Matches 1 or More.

Title: Spring boot Request Mapping URI Patterns


问:
How to access existing user email in devise in ruby on rails
I am using ruby on rails with Devise gem to authenticate user. Every time a new user signs with his/her email address, I can see devise is allocating new user ID to that user and registering there email address. Now I want to display a welcome message for all the first time user ( I do not want this message to appear when they login for 2nd or 3rd time).
To display the message I want to check current_user.email against all the registered email in the user table (logic here is: if the user already exists in the user table then I can safely assume that the user has already visited the website so I prevent the welcome being displayed). I am not sure how to access all the email id's in the table?? also where to do this check. I want this welcome message to be the first thing user sees as soon as there sign in is successful. Can anyone help please.

I tried to use "resource" resource_name" within sessions controller but nothing works. Not sure weather those are even remotely relevant.

```<code>    # POST /resource/sign_in
    def create
      self.resource = warden.authenticate!(auth_options)
      $sign = sign_in_count
      set_flash_message!(:notice, :signed_in)
      sign_in(resource_name, resource)
      yield resource if block_given?
      respond_with resource, location: after_sign_in_path_for(resource)
    end
</code>```

I am trying to assign sign_in_count for logged in user to a global variable called $sign so that I can use it's value to check if user has signed in for first time or not.

答:
sign_in_count is a column in users table. Should be:

```<code># sessions_controller.rb
def create
  super # just call predefined action
  set_flash_message!(:notice, :signed_in) if resource.sign_in_count == 1
end
</code>```

Body:
I am using ruby on rails with Devise gem to authenticate user. Every time a new user signs with his/her email address, I can see devise is allocating new user ID to that user and registering there email address. Now I want to display a welcome message for all the first time user ( I do not want this message to appear when they login for 2nd or 3rd time).
To display the message I want to check current_user.email against all the registered email in the user table (logic here is: if the user already exists in the user table then I can safely assume that the user has already visited the website so I prevent the welcome being displayed). I am not sure how to access all the email id's in the table?? also where to do this check. I want this welcome message to be the first thing user sees as soon as there sign in is successful. Can anyone help please.

I tried to use "resource" resource_name" within sessions controller but nothing works. Not sure weather those are even remotely relevant.

    # POST /resource/sign_in
    def create
      self.resource = warden.authenticate!(auth_options)
      $sign = sign_in_count
      set_flash_message!(:notice, :signed_in)
      sign_in(resource_name, resource)
      yield resource if block_given?
      respond_with resource, location: after_sign_in_path_for(resource)
    end

I am trying to assign sign_in_count for logged in user to a global variable called $sign so that I can use it's value to check if user has signed in for first time or not.

Body:
sign_in_count is a column in users table. Should be:

# sessions_controller.rb
def create
  super # just call predefined action
  set_flash_message!(:notice, :signed_in) if resource.sign_in_count == 1
end


问:
How do I insert a custom HTML file into WordPress without affecting the theme or other parts of the site
I am in the process of setting up a website with another author and want to have a stand alone front page which is a different theme from the rest of the site. Basically he has made the front page in an editor and sent me the file which is linked below. I have made the rest of the website and I just want to insert his front page in.

I have tried just pasting the HTML code into the page under code editor but it is formatted horribly and does not show up the same as when I click on the link.

https://www.w3schools.com/code/tryit.asp?filename=G4GBP5O9HNGN

This is the page I want as the homepage

答:
To add your front page to theme, create a child folder of the theme and create a page template on child theme. Then create a new page from dashboard and select the created page template then go to settings>>readings and check static homepage and select your page.
I hope this works let me know if this works.</p>


问:
Dynamically created Radiobutton list not firing onselected

There is a dynamically created radiolist button and the aim is to fire an even when the radio button is clicked. This is in a panel pnldynamic

```<code>    pnldynamic.Controls.Add(lbl);
                                RadioButtonList rd = new RadioButtonList();

                                foreach (CustomerFile cu in allCustomerFile)
                                {
                                       rd.Items.Add(cu.ApplicationNumber.ToString());

                                }
    rd.AutoPostBack = true;
           rd.SelectedIndexChanged += new EventHandler(radioButton_CheckedChanged);
        pnldynamic.Controls.Add(rd);
</code>```

Following is the eventhandler for radiobuttonlist on selectedindex
  change

```<code>       private void radioButton_CheckedChanged(object sender, EventArgs e)
        {
            RadioButton btn = sender as RadioButton;
            txtReferenceNumber.Text = btn.Text;
                   }
</code>```

The breakpoint in the function is not getting hit when the  radiobuttonlist is selected

答:
Try this:</p>

```<code>RadioButtonList rd = new RadioButtonList();
foreach (CustomerFile cu in allCustomerFile
{
    rd.Items.Add(cu.ApplicationNumber.ToString());
}
rd.AutoPostBack = true;
rd.SelectedIndexChanged += new EventHandler(radioButton_CheckedChanged);
pnldynamic.Controls.Add(rd);
</code>```

Body:
There is a dynamically created radiolist button and the aim is to fire an even when the radio button is clicked. This is in a panel pnldynamic

    pnldynamic.Controls.Add(lbl);
                                RadioButtonList rd = new RadioButtonList();

                                foreach (CustomerFile cu in allCustomerFile)
                                {
                                       rd.Items.Add(cu.ApplicationNumber.ToString());

                                }
    rd.AutoPostBack = true;
           rd.SelectedIndexChanged += new EventHandler(radioButton_CheckedChanged);
        pnldynamic.Controls.Add(rd);

Following is the eventhandler for radiobuttonlist on selectedindex
  change

       private void radioButton_CheckedChanged(object sender, EventArgs e)
        {
            RadioButton btn = sender as RadioButton;
            txtReferenceNumber.Text = btn.Text;
                   }

The breakpoint in the function is not getting hit when the  radiobuttonlist is selected

Body:
Try this:

RadioButtonList rd = new RadioButtonList();
foreach (CustomerFile cu in allCustomerFile
{
    rd.Items.Add(cu.ApplicationNumber.ToString());
}
rd.AutoPostBack = true;
rd.SelectedIndexChanged += new EventHandler(radioButton_CheckedChanged);
pnldynamic.Controls.Add(rd);


问:
How to set the background color of a search container put into a blue top bar?
I'm setting up a search field on my website's topbar and all my attempts to style it have failed. Topbar and topbar icons background color are blue (#6495ed) as it should be, the icons are white (as it should be), but the search container stays white. How to set it blue?

As the search input and button are placed in a search container (= a div), I have set background:#6495ed of the button and its container. I have modified several times their margin, their padding, but I haven't figured out the proper combination.

I've set a JsFiddle and weird, I can't reproduce the problem within JsFiddle! Why, strange isn't it?
https://jsfiddle.net/r5uqb8v0/1/

So this picture should explain.

https://drive.google.com/file/d/1idQKbtKHaOT-QXByAMw1tXR9l9owMUlc/view?usp=sharing

It's same problem on Chrome and Firefox.

I'm coding on a Windows 10, running MySQL 5.7.22, PHP 7.2.4 and Apache 2.4.33 (WampServer).

This is the search field HTML :

```<code><div class="item3 search-container">
  <form action="/action_page.php">
   <input type="text" placeholder="Search..." name="search">
   <button type="submit"><i class="fa fa-search"></i></button>
  </form>
</div>
</code>```

As for the CSS :

```<code>.topnav .search-container {
  border: none;
  outline: none;
  color: inherit;
  padding: 0;
  float: right;
  background: #6495ed;
  margin: 0;
  text-decoration: none;
  cursor: pointer;
}
.topnav .search-container input {
  padding: 0px;
  margin: 0;
  border: none;
  font-size: 1em;
  display: none;
  width: 100%; /* Full width */
  cursor: pointer;
}
.topnav .search-container button {
  font-size: 1.875em;
  border: none;
  outline: none;
  color: white;
  padding: 6px 10px;
  background: #6495ed;
  margin: 0;
  display: inline;
  cursor: pointer;
  width: 100%; /* Full width */
}
</code>```

Topbar and topbar icons background color are blue (#6495ed) as it should be, the icons are white (as it should be), but the search container stays white (this is the problem).

Any suggestion would be very appreciated! Thank you already for reading!

Best regards

Samuel

答:
Samuel.
It seems that the code worked locally. I used your JsFiddle code locally and the specified issue could not be replicated. Please refer to the attached screenshot. Be assured, your code works fine.Click to view this image

[At times browsers on our systems make the situation go haywire. It's advised to check if it's updated and you can even try re-installing the browser.]

Body:
I'm setting up a search field on my website's topbar and all my attempts to style it have failed. Topbar and topbar icons background color are blue (#6495ed) as it should be, the icons are white (as it should be), but the search container stays white. How to set it blue?

As the search input and button are placed in a search container (= a div), I have set background:#6495ed of the button and its container. I have modified several times their margin, their padding, but I haven't figured out the proper combination.

I've set a JsFiddle and weird, I can't reproduce the problem within JsFiddle! Why, strange isn't it?
https://jsfiddle.net/r5uqb8v0/1/

So this picture should explain.

https://drive.google.com/file/d/1idQKbtKHaOT-QXByAMw1tXR9l9owMUlc/view?usp=sharing

It's same problem on Chrome and Firefox.

I'm coding on a Windows 10, running MySQL 5.7.22, PHP 7.2.4 and Apache 2.4.33 (WampServer).

This is the search field HTML :

  <form action="/action_page.php">
   <input type="text" placeholder="Search..." name="search">
   <button type="submit"></button>
  </form>

As for the CSS :

.topnav .search-container {
  border: none;
  outline: none;
  color: inherit;
  padding: 0;
  float: right;
  background: #6495ed;
  margin: 0;
  text-decoration: none;
  cursor: pointer;
}
.topnav .search-container input {
  padding: 0px;
  margin: 0;
  border: none;
  font-size: 1em;
  display: none;
  width: 100%; /* Full width */
  cursor: pointer;
}
.topnav .search-container button {
  font-size: 1.875em;
  border: none;
  outline: none;
  color: white;
  padding: 6px 10px;
  background: #6495ed;
  margin: 0;
  display: inline;
  cursor: pointer;
  width: 100%; /* Full width */
}

Topbar and topbar icons background color are blue (#6495ed) as it should be, the icons are white (as it should be), but the search container stays white (this is the problem).

Any suggestion would be very appreciated! Thank you already for reading!

Best regards

Samuel


答:
Let's do it in Javascript in a snippet :

class HomeComponent {
  constructor() {
    this.image = {};
    this.images = [this.image];
    this.ngOnInit();
  }

  ngOnInit() {
    for (let i = 0; i < 3; i++) {
      this.image = {name: "image"+i, height: 20+i};
      this.images[i] = this.image;
    }

    console.log(this.images[1][0]);
    console.log(this.images[1][1]);
  }

}

let x = new HomeComponent();```
</div>
</div>
</p>

<p>Now let's break it up : </p>

<p>1 - you create an empty image : <code>image = {}</code><br>
2 - you create an array containing this image : <code>images = [{}]</code><br>
3 - you create a loop that iterates 3 times<br>
4 - in it, you change the image and push it in the array  </p>

<p>You then have an array of 3 elements (because you override the first value), with each having a name and height properties, that aren't the same. </p>

<p>You then try to display the key "0" & "1" of the second image of the array. </p>

<p>But it just has "name" and "height" ! </p>

<p>If you want to print the keys of the second object, you can try this instead : </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>class HomeComponent {
  constructor() {
    this.image = {};
    this.images = [this.image];
    this.ngOnInit();
  }

  ngOnInit() {
    for (let i = 0; i < 3; i++) {
      this.image = {name: "image"+i, height: 20+i};
      this.images[i] = this.image;
    }

    console.log(Object.entries(this.images[1]));
  }

}

let x = new HomeComponent();</code>```

Title: Confused about Typescript object types {} []

Body:
Let's do it in Javascript in a snippet :

class HomeComponent {
  constructor() {
    this.image = {};
    this.images = [this.image];
    this.ngOnInit();
  }

  ngOnInit() {
    for (let i = 0; i < 3; i++) {
      this.image = {name: "image"+i, height: 20+i};
      this.images[i] = this.image;
    }

    console.log(this.images[1][0]);
    console.log(this.images[1][1]);
  }

}

let x = new HomeComponent();

Now let's break it up :

1 - you create an empty image : image = {}

2 - you create an array containing this image : images = [{}]

3 - you create a loop that iterates 3 times

4 - in it, you change the image and push it in the array

You then have an array of 3 elements (because you override the first value), with each having a name and height properties, that aren't the same.

You then try to display the key "0" & "1" of the second image of the array.

But it just has "name" and "height" !

If you want to print the keys of the second object, you can try this instead :

class HomeComponent {
  constructor() {
    this.image = {};
    this.images = [this.image];
    this.ngOnInit();
  }

  ngOnInit() {
    for (let i = 0; i < 3; i++) {
      this.image = {name: "image"+i, height: 20+i};
      this.images[i] = this.image;
    }

    console.log(Object.entries(this.images[1]));
  }

}

let x = new HomeComponent();


问:
Azure recognizeText returns empty result
I have been using the OCR API for a while now, but I would like to see if the recognizeText API improved performance. The issue is that calling the recognizeText API just returns an empty string.

If I change the API call to /vision/v2.0/ocr then everything works great.

```<code>import http.client, urllib.request, urllib.parse, urllib.error, base64

headers = {
    # Request headers
    'Content-Type': 'application/octet-stream',
    'Ocp-Apim-Subscription-Key': 'MYAPIKEY',
}

params = urllib.parse.urlencode({
    # Request parameters
    'mode': 'Printed',
})

with open(filename, 'rb') as f:
    data_image = f.read()

try:
    conn = http.client.HTTPSConnection('canadacentral.api.cognitive.microsoft.com')
    conn.request("POST", "/vision/v2.0/recognizeText?%s" % params, data_image, headers)
    response = conn.getresponse()
    data = response.read()
    print(data)
    conn.close()
except Exception as e:
    print("[Errno {0}] {1}".format(e.errno, e.strerror))
</code>```

答:
Please do read the API specification: https://westus.dev.cognitive.microsoft.com/docs/services/5adf991815e1060e6355ad44/operations/587f2c6a154055056008f200

The API only returns 202-Accepted (if your request was valid). This includes a header Operation-Location which contains an URL. You make subsequent requests to that URL to retrieve the status / result of your request.

Body:
I have been using the OCR API for a while now, but I would like to see if the recognizeText API improved performance. The issue is that calling the recognizeText API just returns an empty string.

If I change the API call to /vision/v2.0/ocr then everything works great.

import http.client, urllib.request, urllib.parse, urllib.error, base64

headers = {
    # Request headers
    'Content-Type': 'application/octet-stream',
    'Ocp-Apim-Subscription-Key': 'MYAPIKEY',
}

params = urllib.parse.urlencode({
    # Request parameters
    'mode': 'Printed',
})

with open(filename, 'rb') as f:
    data_image = f.read()

try:
    conn = http.client.HTTPSConnection('canadacentral.api.cognitive.microsoft.com')
    conn.request("POST", "/vision/v2.0/recognizeText?%s" % params, data_image, headers)
    response = conn.getresponse()
    data = response.read()
    print(data)
    conn.close()
except Exception as e:
    print("[Errno {0}] {1}".format(e.errno, e.strerror))


问:
Is it appropriate to use Microsoft.Practices.EnterpriseLibrary.Caching with ASP.NET?
Working on a legacy ASP.NET application we've found that ASP.NET session gets used for caching some objects, but for some objects Microsoft.Practices.EnterpriseLibrary.Caching gets used.

Is there any reason to use Microsoft.Practices.EnterpriseLibrary.Caching over standard ASP.NET Session?

Edit

In my scenario, the Enterprise Library caching is actually being used to cache per-user data by appending the ASP.NET Session ID to the cached item's key.

答: Yes... Session is mainly for user specific data storage in the application and cache can be used for both user specific and application specific data storages.</p>

ContentLicense: CC BY-SA 2.5


问:
List files not matching a pattern?
Here's how one might list all files matching a pattern in bash:

```<code>ls *.jar
</code>```

How to list the complement of a pattern? i.e. all files not matching *.jar?

答:
Another approach can be using ls -I flag (Ignore-pattern).

```<code>ls -I '*.jar'
</code>```

Title: List files not matching a pattern?

Body:
Here's how one might list all files matching a pattern in bash:

ls *.jar

How to list the complement of a pattern? i.e. all files not matching *.jar?

Body:
Another approach can be using ls -I flag (Ignore-pattern).

ls -I '*.jar'


问:
How do we apply JSON Schema Validation to message response?
I am trying to write some sample code with Citrus Framework. Being my first attempt, I am unable to validate the JSON schema for response message.

I have added schema-repository to citrus-context.xml file but do not knnow how to use this with Java code.

Citrus-Context File

```<code><citrus:schema-repository id="schemaRepository" type="json">
        <citrus:schemas>
            <citrus:schema id="petCreation" location="classpath:org/logica/citrus/samples/PetCreationJSONSchema.json"/>
        </citrus:schemas>
</citrus:schema-repository>
</code>```

Java File

```<code>@CitrusTest
    public void end2endTest()
    {
        http().client(restClient).send().post("/pet").contentType("application/json").payload(new ClassPathResource("org\\logica\\citrus\\samples\\PetJSONCreation.json"));

        http().client(restClient).receive().response(HttpStatus.OK).messageType(MessageType.JSON);
    }

</code>```

Where to apply schema validation code if working with JSON?

答:
Once the Json schema is available in the schema repository the validation is automatically done upon processing the incoming message in a receive action.

The only thing you need to do is to provide the schema name on that receive that you would like to use for the validation.

http().client(restClient)
      .receive()
      .response(HttpStatus.OK)
      .messageType(MessageType.JSON)
      .jsonSchema("petCreation");
```

With XML schema Citrus can auto pick the right schema from the repository by its namespace. In Json we do not have something like namespaces so you need to give the schema name explicitly.

Body:
I am trying to write some sample code with Citrus Framework. Being my first attempt, I am unable to validate the JSON schema for response message.

I have added schema-repository to citrus-context.xml file but do not knnow how to use this with Java code.

Citrus-Context File

<citrus:schema-repository id="schemaRepository" type="json">
        <citrus:schemas>
            <citrus:schema id="petCreation" location="classpath:org/logica/citrus/samples/PetCreationJSONSchema.json"/>
        </citrus:schemas>
</citrus:schema-repository>

Java File

@CitrusTest
    public void end2endTest()
    {
        http().client(restClient).send().post("/pet").contentType("application/json").payload(new ClassPathResource("org\\logica\\citrus\\samples\\PetJSONCreation.json"));

        http().client(restClient).receive().response(HttpStatus.OK).messageType(MessageType.JSON);
    }

Where to apply schema validation code if working with JSON?

Body:
Once the Json schema is available in the schema repository the validation is automatically done upon processing the incoming message in a receive action.

The only thing you need to do is to provide the schema name on that receive that you would like to use for the validation.

http().client(restClient)
      .receive()
      .response(HttpStatus.OK)
      .messageType(MessageType.JSON)
      .jsonSchema("petCreation");

With XML schema Citrus can auto pick the right schema from the repository by its namespace. In Json we do not have something like namespaces so you need to give the schema name explicitly.


问:
Connect to Kubernetes mongo db in different namespace
Can anyone point out how to connect to the mongo db instance using mongo client using either command line client or from .net core programs with connection strings?

We have created a sample cluster in digitalocean with a namespace, let's say mongodatabase.

We installed the mongo statefulset with 3 replicas. We are able to successfully connect with the below command
 kubectl --kubeconfig=configfile.yaml -n mongodatabase exec -ti mongo-0 mongo
But when we connect from a different namespace or from default namespace with the pod names in the below format, it doesn't work.

```<code> kubectl --kubeconfig=configfile.yaml  exec -ti mongo-0.mongo.mongodatabase.cluster.svc.local mongo
</code>```

where mongo-0.mongo.mongodatabase.cluster.svc.local is in pod-0.service_name.namespace.cluster.svc.local (also tried pod-0.statfulset_name.namespace.cluster.svc.local and pod-0.service_name.statefulsetname.namespace.cluster.svc.local) etc.,

Can any one help with the correct dns name/connection string to be used while connecting with mongo client in command line and also from the programs like java/.net core etc.,?

Also should we use kubernetes deployment instead of statefulsets here?

答:
This is how you can get inside mongo-0 pod</p>

```<code>kubectl --kubeconfig=configfile.yaml  exec -ti mongo-0 sh
</code>```

Body:
Can anyone point out how to connect to the mongo db instance using mongo client using either command line client or from .net core programs with connection strings?

We have created a sample cluster in digitalocean with a namespace, let's say mongodatabase.

We installed the mongo statefulset with 3 replicas. We are able to successfully connect with the below command
 kubectl --kubeconfig=configfile.yaml -n mongodatabase exec -ti mongo-0 mongo
But when we connect from a different namespace or from default namespace with the pod names in the below format, it doesn't work.

 kubectl --kubeconfig=configfile.yaml  exec -ti mongo-0.mongo.mongodatabase.cluster.svc.local mongo

where mongo-0.mongo.mongodatabase.cluster.svc.local is in pod-0.service_name.namespace.cluster.svc.local (also tried pod-0.statfulset_name.namespace.cluster.svc.local and pod-0.service_name.statefulsetname.namespace.cluster.svc.local) etc.,

Can any one help with the correct dns name/connection string to be used while connecting with mongo client in command line and also from the programs like java/.net core etc.,?

Also should we use kubernetes deployment instead of statefulsets here?

Body:
This is how you can get inside mongo-0 pod

kubectl --kubeconfig=configfile.yaml  exec -ti mongo-0 sh


问:
Multi-Select listbox - check if user selected Select All option
I have a MultiSelect Listbox

```<code>@Html.ListBoxFor(model => model.DealerScopeDealerProvider.DealerScopeProvider, new MultiSelectList(providers, "ProviderCode", "ProviderName"), new { id = "providerfilter" })

$('#providerfilter').multiselect({
    search: true,
    selectAll: true,
});
</code>```

which renders HTML like this:

```<code><select id="providerfilter" multiple="multiple">
<option></option>
</select>
<div>
<a href="#" class="ms-selectall global chkimg">Select all</a>
<a href="#" class="ms-unselectall global unchkimg">Unselect all</a>
<a href="#" class="crosimg"></a>
</div>
</code>```

I want to know if user selected Select all option or not. How can I achieve this using jquery?

答:
use below jquery to get weather checkbox is select or not</p>

```<code>  if ($('.ms-selectall').is(":checked"))
  {
     // selectall button is selected
  }
  else if($('.ms-unselectall ').is(":checked"))
  {
     // unselectall  button is selected
  }
</code>```

Body:
I have a MultiSelect Listbox

@Html.ListBoxFor(model => model.DealerScopeDealerProvider.DealerScopeProvider, new MultiSelectList(providers, "ProviderCode", "ProviderName"), new { id = "providerfilter" })

$('#providerfilter').multiselect({
    search: true,
    selectAll: true,
});

which renders HTML like this:

<select id="providerfilter" multiple="multiple">
<option></option>
</select>

Select all
Unselect all

I want to know if user selected Select all option or not. How can I achieve this using jquery?

Body:
use below jquery to get weather checkbox is select or not

  if ($('.ms-selectall').is(":checked"))
  {
     // selectall button is selected
  }
  else if($('.ms-unselectall ').is(":checked"))
  {
     // unselectall  button is selected
  }


问:
Python turtle stops responding after starting a loop
I'm making a decision based game using loops inputs and stuff for a end of the year project. That includes all that we have learn this year and I have stumbled upon an issue that I have no clue how to fix. When I attempt to start a loop after running my turtle code, I get a not responding screen.

I tried putting a main loop after my turtle code, but that would not allow me to continue with my game. So I tried putting it at the end of the code and it still did not work. The turtles don't stop or anything they still move, but  when you continue with the game by entering your choice, the turtles confine moving.

I am also using the latest version of turtle and python. I don't know how to fix this so if someone could help me that would be nice.

Note: The code is an example and not the actual game and that the error occurs during the input.

```<code>import turtle
windw = turtle.Screen()
char = turtle.Turtle()

char.goto(0,10)
XD = True
while(XD):
    q = input("enter p")
</code>```

答:
The input command is what is blocking it instead use something like:</p>

```<code>ts = t.getscreen()
def callback():

    q = input("enter p")
    if q:
        dosomething()
#listens for the key q to be pressed
ts.onkey(callback,"q")
ts.listen()
t.mainloop()
</code>```

Body:
I'm making a decision based game using loops inputs and stuff for a end of the year project. That includes all that we have learn this year and I have stumbled upon an issue that I have no clue how to fix. When I attempt to start a loop after running my turtle code, I get a not responding screen.

I tried putting a main loop after my turtle code, but that would not allow me to continue with my game. So I tried putting it at the end of the code and it still did not work. The turtles don't stop or anything they still move, but  when you continue with the game by entering your choice, the turtles confine moving.

I am also using the latest version of turtle and python. I don't know how to fix this so if someone could help me that would be nice.

Note: The code is an example and not the actual game and that the error occurs during the input.

import turtle
windw = turtle.Screen()
char = turtle.Turtle()

char.goto(0,10)
XD = True
while(XD):
    q = input("enter p")

Body:
The input command is what is blocking it instead use something like:

ts = t.getscreen()
def callback():

    q = input("enter p")
    if q:
        dosomething()
#listens for the key q to be pressed
ts.onkey(callback,"q")
ts.listen()
t.mainloop()


问:
Stop the autoscroll in scrollview on user interaction swift
I using the pagecontroller in my application.

it is working fine every thing it will scroll automatically for every 3 sec time and current position also changed based on user custom swipe.

But I having one issue here when user manually swipe the scrollview on that time I want to stop the auto scroll.

Please find with the my following code.

```<code>var slides:[Slide] = [];
var offSet: CGFloat = 0
override func viewDidLoad() {
    super.viewDidLoad()

    slides = createSlides()
    setupSlideScrollView(slides: slides)

    pageControl.numberOfPages = slides.count
    pageControl.currentPage = 0
    view.bringSubview(toFront: pageControl)

    let timer = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(autoScroll), userInfo: nil, repeats: true)

}

@objc func autoScroll() {
    let totalPossibleOffset = CGFloat(slides.count - 1) * self.view.bounds.size.width
    if offSet == totalPossibleOffset {
        offSet = 0 // come back to the first image after the last image
    }
    else {
        offSet += self.view.bounds.size.width
    }
    DispatchQueue.main.async() {
        UIView.animate(withDuration: 0.3, delay: 0, options: UIViewAnimationOptions.curveLinear, animations: {
            self.scrollView.contentOffset.x = CGFloat(self.offSet)
        }, completion: nil)
    }
}
</code>```

答:
The code is untested, You should check with current index with your total number slides count

Create one global index like below and change your conditions. And you need to manage this index while swipe function as well and Invalidate your timer while swipe. Your timer object should be in global

```<code>timer.invalidate()

 var currentPage = 0
        @objc func autoScroll() {
            let totalPossibleOffset = 0
            if currentPage == slides.count {
                currentPage = 0 // come back to the first image after the last image
                totalPossibleOffset = 0
            }
            else {
currentPage = currentPage + 1
                totalPossibleOffset = currentPage * self.view.bounds.size.width

            }
            DispatchQueue.main.async() {
                UIView.animate(withDuration: 0.3, delay: 0, options: UIViewAnimationOptions.curveLinear, animations: {
                    self.scrollView.contentOffset.x = CGFloat(totalPossibleOffset)
                }, completion: nil)
            }
        }
</code>```

Body:
I using the pagecontroller in my application.

it is working fine every thing it will scroll automatically for every 3 sec time and current position also changed based on user custom swipe.

But I having one issue here when user manually swipe the scrollview on that time I want to stop the auto scroll.

Please find with the my following code.

var slides:[Slide] = [];
var offSet: CGFloat = 0
override func viewDidLoad() {
    super.viewDidLoad()

    slides = createSlides()
    setupSlideScrollView(slides: slides)

    pageControl.numberOfPages = slides.count
    pageControl.currentPage = 0
    view.bringSubview(toFront: pageControl)

    let timer = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(autoScroll), userInfo: nil, repeats: true)

}

@objc func autoScroll() {
    let totalPossibleOffset = CGFloat(slides.count - 1) * self.view.bounds.size.width
    if offSet == totalPossibleOffset {
        offSet = 0 // come back to the first image after the last image
    }
    else {
        offSet += self.view.bounds.size.width
    }
    DispatchQueue.main.async() {
        UIView.animate(withDuration: 0.3, delay: 0, options: UIViewAnimationOptions.curveLinear, animations: {
            self.scrollView.contentOffset.x = CGFloat(self.offSet)
        }, completion: nil)
    }
}

Body:
The code is untested, You should check with current index with your total number slides count

Create one global index like below and change your conditions. And you need to manage this index while swipe function as well and Invalidate your timer while swipe. Your timer object should be in global

timer.invalidate()

 var currentPage = 0
        @objc func autoScroll() {
            let totalPossibleOffset = 0
            if currentPage == slides.count {
                currentPage = 0 // come back to the first image after the last image
                totalPossibleOffset = 0
            }
            else {
currentPage = currentPage + 1
                totalPossibleOffset = currentPage * self.view.bounds.size.width

            }
            DispatchQueue.main.async() {
                UIView.animate(withDuration: 0.3, delay: 0, options: UIViewAnimationOptions.curveLinear, animations: {
                    self.scrollView.contentOffset.x = CGFloat(totalPossibleOffset)
                }, completion: nil)
            }
        }


问:
saveGIF() returns empty GIF
In R I am trying to get an animated GIF based on several images. I wrote a function returning the images and use the saveGIF() function of the animation package to create the GIF. The function returning the images works (I see the images popping up in the Viewer). When using saveGIF a GIF is created, there is no error message but the GIF is empty.</p>

```<code> library(leaflet)
 library(mapview)
 library(animation)

  latitude = c(seq(48.13608, 52.48608, 0.00145))
  longitude = c(seq(11.57278, 13.40278, 0.00061))

  sampledf <- as.data.frame(cbind(longitude, latitude))

  plot.1 <- function(df)
  {
  for (i in seq(1,nrow(df),300)){
  m<- leaflet() %>%
  addTiles() %>%
  setView( lng = 12.48778
           , lat = 50.31108
           , zoom = 4 )    %>%

  addPolylines(data = df[1:i,],
               lng = ~longitude,
               lat = ~latitude,
               color = ~"red")

  print(m)
 }
 }

  saveGIF(plot.1(sampledf),movie.name="test.gif", interval=0.5, ani.width=1980/2, ani.height=1080/2)
</code>```

答:
This might be a convoluted way to approach but I could do this by first creating png files for the sampledf data and then used magick library for producing gif's.

```<code>library(leaflet)
library(mapview)
library(magick)

counter <- 1
for (i in seq(1,nrow(sampledf),300)){

    m <- leaflet() %>%
          addTiles() %>%
          setView( lng = 12.48778
                 , lat = 50.31108
                 , zoom = 4 )    %>%
           addPolylines(data = sampledf[1:i,],
                        lng = ~longitude,
                        lat = ~latitude,
                        color = ~"red")

     mapshot(m, file = paste0("plot_", counter, ".png"))
     counter = counter + 1
}
file_names <- list.files(pattern = "plot_\\d+.png$", full.names = TRUE)

image_read(file_names) %>%
   image_animate(fps = 1) %>%
   image_write("output.gif")
</code>```

Title: saveGIF() returns empty GIF

Body:
In R I am trying to get an animated GIF based on several images. I wrote a function returning the images and use the saveGIF() function of the animation package to create the GIF. The function returning the images works (I see the images popping up in the Viewer). When using saveGIF a GIF is created, there is no error message but the GIF is empty.

 library(leaflet)
 library(mapview)
 library(animation)

  latitude = c(seq(48.13608, 52.48608, 0.00145))
  longitude = c(seq(11.57278, 13.40278, 0.00061))

  sampledf <- as.data.frame(cbind(longitude, latitude))

  plot.1 <- function(df)
  {
  for (i in seq(1,nrow(df),300)){
  m<- leaflet() %>%
  addTiles() %>%
  setView( lng = 12.48778
           , lat = 50.31108
           , zoom = 4 )    %>%

  addPolylines(data = df[1:i,],
               lng = ~longitude,
               lat = ~latitude,
               color = ~"red")

  print(m)
 }
 }

  saveGIF(plot.1(sampledf),movie.name="test.gif", interval=0.5, ani.width=1980/2, ani.height=1080/2)

Body:
This might be a convoluted way to approach but I could do this by first creating png files for the sampledf data and then used magick library for producing gif's.

library(leaflet)
library(mapview)
library(magick)

counter <- 1
for (i in seq(1,nrow(sampledf),300)){

    m <- leaflet() %>%
          addTiles() %>%
          setView( lng = 12.48778
                 , lat = 50.31108
                 , zoom = 4 )    %>%
           addPolylines(data = sampledf[1:i,],
                        lng = ~longitude,
                        lat = ~latitude,
                        color = ~"red")

     mapshot(m, file = paste0("plot_", counter, ".png"))
     counter = counter + 1
}
file_names <- list.files(pattern = "plot_\\d+.png$", full.names = TRUE)

image_read(file_names) %>%
   image_animate(fps = 1) %>%
   image_write("output.gif")


问:
How to Print Values in console Without passing in any Function?
I just want to print something in console in my typescript file. But whenever I tried to do the same , it gives a error.

```<code>console.log(this.dataList);
</code>```

Error:

error TS2391: Function implementation is missing or not immediately following the declaration.

答: Try to put the console log in init function or in the constructor. </p>

Body:
I just want to print something in console in my typescript file. But whenever I tried to do the same , it gives a error.

console.log(this.dataList);

Error:

error TS2391: Function implementation is missing or not immediately following the declaration.


问:
ImageCropper.Forms plugin not working in Xamarin.Forms iOS
I am using this plugin and ImageCropper.Forms nuget package for cropping images in Xamarin.Forms

My Android project is working fine using above example but in iOS cropping window does not open

答:
I Believe you are using Cropper from a page pushed using 'Navigation.PushModalAsync', try 'Navigation.PushAsync'.

I've raised an issue on github
https://github.com/stormlion227/ImageCropper.Forms/issues/22


问:
How can i display a particular product?
I am trying to display a particular product by clicking on it from the list

```<code><ul>
    <% products.each do |product| %>
    <tr>

        <a href="<%= products_path(@product) %>"><%= product.title %> .   </a>
        <br/>

    </tr>
    <% end %>
</ul>
</code>```

Expected results should be products/1 but the result is products.1 and should displays a list of products

答:
If you want to do in this way instead of

```<code><ul>
    <% products.each do |product| %>
    <tr>

        <a href="<%= products_path(@product) %>"><%= product.title %> .   </a>
        <br/>

    </tr>
    <% end %>
</ul>
</code>```

try

```<code><ul>
    <% products.each do |product| %>
    <tr>

        <a href="/products/#{product.id}"><%= product.title %></a>
        <br/>

    </tr>
    <% end %>
</ul>
</code>```

but in rails way you can do

```<code><ul>
    <% products.each do |product| %>
    <tr>

        <%= link_to product.title, product_path(product) %>

        <br/>

    </tr>
    <% end %>
</ul>
</code>```

or

```<code><ul>
        <% products.each do |product| %>
        <tr>

            <%= link_to product.title, product %>

            <br/>

        </tr>
        <% end %>
    </ul>
</code>```

and in routes you shoud specify

```<code>resources :products
</code>```

Title: How can i display a particular product?

Body:
I am trying to display a particular product by clicking on it from the list

    <% products.each do |product| %>

        <a href="<%= products_path(@product) %>"><%= product.title %> .

    <% end %>

Expected results should be products/1 but the result is products.1 and should displays a list of products

Body:
If you want to do in this way instead of

<ul>
    <% products.each do |product| %>
    <tr>

        <a href="<%= products_path(@product) %>"><%= product.title %> .   </a>
        <br/>

    </tr>
    <% end %>
</ul>

try

<ul>
    <% products.each do |product| %>
    <tr>

        <a href="/products/#{product.id}"><%= product.title %></a>
        <br/>

    </tr>
    <% end %>
</ul>

but in rails way you can do

<ul>
    <% products.each do |product| %>
    <tr>

        <%= link_to product.title, product_path(product) %>

        <br/>

    </tr>
    <% end %>
</ul>

or

<ul>
        <% products.each do |product| %>
        <tr>

            <%= link_to product.title, product %>

            <br/>

        </tr>
        <% end %>
    </ul>

and in routes you shoud specify

resources :products


问:
need to remove the last zeros in line
need to read a file. check for the zeros in the last of each line . if the last digit is zero I want to delete it .please help me for this </p>

```<code>input="temp.txt"
while IFS= read -r line
do
echo "output    :$line"

if [[ $line == 0$ ]]; then
  echo " blash "
  else
    echo "anotherblash"
  fi

done < "$input"
</code>```

答:
In the expression command [[ $line == 0$ ]] you use the regular expression 0$, but, as man sh tells:

When the == and != operators are used, the string to  the  right
                of the operator is considered a pattern and matched according to
                the rules described below under Pattern Matching. …

An  additional  binary operator, =~, is available, with the same
                precedence as == and !=.  When it is used,  the  string  to  the
                right  of the operator is considered an extended regular expres-
                sion and matched accordingly (as in regex(3)).

So, since you use the == operator, you have to specify a pattern as with filename matching, i. e. [[ $line == *0 ]].

Title: need to remove the last zeros in line

Body:
need to read a file. check for the zeros in the last of each line . if the last digit is zero I want to delete it .please help me for this

input="temp.txt"
while IFS= read -r line
do
echo "output    :$line"

if [[ $line == 0$ ]]; then
  echo " blash "
  else
    echo "anotherblash"
  fi

done < "$input"


问:
Hangfire is stopping with log caught stopping signal
I have configured Hangfire for my Web API solution. But the Hangfire stops working after sometime logging about stopping signal. However, if API is sit again it loads and works normally. The log produced by Hangfire before stopping is as below. What should I do to prevent this.

[137] INFO Hangfire.Server.BackgroundServerProcess - Server xyz:26756:c4da0558 caught stopping signal...
  [ServerWatchdog #1] DEBUG Hangfire.Processing.BackgroundExecution - Execution loop ServerWatchdog:32e9252b stopped in 2.2406 ms
  [ExpirationManager #1] DEBUG Hangfire.Processing.BackgroundExecution - Execution loop ExpirationManager:802eb676 stopped in 2.2681 ms
  [Worker #3] DEBUG Hangfire.Processing.BackgroundExecution - Execution loop Worker:3d798436 stopped in 2.4496 ms
  [CountersAggregator #1] DEBUG Hangfire.Processing.BackgroundExecution - Execution loop CountersAggregator:f6091560 stopped in 3.1411 ms
  [Worker #2] DEBUG Hangfire.Processing.BackgroundExecution - Execution loop Worker:8b960c88 stopped in 3.7784 ms
  [Worker #2] DEBUG Hangfire.Processing.BackgroundExecution - Execution loop Worker:8b960c88 stopped in 3.7784 ms
  [Worker #4] DEBUG Hangfire.Processing.BackgroundExecution - Execution loop Worker:8e0e3cc8 stopped in 4.2624 ms
  [DelayedJobScheduler #1] DEBUG Hangfire.Processing.BackgroundExecution - Execution loop DelayedJobScheduler:066c3859 stopped in 4.5509 ms
  [136] INFO Hangfire.Server.BackgroundServerProcess - Server xyz:26756:c4da0558 caught stopped signal...
  [Worker #1] DEBUG Hangfire.Processing.BackgroundExecution - Execution loop Worker:dfcd3314 stopped in 5.7981 ms
  [RecurringJobScheduler #1] DEBUG Hangfire.Processing.BackgroundExecution - Execution loop RecurringJobScheduler:2b8e4675 stopped in 6.1803 ms
  [ServerJobCancellationWatcher #1] DEBUG Hangfire.Processing.BackgroundExecution - Execution loop ServerJobCancellationWatcher:554692cc stopped in 6.216 ms
  [BackgroundServerProcess #1] INFO Hangfire.Server.BackgroundServerProcess - Server xyz:26756:c4da0558 All dispatchers stopped
  [ServerHeartbeatProcess #1] DEBUG Hangfire.Processing.BackgroundExecution - Execution loop ServerHeartbeatProcess:f3cc4077 stopped in 8.3409 ms
  [BackgroundServerProcess #1] DEBUG Hangfire.Server.BackgroundServerProcess - Server xyz:26756:c4da0558 is reporting itself as stopped...
  [BackgroundServerProcess #1] INFO Hangfire.Server.BackgroundServerProcess - Server xyz:26756:c4da0558 successfully reported itself as stopped in 199.8624 ms
  [BackgroundServerProcess #1] DEBUG Hangfire.Processing.BackgroundExecution - Execution loop BackgroundServerProcess:dd1eaf65 stopped in 214.6647 ms
  [BackgroundServerProcess #1] INFO Hangfire.Server.BackgroundServerProcess - Server virtuadeskdev04:26756:c4da0558 has been stopped in total 212.7921 ms

答: This was because of Application Pool Idleness set to 20 minutes. I have changed the Start type to  Always Running and now Hangfire does not stop.


问:
Instead of using a hard coded values in JavaScript, is it possible to use a cron to do it?
It's probably easiest to understand by looking at this fiddle:

http://jsfiddle.net/TdBdW/1/ - apologies for the lack of css.

As you can see, for my dynamically generated dropdowns and textboxes I have a big list of hardcoded values. I would have liked to have pulled these straight from a database but the queries take too long to run for them to be used in real-time - i.e. when the user clicks on a drop-down or tries to type in the auto-complete box.

Instead what I would like to do is have the relevant queries run nightly using a cron job but the question is how to take the results of the query and put them into my javascript file.

Anyone have any ideas how to implement this?

Any help is greatly appreciated.

Martin

答:
The best route to achieve what you want ("cron job creates data for use by javascript") is to go via JSON. This involves:

Create a cron job that a) fetches the data, and b) writes it to a file formatted using JSON conventions which is accessible from your web server,

Amend your html to include the file created by the cron job.

For simplicity you could create the javascript file using contents similar to the following:

```<code>var agentValues = [
        "excel",
        "msword",
        "ppt",
];
</code>```

You can easily create this with a static first and last line, and simply add the quoted values from your query in between. You can then load this file into your html document like any other javascript:

```<code><script type="text/javascript" src="..."></script>
</code>```

When you populate the autocomplete values, simply use a for loop over this array:

```<code>for (var i = 0; i < agentValues.length; i++) {
    $("<option>" + agentValues[i] + "</option>").appendTo($values);
}
</code>```

The above would be the most basic version of achieving your aims, and you can improve on it, e.g. by:

Adding error checking

Structuring your namespace so that you don't have many top-level variables

Adding the data values to your existing javascript, rather than a separate file

etc.

Body:
The best route to achieve what you want ("cron job creates data for use by javascript") is to go via JSON. This involves:

Create a cron job that a) fetches the data, and b) writes it to a file formatted using JSON conventions which is accessible from your web server,

Amend your html to include the file created by the cron job.

For simplicity you could create the javascript file using contents similar to the following:

var agentValues = [
        "excel",
        "msword",
        "ppt",
];

You can easily create this with a static first and last line, and simply add the quoted values from your query in between. You can then load this file into your html document like any other javascript:

<script type="text/javascript" src="..."></script>

When you populate the autocomplete values, simply use a for loop over this array:

for (var i = 0; i < agentValues.length; i++) {
    $("<option>" + agentValues[i] + "</option>").appendTo($values);
}

The above would be the most basic version of achieving your aims, and you can improve on it, e.g. by:

Adding error checking

Structuring your namespace so that you don't have many top-level variables

Adding the data values to your existing javascript, rather than a separate file

etc.


问:
PrimeNG p-table Editable Column Event Callback not working
I'm setting up a table with users details.

I'm using Angular and PrimeNG.

How can i get an event back when the row is edited and return the new data edited or a flag?

There is another way to notify that the row is modified?

Using this table: https://www.primefaces.org/primeng/#/table/edit

Example:

Before Edit ->

```<code>{"name":"Mario","surname":"Rossi","mail":"mariorossi@live.it", "phone":"003900000"}
</code>```

After Edit ->

```<code>{"name":"Mario","surname":"Rossi","mail":"mariorossi@virgilio.it", "phone":"003900000", "flag":"edit"}
</code>```

Thanks in advance :)

i've already put these callbacks but they are not working

(onEdit)="onEdit($event)" (onEditComplete)="onEditComplete($event)"
```

<pre class="lang-html prettyprint-override"><code><p-table [value]="users" >
    <ng-template pTemplate="header">
        <tr>
            <th>Nome</th>
            <th>Cognome</th>
            <th>Email</th>
            <th>Cellulare</th>
            <th>Delete</th>
        </tr>
    </ng-template>
    <ng-template pTemplate="body" let-user>
        <tr>
            <td pEditableColumn styleClass="col-button">

                <p-cellEditor>
                    <ng-template pTemplate="input">
                        <input pInputText type="text" [(ngModel)]="user.name">
                    </ng-template>
                    <ng-template pTemplate="output">
                        {{user.name}}
                    </ng-template>
                </p-cellEditor>
            </td>
            <td pEditableColumn>
                <p-cellEditor>
                    <ng-template pTemplate="input">
                        <input pInputText type="text" [(ngModel)]="user.surname" required>
                    </ng-template>
                    <ng-template pTemplate="output">
                        {{user.surname}}
                    </ng-template>
                </p-cellEditor>
            </td>
            <td>
                <p-cellEditor>
                    <ng-template pTemplate="input">
                        <input pInputText type="text" [(ngModel)]="user.mail" required>
                    </ng-template>
                    <ng-template pTemplate="output">
                        {{user.mail}}
                    </ng-template>
                </p-cellEditor>
            </td>
            <td pEditableColumn>
                <p-cellEditor>
                    <ng-template pTemplate="input">
                        <input pInputText type="text" [(ngModel)]="user.phone" required>
                    </ng-template>
                    <ng-template pTemplate="output">
                        {{user.phone}}
                    </ng-template>
                </p-cellEditor>
            </td>
            <td><button text="Elimina Utente" type="button" pButton (click)="removeUser(user)" icon="pi pi-times" class="ui-button-danger" title="Elimina Utente"></button>
            </td>
        </tr>
    </ng-template>
</p-table>
</code>```

答:
According to the Cell Editing section in the documentation:

If you require the edited row data or the selected field in the onEditInit, onEditComplete, and onEditCancel events, bind the row data to the pEditableColumn directive and the field to the pEditableColumnField directive.

```<code><td [pEditableColumn]="rowData" [pEditableColumnField]="'year'">
</code>```

Body:
I'm setting up a table with users details.

I'm using Angular and PrimeNG.

How can i get an event back when the row is edited and return the new data edited or a flag?

There is another way to notify that the row is modified?

Using this table: https://www.primefaces.org/primeng/#/table/edit

Example:

Before Edit ->

{"name":"Mario","surname":"Rossi","mail":"mariorossi@live.it", "phone":"003900000"}

After Edit ->

{"name":"Mario","surname":"Rossi","mail":"mariorossi@virgilio.it", "phone":"003900000", "flag":"edit"}

Thanks in advance :)

i've already put these callbacks but they are not working

(onEdit)="onEdit($event)" (onEditComplete)="onEditComplete($event)"

    <ng-template pTemplate="header">

            Nome
            Cognome
            Email
            Cellulare
            Delete

    </ng-template>
    <ng-template pTemplate="body" let-user>

                    <ng-template pTemplate="input">
                        <input pInputText type="text" [(ngModel)]="user.name">
                    </ng-template>
                    <ng-template pTemplate="output">
                        {{user.name}}
                    </ng-template>

                    <ng-template pTemplate="input">
                        <input pInputText type="text" [(ngModel)]="user.surname" required>
                    </ng-template>
                    <ng-template pTemplate="output">
                        {{user.surname}}
                    </ng-template>

                    <ng-template pTemplate="input">
                        <input pInputText type="text" [(ngModel)]="user.mail" required>
                    </ng-template>
                    <ng-template pTemplate="output">
                        {{user.mail}}
                    </ng-template>

                    <ng-template pTemplate="input">
                        <input pInputText type="text" [(ngModel)]="user.phone" required>
                    </ng-template>
                    <ng-template pTemplate="output">
                        {{user.phone}}
                    </ng-template>

            <button text="Elimina Utente" type="button" pButton (click)="removeUser(user)" icon="pi pi-times" class="ui-button-danger" title="Elimina Utente"></button>

    </ng-template>

Body:
According to the Cell Editing section in the documentation:

If you require the edited row data or the selected field in the onEditInit, onEditComplete, and onEditCancel events, bind the row data to the pEditableColumn directive and the field to the pEditableColumnField directive.

<td [pEditableColumn]="rowData" [pEditableColumnField]="'year'">