问:
Horizontal XOR in AVX
Is there a way to XOR horizontally an AVX register—specifically, to XOR the four 64-bit components of a 256-bit register?

The goal is to get the XOR of all 4 64-bit components of an AVX register. It would essentially be doing the same thing as a horizontal add (_mm256_hadd_epi32()), except that I want to XOR instead of ADD.

The scalar code is:

```<code>inline uint64_t HorizontalXor(__m256i t) {
  return t.m256i_u64[0] ^ t.m256i_u64[1] ^ t.m256i_u64[2] ^ t.m256i_u64[3];
}
</code>```

答:
As stated in the comments, the fastest code very likely uses scalar operations, doing everything in the integer registers. All you need to do is extract the four packed 64-bit integers, then you have three XOR instructions, and you're done. This can be done pretty efficiently, and it leaves the result in an integer register, which is what your sample code suggests that you would want.

MSVC already generates pretty good code for the scalar function that you show as an example in the question:

```<code>inline uint64_t HorizontalXor(__m256i t) {
  return t.m256i_u64[0] ^ t.m256i_u64[1] ^ t.m256i_u64[2] ^ t.m256i_u64[3];
}
</code>```

Assuming that t is in ymm1, the resulting disassembly will be something like this:

```<code>vextractf128 xmm0, ymm1, 1
vpextrq      rax,  xmm0, 1
vmovq        rcx,  xmm1
xor          rax,  rcx
vpextrq      rcx,  xmm1, 1
vextractf128 xmm0, ymm1, 1
xor          rax,  rcx
vmovq        rcx,  xmm0
xor          rax,  rcx
</code>```

…with the result left in RAX. If this accurately reflects what you need (a scalar uint64_t result), then this code would be sufficient.

You can slightly improve it by using intrinsics:

```<code>inline uint64_t _mm256_hxor_epu64(__m256i x)
{
   const __m128i temp = _mm256_extracti128_si256(x, 1);
   return (uint64_t&)x
          ^ (uint64_t)(_mm_extract_epi64(_mm256_castsi256_si128(x), 1))
          ^ (uint64_t&)(temp)
          ^ (uint64_t)(_mm_extract_epi64(temp, 1));
}
</code>```

Then you'll get the following disassembly (again, assuming that x is in ymm1):

```<code>vextracti128 xmm2, ymm1, 1
vpextrq      rcx,  xmm2, 1
vpextrq      rax,  xmm1, 1
xor          rax,  rcx
vmovq        rcx,  xmm1
xor          rax,  rcx
vmovq        rcx,  xmm2
xor          rax,  rcx
</code>```

Notice that we were able to elide one extraction instruction, and that we've ensured VEXTRACTI128 was used instead of VEXTRACTF128 (although, this choice probably does not matter).

You'll see similar output on other compilers. For example, here's GCC 7.1 (with x assumed to be in ymm0):

```<code>vextracti128 xmm2, ymm0, 0x1
vpextrq      rax,  xmm0, 1
vmovq        rdx,  xmm2
vpextrq      rcx,  xmm2, 1
xor          rax,  rdx
vmovq        rdx,  xmm0
xor          rax,  rdx
xor          rax,  rcx
</code>```

The same instructions are there, but they've been slightly reordered. The intrinsics allow the compiler's scheduler to order as it deems best. Clang 4.0 schedules them differently yet:

```<code>vmovq        rax,  xmm0
vpextrq      rcx,  xmm0, 1
xor          rcx,  rax
vextracti128 xmm0, ymm0, 1
vmovq        rdx,  xmm0
xor          rdx,  rcx
vpextrq      rax,  xmm0, 1
xor          rax,  rdx
</code>```

And, of course, this ordering is always subject to change when the code gets inlined.

On the other hand, if you want the result to be in an AVX register, then you first need to decide how you want it to be stored. I guess you would just store the single 64-bit result as a scalar, something like:

```<code>inline __m256i _mm256_hxor(__m256i x)
{
   const __m128i temp = _mm256_extracti128_si256(x, 1);
   return _mm256_set1_epi64x((uint64_t&)x
                             ^ (uint64_t)(_mm_extract_epi64(_mm256_castsi256_si128(x), 1))
                             ^ (uint64_t&)(temp)
                             ^ (uint64_t)(_mm_extract_epi64(temp, 1)));
}
</code>```

But now you're doing a lot of data shuffling, negating any performance boost that you would possibly see from vectorizing the code.

Speaking of which, I'm not really sure how you got yourself into a situation where you need to do horizontal operations like this in the first place. SIMD operations are designed to scale vertically, not horizontally. If you're still in the implementation phase, it may be appropriate to reconsider the design. In particular, you should be generating the 4 integer values in 4 different AVX registers, rather than packing them all into one.

If you actually want 4 copies of the result packed into an AVX register, then you could do something like this:

```<code>inline __m256i _mm256_hxor(__m256i x)
{
   const __m256i temp = _mm256_xor_si256(x,
                                         _mm256_permute2f128_si256(x, x, 1));
   return _mm256_xor_si256(temp,
                           _mm256_shuffle_epi32(temp, _MM_SHUFFLE(1, 0, 3, 2)));
}
</code>```

This still exploits a bit of parallelism by doing two XORs at once, meaning that only two XOR operations are required in all, instead of three.

If it helps to visualize it, this basically does:

```<code>   A         B         C         D           ⟵ input
  XOR       XOR       XOR       XOR
   C         D         A         B           ⟵ permuted input
=====================================
  A^C       B^D       A^C        B^D         ⟵ intermediate result
  XOR       XOR       XOR        XOR
  B^D       A^C       B^D        A^C         ⟵ shuffled intermediate result
======================================
A^C^B^D   A^C^B^D   A^C^B^D    A^C^B^D      ⟵ final result
</code>```

On practically all compilers, these intrinsics will produce the following assembly code:

```<code>vperm2f128  ymm0, ymm1, ymm1, 1    ; input is in YMM1
vpxor       ymm2, ymm0, ymm1
vpshufd     ymm1, ymm2, 78
vpxor       ymm0, ymm1, ymm2
</code>```

