问:
Remove active accordion when click on another accordion in JavaScript
I need help with solving the JavaScript code for my sidebar. I saw a lot of reference and help are usually get it done by jQuery. I know jQuery is powerful but I prefer stay with regular JavaScript since I'm very new to it.

If you are reading this please don't anyhow mark as duplicate or devote because I'm doing the JavaScript research for sometime and I hope this post will become useful for myself and other people who want to use regular JavaScript.

Moving on, I actually learn to create a simple accordion from w3Schools which you can refer it at here.

In the meantime I have successfully create my custom sidebar. But the thing is I want my active accordion to be closed when clicked on other accordion.

Playground:

const sideBar = document.getElementsByClassName('pisti-sidebar');

for (let i = 0; i < sideBar.length; i++) {
  sideBar[i].addEventListener('click', function() {
    const sideBarTitle = this.nextElementSibling;

    sideBarTitle.style.display == 'none';

    if (sideBarTitle.style.display === 'block') {
      sideBarTitle.style.display = 'none';
    } else {
      sideBarTitle.style.display = 'block';
      document.querySelectorAll('.pisti-sidebar')[i].classList.remove('onload-active');
      document.querySelectorAll('.pisti-sidebar-title')[i].classList.remove('onload-active');

    }
  });
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background: #000000 !important;
  width: 100vw;
  height: 100vh;
  padding: 20px;
}

/* pisti-sidebar goes here */

.pisti-sidebar {
  background: none !important;
  border: none;
  border-left: 2px solid #888888;
  color: #888888;
  cursor: pointer;
  font-size: 20px;
  font-weight: 400;
  padding: 10px 30px 10px 20px;
  text-align: left;
  transition: 0.3s all ease;
  width: 100%;
}

.pisti-sidebar:first-child {
  padding-top: 0;
}

.pisti-sidebar-title {
  border-left: 2px solid #888888;
  display: none;
  overflow: hidden;
  transition: 0.3s all ease;
}

.pisti-sidebar:hover {
  border-color: #FFFFFF;
  color: #f7cc1b;
  transition: 0.3s all ease;
}

.pisti-sidebar-active,
.pisti-sidebar:active,
.pisti-sidebar:focus {
  border-color: #FFFFFF;
  color: #f7cc1b !important;
  outline: none;
}

.pisti-sidebar:focus+.pisti-sidebar-title {
  border-color: #FFFFFF;
  transition: 0.3s all ease;
}

.pisti-sidebar-content {
  color: #888888 !important;
  display: block;
  font-size: 16px;
  padding: 0px 30px 10px 30px;
  transition: 0.3s all ease;
}

.pisti-sidebar-content:hover {
  color: #FFFFFF !important;
  text-decoration: none;
  transition: 0.3s all ease;
}

.pisti-sidebar-content:first-child {
  padding-top: 10px;
}

.pisti-sidebar-content:last-child {
  padding-bottom: 10px;
}

/* pisti-sidebar active */

.onload-active {
  color: #f7cc1b;
  border-color: #FFFFFF;
  display: block;
}

.onload-unactive {
  color: #FFFFFF;
  border-color: #888888;
}

.pisti-sidebar:focus+.pisti-sidebar-title {
  border-color: #FFFFFF;
  transition: 0.3s all ease;
}

.pisti-sidebar-title-active {
  border-color: #FFFFFF;
}

.pisti-sidebar-title-active,
.pisti-sidebar-content-active {
  color: #f7cc1b !important;
}

.pisti-sidebar-content-active::before {
  background-color: #FFFFFF;
  border-top-right-radius: 2px;
  border-bottom-right-radius: 2px;
  content: '';
  height: 10px;
  left: 16px;
  margin-top: 8px;
  position: absolute;
  width: 6px;
}</code>```

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

      <button class="pisti-sidebar onload-active" data-pisti-sidebar="pisti-sidebar-1">Appareal</button>

        Custom shirt
        Event shirt
        Corporate shirt

      <button class="pisti-sidebar" data-pisti-sidebar="pisti-sidebar-2">Digital Printing</button>

        Poster
        Banner
        Bunting

      <button class="pisti-sidebar" data-pisti-sidebar="pisti-sidebar-3">Offset Printing</button>

        Name card
        Flyer
        Booklet

```
</div>
</div>
</p>

<p>For further explain I actually added:</p>

```document.querySelectorAll('.pisti-sidebar')[0].classList.remove('onload-active');
document.querySelectorAll('.pisti-sidebar-title')[0].classList.remove('onload-active');
```

to remove the class on first accordion so it will close it. But I have no idea how can I close the second accordion when I clicked on third or first accordion.

答:
Changed the CSS & JS to exclude the list being toggled in the for loop. Instead just toggle the .active class on the button and use the adjacent selector .pisti-sidebar.active + .pisti-sidebar-title to show its list.

const sideBars = document.getElementsByClassName('pisti-sidebar');