(I had come up with this on my way to bed after first posting this answer, and planned to come back and update the answer, but I see that wim beat me to the punch on posting it. Oh well, it's still a better approach than what I first had, so it still merits being included here.)

And, of course, if you wanted this in an integer register, you would just need a simple VMOVQ:

```<code>vextractf128 xmm0, ymm1, 1
vpextrq      rax,  xmm0, 1
vmovq        rcx,  xmm1
xor          rax,  rcx
vpextrq      rcx,  xmm1, 1
vextractf128 xmm0, ymm1, 1
xor          rax,  rcx
vmovq        rcx,  xmm0
xor          rax,  rcx
</code>```0

The question is, would this be faster than the scalar code above. And the answer is, yes, probably. Although you are doing the XORs using the AVX execution units, instead of the completely separate integer execution units, there are fewer AVX shuffles/permutes/extracts that need to be done, which means less overhead. So I might also have to eat my words on scalar code being the fastest implementation. But it really depends on what you're doing and how the instructions can be scheduled/interleaved.

Title: Horizontal XOR in AVX

Body:
Is there a way to XOR horizontally an AVX register—specifically, to XOR the four 64-bit components of a 256-bit register?

The goal is to get the XOR of all 4 64-bit components of an AVX register. It would essentially be doing the same thing as a horizontal add (_mm256_hadd_epi32()), except that I want to XOR instead of ADD.

The scalar code is:

inline uint64_t HorizontalXor(__m256i t) {
  return t.m256i_u64[0] ^ t.m256i_u64[1] ^ t.m256i_u64[2] ^ t.m256i_u64[3];
}

Body:
As stated in the comments, the fastest code very likely uses scalar operations, doing everything in the integer registers. All you need to do is extract the four packed 64-bit integers, then you have three XOR instructions, and you're done. This can be done pretty efficiently, and it leaves the result in an integer register, which is what your sample code suggests that you would want.

MSVC already generates pretty good code for the scalar function that you show as an example in the question:

inline uint64_t HorizontalXor(__m256i t) {
  return t.m256i_u64[0] ^ t.m256i_u64[1] ^ t.m256i_u64[2] ^ t.m256i_u64[3];
}

Assuming that t is in ymm1, the resulting disassembly will be something like this:

vextractf128 xmm0, ymm1, 1
vpextrq      rax,  xmm0, 1
vmovq        rcx,  xmm1
xor          rax,  rcx
vpextrq      rcx,  xmm1, 1
vextractf128 xmm0, ymm1, 1
xor          rax,  rcx
vmovq        rcx,  xmm0
xor          rax,  rcx

…with the result left in RAX. If this accurately reflects what you need (a scalar uint64_t result), then this code would be sufficient.

You can slightly improve it by using intrinsics:

inline uint64_t _mm256_hxor_epu64(__m256i x)
{
   const __m128i temp = _mm256_extracti128_si256(x, 1);
   return (uint64_t&)x
          ^ (uint64_t)(_mm_extract_epi64(_mm256_castsi256_si128(x), 1))
          ^ (uint64_t&)(temp)
          ^ (uint64_t)(_mm_extract_epi64(temp, 1));
}

Then you'll get the following disassembly (again, assuming that x is in ymm1):

vextracti128 xmm2, ymm1, 1
vpextrq      rcx,  xmm2, 1
vpextrq      rax,  xmm1, 1
xor          rax,  rcx
vmovq        rcx,  xmm1
xor          rax,  rcx
vmovq        rcx,  xmm2
xor          rax,  rcx

Notice that we were able to elide one extraction instruction, and that we've ensured VEXTRACTI128 was used instead of VEXTRACTF128 (although, this choice probably does not matter).

You'll see similar output on other compilers. For example, here's GCC 7.1 (with x assumed to be in ymm0):

vextracti128 xmm2, ymm0, 0x1
vpextrq      rax,  xmm0, 1
vmovq        rdx,  xmm2
vpextrq      rcx,  xmm2, 1
xor          rax,  rdx
vmovq        rdx,  xmm0
xor          rax,  rdx
xor          rax,  rcx

The same instructions are there, but they've been slightly reordered. The intrinsics allow the compiler's scheduler to order as it deems best. Clang 4.0 schedules them differently yet:

vmovq        rax,  xmm0
vpextrq      rcx,  xmm0, 1
xor          rcx,  rax
vextracti128 xmm0, ymm0, 1
vmovq        rdx,  xmm0
xor          rdx,  rcx
vpextrq      rax,  xmm0, 1
xor          rax,  rdx

And, of course, this ordering is always subject to change when the code gets inlined.

On the other hand, if you want the result to be in an AVX register, then you first need to decide how you want it to be stored. I guess you would just store the single 64-bit result as a scalar, something like:

inline __m256i _mm256_hxor(__m256i x)
{
   const __m128i temp = _mm256_extracti128_si256(x, 1);
   return _mm256_set1_epi64x((uint64_t&)x
                             ^ (uint64_t)(_mm_extract_epi64(_mm256_castsi256_si128(x), 1))
                             ^ (uint64_t&)(temp)
                             ^ (uint64_t)(_mm_extract_epi64(temp, 1)));
}

But now you're doing a lot of data shuffling, negating any performance boost that you would possibly see from vectorizing the code.

Speaking of which, I'm not really sure how you got yourself into a situation where you need to do horizontal operations like this in the first place. SIMD operations are designed to scale vertically, not horizontally. If you're still in the implementation phase, it may be appropriate to reconsider the design. In particular, you should be generating the 4 integer values in 4 different AVX registers, rather than packing them all into one.

If you actually want 4 copies of the result packed into an AVX register, then you could do something like this:

inline __m256i _mm256_hxor(__m256i x)
{
   const __m256i temp = _mm256_xor_si256(x,
                                         _mm256_permute2f128_si256(x, x, 1));
   return _mm256_xor_si256(temp,
                           _mm256_shuffle_epi32(temp, _MM_SHUFFLE(1, 0, 3, 2)));
}

This still exploits a bit of parallelism by doing two XORs at once, meaning that only two XOR operations are required in all, instead of three.

If it helps to visualize it, this basically does:

   A         B         C         D           ⟵ input
  XOR       XOR       XOR       XOR
   C         D         A         B           ⟵ permuted input
=====================================
  A^C       B^D       A^C        B^D         ⟵ intermediate result
  XOR       XOR       XOR        XOR
  B^D       A^C       B^D        A^C         ⟵ shuffled intermediate result
======================================
A^C^B^D   A^C^B^D   A^C^B^D    A^C^B^D      ⟵ final result

On practically all compilers, these intrinsics will produce the following assembly code:

vperm2f128  ymm0, ymm1, ymm1, 1    ; input is in YMM1
vpxor       ymm2, ymm0, ymm1
vpshufd     ymm1, ymm2, 78
vpxor       ymm0, ymm1, ymm2

(I had come up with this on my way to bed after first posting this answer, and planned to come back and update the answer, but I see that wim beat me to the punch on posting it. Oh well, it's still a better approach than what I first had, so it still merits being included here.)

And, of course, if you wanted this in an integer register, you would just need a simple VMOVQ:

vperm2f128  ymm0, ymm1, ymm1, 1    ; input is in YMM1
vpxor       ymm2, ymm0, ymm1
vpshufd     ymm1, ymm2, 78
vpxor       ymm0, ymm1, ymm2
vmovq       rax,  xmm0

The question is, would this be faster than the scalar code above. And the answer is, yes, probably. Although you are doing the XORs using the AVX execution units, instead of the completely separate integer execution units, there are fewer AVX shuffles/permutes/extracts that need to be done, which means less overhead. So I might also have to eat my words on scalar code being the fastest implementation. But it really depends on what you're doing and how the instructions can be scheduled/interleaved.


来源: stackexchange

问:
Given a file, find the ten most frequently occurring words as efficiently as possible
This is apparently an interview question (found it in a collection of interview questions), but even if it's not it's pretty cool.

We are told to do this efficiently on all complexity measures. I thought of creating a HashMap that maps the words to their frequency. That would be O(n) in time and space complexity, but since there may be lots of words we cannot assume that we can store everything in memory.

I must add that nothing in the question says that the words cannot be stored in memory, but what if that were the case? If that's not the case, then the question does not seem as challenging.

答:
Depending on the size of the input data, it may or may not be a good idea to keep a HashMap. Say for instance, our hash-map is too big to fit into main memory. This can cause a very high number of memory transfers as most hash-map implementations need random access and would not be very good on the cache.

In such cases sorting the input data would be a better solution.

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 2.5


问:
How to implement onBlur/onFocus for a div with nested input fields?
There is a
 and a couple of nested <input>s. onBlur fires every time user clicks on one of the <input>s.

This is a bit frustrating that onBlur happens when I hit something inside the div. After an hour of searching I still wasn't able to find any good solution.

This sample of code shows what I'm talking about:

```<code>class Thing extends React.Component {
  handleBlur(e) {
    console.log('blur');
  }
  handleFocus(e) {
    console.log('focus');
  }
  render() {
    return (
      <div onFocus={this.handleFocus} onBlur={this.handleBlur} tabIndex="1">
        <div>
          <input type="text" value="Hello," />
        </div>
        <div>
          <input type="text" value="Thing" />
        </div>
      </div>
    );
  }
}
</code>```

You may play around with the code over here.

However my ultimate goal is to make this thing working properly.

答:
How about splitting the inputs into a single, independent component?

app.js

```<code>class Thing extends React.Component {
  handleBlur(val, event) {
    console.log(val, event);
  }
  handleFocus(val, event) {
    console.log(val, event);
  }

  data = ['Hello, ', 'Thing'];

  render() {
    return (
      <div tabIndex="1">
        {this.data.map((v, i) => <Input value={v} key={i} onFocus={this.handleFocus} onBlur={this.handleBlur} />)}
      </div>
    );
  }
}
</code>```

Input.js

```<code>import React from 'react';

export class Input extends React.PureComponent {

  handleF = () => {
    this.props.onFocus(this.props.value, 'focus');
  }

  handleB = () => {
    this.props.onBlur(this.props.value, 'blur');
  }

  render() {
    return <input type="text" onFocus={this.handleF} onBlur={this.handleB} />;
  }
}

export default Input;
</code>```

https://codesandbox.io/s/J6o5Ey9Jg

Body:
There is a
 and a couple of nested <input>s. onBlur fires every time user clicks on one of the <input>s.

This is a bit frustrating that onBlur happens when I hit something inside the div. After an hour of searching I still wasn't able to find any good solution.

This sample of code shows what I'm talking about:

class Thing extends React.Component {
  handleBlur(e) {
    console.log('blur');
  }
  handleFocus(e) {
    console.log('focus');
  }
  render() {
    return (

          <input type="text" value="Hello," />

          <input type="text" value="Thing" />

    );
  }
}

You may play around with the code over here.

However my ultimate goal is to make this thing working properly.

Body:
How about splitting the inputs into a single, independent component?

app.js

class Thing extends React.Component {
  handleBlur(val, event) {
    console.log(val, event);
  }
  handleFocus(val, event) {
    console.log(val, event);
  }

  data = ['Hello, ', 'Thing'];

  render() {
    return (
      <div tabIndex="1">
        {this.data.map((v, i) => <Input value={v} key={i} onFocus={this.handleFocus} onBlur={this.handleBlur} />)}
      </div>
    );
  }
}

Input.js

import React from 'react';

export class Input extends React.PureComponent {

  handleF = () => {
    this.props.onFocus(this.props.value, 'focus');
  }

  handleB = () => {
    this.props.onBlur(this.props.value, 'blur');
  }

  render() {
    return <input type="text" onFocus={this.handleF} onBlur={this.handleB} />;
  }
}

export default Input;

https://codesandbox.io/s/J6o5Ey9Jg


问:
How to increase timeout while querying data from WebService
I'm able to query web service in ActionMethod of the controller, but unable to query it at the Application Startup.

Problem Description:
I'm developing a WebApplication on ASP.net MVC 5, It makes use of data retrieved from a SOAP web service Autotask API. Let me just say it here, there are some records that have to be loaded/cached from the API before a user could do other operations.

So for communication between WebApp & Webservice,

I added a Service Reference with provided WSDL.

Created proxy class from it and while developing I've been calling Webservice in Controller's ActionMethods.

So in the View anytime user click a given link, a call to the Webservice is made. the retrieved list of records is cached within the app so that next time we won't have to make another call to Webservice. It's working fine.

What I'm trying to Achieve

In production, it'd be ideal to load these records at the application startup.

So I moved the call to Webservice from controller's ActionMethod to Application_Start() method in Global.asax.cs.

But When I start the app and at the time of querying data from Webservice. It results in error

The content type text/html; charset=utf-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8)

As I'm expecting records of data in XML format, Server returns with error The remote server returned an error: (500) Internal Server Error. stating the 'Username & Password is incorrect'

But I believe that's not the actual case. Because of two solid reasons

I'm successfully connecting to Webservice using same credentials in the Controller's ActionMethod, as described above.

Because of the following exceptions.

Server stack trace:
     at System.ServiceModel.Channels.HttpChannelUtilities.ValidateRequestReplyResponse(HttpWebRequest request, HttpWebResponse response, HttpChannelFactory1 factory, WebException responseException, ChannelBinding channelBinding)
     at System.ServiceModel.Channels.HttpChannelFactory1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
     at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
     at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
     at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
     at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
     at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)

Also having an Inner Exception.

at System.Net.HttpWebRequest.GetResponse()
     at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)

To me, it shows that request timeout is being expired. I tried modifying the binding configuration to following, As explained in here WCF Service, How to increase the timeout?

```<code><system.serviceModel>
<bindings>
  <basicHttpBinding>
    <binding name="ATWS15" />
    <binding name="IncreasedTimeout" sendTimeout="00:10:00"></binding>
  </basicHttpBinding>
</bindings>
<client>
  <endpoint address="http://webservices.address.toApi.net/atws.asmx"
    binding="basicHttpBinding" bindingConfiguration="IncreasedTimeout" contract="AutoTaskProxy.ATWS15"
     />
</client>
</code>```

If anyone can help me, what am I doing wrong here.? I'm able to query webservice in ActionMethod of the controller, but unable to query it at the Application Startup

答:
You have response timeout exception, try to increase receiveTimeout</p>

```<code><bindings>
  <basicHttpBinding>
    <binding name="ATWS15" />
    <binding name="IncreasedTimeout" sendTimeout="00:10:00" receiveTimeout="00:10:00"></binding>
  </basicHttpBinding>
</bindings>
</code>```

Body:
I'm able to query web service in ActionMethod of the controller, but unable to query it at the Application Startup.

Problem Description:
I'm developing a WebApplication on ASP.net MVC 5, It makes use of data retrieved from a SOAP web service Autotask API. Let me just say it here, there are some records that have to be loaded/cached from the API before a user could do other operations.

So for communication between WebApp & Webservice,

I added a Service Reference with provided WSDL.

Created proxy class from it and while developing I've been calling Webservice in Controller's ActionMethods.

So in the View anytime user click a given link, a call to the Webservice is made. the retrieved list of records is cached within the app so that next time we won't have to make another call to Webservice. It's working fine.

What I'm trying to Achieve

In production, it'd be ideal to load these records at the application startup.

So I moved the call to Webservice from controller's ActionMethod to Application_Start() method in Global.asax.cs.

But When I start the app and at the time of querying data from Webservice. It results in error

The content type text/html; charset=utf-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8)

As I'm expecting records of data in XML format, Server returns with error The remote server returned an error: (500) Internal Server Error. stating the 'Username & Password is incorrect'

But I believe that's not the actual case. Because of two solid reasons

I'm successfully connecting to Webservice using same credentials in the Controller's ActionMethod, as described above.

Because of the following exceptions.

Server stack trace:
     at System.ServiceModel.Channels.HttpChannelUtilities.ValidateRequestReplyResponse(HttpWebRequest request, HttpWebResponse response, HttpChannelFactory1 factory, WebException responseException, ChannelBinding channelBinding)
     at System.ServiceModel.Channels.HttpChannelFactory1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
     at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
     at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
     at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
     at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
     at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)

Also having an Inner Exception.

at System.Net.HttpWebRequest.GetResponse()
     at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)

To me, it shows that request timeout is being expired. I tried modifying the binding configuration to following, As explained in here WCF Service, How to increase the timeout?

<system.serviceModel>
<bindings>
  <basicHttpBinding>
    <binding name="ATWS15" />
    <binding name="IncreasedTimeout" sendTimeout="00:10:00"></binding>
  </basicHttpBinding>
</bindings>
<client>
  <endpoint address="http://webservices.address.toApi.net/atws.asmx"
    binding="basicHttpBinding" bindingConfiguration="IncreasedTimeout" contract="AutoTaskProxy.ATWS15"
     />
</client>

If anyone can help me, what am I doing wrong here.? I'm able to query webservice in ActionMethod of the controller, but unable to query it at the Application Startup

Body:
You have response timeout exception, try to increase receiveTimeout

<bindings>
  <basicHttpBinding>
    <binding name="ATWS15" />
    <binding name="IncreasedTimeout" sendTimeout="00:10:00" receiveTimeout="00:10:00"></binding>
  </basicHttpBinding>
</bindings>


问:
Delete a row with condition on the same table in mysql
I have to delete a row with max(id) from a table in MySQL.
I am using query::

```<code> DELETE
 FROM master
 WHERE id=(
 SELECT MAX(id)
 FROM master)
</code>```

but getting error No. 1093.

Can anybody please help me??

答:
```<code>DELETE FROM Test WHERE id IN(SELECT MAX(id) FROM Test);
</code>```

This seems to be cross SQL vendor friendly. The LIMIT option in MySQL becomes this in SQL SERVER.

```<code> DELETE FROM Test WHERE id IN(SELECT TOP 1 id FROM Test ORDER BY id DESC );
</code>```

See here

Body:
I have to delete a row with max(id) from a table in MySQL.
I am using query::

 DELETE
 FROM master
 WHERE id=(
 SELECT MAX(id)
 FROM master)

but getting error No. 1093.

Can anybody please help me??

Body:
DELETE FROM Test WHERE id IN(SELECT MAX(id) FROM Test);

This seems to be cross SQL vendor friendly. The LIMIT option in MySQL becomes this in SQL SERVER.

 DELETE FROM Test WHERE id IN(SELECT TOP 1 id FROM Test ORDER BY id DESC );

See here


问:
Webdriver 3.1.0.0 Firefox 47.0.2 and Geckodriver 0.17.0 unable to change URL
I am using C# 4.6.2 in Visual Studio Enterprise 2015 on Windows 7 Enterprise SP1 x64

I updated to Webdriver 3.1.0.0, Firefox 46.0.2 and Geckodriver 0.17.0 and when I run my tests now geckodriver and Firefox opens, but setting WebDriver's (FirefoxDriver) Url property does nothing. Getting the Url property's value seems to always be the string

```<code>"System.Collections.Generic.Dictionary`2[System.String,System.Object]"
</code>```

even if I manually go to a URL in the browser window.

I have tried both the 32 bit and the 64 bit version of Geckodriver  and had exactly the same problem with both.

The code that the test is running is:

```<code>private readonly string rootUrl = "https://localhost:44388/Home/CaseList";
</code>```

...

```<code>WebDriver.Url = rootUrl;
</code>```

If I use the immediate window I have the following result

```<code>Browser.WebDriver.Url="http://www.google.com"
Exception thrown: 'System.Net.WebException' in System.dll
Exception thrown: 'System.Net.WebException' in System.dll
"http://www.google.com"
</code>```

Browser is our own static class with the property

```<code>public static IWebDriver WebDriver
</code>```

If I create a new FirefoxDriver using the default constructor in the immediate window it opens successfully, but I get this feedback

```<code>webDriver = new FirefoxDriver()
Exception thrown: 'System.Net.Sockets.SocketException' in System.dll
{OpenQA.Selenium.Firefox.FirefoxDriver}
    ApplicationCache: '((OpenQA.Selenium.Remote.RemoteWebDriver)(webDriver = new FirefoxDriver())).ApplicationCache' threw an exception of type 'System.InvalidOperationException'
    Capabilities: {Capabilities [BrowserName=, IsJavaScriptEnabled=False, Platform=Any, Version=]}
    CommandExecutor: {OpenQA.Selenium.Remote.DriverServiceCommandExecutor}
    CurrentWindowHandle: "System.Collections.Generic.Dictionary`2[System.String,System.Object]"
    FileDetector: {OpenQA.Selenium.DefaultFileDetector}
    HasApplicationCache: false
    HasLocationContext: false
    HasWebStorage: false
    IsMarionette: true
    IsSpecificationCompliant: true
    Keyboard: {OpenQA.Selenium.Remote.RemoteKeyboard}
    LocationContext: '((OpenQA.Selenium.Remote.RemoteWebDriver)(webDriver = new FirefoxDriver())).LocationContext' threw an exception of type 'System.InvalidOperationException'
    Mouse: {OpenQA.Selenium.Remote.RemoteMouse}
    OpenQA.Selenium.Internal.IActionExecutor.IsActionExecutor: true
    PageSource: "System.Collections.Generic.Dictionary`2[System.String,System.Object]"
    SessionId: {OpenQA.Selenium.Remote.SessionId}
    Title: "System.Collections.Generic.Dictionary`2[System.String,System.Object]"
    Url: "System.Collections.Generic.Dictionary`2[System.String,System.Object]"
    WebStorage: '((OpenQA.Selenium.Remote.RemoteWebDriver)(webDriver = new FirefoxDriver())).WebStorage' threw an exception of type 'System.InvalidOperationException'
    WindowHandles: '((OpenQA.Selenium.Remote.RemoteWebDriver)(webDriver = new FirefoxDriver())).WindowHandles' threw an exception of type 'System.InvalidCastException'
    appCache: null
    capabilities: {Capabilities [BrowserName=, IsJavaScriptEnabled=False, Platform=Any, Version=]}
    executor: {OpenQA.Selenium.Remote.DriverServiceCommandExecutor}
    fileDetector: {OpenQA.Selenium.DefaultFileDetector}
    keyboard: {OpenQA.Selenium.Remote.RemoteKeyboard}
    locationContext: null
    mouse: {OpenQA.Selenium.Remote.RemoteMouse}
    sessionId: {OpenQA.Selenium.Remote.SessionId}
    storage: null
</code>```

Any ideas on how to fix these issues?

答: Thanks to Selenium IRC found out that I needed to update Firefox again (to 54) and update Webdriver again ( to 3.3) now it seems to be working OK again.</p>

Body:
I am using C# 4.6.2 in Visual Studio Enterprise 2015 on Windows 7 Enterprise SP1 x64

I updated to Webdriver 3.1.0.0, Firefox 46.0.2 and Geckodriver 0.17.0 and when I run my tests now geckodriver and Firefox opens, but setting WebDriver's (FirefoxDriver) Url property does nothing. Getting the Url property's value seems to always be the string

"System.Collections.Generic.Dictionary`2[System.String,System.Object]"

even if I manually go to a URL in the browser window.

I have tried both the 32 bit and the 64 bit version of Geckodriver  and had exactly the same problem with both.

The code that the test is running is:

private readonly string rootUrl = "https://localhost:44388/Home/CaseList";

...

WebDriver.Url = rootUrl;

If I use the immediate window I have the following result

Browser.WebDriver.Url="http://www.google.com"
Exception thrown: 'System.Net.WebException' in System.dll
Exception thrown: 'System.Net.WebException' in System.dll
"http://www.google.com"

Browser is our own static class with the property

public static IWebDriver WebDriver

If I create a new FirefoxDriver using the default constructor in the immediate window it opens successfully, but I get this feedback

webDriver = new FirefoxDriver()
Exception thrown: 'System.Net.Sockets.SocketException' in System.dll
{OpenQA.Selenium.Firefox.FirefoxDriver}
    ApplicationCache: '((OpenQA.Selenium.Remote.RemoteWebDriver)(webDriver = new FirefoxDriver())).ApplicationCache' threw an exception of type 'System.InvalidOperationException'
    Capabilities: {Capabilities [BrowserName=, IsJavaScriptEnabled=False, Platform=Any, Version=]}
    CommandExecutor: {OpenQA.Selenium.Remote.DriverServiceCommandExecutor}
    CurrentWindowHandle: "System.Collections.Generic.Dictionary`2[System.String,System.Object]"
    FileDetector: {OpenQA.Selenium.DefaultFileDetector}
    HasApplicationCache: false
    HasLocationContext: false
    HasWebStorage: false
    IsMarionette: true
    IsSpecificationCompliant: true
    Keyboard: {OpenQA.Selenium.Remote.RemoteKeyboard}
    LocationContext: '((OpenQA.Selenium.Remote.RemoteWebDriver)(webDriver = new FirefoxDriver())).LocationContext' threw an exception of type 'System.InvalidOperationException'
    Mouse: {OpenQA.Selenium.Remote.RemoteMouse}
    OpenQA.Selenium.Internal.IActionExecutor.IsActionExecutor: true
    PageSource: "System.Collections.Generic.Dictionary`2[System.String,System.Object]"
    SessionId: {OpenQA.Selenium.Remote.SessionId}
    Title: "System.Collections.Generic.Dictionary`2[System.String,System.Object]"
    Url: "System.Collections.Generic.Dictionary`2[System.String,System.Object]"
    WebStorage: '((OpenQA.Selenium.Remote.RemoteWebDriver)(webDriver = new FirefoxDriver())).WebStorage' threw an exception of type 'System.InvalidOperationException'
    WindowHandles: '((OpenQA.Selenium.Remote.RemoteWebDriver)(webDriver = new FirefoxDriver())).WindowHandles' threw an exception of type 'System.InvalidCastException'
    appCache: null
    capabilities: {Capabilities [BrowserName=, IsJavaScriptEnabled=False, Platform=Any, Version=]}
    executor: {OpenQA.Selenium.Remote.DriverServiceCommandExecutor}
    fileDetector: {OpenQA.Selenium.DefaultFileDetector}
    keyboard: {OpenQA.Selenium.Remote.RemoteKeyboard}
    locationContext: null
    mouse: {OpenQA.Selenium.Remote.RemoteMouse}
    sessionId: {OpenQA.Selenium.Remote.SessionId}
    storage: null