for (let sideBar of sideBars) {
  sideBar.onclick = e => {
    var thisEl = e.target;
    if (thisEl.classList.contains('active')) {
      thisEl.classList.remove('active');
    } else {
      thisEl.classList.add('active');
      for (activeSideBar of sideBars) {
        if (activeSideBar != thisEl) {
          activeSideBar.classList.remove('active');
        }
      }
    }
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background: #000000 !important;
  width: 100vw;
  height: 100vh;
  padding: 20px;
}

.pisti-sidebar {
  background: none !important;
  border: none;
  border-left: 2px solid #888888;
  color: #888888;
  cursor: pointer;
  font-size: 20px;
  font-weight: 400;
  padding: 10px 30px 10px 20px;
  text-align: left;
  transition: 0.3s all ease;
  width: 100%;
}

.pisti-sidebar:first-child {
  padding-top: 0;
}

.pisti-sidebar-title {
  border-left: 2px solid #888888;
  display: none;
  overflow: hidden;
  transition: 0.3s all ease;
}

.pisti-sidebar:active,
.pisti-sidebar:focus {
  outline: none;
}

.pisti-sidebar.active+.pisti-sidebar-title {
  display: block;
}

.pisti-sidebar-content {
  color: #888888 !important;
  display: block;
  font-size: 16px;
  padding: 0px 30px 10px 30px;
  transition: 0.3s all ease;
}

.pisti-sidebar-content:hover {
  color: #FFFFFF !important;
  text-decoration: none;
  transition: 0.3s all ease;
}

.pisti-sidebar-content:first-child {
  padding-top: 10px;
}

.pisti-sidebar-content:last-child {
  padding-bottom: 10px;
}

.active {
  color: #f7cc1b;
  border-color: #FFFFFF;
  display: block;
}

.onload-unactive {
  color: #FFFFFF;
  border-color: #888888;
}

.pisti-sidebar:focus+.pisti-sidebar-title {
  border-color: #FFFFFF;
  transition: 0.3s all ease;
}

.pisti-sidebar-title-active {
  border-color: #FFFFFF;
}

.pisti-sidebar-title-active,
.pisti-sidebar-content-active {
  color: #f7cc1b !important;
}

.pisti-sidebar-content-active::before {
  background-color: #FFFFFF;
  border-top-right-radius: 2px;
  border-bottom-right-radius: 2px;
  content: '';
  height: 10px;
  left: 16px;
  margin-top: 8px;
  position: absolute;
  width: 6px;
}</code>```

      <button class="pisti-sidebar active" data-pisti-sidebar="pisti-sidebar-1">Appareal</button>

        Custom shirt
        Event shirt
        Corporate shirt

      <button class="pisti-sidebar" data-pisti-sidebar="pisti-sidebar-2">Digital Printing</button>

        Poster
        Banner
        Bunting

      <button class="pisti-sidebar" data-pisti-sidebar="pisti-sidebar-3">Offset Printing</button>

        Name card
        Flyer
        Booklet

```

Body:
I need help with solving the JavaScript code for my sidebar. I saw a lot of reference and help are usually get it done by jQuery. I know jQuery is powerful but I prefer stay with regular JavaScript since I'm very new to it.

If you are reading this please don't anyhow mark as duplicate or devote because I'm doing the JavaScript research for sometime and I hope this post will become useful for myself and other people who want to use regular JavaScript.

Moving on, I actually learn to create a simple accordion from w3Schools which you can refer it at here.

In the meantime I have successfully create my custom sidebar. But the thing is I want my active accordion to be closed when clicked on other accordion.

Playground:

const sideBar = document.getElementsByClassName('pisti-sidebar');

for (let i = 0; i < sideBar.length; i++) {
  sideBar[i].addEventListener('click', function() {
    const sideBarTitle = this.nextElementSibling;

    sideBarTitle.style.display == 'none';

    if (sideBarTitle.style.display === 'block') {
      sideBarTitle.style.display = 'none';
    } else {
      sideBarTitle.style.display = 'block';
      document.querySelectorAll('.pisti-sidebar')[i].classList.remove('onload-active');
      document.querySelectorAll('.pisti-sidebar-title')[i].classList.remove('onload-active');

    }
  });
}

body {
  background: #000000 !important;
  width: 100vw;
  height: 100vh;
  padding: 20px;
}

/* pisti-sidebar goes here */

.pisti-sidebar {
  background: none !important;
  border: none;
  border-left: 2px solid #888888;
  color: #888888;
  cursor: pointer;
  font-size: 20px;
  font-weight: 400;
  padding: 10px 30px 10px 20px;
  text-align: left;
  transition: 0.3s all ease;
  width: 100%;
}

.pisti-sidebar:first-child {
  padding-top: 0;
}

.pisti-sidebar-title {
  border-left: 2px solid #888888;
  display: none;
  overflow: hidden;
  transition: 0.3s all ease;
}

.pisti-sidebar:hover {
  border-color: #FFFFFF;
  color: #f7cc1b;
  transition: 0.3s all ease;
}

.pisti-sidebar-active,
.pisti-sidebar:active,
.pisti-sidebar:focus {
  border-color: #FFFFFF;
  color: #f7cc1b !important;
  outline: none;
}

.pisti-sidebar:focus+.pisti-sidebar-title {
  border-color: #FFFFFF;
  transition: 0.3s all ease;
}

.pisti-sidebar-content {
  color: #888888 !important;
  display: block;
  font-size: 16px;
  padding: 0px 30px 10px 30px;
  transition: 0.3s all ease;
}

.pisti-sidebar-content:hover {
  color: #FFFFFF !important;
  text-decoration: none;
  transition: 0.3s all ease;
}

.pisti-sidebar-content:first-child {
  padding-top: 10px;
}

.pisti-sidebar-content:last-child {
  padding-bottom: 10px;
}

/* pisti-sidebar active */

.onload-active {
  color: #f7cc1b;
  border-color: #FFFFFF;
  display: block;
}

.onload-unactive {
  color: #FFFFFF;
  border-color: #888888;
}

.pisti-sidebar:focus+.pisti-sidebar-title {
  border-color: #FFFFFF;
  transition: 0.3s all ease;
}

.pisti-sidebar-title-active {
  border-color: #FFFFFF;
}

.pisti-sidebar-title-active,
.pisti-sidebar-content-active {
  color: #f7cc1b !important;
}

.pisti-sidebar-content-active::before {
  background-color: #FFFFFF;
  border-top-right-radius: 2px;
  border-bottom-right-radius: 2px;
  content: '';
  height: 10px;
  left: 16px;
  margin-top: 8px;
  position: absolute;
  width: 6px;
}

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

      <button class="pisti-sidebar onload-active" data-pisti-sidebar="pisti-sidebar-1">Appareal</button>

        Custom shirt
        Event shirt
        Corporate shirt

      <button class="pisti-sidebar" data-pisti-sidebar="pisti-sidebar-2">Digital Printing</button>

        Poster
        Banner
        Bunting

      <button class="pisti-sidebar" data-pisti-sidebar="pisti-sidebar-3">Offset Printing</button>

        Name card
        Flyer
        Booklet

For further explain I actually added:

document.querySelectorAll('.pisti-sidebar')[0].classList.remove('onload-active');
document.querySelectorAll('.pisti-sidebar-title')[0].classList.remove('onload-active');

to remove the class on first accordion so it will close it. But I have no idea how can I close the second accordion when I clicked on third or first accordion.

Body:
Changed the CSS & JS to exclude the list being toggled in the for loop. Instead just toggle the .active class on the button and use the adjacent selector .pisti-sidebar.active + .pisti-sidebar-title to show its list.

const sideBars = document.getElementsByClassName('pisti-sidebar');

for (let sideBar of sideBars) {
  sideBar.onclick = e => {
    var thisEl = e.target;
    if (thisEl.classList.contains('active')) {
      thisEl.classList.remove('active');
    } else {
      thisEl.classList.add('active');
      for (activeSideBar of sideBars) {
        if (activeSideBar != thisEl) {
          activeSideBar.classList.remove('active');
        }
      }
    }
  }
}

body {
  background: #000000 !important;
  width: 100vw;
  height: 100vh;
  padding: 20px;
}

.pisti-sidebar {
  background: none !important;
  border: none;
  border-left: 2px solid #888888;
  color: #888888;
  cursor: pointer;
  font-size: 20px;
  font-weight: 400;
  padding: 10px 30px 10px 20px;
  text-align: left;
  transition: 0.3s all ease;
  width: 100%;
}

.pisti-sidebar:first-child {
  padding-top: 0;
}

.pisti-sidebar-title {
  border-left: 2px solid #888888;
  display: none;
  overflow: hidden;
  transition: 0.3s all ease;
}

.pisti-sidebar:active,
.pisti-sidebar:focus {
  outline: none;
}

.pisti-sidebar.active+.pisti-sidebar-title {
  display: block;
}

.pisti-sidebar-content {
  color: #888888 !important;
  display: block;
  font-size: 16px;
  padding: 0px 30px 10px 30px;
  transition: 0.3s all ease;
}

.pisti-sidebar-content:hover {
  color: #FFFFFF !important;
  text-decoration: none;
  transition: 0.3s all ease;
}

.pisti-sidebar-content:first-child {
  padding-top: 10px;
}

.pisti-sidebar-content:last-child {
  padding-bottom: 10px;
}

.active {
  color: #f7cc1b;
  border-color: #FFFFFF;
  display: block;
}

.onload-unactive {
  color: #FFFFFF;
  border-color: #888888;
}

.pisti-sidebar:focus+.pisti-sidebar-title {
  border-color: #FFFFFF;
  transition: 0.3s all ease;
}

.pisti-sidebar-title-active {
  border-color: #FFFFFF;
}

.pisti-sidebar-title-active,
.pisti-sidebar-content-active {
  color: #f7cc1b !important;
}

.pisti-sidebar-content-active::before {
  background-color: #FFFFFF;
  border-top-right-radius: 2px;
  border-bottom-right-radius: 2px;
  content: '';
  height: 10px;
  left: 16px;
  margin-top: 8px;
  position: absolute;
  width: 6px;
}

<div class="container">
  <div class="row">
    <div class="col-12">
      <button class="pisti-sidebar active" data-pisti-sidebar="pisti-sidebar-1">Appareal</button>
      <!-- pisti-sidebar-active -->
      <div class="pisti-sidebar-title">
        <!-- pisti-sidebar-title-active -->
        <a href="#" class="pisti-sidebar-content">Custom shirt</a>
        <a href="#" class="pisti-sidebar-content">Event shirt</a>
        <a href="#" class="pisti-sidebar-content">Corporate shirt</a>
        <!-- pisti-sidebar-content-active -->
      </div>

      <button class="pisti-sidebar" data-pisti-sidebar="pisti-sidebar-2">Digital Printing</button>
      <!-- pisti-sidebar-active -->
      <div class="pisti-sidebar-title">
        <!-- pisti-sidebar-title-active -->
        <a href="#" class="pisti-sidebar-content">Poster</a>
        <a href="#" class="pisti-sidebar-content">Banner</a>
        <a href="#" class="pisti-sidebar-content">Bunting</a>
        <!-- pisti-sidebar-content-active -->
      </div>

      <button class="pisti-sidebar" data-pisti-sidebar="pisti-sidebar-3">Offset Printing</button>
      <!-- pisti-sidebar-active -->
      <div class="pisti-sidebar-title">
        <!-- pisti-sidebar-title-active -->
        <a href="#" class="pisti-sidebar-content">Name card</a>
        <a href="#" class="pisti-sidebar-content">Flyer</a>
        <a href="#" class="pisti-sidebar-content">Booklet</a>
        <!-- pisti-sidebar-content-active -->
      </div>
    </div>
  </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>


来源: stackexchange

答: We reduced the number of parallel instances of HttpClient being created. That fixed the problem for us.</p>

ContentLicense: CC BY-SA 4.0

Title: Sigabrt -6 xamarin.forms threadpool when running multiple Http calls

Body:
We have a Xamarin.Forms app which is crashing with 'signal 6 (SIGABRT), code -6 (SI_TKILL), fault addr -------- java_vm_ext.cc:534] JNI DETECTED ERROR IN APPLICATION: use of deleted global reference 0x3ce2'

We are running multiple calls to web services with HttpClient in parallel using Task.WhenAll()

The crash is random and due to this we are unable to identify the root cause.

    07-27 19:21:52.443 11988-11988/? A/DEBUG: *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
Build fingerprint: 'google/walleye/walleye:8.1.0/OPM2.171026.006.G1/4820017:user/release-keys'
Revision: 'MP1'
ABI: 'arm64'
pid: 11908, tid: 11942, name: Threadpool work  >>> com.companyname.appname <<<
signal 6 (SIGABRT), code -6 (SI_TKILL), fault addr --------
07-27 19:21:52.446 11988-11988/? A/DEBUG: Abort message: 'java_vm_ext.cc:534] JNI DETECTED ERROR IN APPLICATION: use of deleted global reference 0x3ce2'
    x0   0000000000000000  x1   0000000000002ea6  x2   0000000000000006  x3   0000000000000008
    x4   0000000000000000  x5   0000000000000000  x6   0000000000000000  x7   7f7f7f7f7f7f7f7f
    x8   0000000000000083  x9   0000000010000000  x10  00000070d01fb5f0  x11  0000000000000001
    x12  00000070d01fb0e8  x13  ffffffffffffffff  x14  ff00000000000000  x15  ffffffffffffffff
    x16  0000006366ab0fa8  x17  0000007174b8052c  x18  0000000000000000  x19  0000000000002e84
07-27 19:21:52.447 11988-11988/? A/DEBUG:     x20  0000000000002ea6  x21  0000000000000083  x22  0000000000000002  x23  00000070d01fe588
    x24  00000070d01fb689  x25  00000000000006aa  x26  00000070eb715600  x27  00000000000006a9
    x28  0000000000000043  x29  00000070d01fb630  x30  0000007174b35760
    sp   00000070d01fb5f0  pc   0000007174b35788  pstate 0000000060000000
07-27 19:21:52.449 11988-11988/? A/DEBUG: backtrace:
    #00 pc 000000000001d788  /system/lib64/libc.so (abort+120)
    #01 pc 0000000000475af0  /system/lib64/libart.so (art::Runtime::Abort(char const*)+552)
    #02 pc 000000000056b3ec  /system/lib64/libart.so (android::base::LogMessage::~LogMessage()+1004)
    #03 pc 00000000002fe620  /system/lib64/libart.so (art::JavaVMExt::JniAbort(char const*, char const*)+1712)
    #04 pc 00000000002fe878  /system/lib64/libart.so (art::JavaVMExt::JniAbortF(char const*, char const*, ...)+180)
    #05 pc 00000000004a1fc8  /system/lib64/libart.so (art::Thread::DecodeJObject(_jobject*) const+464)
    #06 pc 000000000010d3d8  /system/lib64/libart.so (art::ScopedCheck::CheckInstance(art::ScopedObjectAccess&, art::ScopedCheck::InstanceKind, _jobject*, bool)+96)
    #07 pc 000000000010c03c  /system/lib64/libart.so (art::ScopedCheck::Check(art::ScopedObjectAccess&, bool, char const*, art::JniValueType*)+644)
    #08 pc 000000000010f310  /system/lib64/libart.so (art::CheckJNI::DeleteRef(char const*, _JNIEnv*, _jobject*, art::IndirectRefKind)+632)
07-27 19:21:52.450 11988-11988/? A/DEBUG:     #09 pc 000000000000f384  <anonymous:0000007174a43000>


问:
cURL request with HttpClient - how to set the timeout on the server connection (WinInet)
I am sending cURL request using HttpClient through the method described here under.

The parameter used for this method are:

SelectedProxy = a custom class that stores my proxy's parameters

Parameters.WcTimeout = the timeout

url, header, content = the cURL request (based on this tool to convert to C# https://curl.olsh.me/).

```<code>        const SslProtocols _Tls12 = (SslProtocols)0x00000C00;
        const SecurityProtocolType Tls12 = (SecurityProtocolType)_Tls12;
        ServicePointManager.SecurityProtocol = Tls12;
        string source = "";

        using (var handler = new HttpClientHandler())
        {
            handler.UseCookies = usecookies;
            WebProxy wp = new WebProxy(SelectedProxy.Address);
            handler.Proxy = wp;

            using (var httpClient = new HttpClient(handler))
            {
                httpClient.Timeout = Parameters.WcTimeout;

                using (var request = new HttpRequestMessage(new HttpMethod(HttpMethod), url))
                {
                    if (headers != null)
                    {
                        foreach (var h in headers)
                        {
                            request.Headers.TryAddWithoutValidation(h.Item1, h.Item2);
                        }
                    }
                    if (content != "")
                    {
                        request.Content = new StringContent(content, Encoding.UTF8, "application/x-www-form-urlencoded");
                    }

                    HttpResponseMessage response = new HttpResponseMessage();
                    try
                    {
                        response = await httpClient.SendAsync(request);
                    }
                    catch (Exception e)
                    {
                        //Here the exception happens
                    }
                    source = await response.Content.ReadAsStringAsync();
                }
            }
        }
        return source;
</code>```

If I am running this without proxy, it works like a charm.
When I send a request using a proxy which I tested first from Chrome, I have the following error on my try {} catch {}. Here is the error tree

```<code>{"An error occurred while sending the request."}
    InnerException {"Unable to connect to the remote server"}
        InnerException {"A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond [ProxyAdress]"}
        SocketErrorCode: TimedOut
</code>```

By using a Stopwatch I see that the TimedOut occurred after around 30 sec.

I tried a few different handler based on the following links What's the difference between HttpClient.Timeout and using the WebRequestHandler timeout properties?, HttpClient Timeout confusion or with the WinHttpHandler.

It's worth noting that WinHttpHandler allow for a different error code, i.e. Error 12002 calling WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, 'The operation timed out'. The underlying reason is the same though it helped to target where it bugs (i.e. WinInet) which confirms also what @DavidWright was saying regarding that timeouts from HttpClient manages a different part of the request sending.

Hence my issue is coming from the time it takes to establish a connection to the server, which triggers the 30sec timeout from WinInet.

My question is then How to change those timeout?

On a side note, it's worth noting that Chrome, which uses WinInet, does not seem to suffer from this timeout, nor Cefsharp on which a big part of my app is based, and through which the same proxies can properly send requests.

答:
So thanks to @DavidWright I understand a few things:

Before that the HttpRequestMessage is sent and the timeout from HttpClient starts, a TCP connection to the server is initiated

The TCP connection has its own timeout, defined at OS level, and we do not identified a way to change it at run time from C# (question pending if anyone want to contribute)

Insisting on trying to connect works as each try benefits from previous tries, though proper exception management & manual timeout counter needs to be implemented (I actually considered a number of tries in my code, assuming each try is around 30sec)

All this together ended up in the following code:

```<code>        const SslProtocols _Tls12 = (SslProtocols)0x00000C00;
        const SecurityProtocolType Tls12 = (SecurityProtocolType)_Tls12;
        ServicePointManager.SecurityProtocol = Tls12;
        var sp = ServicePointManager.FindServicePoint(endpoint);

        sp.ConnectionLeaseTimeout = (int)Parameters.ConnectionLeaseTimeout.TotalMilliseconds;

        string source = "";

        using (var handler = new HttpClientHandler())
        {
            handler.UseCookies = usecookies;
            WebProxy wp = new WebProxy(SelectedProxy.Address);
            handler.Proxy = wp;

            using (var client = new HttpClient(handler))
            {
                client.Timeout = Parameters.WcTimeout;

                int n = 0;
                back:
                using (var request = new HttpRequestMessage(new HttpMethod(HttpMethod), endpoint))
                {

                    if (headers != null)
                    {
                        foreach (var h in headers)
                        {
                            request.Headers.TryAddWithoutValidation(h.Item1, h.Item2);
                        }
                    }
                    if (content != "")
                    {
                        request.Content = new StringContent(content, Encoding.UTF8, "application/x-www-form-urlencoded");
                    }
                    HttpResponseMessage response = new HttpResponseMessage();

                    try
                    {
                        response = await client.SendAsync(request);
                    }
                    catch (Exception e)
                    {
                        if(e.InnerException != null)
                        {
                            if(e.InnerException.InnerException != null)
                            {
                                if (e.InnerException.InnerException.Message.Contains("A connection attempt failed because the connected party did not properly respond after"))
                                {
                                    if (n <= Parameters.TCPMaxTries)
                                    {
                                        n++;
                                        goto back;
                                    }
                                }
                            }
                        }
                        // Manage here other exceptions
                    }
                    source = await response.Content.ReadAsStringAsync();
                }
            }
        }
        return source;
</code>```

On a side note, my current implementation of HttpClient may be problematic in the future. Though being disposable, HttpClient should be defined at App level through a static, and not within a using statement.  To read more about this go here or there.

My issue is that I want to renew the proxy at each request and that it is not set on a per request basis. While it explains the reasdon of the new ConnectionLeaseTimeout parameter (to minimize the time the lease remains open) it is a different topic

Body:
I am sending cURL request using HttpClient through the method described here under.

The parameter used for this method are:

SelectedProxy = a custom class that stores my proxy's parameters

Parameters.WcTimeout = the timeout

url, header, content = the cURL request (based on this tool to convert to C# https://curl.olsh.me/).

        const SslProtocols _Tls12 = (SslProtocols)0x00000C00;
        const SecurityProtocolType Tls12 = (SecurityProtocolType)_Tls12;
        ServicePointManager.SecurityProtocol = Tls12;
        string source = "";

        using (var handler = new HttpClientHandler())
        {
            handler.UseCookies = usecookies;
            WebProxy wp = new WebProxy(SelectedProxy.Address);
            handler.Proxy = wp;

            using (var httpClient = new HttpClient(handler))
            {
                httpClient.Timeout = Parameters.WcTimeout;

                using (var request = new HttpRequestMessage(new HttpMethod(HttpMethod), url))
                {
                    if (headers != null)
                    {
                        foreach (var h in headers)
                        {
                            request.Headers.TryAddWithoutValidation(h.Item1, h.Item2);
                        }
                    }
                    if (content != "")
                    {
                        request.Content = new StringContent(content, Encoding.UTF8, "application/x-www-form-urlencoded");
                    }

                    HttpResponseMessage response = new HttpResponseMessage();
                    try
                    {
                        response = await httpClient.SendAsync(request);
                    }
                    catch (Exception e)
                    {
                        //Here the exception happens
                    }
                    source = await response.Content.ReadAsStringAsync();
                }
            }
        }
        return source;

If I am running this without proxy, it works like a charm.
When I send a request using a proxy which I tested first from Chrome, I have the following error on my try {} catch {}. Here is the error tree

{"An error occurred while sending the request."}
    InnerException {"Unable to connect to the remote server"}
        InnerException {"A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond [ProxyAdress]"}
        SocketErrorCode: TimedOut

By using a Stopwatch I see that the TimedOut occurred after around 30 sec.

I tried a few different handler based on the following links What's the difference between HttpClient.Timeout and using the WebRequestHandler timeout properties?, HttpClient Timeout confusion or with the WinHttpHandler.

It's worth noting that WinHttpHandler allow for a different error code, i.e. Error 12002 calling WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, 'The operation timed out'. The underlying reason is the same though it helped to target where it bugs (i.e. WinInet) which confirms also what @DavidWright was saying regarding that timeouts from HttpClient manages a different part of the request sending.

Hence my issue is coming from the time it takes to establish a connection to the server, which triggers the 30sec timeout from WinInet.

My question is then How to change those timeout?

On a side note, it's worth noting that Chrome, which uses WinInet, does not seem to suffer from this timeout, nor Cefsharp on which a big part of my app is based, and through which the same proxies can properly send requests.

Body:
So thanks to @DavidWright I understand a few things:

Before that the HttpRequestMessage is sent and the timeout from HttpClient starts, a TCP connection to the server is initiated

The TCP connection has its own timeout, defined at OS level, and we do not identified a way to change it at run time from C# (question pending if anyone want to contribute)

Insisting on trying to connect works as each try benefits from previous tries, though proper exception management & manual timeout counter needs to be implemented (I actually considered a number of tries in my code, assuming each try is around 30sec)

All this together ended up in the following code:

        const SslProtocols _Tls12 = (SslProtocols)0x00000C00;
        const SecurityProtocolType Tls12 = (SecurityProtocolType)_Tls12;
        ServicePointManager.SecurityProtocol = Tls12;
        var sp = ServicePointManager.FindServicePoint(endpoint);

        sp.ConnectionLeaseTimeout = (int)Parameters.ConnectionLeaseTimeout.TotalMilliseconds;

        string source = "";

        using (var handler = new HttpClientHandler())
        {
            handler.UseCookies = usecookies;
            WebProxy wp = new WebProxy(SelectedProxy.Address);
            handler.Proxy = wp;

            using (var client = new HttpClient(handler))
            {
                client.Timeout = Parameters.WcTimeout;

                int n = 0;
                back:
                using (var request = new HttpRequestMessage(new HttpMethod(HttpMethod), endpoint))
                {

                    if (headers != null)
                    {
                        foreach (var h in headers)
                        {
                            request.Headers.TryAddWithoutValidation(h.Item1, h.Item2);
                        }
                    }
                    if (content != "")
                    {
                        request.Content = new StringContent(content, Encoding.UTF8, "application/x-www-form-urlencoded");
                    }
                    HttpResponseMessage response = new HttpResponseMessage();

                    try
                    {
                        response = await client.SendAsync(request);
                    }
                    catch (Exception e)
                    {
                        if(e.InnerException != null)
                        {
                            if(e.InnerException.InnerException != null)
                            {
                                if (e.InnerException.InnerException.Message.Contains("A connection attempt failed because the connected party did not properly respond after"))
                                {
                                    if (n <= Parameters.TCPMaxTries)
                                    {
                                        n++;
                                        goto back;
                                    }
                                }
                            }
                        }
                        // Manage here other exceptions
                    }
                    source = await response.Content.ReadAsStringAsync();
                }
            }
        }
        return source;

On a side note, my current implementation of HttpClient may be problematic in the future. Though being disposable, HttpClient should be defined at App level through a static, and not within a using statement.  To read more about this go here or there.

My issue is that I want to renew the proxy at each request and that it is not set on a per request basis. While it explains the reasdon of the new ConnectionLeaseTimeout parameter (to minimize the time the lease remains open) it is a different topic


问:
Ansible - Print message - debug: msg="line1 \n {{ var2 }} \n line3 with var3 = {{ var3 }}"
In Ansible (1.9.4) or 2.0.0

I ran the following action:

```<code>- debug: msg="line1 \n {{ var2 }} \n line3 with var3 = {{ var3 }}"
</code>```

$ cat roles/setup_jenkins_slave/tasks/main.yml

```<code>- debug: msg="Installing swarm slave = {{ slave_name }} at {{ slaves_dir }}/{{ slave_name }}"
  tags:
    - koba

- debug: msg="1 == Slave properties = fsroot[ {{ slave_fsroot }} ], master[ {{ slave_master }} ], connectingToMasterAs[ {{ slave_user }} ], description[ {{ slave_desc }} ], No.Of.Executors[ {{ slave_execs }} ], LABELs[ {{ slave_labels }} ], mode[ {{ slave_mode }} ]"
  tags:
    - koba

- debug: msg="print(2 == Slave properties = \n\nfsroot[ {{ slave_fsroot }} ],\n master[ {{ slave_master }} ],\n connectingToMasterAs[ {{ slave_user }} ],\n description[ {{ slave_desc }} ],\n No.Of.Executors[ {{ slave_execs }} ],\n LABELs[ {{ slave_labels }} ],\n mode[ {{ slave_mode }} ])"
  tags:
    - koba
</code>```

But this is not printing the variable with new lines (for the 3rd debug action)?

答:
Pause module:

The most convenient and simple way I found to display a message with formatting (ex: new lines, tabs ...) is to use the pause module instead of debug module:

```<code>    - pause:
        seconds: 1
        prompt: |
          ======================
            line_1
            line_2
          ======================
</code>```

You can also include a variable that contains formatting (new lines, tabs...) inside the prompt and it will be displayed as expected:

```<code>- name: test
  hosts: all
  vars:
    line3: "\n  line_3"
  tasks:
    - pause:
        seconds: 1
        prompt: |
          /////////////////
            line_1
            line_2 {{ line3 }}
          /////////////////
</code>```

Tip:

when you want to display an output from a command, and instead of running an extra task to run the command and register the output, you can directly use the pipe lookup inside the prompt and do the job in one shot:

```<code>    - pause:
        seconds: 1
        prompt: |
          =========================
            line_1
            {{ lookup('pipe', 'echo "line_2 with \t tab \n  line_3 "') }}
            line_4
          =========================
</code>```

Extra notes regarding the pause module:

If you have multiple hosts, note that the pause task will run
only once against the first host in the list of hosts.

This means that if the variable you want to display exists only in
part of the hosts and the first host does not contain that variable
then you will get an error.

To avoid such an issue, use {{ hostvars['my_host']['my_var'] }}
instead of {{ my_var }}

Combining pause with when conditional might skip the task! Why?
Because the task will only run once against the first host which
might not conform to the stated when conditions.

To avoid this, don't use conditions that constrain the number of
hosts! As you don't need it either, because you know that the task will
run only once anyway. Also use hostvars stated above to make sure
you get the needed variable whatever the picked up host is.

Example:

Incorrect:

```<code>- name: test
  hosts: host1,host2
  vars:
    display_my_var: true
  tasks:
    - when: inventory_hostname == 'host2'
      set_fact:
        my_var: "hi there"
    - when:
      - display_my_var|bool
      - inventory_hostname == 'host2'
      pause:
        seconds: 1
        prompt: |
          {{ my_var }}
</code>```

This example will skip the pause task, because it will choose only the first host host1 and then starts to evaluate conditions, when it finds that host1 is not conforming to the second condition it will skip the task.

Correct:

```<code>- name: test
  hosts: host1,host2
  vars:
    display_my_var: true
  tasks:
    - when: inventory_hostname == 'host2'
      set_fact:
        my_var: "hi there"
    - when: display_my_var|bool
      pause:
        seconds: 1
        prompt: |
          {{ hostvars['host2']['my_var'] }}
</code>```

Another example to display messages where the content depends on the host:

```<code>    - set_fact:
        my_var: "hi from {{ inventory_hostname }}"
    - pause:
        seconds: 1
        prompt: |
          {% for host in ansible_play_hosts %}
            {{ hostvars[host]['my_var'] }}
          {% endfor %}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In Ansible (1.9.4) or 2.0.0

I ran the following action:

- debug: msg="line1 \n {{ var2 }} \n line3 with var3 = {{ var3 }}"

$ cat roles/setup_jenkins_slave/tasks/main.yml

- debug: msg="Installing swarm slave = {{ slave_name }} at {{ slaves_dir }}/{{ slave_name }}"
  tags:
    - koba

- debug: msg="1 == Slave properties = fsroot[ {{ slave_fsroot }} ], master[ {{ slave_master }} ], connectingToMasterAs[ {{ slave_user }} ], description[ {{ slave_desc }} ], No.Of.Executors[ {{ slave_execs }} ], LABELs[ {{ slave_labels }} ], mode[ {{ slave_mode }} ]"
  tags:
    - koba

- debug: msg="print(2 == Slave properties = \n\nfsroot[ {{ slave_fsroot }} ],\n master[ {{ slave_master }} ],\n connectingToMasterAs[ {{ slave_user }} ],\n description[ {{ slave_desc }} ],\n No.Of.Executors[ {{ slave_execs }} ],\n LABELs[ {{ slave_labels }} ],\n mode[ {{ slave_mode }} ])"
  tags:
    - koba

But this is not printing the variable with new lines (for the 3rd debug action)?

Body:
Pause module:

The most convenient and simple way I found to display a message with formatting (ex: new lines, tabs ...) is to use the pause module instead of debug module:

    - pause:
        seconds: 1
        prompt: |
          ======================
            line_1
            line_2
          ======================

You can also include a variable that contains formatting (new lines, tabs...) inside the prompt and it will be displayed as expected:

- name: test
  hosts: all
  vars:
    line3: "\n  line_3"
  tasks:
    - pause:
        seconds: 1
        prompt: |
          /////////////////
            line_1
            line_2 {{ line3 }}
          /////////////////

Tip:

when you want to display an output from a command, and instead of running an extra task to run the command and register the output, you can directly use the pipe lookup inside the prompt and do the job in one shot:

    - pause:
        seconds: 1
        prompt: |
          =========================
            line_1
            {{ lookup('pipe', 'echo "line_2 with \t tab \n  line_3 "') }}
            line_4
          =========================

Extra notes regarding the pause module:

If you have multiple hosts, note that the pause task will run
only once against the first host in the list of hosts.

This means that if the variable you want to display exists only in
part of the hosts and the first host does not contain that variable
then you will get an error.

To avoid such an issue, use {{ hostvars['my_host']['my_var'] }}
instead of {{ my_var }}

Combining pause with when conditional might skip the task! Why?
Because the task will only run once against the first host which
might not conform to the stated when conditions.

To avoid this, don't use conditions that constrain the number of
hosts! As you don't need it either, because you know that the task will
run only once anyway. Also use hostvars stated above to make sure
you get the needed variable whatever the picked up host is.

Example:

Incorrect:

- name: test
  hosts: host1,host2
  vars:
    display_my_var: true
  tasks:
    - when: inventory_hostname == 'host2'
      set_fact:
        my_var: "hi there"
    - when:
      - display_my_var|bool
      - inventory_hostname == 'host2'
      pause:
        seconds: 1
        prompt: |
          {{ my_var }}

This example will skip the pause task, because it will choose only the first host host1 and then starts to evaluate conditions, when it finds that host1 is not conforming to the second condition it will skip the task.

Correct:

- name: test
  hosts: host1,host2
  vars:
    display_my_var: true
  tasks:
    - when: inventory_hostname == 'host2'
      set_fact:
        my_var: "hi there"
    - when: display_my_var|bool
      pause:
        seconds: 1
        prompt: |
          {{ hostvars['host2']['my_var'] }}

Another example to display messages where the content depends on the host:

    - set_fact:
        my_var: "hi from {{ inventory_hostname }}"
    - pause:
        seconds: 1
        prompt: |
          {% for host in ansible_play_hosts %}
            {{ hostvars[host]['my_var'] }}
          {% endfor %}


问:
Count operation not working on aggregated IgniteDataFrame
I am working with Apache Spark and Apache Ignite. I have a spark dataset which I wrote in Ignite using following code

```<code>dataset.write()
                .mode(SaveMode.Overwrite)
                .format(FORMAT_IGNITE())
                .option(OPTION_CONFIG_FILE(), "ignite-server-config.xml")
                .option(OPTION_TABLE(), "CUSTOM_VALUES")
                .option(OPTION_CREATE_TABLE_PRIMARY_KEY_FIELDS(), "ID")
                .save();
</code>```

And I am reading it again to perform group by operation which will be pushed to Ignite.

```<code>  Dataset igniteDataset = sparkSession.read()
                .format(FORMAT_IGNITE())
                .option(OPTION_CONFIG_FILE(), "ignite-server-config.xml")
                .option(OPTION_TABLE(), "CUSTOM_VALUES")
                .load();

        RelationalGroupedDataset idGroupedData = igniteDataset.groupBy(customized_id);

        Dataset<Row> result = idGroupedData.agg(count(id).as("count_id"),
                count(fid).as("count_custom_field_id"),
                count(type).as("count_customized_type"),
                count(val).as("count_value"), count(customized_id).as("groupCount"));
</code>```

Now, I want to get the number of rows returned by groupby action. So, I am calling count() on dataset asresult.count();

When I do this, I get following exception.

```<code>Caused by: org.h2.jdbc.JdbcSQLException: Syntax error in SQL statement "SELECT COUNT(1) AS COUNT FROM (SELECT  FROM CUSTOM_VALUES GROUP[*] BY CUSTOMIZED_ID) TABLE1 "; expected "., (, USE, AS, RIGHT, LEFT, FULL, INNER, JOIN, CROSS, NATURAL, ,, SELECT"; SQL statement:
SELECT COUNT(1) AS count FROM (SELECT  FROM CUSTOM_VALUES GROUP BY CUSTOMIZED_ID) table1 [42001-197]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:357)
    at org.h2.message.DbException.getSyntaxError(DbException.java:217)
</code>```

Other functions such as show(), collectAsList().size(); works.

What am I missing here ?

答:
I tested your example against the last community version 8.7.5 of GridGain that is the opensource version of Gridgain based on Ignite 2.7.0 sources with a subset of additional fixes (https://www.gridgain.com/resources/download).

Here is the code:

```<code>public class Main {
    public static void main(String[] args) {
        if (args.length < 1)
            throw new IllegalArgumentException("You should set the path to client configuration file.");

        String configPath = args[0];

        SparkSession session = SparkSession.builder()
                .enableHiveSupport()
                .getOrCreate();

        Dataset<Row> igniteDataset = session.read()
                .format(IgniteDataFrameSettings.FORMAT_IGNITE())                  //Data source
                .option(IgniteDataFrameSettings.OPTION_TABLE(), "Person")         //Table to read.
                .option(IgniteDataFrameSettings.OPTION_CONFIG_FILE(), configPath) //Ignite config.
                .load();

        RelationalGroupedDataset idGroupedData = igniteDataset.groupBy("CITY_ID");

        Dataset<Row> result = idGroupedData.agg(count("id").as("count_id"),
                count("city_id").as("count_city_id"),
                count("name").as("count_name"),
                count("age").as("count_age"),
                count("company").as("count_company"));

        result.show();

        session.close();
    }
}
</code>```

Here are the maven dependencies:

```<code><dependencies>
    <dependency>
        <groupId>org.gridgain</groupId>
        <artifactId>gridgain-core</artifactId>
        <version>8.7.5</version>
    </dependency>
    <dependency>
        <groupId>org.gridgain</groupId>
        <artifactId>ignite-core</artifactId>
        <version>8.7.5</version>
    </dependency>
    <dependency>
        <groupId>org.gridgain</groupId>
        <artifactId>ignite-spring</artifactId>
        <version>8.7.5</version>
    </dependency>
    <dependency>
        <groupId>org.gridgain</groupId>
        <artifactId>ignite-indexing</artifactId>
        <version>8.7.5</version>
    </dependency>
    <dependency>
        <groupId>org.gridgain</groupId>
        <artifactId>ignite-spark</artifactId>
        <version>8.7.5</version>
    </dependency>
</dependencies>
</code>```

Here is the cache configuration:

```<code>    <property name="cacheConfiguration">
        <list>
            <bean class="org.apache.ignite.configuration.CacheConfiguration">
                <property name="name" value="Person"/>
                <property name="cacheMode" value="PARTITIONED"/>
                <property name="atomicityMode" value="ATOMIC"/>
                <property name="sqlSchema" value="PUBLIC"/>

                <property name="queryEntities">
                    <list>
                        <bean class="org.apache.ignite.cache.QueryEntity">
                            <property name="keyType" value="PersonKey"/>
                            <property name="valueType" value="PersonValue"/>
                            <property name="tableName" value="Person"/>

                            <property name="keyFields">
                                <list>
                                    <value>id</value>
                                    <value>city_id</value>
                                </list>
                            </property>

                            <property name="fields">
                                <map>
                                    <entry key="id" value="java.lang.Integer"/>
                                    <entry key="city_id" value="java.lang.Integer"/>
                                    <entry key="name" value="java.lang.String"/>
                                    <entry key="age" value="java.lang.Integer"/>
                                    <entry key="company" value="java.lang.String"/>
                                </map>
                            </property>

                            <property name="aliases">
                                <map>
                                    <entry key="id" value="id"/>
                                    <entry key="city_id" value="city_id"/>
                                    <entry key="name" value="name"/>
                                    <entry key="age" value="age"/>
                                    <entry key="company" value="company"/>
                                </map>
                            </property>
                        </bean>
                    </list>
                </property>
            </bean>
        </list>
    </property>
</code>```

Using Spark 2.3.0 that is only supported for ignite-spark dependency I have next result on my test data:

Data:

```<code>ID,CITY_ID,NAME,AGE,COMPANY,
4,1,Justin Bronte,23,bank,
3,1,Helen Richard,49,bank,
</code>```

Result:

```<code>+-------+--------+-------------+----------+---------+-------------+
|CITY_ID|count_id|count_city_id|count_name|count_age|count_company|
+-------+--------+-------------+----------+---------+-------------+
|      1|       2|            2|         2|        2|            2|
+-------+--------+-------------+----------+---------+-------------+
</code>```

Also, this code could be fully applied to Ignite 2.7.0.

Body:
I am working with Apache Spark and Apache Ignite. I have a spark dataset which I wrote in Ignite using following code

dataset.write()
                .mode(SaveMode.Overwrite)
                .format(FORMAT_IGNITE())
                .option(OPTION_CONFIG_FILE(), "ignite-server-config.xml")
                .option(OPTION_TABLE(), "CUSTOM_VALUES")
                .option(OPTION_CREATE_TABLE_PRIMARY_KEY_FIELDS(), "ID")
                .save();

And I am reading it again to perform group by operation which will be pushed to Ignite.

  Dataset igniteDataset = sparkSession.read()
                .format(FORMAT_IGNITE())
                .option(OPTION_CONFIG_FILE(), "ignite-server-config.xml")
                .option(OPTION_TABLE(), "CUSTOM_VALUES")
                .load();

        RelationalGroupedDataset idGroupedData = igniteDataset.groupBy(customized_id);

        Dataset<Row> result = idGroupedData.agg(count(id).as("count_id"),
                count(fid).as("count_custom_field_id"),
                count(type).as("count_customized_type"),
                count(val).as("count_value"), count(customized_id).as("groupCount"));

Now, I want to get the number of rows returned by groupby action. So, I am calling count() on dataset asresult.count();

When I do this, I get following exception.

Caused by: org.h2.jdbc.JdbcSQLException: Syntax error in SQL statement "SELECT COUNT(1) AS COUNT FROM (SELECT  FROM CUSTOM_VALUES GROUP[*] BY CUSTOMIZED_ID) TABLE1 "; expected "., (, USE, AS, RIGHT, LEFT, FULL, INNER, JOIN, CROSS, NATURAL, ,, SELECT"; SQL statement:
SELECT COUNT(1) AS count FROM (SELECT  FROM CUSTOM_VALUES GROUP BY CUSTOMIZED_ID) table1 [42001-197]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:357)
    at org.h2.message.DbException.getSyntaxError(DbException.java:217)

Other functions such as show(), collectAsList().size(); works.

What am I missing here ?

Body:
I tested your example against the last community version 8.7.5 of GridGain that is the opensource version of Gridgain based on Ignite 2.7.0 sources with a subset of additional fixes (https://www.gridgain.com/resources/download).

Here is the code:

public class Main {
    public static void main(String[] args) {
        if (args.length < 1)
            throw new IllegalArgumentException("You should set the path to client configuration file.");

        String configPath = args[0];

        SparkSession session = SparkSession.builder()
                .enableHiveSupport()
                .getOrCreate();

        Dataset<Row> igniteDataset = session.read()
                .format(IgniteDataFrameSettings.FORMAT_IGNITE())                  //Data source
                .option(IgniteDataFrameSettings.OPTION_TABLE(), "Person")         //Table to read.
                .option(IgniteDataFrameSettings.OPTION_CONFIG_FILE(), configPath) //Ignite config.
                .load();

        RelationalGroupedDataset idGroupedData = igniteDataset.groupBy("CITY_ID");

        Dataset<Row> result = idGroupedData.agg(count("id").as("count_id"),
                count("city_id").as("count_city_id"),
                count("name").as("count_name"),
                count("age").as("count_age"),
                count("company").as("count_company"));

        result.show();

        session.close();
    }
}

Here are the maven dependencies:

<dependencies>
    <dependency>
        <groupId>org.gridgain</groupId>
        <artifactId>gridgain-core</artifactId>
        <version>8.7.5</version>
    </dependency>
    <dependency>
        <groupId>org.gridgain</groupId>
        <artifactId>ignite-core</artifactId>
        <version>8.7.5</version>
    </dependency>
    <dependency>
        <groupId>org.gridgain</groupId>
        <artifactId>ignite-spring</artifactId>
        <version>8.7.5</version>
    </dependency>
    <dependency>
        <groupId>org.gridgain</groupId>
        <artifactId>ignite-indexing</artifactId>
        <version>8.7.5</version>
    </dependency>
    <dependency>
        <groupId>org.gridgain</groupId>
        <artifactId>ignite-spark</artifactId>
        <version>8.7.5</version>
    </dependency>
</dependencies>

Here is the cache configuration:

    <property name="cacheConfiguration">
        <list>
            <bean class="org.apache.ignite.configuration.CacheConfiguration">
                <property name="name" value="Person"/>
                <property name="cacheMode" value="PARTITIONED"/>
                <property name="atomicityMode" value="ATOMIC"/>
                <property name="sqlSchema" value="PUBLIC"/>

                <property name="queryEntities">
                    <list>
                        <bean class="org.apache.ignite.cache.QueryEntity">
                            <property name="keyType" value="PersonKey"/>
                            <property name="valueType" value="PersonValue"/>
                            <property name="tableName" value="Person"/>

                            <property name="keyFields">
                                <list>
                                    <value>id</value>
                                    <value>city_id</value>
                                </list>
                            </property>

                            <property name="fields">
                                <map>
                                    <entry key="id" value="java.lang.Integer"/>
                                    <entry key="city_id" value="java.lang.Integer"/>
                                    <entry key="name" value="java.lang.String"/>
                                    <entry key="age" value="java.lang.Integer"/>
                                    <entry key="company" value="java.lang.String"/>
                                </map>
                            </property>

                            <property name="aliases">
                                <map>
                                    <entry key="id" value="id"/>
                                    <entry key="city_id" value="city_id"/>
                                    <entry key="name" value="name"/>
                                    <entry key="age" value="age"/>
                                    <entry key="company" value="company"/>
                                </map>
                            </property>
                        </bean>
                    </list>
                </property>
            </bean>
        </list>
    </property>

Using Spark 2.3.0 that is only supported for ignite-spark dependency I have next result on my test data:

Data:

ID,CITY_ID,NAME,AGE,COMPANY,
4,1,Justin Bronte,23,bank,
3,1,Helen Richard,49,bank,

Result:

+-------+--------+-------------+----------+---------+-------------+
|CITY_ID|count_id|count_city_id|count_name|count_age|count_company|
+-------+--------+-------------+----------+---------+-------------+
|      1|       2|            2|         2|        2|            2|
+-------+--------+-------------+----------+---------+-------------+

Also, this code could be fully applied to Ignite 2.7.0.


问:
MAXIFS multiple criteria ignoring NA() data
I am trying to get the maximum value of a column within a certain range and ignore the NA() values that are in the column. All of the data in the column that is not NA() is greater than zero. I have tried ignoring the NA(), >=0 and the AGGREGATE function does not have the MAXIFS only the MAX function.

```<code>=MAXIFS(SR_Layer2,Chainage,">="&D12,Chainage,"<="&E12,SR_Layer2,"<>NA()")
=MAXIFS(SR_Layer2,Chainage,">="&D12,Chainage,"<="&E12,SR_Layer2,">=0")
</code>```

It displays the #VALUE!

Body:
I am trying to get the maximum value of a column within a certain range and ignore the NA() values that are in the column. All of the data in the column that is not NA() is greater than zero. I have tried ignoring the NA(), >=0 and the AGGREGATE function does not have the MAXIFS only the MAX function.

=MAXIFS(SR_Layer2,Chainage,">="&D12,Chainage,"<="&E12,SR_Layer2,"<>NA()")
=MAXIFS(SR_Layer2,Chainage,">="&D12,Chainage,"<="&E12,SR_Layer2,">=0")

It displays the #VALUE!

Body: Try: =MAXIFS(A2:A6,A2:A6,"<>" & "#N/A")


问:
Cannot get kubectl logs on worker nodes
I created a cluster of k8s consisting of one master node and three worker nodes. (master node can do master and worker role). Everything was good. I can deploy pod, exec pod, get logs... but I have some log problem. I cannot get logs from worker node. I only get logs from master node kubeclt logs <pod-name>

This is my error msg:

```<code>error: You must be logged in to the server (the server has asked for the client to provide credentials ( pods/log nginx))
</code>```

It occurred only worker node scheduled pod. Help me..

答:
On your master node check kubelet logs

```<code>journalctl -u kubelet
</code>```

There you might see something like

```<code>Flag --some-flag has been deprecated, This parameter should be set via the config file specified by the Kubelet's --config flag
</code>```

Remove those flags  and put it into the kubelet config file /var/lib/kubelet/config.yaml

Also the default Authentication and Authorization to Kubelet's API differs between cli args and config files, so you should make sure to set the "legacy defaults" in the config file to preserve existing behavior.

Here is the snippet of my config.yaml

```<code>authentication:
  anonymous:
    enabled: false #set true to enable
  webhook:
    cacheTTL: 2m0s
    enabled: true
  x509:
    clientCAFile: /etc/kubernetes/pki/ca.crt
authorization:
  mode: Webhook
  webhook:
    cacheAuthorizedTTL: 5m0s
    cacheUnauthorizedTTL: 30s
</code>```

Title: Cannot get kubectl logs on worker nodes

Body:
I created a cluster of k8s consisting of one master node and three worker nodes. (master node can do master and worker role). Everything was good. I can deploy pod, exec pod, get logs... but I have some log problem. I cannot get logs from worker node. I only get logs from master node kubeclt logs <pod-name>

This is my error msg:

error: You must be logged in to the server (the server has asked for the client to provide credentials ( pods/log nginx))

It occurred only worker node scheduled pod. Help me..

Body:
On your master node check kubelet logs

journalctl -u kubelet

There you might see something like

Flag --some-flag has been deprecated, This parameter should be set via the config file specified by the Kubelet's --config flag

Remove those flags  and put it into the kubelet config file /var/lib/kubelet/config.yaml

Also the default Authentication and Authorization to Kubelet's API differs between cli args and config files, so you should make sure to set the "legacy defaults" in the config file to preserve existing behavior.

Here is the snippet of my config.yaml

authentication:
  anonymous:
    enabled: false #set true to enable
  webhook:
    cacheTTL: 2m0s
    enabled: true
  x509:
    clientCAFile: /etc/kubernetes/pki/ca.crt
authorization:
  mode: Webhook
  webhook:
    cacheAuthorizedTTL: 5m0s
    cacheUnauthorizedTTL: 30s


问:
Can't share PDF file with WhatsApp or email (Only IOS)
I use react-native-share package

https://www.npmjs.com/package/react-native-share

i try to share base64 in this way:

```<code>import Share from 'react-native-share'
//
const base64File = //base64 file
const pdf = "data:application/pdf;base64," + base64File
const options = { title: 'Share via', url: pdf };
Share.open(options)
</code>```

It works in android but not in IOS, when i try to share tiff file it works in IOS but not pdf

When i try this informs me - this file cannot be shared

答:
Solution

```<code>import Share from 'react-native-share'
import RNFetchBlob from 'rn-fetch-blob'
//
const base64File = //base64 file
const pdf = "data:application/pdf;base64," + base64File
let filePath = '';
const path = RNFetchBlob.fs.dirs.DocumentDir + '/someFileName.pdf';
const configOptions = { fileCache: true, path };
let fullPath = await RNFetchBlob.config(configOptions).fetch('GET', encodeURI(fileUrl))
filePath = fullPath.path();
let options = {
    title: 'Share via'
    type: type,
    url: filePath // (Platform.OS === 'android' ? 'file://' + filePath)
};
Share.open(options)
</code>```

Body:
I use react-native-share package

https://www.npmjs.com/package/react-native-share

i try to share base64 in this way:

import Share from 'react-native-share'
//
const base64File = //base64 file
const pdf = "data:application/pdf;base64," + base64File
const options = { title: 'Share via', url: pdf };
Share.open(options)

It works in android but not in IOS, when i try to share tiff file it works in IOS but not pdf

When i try this informs me - this file cannot be shared

Body:
Solution

import Share from 'react-native-share'
import RNFetchBlob from 'rn-fetch-blob'
//
const base64File = //base64 file
const pdf = "data:application/pdf;base64," + base64File
let filePath = '';
const path = RNFetchBlob.fs.dirs.DocumentDir + '/someFileName.pdf';
const configOptions = { fileCache: true, path };
let fullPath = await RNFetchBlob.config(configOptions).fetch('GET', encodeURI(fileUrl))
filePath = fullPath.path();
let options = {
    title: 'Share via'
    type: type,
    url: filePath // (Platform.OS === 'android' ? 'file://' + filePath)
};
Share.open(options)


问:
Error while running Angular 7 in Google App Script (Google doc Add-on)
I am trying to run Angular cli generated default app, in Google doc add-on (Google App Script) project, As in google app script only .gs and .html files are allowed i have moved all angular's build JS files in script tags and added them as html. But when i run the add-on i am getting this error

```<code>userCodeAppPanel:6862 Uncaught Error: Can't resolve all parameters for ApplicationModule: (?).
    at syntaxError (userCodeAppPanel:6862)
    at CompileMetadataResolver.push../node_modules/@angular/compiler/fesm5/compiler.js.CompileMetadataResolver._getDependenciesMetadata (userCodeAppPanel:22346)
    at CompileMetadataResolver.push../node_modules/@angular/compiler/fesm5/compiler.js.CompileMetadataResolver._getTypeMetadata (userCodeAppPanel:22241)
    at CompileMetadataResolver.push../node_modules/@angular/compiler/fesm5/compiler.js.CompileMetadataResolver.getNgModuleMetadata (userCodeAppPanel:22109)
    at CompileMetadataResolver.push../node_modules/@angular/compiler/fesm5/compiler.js.CompileMetadataResolver.getNgModuleSummary (userCodeAppPanel:21920)
    at userCodeAppPanel:22033
    at Array.forEach (<anonymous>)
    at CompileMetadataResolver.push../node_modules/@angular/compiler/fesm5/compiler.js.CompileMetadataResolver.getNgModuleMetadata (userCodeAppPanel:22021)
    at CompileMetadataResolver.push../node_modules/@angular/compiler/fesm5/compiler.js.CompileMetadataResolver.getNgModuleSummary (userCodeAppPanel:21920)
    at userCodeAppPanel:22006
</code>```

Directory structure in google app script project

my modified index.html for app-script

```<code><!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>AngularAddOn</title>

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>

  <?!= include('runtime.js');?>
  <?!= include('vendor.js');?>
  <?!= include('styles.js');?>
  <?!= include('main.js');?>
  <?!= include('polyfills.js');?>
  <?!= include('es2015-polyfills.js');?>

  <app-root></app-root>
</body>
</html>
</code>```

And here is my code.gs file

```<code>function myFunction() {

}
function onOpen(e) {
  DocumentApp.getUi().createAddonMenu()
    .addItem('Manage Citations', 'showSidebar')
    // .addItem("test dialog", 'showDialog')
    .addToUi();
}

function showSidebar() {
  var html = HtmlService.createTemplateFromFile('index').evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME).setTitle('wizdom.ai');
  DocumentApp.getUi().showSidebar(html);
}

function include(filename) {
  return HtmlService.createHtmlOutputFromFile(filename).getContent();
}
</code>```

Is it impossible to run angular in google add-on? or am i missing something?

i already tried adding following to polyfills.ts but no luck

```<code>import 'core-js/es7/reflect';
</code>```

Thanks

答:
According to this other question,  How to use AngularJS within Google Apps Script someone suggested to

"move the angular.js include script statement into the head section"

I see yours are in the body section. Change them to the head and it should work.

Body:
I am trying to run Angular cli generated default app, in Google doc add-on (Google App Script) project, As in google app script only .gs and .html files are allowed i have moved all angular's build JS files in script tags and added them as html. But when i run the add-on i am getting this error

userCodeAppPanel:6862 Uncaught Error: Can't resolve all parameters for ApplicationModule: (?).
    at syntaxError (userCodeAppPanel:6862)
    at CompileMetadataResolver.push../node_modules/@angular/compiler/fesm5/compiler.js.CompileMetadataResolver._getDependenciesMetadata (userCodeAppPanel:22346)
    at CompileMetadataResolver.push../node_modules/@angular/compiler/fesm5/compiler.js.CompileMetadataResolver._getTypeMetadata (userCodeAppPanel:22241)
    at CompileMetadataResolver.push../node_modules/@angular/compiler/fesm5/compiler.js.CompileMetadataResolver.getNgModuleMetadata (userCodeAppPanel:22109)
    at CompileMetadataResolver.push../node_modules/@angular/compiler/fesm5/compiler.js.CompileMetadataResolver.getNgModuleSummary (userCodeAppPanel:21920)
    at userCodeAppPanel:22033
    at Array.forEach (<anonymous>)
    at CompileMetadataResolver.push../node_modules/@angular/compiler/fesm5/compiler.js.CompileMetadataResolver.getNgModuleMetadata (userCodeAppPanel:22021)
    at CompileMetadataResolver.push../node_modules/@angular/compiler/fesm5/compiler.js.CompileMetadataResolver.getNgModuleSummary (userCodeAppPanel:21920)
    at userCodeAppPanel:22006

Directory structure in google app script project

my modified index.html for app-script

<!doctype html>

  <meta charset="utf-8">
  <title>AngularAddOn</title>

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">

  <?!= include('runtime.js');?>
  <?!= include('vendor.js');?>
  <?!= include('styles.js');?>
  <?!= include('main.js');?>
  <?!= include('polyfills.js');?>
  <?!= include('es2015-polyfills.js');?>

  <app-root></app-root>

And here is my code.gs file

function myFunction() {

}
function onOpen(e) {
  DocumentApp.getUi().createAddonMenu()
    .addItem('Manage Citations', 'showSidebar')
    // .addItem("test dialog", 'showDialog')
    .addToUi();
}

function showSidebar() {
  var html = HtmlService.createTemplateFromFile('index').evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME).setTitle('wizdom.ai');
  DocumentApp.getUi().showSidebar(html);
}

function include(filename) {
  return HtmlService.createHtmlOutputFromFile(filename).getContent();
}

Is it impossible to run angular in google add-on? or am i missing something?

i already tried adding following to polyfills.ts but no luck

import 'core-js/es7/reflect';

Thanks


问:
Vue-i18n Single File Component Not Working
I am trying to implement v-i18n to my project with sfc method. I couldn't make it work. I will not make you confuse with my project, that's why just modified with adding 10-15 lines of code to official v-i18n sfc example.

This is very simply shows my question.

For those who prefer check this very tiny question project on github

https://github.com/berkansivri/V-i18n-Question

Component1.vue

```<code><template>
    <p>{{$t('lang')}}</p>
</template>

<i18n>
{
  "en":{
    "lang" : "English"
  },
  "es":{
    "lang": "Espanol"
  }
}
</i18n>
</code>```

App.vue

```<code><template>
  <div id="app">
    <label for="locale">locale</label>
    <select v-model="locale">
      <option>en</option>
      <option>es</option>
    </select>
    <p>message: {{ $t('hello') }}</p>
    <Comp1></Comp1>
  </div>
</template>

<i18n>
{
  "en": {
    "hello": "hello"
  },
  "es": {
    "hello": "hola"
  }
}
</i18n>

<script>
import Comp1 from './components/component1'
export default {
  components:{
    Comp1
  },
  name: 'App',
  data () { return { locale: 'en' } },
  watch: {
    locale (val) {
      this.$i18n.locale = val
    }
  }
}
</script>
</code>```

So, multiple <i18n>tag in multiple components. I just modified $i18n.locale from App.vue but it did not fire related i18n function $t('lang') on Component1, just modifies $t('hello') on itself.
How can I make it work?

答:
using vue devtools u will find out that messages of $i18n in single file component is different from each other, so they are different objects.

u need to do is:

i18n.js

```<code>import Vue from 'vue'
import VueI18n from 'vue-i18n'
import messages from '@/lang'

Vue.use(VueI18n)

const i18n = new VueI18n({
  locale: 'cn',
  fallbackLocale: 'en',
  messages
})

export default i18n
</code>```

App.vue

```<code>import i18n from "./i18n.js"
i18n.locale = "en"
</code>```

Body:
I am trying to implement v-i18n to my project with sfc method. I couldn't make it work. I will not make you confuse with my project, that's why just modified with adding 10-15 lines of code to official v-i18n sfc example.

This is very simply shows my question.

For those who prefer check this very tiny question project on github

https://github.com/berkansivri/V-i18n-Question

Component1.vue

<template>

{{$t('lang')}}

</template>

<i18n>
{
  "en":{
    "lang" : "English"
  },
  "es":{
    "lang": "Espanol"
  }
}
</i18n>

App.vue

<template>

    locale
    <select v-model="locale">
      <option>en</option>
      <option>es</option>
    </select>

message: {{ $t('hello') }}

    <Comp1></Comp1>

</template>

<i18n>
{
  "en": {
    "hello": "hello"
  },
  "es": {
    "hello": "hola"
  }
}
</i18n>

So, multiple <i18n>tag in multiple components. I just modified $i18n.locale from App.vue but it did not fire related i18n function $t('lang') on Component1, just modifies $t('hello') on itself.
How can I make it work?

Body:
using vue devtools u will find out that messages of $i18n in single file component is different from each other, so they are different objects.

u need to do is:

i18n.js

import Vue from 'vue'
import VueI18n from 'vue-i18n'
import messages from '@/lang'

Vue.use(VueI18n)

const i18n = new VueI18n({
  locale: 'cn',
  fallbackLocale: 'en',
  messages
})

export default i18n

App.vue

import i18n from "./i18n.js"
i18n.locale = "en"


问:
How do I stop File Explorer from running?
File Explorer lately has been getting very annoying. All the ads about OneDrive keep popping up. The ads are making me go crazy, I know how to access files using cmd, so I don't need File Explorer. How do I prevent File Explorer from running?

I've tried searching all over the internet, but all the results only show how to remove Quick Access or how to prevent File Explorer from running at startup. I want File Explorer to NEVER run again.

答:
You could instead try to simply disable the notifications you're having the issue with:

@Reg Add HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced /V ShowSyncProviderNotifications /T REG_DWORD /V 0 /F >NUL
```


问:
How to change colors in react component
In reactstrap we can set colors with default styles(such as primary, secondary, success, warning....) but how do I change it with the Hex color code?
For example, how do I change 'warning' to '#008080'?

```<code><AppSwitch
  className={'mx-1'}
  variant={'pill'}
  color={'warning'} //it dones't work with {'#008080'}
  default checked
  onChange={this.handler} />
</code>```

I've also tried something like this but didn't work either:

```<code>state = {
  color: '#008080'
}

<AppSwitch
  className={'mx-1'}
  variant={'pill'}
  color={'this.state.color'}
  default checked
  onChange={this.handler} />
</code>```

答: If it's okay to change color for all 'warning', you can use BOOTSTRAP.BUILD. You can change color by hex color code in this editor. Export bootstrap.css from it, and refer it in your code instead of bootstrap's default one.</p>

Title: How to change colors in react component

Body:
In reactstrap we can set colors with default styles(such as primary, secondary, success, warning....) but how do I change it with the Hex color code?
For example, how do I change 'warning' to '#008080'?

<AppSwitch
  className={'mx-1'}
  variant={'pill'}
  color={'warning'} //it dones't work with {'#008080'}
  default checked
  onChange={this.handler} />

I've also tried something like this but didn't work either:

state = {
  color: '#008080'
}

<AppSwitch
  className={'mx-1'}
  variant={'pill'}
  color={'this.state.color'}
  default checked
  onChange={this.handler} />


问:
Should I assume sender can be null?
Should I assume a sender (of a CLR event handler) or a d (of a dependency event handler) be null and write some code for the case? Or can I simply mark them as [NotNull] and ignore warnings?

I'm using VS2019 + ReShaper to build a C# project. When "Value Analysis Mode" of R# is set to "Pessimistic (an entity is assumed when it doesn't have explicit NotNull attribute)", it warns sender and d can be null.