Any ideas on how to fix these issues?


问:
Flexgrid holy grail with 100% height
I have a twist on the "holy grail" layout and you'll notice that the #main has a min-height: 800px.  What I'm really looking for is 100% height, then as I add content within the section the rest of the layout continues down with it (as it currently does).

Any idea how to achieve this, with 100% height and not explicitly setting 800px?

body {
  font: 24px Helvetica;
  background: #999999;
  margin: 0;
  padding: 0;
  height: 100%;
}

#main {
  min-height: 800px;
  margin: 0;
  padding: 0;
  display: flex;
  flex-flow: row;
}

#main>article {
  border: 1px solid #cccc33;
  background: #dddd88;
  flex: 3 1 60%;
  order: 3;
}

#main>nav {
  border: 1px solid #8888bb;
  background: #ccccff;
  flex: 1 6 70px;
  order: 1;
  max-width: 70px;
  min-width: 70px;
}

#main>aside {
  border: 1px solid #8888bb;
  background: #ccccff;
  flex: 1 6 300px;
  order: 2;
  max-width: 300px;
  min-width: 300px;
}

header {
  display: block;
  padding: 5px;
  min-height: 70px;
  border: 1px solid #eebb55;
  background: #ffeebb;
}

section {
  margin: 10px;
}

.container {
  margin: 0;
  padding: 0;
  display: flex;
  flex-flow: row;
}

.container>.field {
  width: 100%;
  background: #dddd88;
  order: 2;
}

.container>.left {
  width: 4px;
  background: black;
  order: 1;
}

.container>.right {
  width: 4px;
  background: black;
  order: 3;
  display: flex;
}

.top,
.bottom {
  display: block;
  height: 4px;
  background: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id='main'>
  <article>
    <header>header</header>
    <section>
      <div class="top"></div>
      <div class="container">
        <div class="field">
          Sub Container w/ borders
        </div>
        <div class="left"></div>
        <div class="right"></div>
      </div>
      <div class="bottom"></div>
    </section>
  </article>
  <nav>nav</nav>
  <aside>aside</aside>
</div></code>```

答:
If you want an element to occupy 100% viewport height, with the option to expand to accommodate additional content, use min-height: 100vh (demo).

For reasons explained in the following posts, percentage heights are not as efficient and easy to use as viewport percentage heights.

Working with the CSS height property and percentage values

Font size with percentage value (%) not scaling with screen size

Title: Flexgrid holy grail with 100% height

Body:
I have a twist on the "holy grail" layout and you'll notice that the #main has a min-height: 800px.  What I'm really looking for is 100% height, then as I add content within the section the rest of the layout continues down with it (as it currently does).

Any idea how to achieve this, with 100% height and not explicitly setting 800px?

body {
  font: 24px Helvetica;
  background: #999999;
  margin: 0;
  padding: 0;
  height: 100%;
}

#main {
  min-height: 800px;
  margin: 0;
  padding: 0;
  display: flex;
  flex-flow: row;
}

#main>article {
  border: 1px solid #cccc33;
  background: #dddd88;
  flex: 3 1 60%;
  order: 3;
}

#main>nav {
  border: 1px solid #8888bb;
  background: #ccccff;
  flex: 1 6 70px;
  order: 1;
  max-width: 70px;
  min-width: 70px;
}

#main>aside {
  border: 1px solid #8888bb;
  background: #ccccff;
  flex: 1 6 300px;
  order: 2;
  max-width: 300px;
  min-width: 300px;
}

header {
  display: block;
  padding: 5px;
  min-height: 70px;
  border: 1px solid #eebb55;
  background: #ffeebb;
}

section {
  margin: 10px;
}

.container {
  margin: 0;
  padding: 0;
  display: flex;
  flex-flow: row;
}

.container>.field {
  width: 100%;
  background: #dddd88;
  order: 2;
}

.container>.left {
  width: 4px;
  background: black;
  order: 1;
}

.container>.right {
  width: 4px;
  background: black;
  order: 3;
  display: flex;
}

.top,
.bottom {
  display: block;
  height: 4px;
  background: red;
}

    header

          Sub Container w/ borders

  nav
  aside


问:
VS2017RC Typescript not generating javascript
In VS 2017 changes to a typescript file no longer result in any javascript being created, despite a message on the lower bar saying "outputs generated successfully".

I've tried on 2 machines with the same version of VS installed and using a simple test project with the same result

is this a bug?

has something changed in the way you work with typescript in VS 2017?

do I need a tsconfig.json file? I have never needed one in the past...

答: You need an tsconfig.json file for Visual Studio to build ts files into js.</p>


问:
Can not handle properly a simple exception
I wrote a PHP class to manage some statistic functions but there are some functions that need a minimum of elements i.e. >0.
So I added a try catch and I still get the same error.

```<code>/**
 * Calculates the minimum for a given set of values.
 *
 * @param array $values The input values
 * @return float|int The minimum of values as an integer or float
 */
public static function min($values)
{
    try {
        min($values);
    } catch (Exception $e) {
        return 0;
    }
}
</code>```

And I get:

```<code>ErrorException in Statistics.php line 41: min(): Array must contain at least one element
</code>```

Thanks in advance.

答:
Your ErrorException is being thrown by your framework. (something like Can I try/catch a warning?)

Normally, min triggers a Warning

As per the min() docs:

min() returns the parameter value considered "lowest" according to standard comparisons. If multiple values of different types evaluate as equal (e.g. 0 and 'abc') the first provided to the function will be returned.

If an empty array is passed, then FALSE will be returned and an E_WARNING error will be emitted.

In your case, $values is an empty array.

To avoid that, you can use this:

```<code>public static function min($values)
{
    if (empty($values)){
        return null; // better than 0. 0 is a valid minimum
    }

    return min($values);
}
</code>```

Body:
I wrote a PHP class to manage some statistic functions but there are some functions that need a minimum of elements i.e. >0.
So I added a try catch and I still get the same error.

/**
 * Calculates the minimum for a given set of values.
 *
 * @param array $values The input values
 * @return float|int The minimum of values as an integer or float
 */
public static function min($values)
{
    try {
        min($values);
    } catch (Exception $e) {
        return 0;
    }
}

And I get:

ErrorException in Statistics.php line 41: min(): Array must contain at least one element

Thanks in advance.

Body:
Your ErrorException is being thrown by your framework. (something like Can I try/catch a warning?)

Normally, min triggers a Warning

As per the min() docs:

min() returns the parameter value considered "lowest" according to standard comparisons. If multiple values of different types evaluate as equal (e.g. 0 and 'abc') the first provided to the function will be returned.

If an empty array is passed, then FALSE will be returned and an E_WARNING error will be emitted.

In your case, $values is an empty array.

To avoid that, you can use this:

public static function min($values)
{
    if (empty($values)){
        return null; // better than 0. 0 is a valid minimum
    }

    return min($values);
}


问:
MySQL: Number of subsequent occurrences
I have a table with four columns: id, from, to, msg.

The rows can look like this:

```<code>1 - foo - bar - hello
2 - foo - bar - zup?
3 - bar - foo - hi
4 - bar - foo - going okay
5 - bar - foo - you?
</code>```

Now I wanna know how many times "bar" has tried to "talk" to "foo" without response. Like I wanna count the number of occurrences since "foo" was on the sending end.

In this example, before the next entry, it should return 3.

Is this possible in pure (My)SQL?

I'm using php on the server side.

Thanks for any tips and advice! =)

答:
Give this a go.

It assumes a table name of convo and the id is autoincrementing.

This is just the mysql but the PHP calls can be added quite cleanly if you wrapped it in a function that passes in the from and to variables.

```<code>SELECT
  count(*) AS unreplied
FROM
  `convo`
WHERE
  `convo`.`from` = 'bar' AND
  `convo`.`to` = 'foo' AND
  `convo`.`id` > (SELECT
                    id
                  FROM
                    `convo`
                  WHERE
                    `convo`.`from` = 'foo' AND
                    `convo`.`to` = 'bar'
                  ORDER BY
                    `convo`.`id` DESC
                  LIMIT 1)
</code>```

Title: MySQL: Number of subsequent occurrences

Body:
I have a table with four columns: id, from, to, msg.

The rows can look like this:

1 - foo - bar - hello
2 - foo - bar - zup?
3 - bar - foo - hi
4 - bar - foo - going okay
5 - bar - foo - you?

Now I wanna know how many times "bar" has tried to "talk" to "foo" without response. Like I wanna count the number of occurrences since "foo" was on the sending end.

In this example, before the next entry, it should return 3.

Is this possible in pure (My)SQL?

I'm using php on the server side.

Thanks for any tips and advice! =)

Body:
Give this a go.

It assumes a table name of convo and the id is autoincrementing.

This is just the mysql but the PHP calls can be added quite cleanly if you wrapped it in a function that passes in the from and to variables.

SELECT
  count(*) AS unreplied
FROM
  `convo`
WHERE
  `convo`.`from` = 'bar' AND
  `convo`.`to` = 'foo' AND
  `convo`.`id` > (SELECT
                    id
                  FROM
                    `convo`
                  WHERE
                    `convo`.`from` = 'foo' AND
                    `convo`.`to` = 'bar'
                  ORDER BY
                    `convo`.`id` DESC
                  LIMIT 1)


问:
How do I import opencv without using pip?
I'm writing an application in Python 2.5 and I want to be able to import opencv (https://github.com/opencv/opencv) or cv2 without using pip. I want to use opencv or cv2 so that I can programmatically turn a sequence of images to a video. Would this be as simple as copying and pasting all the files from opencv's GitHub onto my GitHub? That way, I could open a source code file from my GitHub and do "import opencv" or "import cv2". </p>

<p>If not, how would I do this? </p>

答:
You need to install the files using pip because python will look in a certain directory containing packages when you do an import statement. This way, you can import the package in any python code file you do. Installing it puts it in said directory.

Alternatively, you can import a file or directory, so you could download the git files and put it in the working directory of your code file. This works because you can import files/directories that are in your current working directory. (Note that if you make a different file and want to use it there, you'll have to copy over the files to that directory too.)

Body:
I'm writing an application in Python 2.5 and I want to be able to import opencv (https://github.com/opencv/opencv) or cv2 without using pip. I want to use opencv or cv2 so that I can programmatically turn a sequence of images to a video. Would this be as simple as copying and pasting all the files from opencv's GitHub onto my GitHub? That way, I could open a source code file from my GitHub and do "import opencv" or "import cv2".

If not, how would I do this?


问:
Regex to identify 3+ consecutive of same alpha/numeric
I have been trying to write/find a regex that will identify where there are 3+ consecutive instances of an alpha/numeric.

Example:

```<code>CHAIRMAN AAAAAAAND CHIEF EXECUTIVE OFFICER
</code>```

this would be a match b/c of the '**AAAAAAA**'

Thanks!

答:
You can do this with backreferences: .*([A-Za-z0-9])\1\1.*

Here, each \1 matches the character matched in the capturing group.

Experiment with it at Regex101.

Body:
I have been trying to write/find a regex that will identify where there are 3+ consecutive instances of an alpha/numeric.

Example:

CHAIRMAN AAAAAAAND CHIEF EXECUTIVE OFFICER

this would be a match b/c of the '**AAAAAAA**'

Thanks!


问:
Comparing Two Excel workbooks and copying matched data to third workbook
I'm trying to compare two workbooks in excel and have matching column data copy the entire row into a new third workbook. Ex:

Compare

Workbook_1 column A to Workbook_2 column A, if there is a names match, copy the entire row of matching Workbook_1 column A data to the third Workbook (Workbook_3).

This is the code I have:

```<code>Sub RunMe()
Dim lRow, a As Long

Sheets("Workbook_1").Select
lRow = Range("A1").End(alDown).Row

For Each cell In Range("A2:A" & lRow)
    a = 2
    Do
        If cell.Value = Workbook("Workbook_2").Cells(a, "A").Value Then
            cell.EntireRow.Copy Workbook("Workbook_3").Range("A" & Rows.Count).End(alUp).Offset(1, 0)
        End If
        a = a + 1
    Loop Until IsEmpty(Workbook("Workbook_2").Cells(a, "A"))
Next

End Sub
</code>```

I found this code in another website, and I edited the workbook name and created the module for it, run it, but it is not working.

Any help would be appreciated, I am not very good in excel, so can you kindly explain as you would for beginner.

Thanks!

答:
Your current code won't do anything close to what you want it to. Try the below code and see if it works for you. I tried to add some comments explaining what the code is doing. Be sure to change the workbook and worksheet names in the code to match your actual books.</p>

```<code>Sub RunMe()

    Dim wbk1 As Workbook, wbk2 As Workbook, wbk3 As Workbook
    Dim ws1 As Worksheet, ws2 As Worksheet, ws3 As Worksheet
    Dim lRow1 As Long, lCol1 As Long, lRow3 As Long, x As Long
    Dim myValue As String
    Dim Found As Range

    Set wbk1 = Workbooks("Workbook_1.xlsm") 'Be sure to change these to your actual workbook names
    Set ws1 = wbk1.Worksheets("Sheet1") 'Be sure to change these to your actual worksheet names

    Set wbk2 = Workbooks("Workbook_2.xlsm")
    Set ws2 = wbk2.Worksheets("Sheet1")

    Set wbk3 = Workbooks("Workbook_3.xlsm")
    Set ws3 = wbk3.Worksheets("Sheet1")

    'Using a with block means we don't have to define any range coming from book1. ws1.Range("A2") is the same as .Range("A2")
    With ws1
        'Find last row in ws1 Col A
        lRow1 = .Range("A" & .Rows.Count).End(xlUp).Row
        'Find last column in ws1
        lCol1 = .Cells.Find(What:="*", _
            After:=.Cells(1, 1), _
            LookIn:=xlFormulas, _
            LookAt:=xlPart, _
            SearchOrder:=xlByColumns, _
            SearchDirection:=xlPrevious, _
            MatchCase:=False).Column
        'Start loop to search through all values in column A
        For x = 2 To lRow1
            myValue = .Cells(x, 1).Value
            'Look for value in Workbook2 column A
            Set Found = ws2.Cells.Find(What:=myValue, _
                After:=ws2.Cells(1, 1), _
                LookIn:=xlFormulas, _
                LookAt:=xlWhole, _
                SearchOrder:=xlByRows, _
                SearchDirection:=xlPrevious, _
                MatchCase:=False)
            'If Found is not nothing then do something
            If Not Found Is Nothing Then
                'Find last row in ws3 Col A
                lRow3 = ws3.Range("A" & .Rows.Count).End(xlUp).Row
                'Instead of using .copy saying "This Range = That Range" is much faster
                ws3.Range(ws3.Cells(lRow3 + 1, 1), ws3.Cells(lRow3 + 1, lCol1)).Value = .Range(.Cells(x, 1), .Cells(x, lCol1)).Value
            End If
        Next x
    End With

End Sub
</code>```

Body:
I'm trying to compare two workbooks in excel and have matching column data copy the entire row into a new third workbook. Ex:

Compare

Workbook_1 column A to Workbook_2 column A, if there is a names match, copy the entire row of matching Workbook_1 column A data to the third Workbook (Workbook_3).

This is the code I have:

Sub RunMe()
Dim lRow, a As Long

Sheets("Workbook_1").Select
lRow = Range("A1").End(alDown).Row

For Each cell In Range("A2:A" & lRow)
    a = 2
    Do
        If cell.Value = Workbook("Workbook_2").Cells(a, "A").Value Then
            cell.EntireRow.Copy Workbook("Workbook_3").Range("A" & Rows.Count).End(alUp).Offset(1, 0)
        End If
        a = a + 1
    Loop Until IsEmpty(Workbook("Workbook_2").Cells(a, "A"))
Next

End Sub

I found this code in another website, and I edited the workbook name and created the module for it, run it, but it is not working.

Any help would be appreciated, I am not very good in excel, so can you kindly explain as you would for beginner.

Thanks!

Body:
Your current code won't do anything close to what you want it to. Try the below code and see if it works for you. I tried to add some comments explaining what the code is doing. Be sure to change the workbook and worksheet names in the code to match your actual books.

Sub RunMe()

    Dim wbk1 As Workbook, wbk2 As Workbook, wbk3 As Workbook
    Dim ws1 As Worksheet, ws2 As Worksheet, ws3 As Worksheet
    Dim lRow1 As Long, lCol1 As Long, lRow3 As Long, x As Long
    Dim myValue As String
    Dim Found As Range

    Set wbk1 = Workbooks("Workbook_1.xlsm") 'Be sure to change these to your actual workbook names
    Set ws1 = wbk1.Worksheets("Sheet1") 'Be sure to change these to your actual worksheet names

    Set wbk2 = Workbooks("Workbook_2.xlsm")
    Set ws2 = wbk2.Worksheets("Sheet1")

    Set wbk3 = Workbooks("Workbook_3.xlsm")
    Set ws3 = wbk3.Worksheets("Sheet1")

    'Using a with block means we don't have to define any range coming from book1. ws1.Range("A2") is the same as .Range("A2")
    With ws1
        'Find last row in ws1 Col A
        lRow1 = .Range("A" & .Rows.Count).End(xlUp).Row
        'Find last column in ws1
        lCol1 = .Cells.Find(What:="*", _
            After:=.Cells(1, 1), _
            LookIn:=xlFormulas, _
            LookAt:=xlPart, _
            SearchOrder:=xlByColumns, _
            SearchDirection:=xlPrevious, _
            MatchCase:=False).Column
        'Start loop to search through all values in column A
        For x = 2 To lRow1
            myValue = .Cells(x, 1).Value
            'Look for value in Workbook2 column A
            Set Found = ws2.Cells.Find(What:=myValue, _
                After:=ws2.Cells(1, 1), _
                LookIn:=xlFormulas, _
                LookAt:=xlWhole, _
                SearchOrder:=xlByRows, _
                SearchDirection:=xlPrevious, _
                MatchCase:=False)
            'If Found is not nothing then do something
            If Not Found Is Nothing Then
                'Find last row in ws3 Col A
                lRow3 = ws3.Range("A" & .Rows.Count).End(xlUp).Row
                'Instead of using .copy saying "This Range = That Range" is much faster
                ws3.Range(ws3.Cells(lRow3 + 1, 1), ws3.Cells(lRow3 + 1, lCol1)).Value = .Range(.Cells(x, 1), .Cells(x, lCol1)).Value
            End If
        Next x
    End With

End Sub


问:
Virtually turn vector of struct into vector of struct members
I have a function that takes a vector-like input. To simplify things, let's use this print_in_order function:

```<code>#include <iostream>
#include <vector>

template <typename vectorlike>
void print_in_order(std::vector<int> const & order,
                    vectorlike const & printme) {
    for (int i : order)
        std::cout << printme[i] << std::endl;
}

int main() {
    std::vector<int> printme = {100, 200, 300};
    std::vector<int> order = {2,0,1};
    print_in_order(order, printme);
}
</code>```

Now I have a vector<Elem> and want to print a single integer member, Elem.a, for each Elem in the vector. I could do this by creating a new vector<int> (copying a for all Elems) and pass this to the print function - however, I feel like there must be a way to pass a "virtual" vector that, when operator[] is used on it, returns this only the member a. Note that I don't want to change the print_in_order function to access the member, it should remain general.

Is this possible, maybe with a lambda expression?
Full code below.

```<code>#include <iostream>
#include <vector>

struct Elem {
    int a,b;
    Elem(int a, int b) : a(a),b(b) {}
};

template <typename vectorlike>
void print_in_order(std::vector<int> const & order,
                    vectorlike const & printme) {
    for (int i : order)
        std::cout << printme[i] << std::endl;
}

int main() {
    std::vector<Elem> printme = {Elem(1,100), Elem(2,200), Elem(3,300)};
    std::vector<int> order = {2,0,1};

    // how to do this?
    virtual_vector X(printme) // behaves like a std::vector<Elem.a>
    print_in_order(order, X);
}
</code>```

答:
You've got a choice of two data structures

```<code>struct Employee
{
  std::string name;
  double salary;
  long payrollid;
};

std::vector<Employee> employees;
</code>```

Or alternatively

```<code>struct Employees
{
   std::vector<std::string> names;
   std::vector<double> salaries;
   std::vector<long> payrollids;
};
</code>```

C++ is designed with the first option as the default. Other languages such as Javascript tend to encourage the second option.

If you want to find mean salary, option 2 is more convenient. If you want to sort the employees by salary, option 1 is easier to work with.

However you can use lamdas to partially interconvert between the two. The lambda is a trivial little function which takes an Employee and returns a salary for him - so effectively providing a flat vector of doubles we can take the mean of - or takes an index and an Employees and returns an employee, doing a little bit of trivial data reformatting.

Body:
I have a function that takes a vector-like input. To simplify things, let's use this print_in_order function:

#include <iostream>
#include <vector>

template <typename vectorlike>
void print_in_order(std::vector<int> const & order,
                    vectorlike const & printme) {
    for (int i : order)
        std::cout << printme[i] << std::endl;
}

int main() {
    std::vector<int> printme = {100, 200, 300};
    std::vector<int> order = {2,0,1};
    print_in_order(order, printme);
}

Now I have a vector<Elem> and want to print a single integer member, Elem.a, for each Elem in the vector. I could do this by creating a new vector<int> (copying a for all Elems) and pass this to the print function - however, I feel like there must be a way to pass a "virtual" vector that, when operator[] is used on it, returns this only the member a. Note that I don't want to change the print_in_order function to access the member, it should remain general.

Is this possible, maybe with a lambda expression?
Full code below.

#include <iostream>
#include <vector>

struct Elem {
    int a,b;
    Elem(int a, int b) : a(a),b(b) {}
};

template <typename vectorlike>
void print_in_order(std::vector<int> const & order,
                    vectorlike const & printme) {
    for (int i : order)
        std::cout << printme[i] << std::endl;
}

int main() {
    std::vector<Elem> printme = {Elem(1,100), Elem(2,200), Elem(3,300)};
    std::vector<int> order = {2,0,1};

    // how to do this?
    virtual_vector X(printme) // behaves like a std::vector<Elem.a>
    print_in_order(order, X);
}

Body:
You've got a choice of two data structures

struct Employee
{
  std::string name;
  double salary;
  long payrollid;
};

std::vector<Employee> employees;

Or alternatively

struct Employees
{
   std::vector<std::string> names;
   std::vector<double> salaries;
   std::vector<long> payrollids;
};

C++ is designed with the first option as the default. Other languages such as Javascript tend to encourage the second option.

If you want to find mean salary, option 2 is more convenient. If you want to sort the employees by salary, option 1 is easier to work with.

However you can use lamdas to partially interconvert between the two. The lambda is a trivial little function which takes an Employee and returns a salary for him - so effectively providing a flat vector of doubles we can take the mean of - or takes an index and an Employees and returns an employee, doing a little bit of trivial data reformatting.


问:
How do I clear the image cache after editing an image on my site?
I'm using an outside page to update an image in my system. When I'm redirected back to the page I've worked in, I still see the old picture. I don't see my changes until I press ctrl+f5. Is their any way to redirect with history delete or any other solution?</p>

答:
Add a query string to your image source, it will prevent the browser from caching it. Some people use the date, I prefer the GUID

```<code>Guid g = Guid.NewGuid();
string GuidString = Convert.ToBase64String(g.ToByteArray());
GuidString = GuidString.Replace("=", "");
GuidString = GuidString.Replace("+", "");

Image1.ImageUrl = "/path/to/new/image.jpg?r=" + GuidString;
</code>```

It will end up making your image source look similar to this:

```<code> <img src="/path/to/image.jpg?r=Vqad3W8ZUG6oXgFzZIw" id="Image1" runat="server" />
</code>```

Body:
Add a query string to your image source, it will prevent the browser from caching it. Some people use the date, I prefer the GUID

Guid g = Guid.NewGuid();
string GuidString = Convert.ToBase64String(g.ToByteArray());
GuidString = GuidString.Replace("=", "");
GuidString = GuidString.Replace("+", "");

Image1.ImageUrl = "/path/to/new/image.jpg?r=" + GuidString;

It will end up making your image source look similar to this:

 <img src="/path/to/image.jpg?r=Vqad3W8ZUG6oXgFzZIw" id="Image1" runat="server" />


问:
Extra space at the end of UITextView
I added text in UITextView and to understand the boundaries I colored my UITextView with cyan color.

After google.com there is some extra space which I want to remove.

```<code>- (void)viewDidLoad {
        [super viewDidLoad];
        NSString *desc = [self htmlAfterReplacingTagsAndAddingStyle];
        _descriptionTextView.attributedText = [[NSAttributedString alloc] initWithData: [desc dataUsingEncoding:NSUTF8StringEncoding] options: @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
        _descriptionTextView.linkTextAttributes = @{ NSForegroundColorAttributeName: [UIColor blueColor], NSUnderlineStyleAttributeName: [NSNumber numberWithInt:NSUnderlineStyleSingle] };
        _descriptionTextView.dataDetectorTypes = UIDataDetectorTypeLink;
        _descriptionTextView.scrollEnabled = NO;
        [self setTextViewHeight];
    }
</code>```

setTextViewHeight

```<code>- (void)setTextViewHeight {
    UIFont *font = [UIFont fontWithName:@"OpenSans" size:14.0];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, _descriptionContainer.frame.size.width, CGFLOAT_MAX)];
    label.numberOfLines = 0;
    label.lineBreakMode = NSLineBreakByWordWrapping;
    label.font = font;
    NSString *desc = [self htmlAfterReplacingTagsAndAddingStyle];
    label.attributedText = [[NSAttributedString alloc] initWithData: [desc dataUsingEncoding:NSUTF8StringEncoding] options: @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
    [label sizeToFit];
    _descriptionTextView.backgroundColor = UIColor.cyanColor;
    [_descriptionTextView setContentInset:UIEdgeInsetsMake(0, 0, -80, 0)];
    _descriptionContainerHeight.constant = label.frame.size.height;
    }
</code>```

I read about setting content inset but that is not helpful. Changing the value of -80 doesn't have any impact.

I would appreciate some pointers which can help me remove the extra space present at the bottom of uitextView.

答:
You should be able to get somewhere with textContainerInset (see @ReinierMelian answer).  There's also opportunity to vastly simplify the text height measurement...</p>

```<code>UIFont *font = [UIFont fontWithName:@"OpenSans" size:14.0];
CGFloat width = _descriptionTextView.bounds.size.width;
NSString *string = [self htmlAfterReplacingTagsAndAddingStyle];
CGRect rect = [string boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{ NSFontAttributeName:font } context:nil];

CGRect frame = _descriptionTextView.frame;
frame.size = CGSizeMake(width, rect.size.height);
_descriptionTextView.frame = frame;
// due to @ReinierMelian...
_descriptionTextView.extContainerInset = UIEdgeInsetsMake(0, 0, 0, 0);
</code>```

Title: Extra space at the end of UITextView

Body:
I added text in UITextView and to understand the boundaries I colored my UITextView with cyan color.

After google.com there is some extra space which I want to remove.

- (void)viewDidLoad {
        [super viewDidLoad];
        NSString *desc = [self htmlAfterReplacingTagsAndAddingStyle];
        _descriptionTextView.attributedText = [[NSAttributedString alloc] initWithData: [desc dataUsingEncoding:NSUTF8StringEncoding] options: @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
        _descriptionTextView.linkTextAttributes = @{ NSForegroundColorAttributeName: [UIColor blueColor], NSUnderlineStyleAttributeName: [NSNumber numberWithInt:NSUnderlineStyleSingle] };
        _descriptionTextView.dataDetectorTypes = UIDataDetectorTypeLink;
        _descriptionTextView.scrollEnabled = NO;
        [self setTextViewHeight];
    }

setTextViewHeight

- (void)setTextViewHeight {
    UIFont *font = [UIFont fontWithName:@"OpenSans" size:14.0];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, _descriptionContainer.frame.size.width, CGFLOAT_MAX)];
    label.numberOfLines = 0;
    label.lineBreakMode = NSLineBreakByWordWrapping;
    label.font = font;
    NSString *desc = [self htmlAfterReplacingTagsAndAddingStyle];
    label.attributedText = [[NSAttributedString alloc] initWithData: [desc dataUsingEncoding:NSUTF8StringEncoding] options: @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
    [label sizeToFit];
    _descriptionTextView.backgroundColor = UIColor.cyanColor;
    [_descriptionTextView setContentInset:UIEdgeInsetsMake(0, 0, -80, 0)];
    _descriptionContainerHeight.constant = label.frame.size.height;
    }

I read about setting content inset but that is not helpful. Changing the value of -80 doesn't have any impact.

I would appreciate some pointers which can help me remove the extra space present at the bottom of uitextView.

Body:
You should be able to get somewhere with textContainerInset (see @ReinierMelian answer).  There's also opportunity to vastly simplify the text height measurement...

UIFont *font = [UIFont fontWithName:@"OpenSans" size:14.0];
CGFloat width = _descriptionTextView.bounds.size.width;
NSString *string = [self htmlAfterReplacingTagsAndAddingStyle];
CGRect rect = [string boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{ NSFontAttributeName:font } context:nil];

CGRect frame = _descriptionTextView.frame;
frame.size = CGSizeMake(width, rect.size.height);
_descriptionTextView.frame = frame;
// due to @ReinierMelian...
_descriptionTextView.extContainerInset = UIEdgeInsetsMake(0, 0, 0, 0);


问:
JSP displays blank data
I going crazy here trying to figure out, why my JSP doesn't display data in the table.Seems like servlet connects to MySQL and populates data, however I can not push that data to JSP.setAttribute() method is working(objects are there). I can't extract specific information and display it formatted form in the browser.If someone can point me out how troubleshoot this issue... Why JSTL expression doesn't load proper info.Eclipse doesn't return any errors and whole application compiles.... It's just displays empty page.Below you can find the code.

HINT: I was testing if LIST can be pushed and objects can be displayed.It worked, so objects are "visible" to JSP.When I try to load specific info (username, password or email) it returns blank. Thanks for any help/hints.

Below you can find the code.

UserBean.java

```<code>package com.admin;

public class UserBean {
    private String password;
    private String firstname;
    private String lastname;
    private String email;
    private String usertype;
    private String datecreated;
    private String username;

    public UserBean(){};

    public UserBean(String username2, String password2, String firstname2, String lastname2, String email2,
            String usertype2, String datecreated2) {
    }

    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getFirstname() {
        return firstname;
    }
    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }
    public String getLastname() {
        return lastname;
    }
    public void setLastname(String lastname) {
        this.lastname = lastname;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getUsertype() {
        return usertype;
    }
    public void setUsertype(String usertype) {
        this.usertype = usertype;
    }
    public String getDatecreated() {
        return datecreated;
    }
    public void setDatecreated(String datecreated) {
        this.datecreated = datecreated;
    }

}
</code>```

User.DAO.java

```<code>package com.admin;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.clientdb.ConnectionManager;

public class UserDAO {

    public static List<UserBean> listOfUsers()
    {
        List<UserBean> userList=new ArrayList<>();
        String query="SELECT * FROM users";

        try
        {
            Connection conn = ConnectionManager.getConnection();
            Statement stm = conn.createStatement();
            ResultSet rs = stm.executeQuery(query);

            while(rs.next())
            {
                String username=rs.getString("username");
                String password=rs.getString("password");
                String firstname=rs.getString("firstname");
                String lastname=rs.getString("lastname");
                String email=rs.getString("email");
                String usertype=rs.getString("usertype");
                String datecreated=rs.getString("date_created");

                UserBean user=new UserBean(username,password,firstname,lastname,email,usertype,datecreated);
                userList.add(user);
            }
            stm.close();
            rs.close();
            conn.close();
        }
        catch(Exception ex){System.out.println(ex);}

        return userList;

}}
</code>```

UserAdmin.java

```<code>package com.admin;

import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserAdmin extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
            List<UserBean> userList = UserDAO.listOfUsers();
            request.getSession().setAttribute("userList",userList);
    request.getRequestDispatcher("userlist.jsp").forward(request,response);
        }
}
</code>```

userlist.jsp

```<code>    <table class="table table-hover"  style="margin-top:20px;">
  <thead>
    <tr>
      <th>Username</th>
      <th>Password</th>
      <th>First Name</th>
      <th>Last Name</th>
      <th>Email</th>
      <th>User Type</th>
      <th>Date Created</th>
    </tr>
  </thead>
  <tbody>
  <c:forEach items="${userList}" var="user">
    <tr>
      <td><c:out value="${user.username}"/></td>
      <td><c:out value="${user.password}"/></td>
      <td><c:out value="${user.firstname}"/></td>
      <td><c:out value="${user.lastname}"/></td>
      <td><c:out value="${user.email}"/></td>
      <td><c:out value="${user.usertype}"/></td>
      <td><c:out value="${user.datecreated}"/></td>
      <td>
        <a href="reset.html" role="button" class="btn btn-primary">RESET</a>
        <!--  <button type="button" class="btn btn-danger" data-toggle="modal" data-target="#userDeleteModal">DELETE</button>-->
        <a href="deleteUser.do?email=${user.email}" role="button" class="btn btn-danger">DELETE</a>
      </td>
    </tr>
  </c:forEach>
  </tbody>