//// R# warns sender can be null.
private void OnSomethingHappened(object sender, EventArgs e) {
    //// Should I throw an Exception when sender is null?
    //// Or can I simply mark sender as [NotNull]?
}

//// R# warns d can be null.
private static void (DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    //// Should I throw an Exception when d is null?
    //// Or can I simply mark d as [NotNull]?
}
```

答:
It always safe to write null checks:

```<code>if(objectThatShouldNotBeNull == null)
{
  AppropriateAction();
  // if necessary
  return;
}
</code>```

Generally, if it used later in code, IMO it has to be checked for null value.

Especially when sometimes you, or other developers, might want to call this method from code (I do that sometimes - then I follow abocve pattern) and set sender to null.

Title: Should I assume sender can be null?

Body:
It always safe to write null checks:

if(objectThatShouldNotBeNull == null)
{
  AppropriateAction();
  // if necessary
  return;
}

Generally, if it used later in code, IMO it has to be checked for null value.

Especially when sometimes you, or other developers, might want to call this method from code (I do that sometimes - then I follow abocve pattern) and set sender to null.


问:
How do I use webdriver with imported functions?
I have a function that opens up a webdriver session and then calls for external functions based on the input url.

```<code>from externalfunctions import *

def itemiser(url):
regex = re.compile(r'www.(.+).com')
name = regex.search(url).group(1)
options = {
    'a': a,
    'b': b,
    'c': c
}