</table>
</code>```

Title: JSP displays blank data

Body:
I going crazy here trying to figure out, why my JSP doesn't display data in the table.Seems like servlet connects to MySQL and populates data, however I can not push that data to JSP.setAttribute() method is working(objects are there). I can't extract specific information and display it formatted form in the browser.If someone can point me out how troubleshoot this issue... Why JSTL expression doesn't load proper info.Eclipse doesn't return any errors and whole application compiles.... It's just displays empty page.Below you can find the code.

HINT: I was testing if LIST can be pushed and objects can be displayed.It worked, so objects are "visible" to JSP.When I try to load specific info (username, password or email) it returns blank. Thanks for any help/hints.

Below you can find the code.

UserBean.java

package com.admin;

public class UserBean {
    private String password;
    private String firstname;
    private String lastname;
    private String email;
    private String usertype;
    private String datecreated;
    private String username;

    public UserBean(){};

    public UserBean(String username2, String password2, String firstname2, String lastname2, String email2,
            String usertype2, String datecreated2) {
    }

    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getFirstname() {
        return firstname;
    }
    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }
    public String getLastname() {
        return lastname;
    }
    public void setLastname(String lastname) {
        this.lastname = lastname;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getUsertype() {
        return usertype;
    }
    public void setUsertype(String usertype) {
        this.usertype = usertype;
    }
    public String getDatecreated() {
        return datecreated;
    }
    public void setDatecreated(String datecreated) {
        this.datecreated = datecreated;
    }

}

User.DAO.java

package com.admin;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.clientdb.ConnectionManager;

public class UserDAO {

    public static List<UserBean> listOfUsers()
    {
        List<UserBean> userList=new ArrayList<>();
        String query="SELECT * FROM users";

        try
        {
            Connection conn = ConnectionManager.getConnection();
            Statement stm = conn.createStatement();
            ResultSet rs = stm.executeQuery(query);

            while(rs.next())
            {
                String username=rs.getString("username");
                String password=rs.getString("password");
                String firstname=rs.getString("firstname");
                String lastname=rs.getString("lastname");
                String email=rs.getString("email");
                String usertype=rs.getString("usertype");
                String datecreated=rs.getString("date_created");

                UserBean user=new UserBean(username,password,firstname,lastname,email,usertype,datecreated);
                userList.add(user);
            }
            stm.close();
            rs.close();
            conn.close();
        }
        catch(Exception ex){System.out.println(ex);}

        return userList;

}}

UserAdmin.java

package com.admin;

import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserAdmin extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
            List<UserBean> userList = UserDAO.listOfUsers();
            request.getSession().setAttribute("userList",userList);
    request.getRequestDispatcher("userlist.jsp").forward(request,response);
        }
}

userlist.jsp

      Username
      Password
      First Name
      Last Name
      Email
      User Type
      Date Created

  <c:forEach items="${userList}" var="user">

      <c:out value="${user.username}"/>
      <c:out value="${user.password}"/>
      <c:out value="${user.firstname}"/>
      <c:out value="${user.lastname}"/>
      <c:out value="${user.email}"/>
      <c:out value="${user.usertype}"/>
      <c:out value="${user.datecreated}"/>

        RESET

        DELETE

  </c:forEach>

Body: <c:forEach items="${sessionScope.userList}" var="user">


问:
IIS Config Error - This configuration section cannot be used at this path
I am getting the below error when I try to run my website.

The website is hosted on Windows 2012 R2.

Config error:  This configuration section cannot be used at this path. This happens when the section is locked at a parent level. Locking is either by default (overrideModeDefault="Deny"), or set explicitly by a location tag with overrideMode="Deny" or the legacy allowOverride="false".

Error Code : 0x80070021

Config Source:

```<code> 60:     <httpErrors errorMode="Detailed" />
 61:     <handlers>
 62:       <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
</code>```

Below is what all I have tried:

Installed .Net 3.5 using "Add features and roles" in IIS

In the applicationHost file I have made the below code changes:

Changed sections handlers', modules, anonymousAuthentication,          basicAuthentication,etc  overrideModeDefault from "Deny" to "Allow".

Have done "HTTP Activation" in .Net 3.5 as well as 4.5.

Below is my web config file handler code:

```<code><handlers>
  <remove name="ExtensionlessUrlHandler-Integrated-4.0"/>
  <remove name="OPTIONSVerbHandler"/>
  <remove name="TRACEVerbHandler"/>
  <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0"/>
</handlers>
</code>```

Installed all the features in features windows in this path:
Internet Information Service --> World Wide Web Services --> Application development features --> All but CGI have been enabled.

In feature delegation ASP was Read Only earlier, I have changed it to Read/Write

Unlocked handlers using command prompt

But I am still unable to get rid of the error.
My local instance is working perfectly fine. Also, I have a development server on which this website is working, only in my production server I am getting this error.

Please help me to find out what might be causing this problem.

答: Click on your project properties, go to the web section, from the Servers section, change from IIS express to Local IIS, it will create a virtual directory for you</p>

Body:
I am getting the below error when I try to run my website.

The website is hosted on Windows 2012 R2.

Config error:  This configuration section cannot be used at this path. This happens when the section is locked at a parent level. Locking is either by default (overrideModeDefault="Deny"), or set explicitly by a location tag with overrideMode="Deny" or the legacy allowOverride="false".

Error Code : 0x80070021

Config Source:

 60:     <httpErrors errorMode="Detailed" />
 61:     <handlers>
 62:       <remove name="ExtensionlessUrlHandler-Integrated-4.0" />

Below is what all I have tried:

Installed .Net 3.5 using "Add features and roles" in IIS

In the applicationHost file I have made the below code changes:

Changed sections handlers', modules, anonymousAuthentication,          basicAuthentication,etc  overrideModeDefault from "Deny" to "Allow".

Have done "HTTP Activation" in .Net 3.5 as well as 4.5.

Below is my web config file handler code:

<handlers>
  <remove name="ExtensionlessUrlHandler-Integrated-4.0"/>
  <remove name="OPTIONSVerbHandler"/>
  <remove name="TRACEVerbHandler"/>
  <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0"/>
</handlers>

Installed all the features in features windows in this path:
Internet Information Service --> World Wide Web Services --> Application development features --> All but CGI have been enabled.

In feature delegation ASP was Read Only earlier, I have changed it to Read/Write

Unlocked handlers using command prompt

But I am still unable to get rid of the error.
My local instance is working perfectly fine. Also, I have a development server on which this website is working, only in my production server I am getting this error.

Please help me to find out what might be causing this problem.


问:
VSTO Outlook Add-in Move folders up and down
i have an outlook add-in in which a folder is selected.Now what i want is, i want to move the folder up and down using C#. Is there someone that can help me in this case. You help is greatly appreciated.</p>

答:
You will need to set the PR_SORT_POSITION Extended MAPI property using MAPIFolder.PropertyAccessor.SetProperty. You can see that property (if the  particular folder was manually reordered) in OutlookSpy (I am its author - click IMAPIFolder button).

See https://blogs.msdn.microsoft.com/stephen_griffin/2013/11/08/mapi-provider-sorting/ for more details.

ContentLicense: CC BY-SA 4.0


问:
Highcharts polar wind rose chart with segments in trapezoid form
I am using extjs and highcharts to develop a wind rose chart. I need to display the data as trapezoids with straight edges, rather than the default display of the segments with arcs as delimiters. Here is an image of what I am trying to do

I have been able to integrate the highcharts object into my application using the wrapper provided by JoeKuan

However I am not seeing in the highcharts documentation how I can configure the polar chart columns into straight edged segments as seen in the image..

Here is a fiddle of the polar chart as it works currently.. Fiddle

```<code>Highcharts.chart('container', {
    data: {
        table: 'freq',
        startRow: 1,
        endRow: 17,
        endColumn: 7
    },

    chart: {
        polar: true,
        type: 'column'
    },

    title: {
        text: 'Wind rose for South Shore Met Station, Oregon'
    },

    subtitle: {
        text: 'Source: or.water.usgs.gov'
    },

    pane: {
        size: '85%'
    },

    legend: {
        align: 'right',
        verticalAlign: 'top',
        y: 100,
        layout: 'vertical'
    },

    xAxis: {
        tickmarkPlacement: 'on'
    },

    yAxis: {
        min: 0,
        endOnTick: false,
        showLastLabel: true,
        title: {
            text: 'Frequency (%)'
        },
        labels: {
            formatter: function () {
                return this.value + '%';
            }
        },
        reversedStacks: false
    },

    tooltip: {
        valueSuffix: '%'
    },

    plotOptions: {
        series: {
            stacking: 'normal',
            shadow: false,
            groupPadding: 0,
            pointPlacement: 'on'
        }
    }
});
</code>```

All help greatly appreciated

Lisa

答:
You want type: 'area' to achieve that visualization.

```<code>Highcharts.chart('container', {
    data: {
        table: 'freq',
        startRow: 1,
        endRow: 17,
        endColumn: 7
    },

    chart: {
        polar: true,
        type: 'area'
    },
</code>```

http://jsfiddle.net/0mb1s1jd/1/

Body:
I am using extjs and highcharts to develop a wind rose chart. I need to display the data as trapezoids with straight edges, rather than the default display of the segments with arcs as delimiters. Here is an image of what I am trying to do

I have been able to integrate the highcharts object into my application using the wrapper provided by JoeKuan

However I am not seeing in the highcharts documentation how I can configure the polar chart columns into straight edged segments as seen in the image..

Here is a fiddle of the polar chart as it works currently.. Fiddle

Highcharts.chart('container', {
    data: {
        table: 'freq',
        startRow: 1,
        endRow: 17,
        endColumn: 7
    },

    chart: {
        polar: true,
        type: 'column'
    },

    title: {
        text: 'Wind rose for South Shore Met Station, Oregon'
    },

    subtitle: {
        text: 'Source: or.water.usgs.gov'
    },

    pane: {
        size: '85%'
    },

    legend: {
        align: 'right',
        verticalAlign: 'top',
        y: 100,
        layout: 'vertical'
    },

    xAxis: {
        tickmarkPlacement: 'on'
    },

    yAxis: {
        min: 0,
        endOnTick: false,
        showLastLabel: true,
        title: {
            text: 'Frequency (%)'
        },
        labels: {
            formatter: function () {
                return this.value + '%';
            }
        },
        reversedStacks: false
    },

    tooltip: {
        valueSuffix: '%'
    },

    plotOptions: {
        series: {
            stacking: 'normal',
            shadow: false,
            groupPadding: 0,
            pointPlacement: 'on'
        }
    }
});

All help greatly appreciated

Lisa

Body:
You want type: 'area' to achieve that visualization.

Highcharts.chart('container', {
    data: {
        table: 'freq',
        startRow: 1,
        endRow: 17,
        endColumn: 7
    },

    chart: {
        polar: true,
        type: 'area'
    },

http://jsfiddle.net/0mb1s1jd/1/


问:
"too many values to unpack error" when trying to create a batch in pyglet
I have been trying to get batches to work in pyglet, but I am completely confused by the error message "too many values to unpack" coming from the pyglet/graphics/__init__.py file. My guess is that that I am doing something wrong syntaxwise when adding the geometry to the batch.

I cut down my code to the essential parts that create the error:

```<code>from pyglet.gl import *
from pyglet.graphics import *
import pyglet

batch = pyglet.graphics.Batch()
img = pyglet.image.load('pic.png')
texture = img.get_texture()

class TextureEnableGroup(pyglet.graphics.Group):
    def set_state(self):
        glEnable(GL_TEXTURE_2D)
    def unset_state(self):
        glDisable(GL_TEXTURE_2D)

texture_enable_group = TextureEnableGroup()

class TextureBindGroup(pyglet.graphics.Group):
    def __init__(self, texture):
        super(TextureBindGroup, self).__init__(parent=texture_enable_group)
        self.texture = texture
    def set_state(self):
        glBindTexture(GL_TEXTURE_2D, self.texture.id)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
    def __eq__(self, other):
        return (self.__class__ is other.__class__ and self.texture == other.__class__)

batch.add(12, GL_TRIANGLES, TextureBindGroup(texture), (('t2f', (0, 0)), ('v3f', (64, 64, 0)), ('t2f', (1, 1)), ('v3f', (-64, -64, 205)), ('t2f', (0, 1)), ('v3f', (-64, 64, 205)), ('t2f', (1, 1)), ('v3f', (64, -64, 205)), ('t2f', (1, 0)), ('v3f', (64, 64, 0)), ('t2f', (0, 1)), ('v3f', (-64, -64, 205))))
</code>```

答:
Thanks to marcog,
The correct final line of the script is:

```<code>batch.add(6, GL_TRIANGLES, TextureBindGroup(texture), ('v3i', (64, 64, 0, -64, -64, 205, -64, 64, 205, 64, -64, 205, 64, 64, 0, -64, -64, 205)), ('t2i', (0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1)))
</code>```

i.e. problem solved =)

The problem was partially that I sent all the data as a single tuple (which marcog pointed out), as well as passing a wrong value of the length of the batch of geeometry data; 6 vertices instead of 12.

Body:
I have been trying to get batches to work in pyglet, but I am completely confused by the error message "too many values to unpack" coming from the pyglet/graphics/__init__.py file. My guess is that that I am doing something wrong syntaxwise when adding the geometry to the batch.

I cut down my code to the essential parts that create the error:

from pyglet.gl import *
from pyglet.graphics import *
import pyglet

batch = pyglet.graphics.Batch()
img = pyglet.image.load('pic.png')
texture = img.get_texture()

class TextureEnableGroup(pyglet.graphics.Group):
    def set_state(self):
        glEnable(GL_TEXTURE_2D)
    def unset_state(self):
        glDisable(GL_TEXTURE_2D)

texture_enable_group = TextureEnableGroup()

class TextureBindGroup(pyglet.graphics.Group):
    def __init__(self, texture):
        super(TextureBindGroup, self).__init__(parent=texture_enable_group)
        self.texture = texture
    def set_state(self):
        glBindTexture(GL_TEXTURE_2D, self.texture.id)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
    def __eq__(self, other):
        return (self.__class__ is other.__class__ and self.texture == other.__class__)

batch.add(12, GL_TRIANGLES, TextureBindGroup(texture), (('t2f', (0, 0)), ('v3f', (64, 64, 0)), ('t2f', (1, 1)), ('v3f', (-64, -64, 205)), ('t2f', (0, 1)), ('v3f', (-64, 64, 205)), ('t2f', (1, 1)), ('v3f', (64, -64, 205)), ('t2f', (1, 0)), ('v3f', (64, 64, 0)), ('t2f', (0, 1)), ('v3f', (-64, -64, 205))))

Body:
Thanks to marcog,
The correct final line of the script is:

batch.add(6, GL_TRIANGLES, TextureBindGroup(texture), ('v3i', (64, 64, 0, -64, -64, 205, -64, 64, 205, 64, -64, 205, 64, 64, 0, -64, -64, 205)), ('t2i', (0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1)))

i.e. problem solved =)

The problem was partially that I sent all the data as a single tuple (which marcog pointed out), as well as passing a wrong value of the length of the batch of geeometry data; 6 vertices instead of 12.


问:
Why a class's +load() was executed before main() in Objc?
why classes' +load() methods were invoked before project's main function? Is main function not the entrance of app? who invoked +load methods?</p>

答:
From: NSObject +load and +initialize - What do they do?

The runtime sends the load message to each class object, very soon after the class object is loaded in the process's address space. For classes that are part of the program's executable file, the runtime sends the load message very early in the process's lifetime.


问:
(Xamarin iOS): ExecutionEngineException - Attempting to JIT compile method while running in aot-only mode
When running app in release mode on device I am getting error:
ExecutionEngineException - Attempting to JIT compile method ‘AudioJack.ACRAudioJackReader:.ctor (bool)’ while running in aot-only mode. See https://developer.xamarin.com/guides/ios/advanced_topics/limitations/ for more information.

It appeared after latest update of Xamarin iOS.
Works OK on device in debug mode.
Also tried to disable compiler optimizations - didn't help.

I am using iOS binding to AudioJack library and the constructor is causing error.

```<code>[BaseType(typeof(NSObject))]
interface ACRAudioJackReader
{

    [ExportAttribute("initWithMute:")]
    IntPtr Constructor(bool isMute);
}
</code>```

Checked all the articles related to this issue, but didn't find solution yet.

Does anybody have an idea how it can be fixed?

Thank you

答:
TL;DR

You need to turn on Enable optimizations option in the problematic binding project.

I had similar issue to yours.

I work on Mac and switched from Xamarin Studio to the newest Visual Studio for Mac. After update app stoped working on iOS devices but, what’s interesting, simulators were fine.

The error occurred during the runtime when I wanted to initialize objects form this problematic library. My app has few iOS bindings projects but only one caused such problems. I didn’t want to introduce any unnecessary changes into the other projects.

Finally I found out that in my case it is enough to turn on Enable optimizations for the binding project which include this problematic library. The app’s project (which is the only project which use this library) hasn't been changed.

Because I knew that my app was working just before the update, I assumed that this was a Xamarin problem, so I focused only on finding a solution, not a reason.

You can find this option in:

Project Options > Build > Compiler > Enable optimizations

Body:
When running app in release mode on device I am getting error:
ExecutionEngineException - Attempting to JIT compile method ‘AudioJack.ACRAudioJackReader:.ctor (bool)’ while running in aot-only mode. See https://developer.xamarin.com/guides/ios/advanced_topics/limitations/ for more information.

It appeared after latest update of Xamarin iOS.
Works OK on device in debug mode.
Also tried to disable compiler optimizations - didn't help.

I am using iOS binding to AudioJack library and the constructor is causing error.

[BaseType(typeof(NSObject))]
interface ACRAudioJackReader
{

    [ExportAttribute("initWithMute:")]
    IntPtr Constructor(bool isMute);
}

Checked all the articles related to this issue, but didn't find solution yet.

Does anybody have an idea how it can be fixed?

Thank you


问:
MLS / IDX Data in the form of XML
I have an issue and I have been struggling with for weeks, almost a month, I am working on this website for a real estate agent in Toronto, Ontario and the last thing I have to do is get the listing on her website. We are using Wordpress wp-residence theme, this theme is compatible with iHomefinder, however the data I get from iHomefinder does not work with the themes features (maps, searches and even styles) I read somewhere that the only way to use these theme features is to add the listing manually. I found this plugin that will import all the listings

https://en-ca.wordpress.org/plugins/wp-residence-add-on-for-wp-all-import/

But now I need to get my listings in the form of XML, CSV or XLS. I have all my login info and url to get my listing, however in the instructions it says I need to connect via RETS Client, which I do not have...is there anyone out there who can point me in the right direction?

答: You'll need to use an IDX plugin.</p>

Title: MLS / IDX Data in the form of XML

Body: You'll need to use an IDX plugin.


问:
Given a file, find the ten most frequently occurring words as efficiently as possible
This is apparently an interview question (found it in a collection of interview questions), but even if it's not it's pretty cool.

We are told to do this efficiently on all complexity measures. I thought of creating a HashMap that maps the words to their frequency. That would be O(n) in time and space complexity, but since there may be lots of words we cannot assume that we can store everything in memory.

I must add that nothing in the question says that the words cannot be stored in memory, but what if that were the case? If that's not the case, then the question does not seem as challenging.

答:
Optimizing for my own time:

```<code>sort file | uniq -c | sort -nr | head -10
</code>```

Possibly followed by awk '{print $2}' to eliminate the counts.

Body:
Optimizing for my own time:

sort file | uniq -c | sort -nr | head -10

Possibly followed by awk '{print $2}' to eliminate the counts.


答:
No, it wouldn't.

Even worse, opencv depends on binary blobs that are compiled, and as such cannot even be installed completely using pip, you would have to either

Find a binary distribution for your os

compile it yourself

You will find more information on the openCV documentation, for example how to install it on Windows. Installing from the binary distribution is fairly simple, while compiling from source is a much more involved process. In the above mentioned link, you only need to complete one of the two sections to have a working installation

Title: How do I import opencv without using pip?

Body:
I'm writing an application in Python 2.5 and I want to be able to import opencv (https://github.com/opencv/opencv) or cv2 without using pip. I want to use opencv or cv2 so that I can programmatically turn a sequence of images to a video. Would this be as simple as copying and pasting all the files from opencv's GitHub onto my GitHub? That way, I could open a source code file from my GitHub and do "import opencv" or "import cv2".

If not, how would I do this?