if name in options:
    ff = webdriver.Firefox()
    ff.get(url)
    result = options[name]()
    ff.quit()
    print(result)
    return result
</code>```

functions a,b,c are in externalfuntions.py

```<code>def a():
    x = ff.find_element_by_css_selector('body')
    return x
def b():
    x = ff.find_element_by_css_selector('span')
    return x
def c():
    x = ff.find_element_by_css_selector('html')
    return x
</code>```

When I run this, it says that ff is not defined, obviously because the a,b,c functions can't access the webdriver.

How do I do this without having to start a webdriver session every time the a,b,c functions are run.

答:
This is basic Python (indeed, basic programming). If a function needs access to something, you need to pass it:

```<code>result = options[name](ff)
</code>```

and

```<code>def a(ff):
    x = ff.find_element_by_css_selector('body')
    return x
</code>```

etc.

Body:
I have a function that opens up a webdriver session and then calls for external functions based on the input url.

from externalfunctions import *

def itemiser(url):
regex = re.compile(r'www.(.+).com')
name = regex.search(url).group(1)
options = {
    'a': a,
    'b': b,
    'c': c
}

if name in options:
    ff = webdriver.Firefox()
    ff.get(url)
    result = options[name]()
    ff.quit()
    print(result)
    return result

functions a,b,c are in externalfuntions.py

def a():
    x = ff.find_element_by_css_selector('body')
    return x
def b():
    x = ff.find_element_by_css_selector('span')
    return x
def c():
    x = ff.find_element_by_css_selector('html')
    return x

When I run this, it says that ff is not defined, obviously because the a,b,c functions can't access the webdriver.

How do I do this without having to start a webdriver session every time the a,b,c functions are run.

Body:
This is basic Python (indeed, basic programming). If a function needs access to something, you need to pass it:

result = options[name](ff)

and

def a(ff):
    x = ff.find_element_by_css_selector('body')
    return x

etc.


问:
Set user-interaction to false of a native Google Sign In Button
Is there a parameter userIntetaction in GIDSignInButton class? I want the button to become non-responsive after it is pressed once.

```<code>@IBOutlet weak var signInButton: GIDSignInButton!
</code>```

I want to do something like -

```<code>signInButton.setUserInteraction = false
</code>```

答:
GIDSignInButton is a subclass of UIControl. Therefore it inherits the isEnabled property. Try setting this to false.

Also, as others have pointed out, you can also use the userInteractionEnabled field of UIView.

It would be better to use the isEnabled (first option) because that can show a different drawing for the UIControl subclass, if implemented.

Apple Doc for isEnabled

Set the value of this property to true to enable the control or false to disable it. An enabled control is capable of responding to user interactions, whereas a disabled control ignores touch events and may draw itself differently.

Body:
Is there a parameter userIntetaction in GIDSignInButton class? I want the button to become non-responsive after it is pressed once.

@IBOutlet weak var signInButton: GIDSignInButton!

I want to do something like -

signInButton.setUserInteraction = false


问:
When I search in vim and then press “esc” cursor returns to previous position
Something has seemingly happened to my vim install, and I'm not exactly sure what. I'm a long time vim user (although I don't use it as a main editor).

When I search:

```<code>/foo
</code>```

I want to edit the location that it found, so I press ESC (in preparation for getting into insert mode). vim now jumps BACK to where I started from in the file. E.g. if I was on line 0 of a 3000 line file, I search for a particular string, find it at line 1700, and want to edit it - ESC takes me back to line 0.

What's going on? Did I accidentally set some strange mode? Or did I forget a hotkey combination that I should know?

答:
This is the expected behaviour with the incsearch option on:

```<code>Note that the match will be shown, but the cursor will return to its
original position when no match is found and when pressing <Esc>.  You
still need to finish the search command with <Enter> to move the
cursor to the match.
</code>```

If incsearch is not on then the cursor doesn't jump to the first match at all, it doesn't move until you press <Enter>.

Body:
Something has seemingly happened to my vim install, and I'm not exactly sure what. I'm a long time vim user (although I don't use it as a main editor).

When I search:

/foo

I want to edit the location that it found, so I press ESC (in preparation for getting into insert mode). vim now jumps BACK to where I started from in the file. E.g. if I was on line 0 of a 3000 line file, I search for a particular string, find it at line 1700, and want to edit it - ESC takes me back to line 0.

What's going on? Did I accidentally set some strange mode? Or did I forget a hotkey combination that I should know?

Body:
This is the expected behaviour with the incsearch option on:

Note that the match will be shown, but the cursor will return to its
original position when no match is found and when pressing <Esc>.  You
still need to finish the search command with <Enter> to move the
cursor to the match.

If incsearch is not on then the cursor doesn't jump to the first match at all, it doesn't move until you press <Enter>.


问:
OpenCV how to encode raw image information for imencode?
I am in C++.

Assume some mysterious function getData() returns all but only the pixel information of an image.

i.e a char* that points to only the pixel information with no metadata (no width, length, height, nor channels of any form)

Thus we have:

unsigned char *raw_data = getData();

Then we have another function that returns a structure containing the metadata.

eg:

```<code>struct Metadata {
    int width;
    int height;
    int channels;
    //other useful fields
}
</code>```

I now need to prepend the object metadata in the correct way to create a valid image buffer.

So instead of [pixel1, pixel2, pixel3 ...]

I would have, for example [width, height, channels, pixel1, pixel2, pixel3...]

What is the correct order to prepend the metadata and are width, height and channels enough?

答:
You can use Mat constructor to create an image from data and meta data

Mat::Mat(int rows, int cols, int type, void* data, size_t
  step=AUTO_STEP); // documentation here

```<code>cv::Mat image = cv::Mat(height, width, CV_8UC3, raw_data);
</code>```

type argument specifies the number of channels and data format. For example, typical RGB image data is unsigned char and the number of channels is 3 so its type = CV_8UC3

Available OpenCV Mat types are defined cvdef.h

Body:
I am in C++.

Assume some mysterious function getData() returns all but only the pixel information of an image.

i.e a char* that points to only the pixel information with no metadata (no width, length, height, nor channels of any form)

Thus we have:

unsigned char *raw_data = getData();

Then we have another function that returns a structure containing the metadata.

eg:

struct Metadata {
    int width;
    int height;
    int channels;
    //other useful fields
}

I now need to prepend the object metadata in the correct way to create a valid image buffer.

So instead of [pixel1, pixel2, pixel3 ...]

I would have, for example [width, height, channels, pixel1, pixel2, pixel3...]

What is the correct order to prepend the metadata and are width, height and channels enough?

Body:
You can use Mat constructor to create an image from data and meta data

Mat::Mat(int rows, int cols, int type, void* data, size_t
  step=AUTO_STEP); // documentation here

cv::Mat image = cv::Mat(height, width, CV_8UC3, raw_data);

type argument specifies the number of channels and data format. For example, typical RGB image data is unsigned char and the number of channels is 3 so its type = CV_8UC3

Available OpenCV Mat types are defined cvdef.h


问:
How to check whether a string was already entered?
there is a textbox and by entering the name in it, it checks if there is such a name in the dictionary
if there is, it displays a message and asks to rewrite the name
but I have a keypress that skips all Russian letters and after the output of the name correspondence message the game continues
Here is the code with keypress and button with a check if there is such a name or not:
The question is how to get around keypress with a duplicate name?

```<code>private void Button5_Click(object sender, EventArgs e)
    {
        var dict = new Dictionary<string, int>(); // where will the data be imported from the file
        using (var stream = new StreamReader(@"C:\Users\HP\Desktop\photo\results.txt")) // open file
        {
            // auxiliary elements
            var line = "";
            string[] param;
            // go through all the lines
            while ((line = stream.ReadLine()) != null)
            {
                param = line.Split(' '); // Break line
                dict.Add(param[0], Convert.ToInt32(param[1])); // add to dictionary
            }

        }

        if (dict.ContainsKey(textBox1.Text) == false)
        {

        }
        else
        {
            MessageBox.Show("This name already exists!");
        }
    }

private void TextBox1_KeyPress(object sender, KeyPressEventArgs e)
    {

        string Symbol = e.KeyChar.ToString();
        if (!Regex.Match(Symbol, @"[а-яА-Я]").Success && (Symbol != "\b"))
        {
            e.Handled = true;
        }

    }
</code>```

答:
First, I suggest extracting methods, i.e.

```<code>using System.IO;
using System.Linq;

...

private static Dictionary<string, int> AllNames() {
  return File
    .ReadLines(@"C:\Users\HP\Desktop\картинки\results.txt")
    .Where(line => !string.IsNullOrWhiteSpace(line))
    .Select(item => item.Split(' '))
    .ToDictionary(items => items[0],
                  items => int.Parse(items[1]));
}

private static bool NameExists(string name) {
  return AllNames().ContainsKey(name);
}

private static bool IsValidNameCharacter(char value) {
  // Russian letters are valid ones
  if (value >= 'А' && value <= 'Я' ||
      value >= 'а' && value <= 'я' ||
      value == 'ё' ||
      value == 'Ё')
    return true;

  // ...All the others are not
  return false;
}
</code>```

Then in order to prevent adding Russian Letters into names, let's test textBox1.Text at TextChanged:

```<code>private void Button5_Click(object sender, EventArgs e) {
  if (NameExists(textBox1.Text)) {
    // Let us be nice: put keyboard focus on the problem field
    if (textBox1.CanFocus) {
      textBox1.Focus();
      // textBox1.SelectAll(); // if you want to select all the text
    }

    MessageBox.Show("This name already exists!");

    return;
  }

  //given name passed validation control (name is all russian letters and unique)
  //TODO: put relevant code here (start the game?)
}

private void textBox1_TextChanged(object sender, EventArgs e) {
  textBox1.Text = string.Concat(textBox1.Text.Where(c => IsValidNameCharacter(c)));
}
</code>```

Body:
there is a textbox and by entering the name in it, it checks if there is such a name in the dictionary
if there is, it displays a message and asks to rewrite the name
but I have a keypress that skips all Russian letters and after the output of the name correspondence message the game continues
Here is the code with keypress and button with a check if there is such a name or not:
The question is how to get around keypress with a duplicate name?

private void Button5_Click(object sender, EventArgs e)
    {
        var dict = new Dictionary<string, int>(); // where will the data be imported from the file
        using (var stream = new StreamReader(@"C:\Users\HP\Desktop\photo\results.txt")) // open file
        {
            // auxiliary elements
            var line = "";
            string[] param;
            // go through all the lines
            while ((line = stream.ReadLine()) != null)
            {
                param = line.Split(' '); // Break line
                dict.Add(param[0], Convert.ToInt32(param[1])); // add to dictionary
            }

        }

        if (dict.ContainsKey(textBox1.Text) == false)
        {

        }
        else
        {
            MessageBox.Show("This name already exists!");
        }
    }

private void TextBox1_KeyPress(object sender, KeyPressEventArgs e)
    {

        string Symbol = e.KeyChar.ToString();
        if (!Regex.Match(Symbol, @"[а-яА-Я]").Success && (Symbol != "\b"))
        {
            e.Handled = true;
        }

    }

Body:
First, I suggest extracting methods, i.e.

using System.IO;
using System.Linq;

...

private static Dictionary<string, int> AllNames() {
  return File
    .ReadLines(@"C:\Users\HP\Desktop\картинки\results.txt")
    .Where(line => !string.IsNullOrWhiteSpace(line))
    .Select(item => item.Split(' '))
    .ToDictionary(items => items[0],
                  items => int.Parse(items[1]));
}

private static bool NameExists(string name) {
  return AllNames().ContainsKey(name);
}

private static bool IsValidNameCharacter(char value) {
  // Russian letters are valid ones
  if (value >= 'А' && value <= 'Я' ||
      value >= 'а' && value <= 'я' ||
      value == 'ё' ||
      value == 'Ё')
    return true;

  // ...All the others are not
  return false;
}

Then in order to prevent adding Russian Letters into names, let's test textBox1.Text at TextChanged:

private void Button5_Click(object sender, EventArgs e) {
  if (NameExists(textBox1.Text)) {
    // Let us be nice: put keyboard focus on the problem field
    if (textBox1.CanFocus) {
      textBox1.Focus();
      // textBox1.SelectAll(); // if you want to select all the text
    }

    MessageBox.Show("This name already exists!");

    return;
  }

  //given name passed validation control (name is all russian letters and unique)
  //TODO: put relevant code here (start the game?)
}

private void textBox1_TextChanged(object sender, EventArgs e) {
  textBox1.Text = string.Concat(textBox1.Text.Where(c => IsValidNameCharacter(c)));
}


问:
ISSUE: Kendo tooltip with custom angularjs directive and kendoConfirm
My current situation:
kendo tooltip works fine alone.
my new custom angularjs directive with kendoConfirm works fine alone.

but once i try to use them both together on an element, then only the kendo tooltip stops working.

```<code>   <button type="button" title="Disable Item" k-confirm-disable k-confirm-disable-title="'Confirm Disable'" k-confirm-disable-msg="'Are you sure you want to disable this item?'" ng-click="disable(dataItem.id)"  class="btn btn-danger" kendo-tooltip k-content="'Disable Item'" k-options="kendoTooltipOptions">

 $scope.kendoTooltipOptions = {
showAfter: 600,     //time for tooltip appear
position : 'top',
width    : 100
}
</code>```

kendo tooltip only works when I remove the custom angular directive from the element.

```<code>function kConfirmDisable($compile){
return {
    restrict: 'A',
    scope: {
        kConfirmDisableTitle:   '@',
        kConfirmDisableMsg: '@'
    },
    link: function(scope, element, attrs){

        var clickHandlers = $._data(element[0]).events.click;

        clickHandlers.reverse(); //reverse the click event handlers list

        var onClick = function(evt) {
            evt.preventDefault();
            evt.stopImmediatePropagation();
            if(!scope.kConfirmDisableTitle) {
                scope.kConfirmDisableTitle = "Confirm";
            }

            if(!scope.kConfirmDisableMsg) {
                scope.kConfirmDisableMsg = "Are you sure?";
            }

            angular.element("<div></div>").kendoConfirm({
                title: scope.kConfirmDisableTitle.replace(/['"]+/g, ''),
                content: scope.kConfirmDisableMsg.replace(/['"]+/g, ''),
                buttonLayout: "normal",
                visible: false,
                actions: [
                     {
                        text: "No",
                        Primary: false,
                        action: function(){

                            evt.preventDefault();
                            evt.stopImmediatePropagation();
                        }
                    },
                    {
                        text: "Yes",
                        Primary: true,
                        action: function(){

                            element.unbind(this);
                            setTimeout(function() {
                                element.unbind("click", onClick);
                                element.click();
                                evt.preventDefault();
                                evt.stopImmediatePropagation();
                                element.on("click", onClick);
                            },0);
                        }
                    },

                ],
                animation: {
                    open:{
                        effects: "zoom:in",
                        duration: 250
                    },
                    close:{
                        effects: "fade:out",
                        duration: 250
                    }
                },
                open: function(e) {
                   $("html, body").css("overflow", "hidden");
                },
                close: function() {
                    $("html, body").css("overflow", "visible");
                }
            }).data("kendoConfirm").open().result;
        };
        element.on("click", onClick);

        clickHandlers.reverse();
    }
}
}
</code>```

答:
Since Kendo AngularJs source is not available, I can only suggest couple of things:

Try to research what happens if you dont stop the propagation and not stop the default on the click in your directive.
If the scenario is that it does not work immediately on page reload and hovering on the element without using clicks- then this is not relevant.

Avoid using isolated scope in your directive and get the attributes via the $attrs link function parameter. Since you did not specify you get js error, I am assuming Kendo isn't using isolated scope, but it is still a direction to investigate.

Body:
My current situation:
kendo tooltip works fine alone.
my new custom angularjs directive with kendoConfirm works fine alone.

but once i try to use them both together on an element, then only the kendo tooltip stops working.

   <button type="button" title="Disable Item" k-confirm-disable k-confirm-disable-title="'Confirm Disable'" k-confirm-disable-msg="'Are you sure you want to disable this item?'" ng-click="disable(dataItem.id)"  class="btn btn-danger" kendo-tooltip k-content="'Disable Item'" k-options="kendoTooltipOptions">

 $scope.kendoTooltipOptions = {
showAfter: 600,     //time for tooltip appear
position : 'top',
width    : 100
}

kendo tooltip only works when I remove the custom angular directive from the element.

function kConfirmDisable($compile){
return {
    restrict: 'A',
    scope: {
        kConfirmDisableTitle:   '@',
        kConfirmDisableMsg: '@'
    },
    link: function(scope, element, attrs){

        var clickHandlers = $._data(element[0]).events.click;

        clickHandlers.reverse(); //reverse the click event handlers list

        var onClick = function(evt) {
            evt.preventDefault();
            evt.stopImmediatePropagation();
            if(!scope.kConfirmDisableTitle) {
                scope.kConfirmDisableTitle = "Confirm";
            }

            if(!scope.kConfirmDisableMsg) {
                scope.kConfirmDisableMsg = "Are you sure?";
            }

            angular.element("

").kendoConfirm({
                title: scope.kConfirmDisableTitle.replace(/['"]+/g, ''),
                content: scope.kConfirmDisableMsg.replace(/['"]+/g, ''),
                buttonLayout: "normal",
                visible: false,
                actions: [
                     {
                        text: "No",
                        Primary: false,
                        action: function(){

                            evt.preventDefault();
                            evt.stopImmediatePropagation();
                        }
                    },
                    {
                        text: "Yes",
                        Primary: true,
                        action: function(){

                            element.unbind(this);
                            setTimeout(function() {
                                element.unbind("click", onClick);
                                element.click();
                                evt.preventDefault();
                                evt.stopImmediatePropagation();
                                element.on("click", onClick);
                            },0);
                        }
                    },

                ],
                animation: {
                    open:{
                        effects: "zoom:in",
                        duration: 250
                    },
                    close:{
                        effects: "fade:out",
                        duration: 250
                    }
                },
                open: function(e) {
                   $("html, body").css("overflow", "hidden");
                },
                close: function() {
                    $("html, body").css("overflow", "visible");
                }
            }).data("kendoConfirm").open().result;
        };
        element.on("click", onClick);

        clickHandlers.reverse();
    }
}
}