答:
I'm constructing a library that uses async/await, and I would like to know if it is possible to use native modules like fs with the async/await.

Yes. You can do it even simpler with Bluebird than in your example:

```<code>let fs = Promise.promisifyAll(require('fs'));

// and in async function:
let contents = await fs.readFileAsync('file.txt', 'utf-8');
</code>```

Note that you need to add Async at the end of the method names.

Or you can use the mz module, without needing to add Async to the methods. See:

https://www.npmjs.com/package/mz

There are many modules that you can require once you npm install mz - for example you can require('mz/fs') and it instantly lets you use the fs module version that returns promises instead of taking callbacks. Combined with async await it lets you do things like:

```<code>let fs = require('mz/fs');

// and in async function:
let contents = await fs.readFile('file.txt', 'utf-8');
</code>```

The above code is still non-blocking.

See this answer where I show an example of mz version of the crypto module and explain it in more detail:

Which functions could work as synchronous in node.js?

See example:

```<code>let crypto = require('mz/crypto');

async function x() {
  let bytes = await crypto.randomBytes(4);
  console.log(bytes);
}
</code>```

You can do the same with many other modules, including:

child_process

crypto

dns

fs

readline

zlib

I know that async/await it's just Promises in the background, so... is there a native way to promisify a method or function?

Soon Node.js will support that natively - see PR #5020 Adding Core support for Promises:

https://github.com/nodejs/node/pull/5020

but in the meantime you can use mz.

For more context see also the Issue #7549 v1: executing async functions without callbacks should return promises:

https://github.com/nodejs/node-v0.x-archive/issues/7549

See also the Node.js's Promises Working Group Repository:

https://github.com/nodejs/promises

Update: It seems that the PR 5020 mentioned above is not going to land in Node.js any time soon - thanks to Benjamin Gruenbaum for pointing it out in the comments. So it seems that using Bluebird's promisify and promisifyAll and the helpful mz module will be the only easy way to use modern features of the language with the core modules of Node.js. Fortunately they work very well, so it's not a big problem.

Title: Using async/await + Bluebird to promisifyAll

Body:
I'm constructing a library that uses async/await, and I would like to know if it is possible to use native modules like fs with the async/await. I know that async/await it's just Promises in the background, so is there a native way to promisify a method or function? Currently I'm using the Bluebird, but I don't know if it's a bad pattern.

Example:

    const Bluebird = require("bluebird");
    const { access } = require("fs");

    const accessAsync = Bluebird.promisify(access);

    async function checkInput(options) {
      await accessAsync(options.file);
      /// etc
      return options;
    }

    module.exports = (options) => {
      Promise.resolve(options)
        .then(checkInput)
    };

I'm combining both native Promises and Bluebird. Should I only use Bluebird?

Body:
I'm constructing a library that uses async/await, and I would like to know if it is possible to use native modules like fs with the async/await.

Yes. You can do it even simpler with Bluebird than in your example:

let fs = Promise.promisifyAll(require('fs'));

// and in async function:
let contents = await fs.readFileAsync('file.txt', 'utf-8');

Note that you need to add Async at the end of the method names.

Or you can use the mz module, without needing to add Async to the methods. See:

https://www.npmjs.com/package/mz

There are many modules that you can require once you npm install mz - for example you can require('mz/fs') and it instantly lets you use the fs module version that returns promises instead of taking callbacks. Combined with async await it lets you do things like:

let fs = require('mz/fs');

// and in async function:
let contents = await fs.readFile('file.txt', 'utf-8');

The above code is still non-blocking.

See this answer where I show an example of mz version of the crypto module and explain it in more detail:

Which functions could work as synchronous in node.js?

See example:

let crypto = require('mz/crypto');

async function x() {
  let bytes = await crypto.randomBytes(4);
  console.log(bytes);
}

You can do the same with many other modules, including:

child_process

crypto

dns

fs

readline

zlib

I know that async/await it's just Promises in the background, so... is there a native way to promisify a method or function?

Soon Node.js will support that natively - see PR #5020 Adding Core support for Promises:

https://github.com/nodejs/node/pull/5020

but in the meantime you can use mz.

For more context see also the Issue #7549 v1: executing async functions without callbacks should return promises:

https://github.com/nodejs/node-v0.x-archive/issues/7549

See also the Node.js's Promises Working Group Repository:

https://github.com/nodejs/promises

Update: It seems that the PR 5020 mentioned above is not going to land in Node.js any time soon - thanks to Benjamin Gruenbaum for pointing it out in the comments. So it seems that using Bluebird's promisify and promisifyAll and the helpful mz module will be the only easy way to use modern features of the language with the core modules of Node.js. Fortunately they work very well, so it's not a big problem.


来源: stackexchange

问:
Moving Div Box just using pure javascript at certain time
I have saw the problem
Moving Div Box using javascript
and the top upvote answer is good .

But if I want to get the feacture like CSS3 does ,how can I do?

.cuble{
 height: 100px;
 width: 100px;
 background-color: blue;
 transition: all 3s ease-in-out;
}

.cuble:hover{
 transform: translateX(500px);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!Doctype html>
<html>

<body>
<div class="cuble">
</div>

</body></code>```

I don't need ease-in-out effect .I just want hover the div once and even if I mouseout the div ,the div will also moving from left to right  until the setting time. But the Moving Div Box using javascript don't  meet the requirement.

I try to use Promise to achieve the goal ,here is my Javascript code .(anyway,maybe I just want to learn deep about javascript async performance)

```<code>var cuble = document.querySelector('.cuble');
cuble.onmouseover = function(e) {
for (var i = 0; i < 100; i++) {
    var pixels = 5 * i + "px";
    delay(100)
        .then(() => cuble.style.marginLeft = pixels)
  }
}

function delay(t) {
return new Promise(function(resolve) {
    setTimeout(resolve, t)
    });
};
</code>```

How can I fix my Javascript code and  meet the requirement?

答:
The issue is you're creating one hundred promises each with a 100ms delay almost instantly, so they all firing almost instantly.

One way to remedy the issue is increase the delay for each subsequent promise. And you also have to pass the corresponding pixels for each resolve. Something like:

```<code>var cuble = document.querySelector('.cuble');

cuble.onmouseover = function(e) {
  for (var i = 0; i < 100; i++) {
    var pixels = 5 * i + "px";

    delay(i * 20, pixels)
      .then((p) => cuble.style.marginLeft = p)
  }
}

function delay(t, pixels) {
  return new Promise(function(resolve) {
    setTimeout(() => resolve(pixels), t)
  });
};
</code>```

DEMO

An example with no promises and just one function being created and called, instead of creating new function for every step:

```<code>var cuble = document.querySelector('.cuble');

cuble.onmouseover = function() {
  var left = 0,
      ival = setInterval(move, 5);

  function move() {
    if (left === 500) clearInterval(ival);
    cuble.style.marginLeft = left++ + 'px';
  }
}
</code>```

DEMO

ContentLicense: CC BY-SA 3.0

Body:
I have saw the problem
Moving Div Box using javascript
and the top upvote answer is good .

But if I want to get the feacture like CSS3 does ,how can I do?

.cuble{
 height: 100px;
 width: 100px;
 background-color: blue;
 transition: all 3s ease-in-out;
}

.cuble:hover{
 transform: translateX(500px);
}

<!Doctype html>

I don't need ease-in-out effect .I just want hover the div once and even if I mouseout the div ,the div will also moving from left to right  until the setting time. But the Moving Div Box using javascript don't  meet the requirement.

I try to use Promise to achieve the goal ,here is my Javascript code .(anyway,maybe I just want to learn deep about javascript async performance)

var cuble = document.querySelector('.cuble');
cuble.onmouseover = function(e) {
for (var i = 0; i < 100; i++) {
    var pixels = 5 * i + "px";
    delay(100)
        .then(() => cuble.style.marginLeft = pixels)
  }
}

function delay(t) {
return new Promise(function(resolve) {
    setTimeout(resolve, t)
    });
};

How can I fix my Javascript code and  meet the requirement?

Body:
The issue is you're creating one hundred promises each with a 100ms delay almost instantly, so they all firing almost instantly.

One way to remedy the issue is increase the delay for each subsequent promise. And you also have to pass the corresponding pixels for each resolve. Something like:

var cuble = document.querySelector('.cuble');

cuble.onmouseover = function(e) {
  for (var i = 0; i < 100; i++) {
    var pixels = 5 * i + "px";

    delay(i * 20, pixels)
      .then((p) => cuble.style.marginLeft = p)
  }
}

function delay(t, pixels) {
  return new Promise(function(resolve) {
    setTimeout(() => resolve(pixels), t)
  });
};

DEMO

An example with no promises and just one function being created and called, instead of creating new function for every step:

var cuble = document.querySelector('.cuble');

cuble.onmouseover = function() {
  var left = 0,
      ival = setInterval(move, 5);

  function move() {
    if (left === 500) clearInterval(ival);
    cuble.style.marginLeft = left++ + 'px';
  }
}

DEMO


问:
can't declare array in C# POST request
```<code>var resultHttpPost = ZennoPoster.HttpPost("http://box.chomikuj.pl/services/ChomikBoxService.svc",
"<?xml version='1.0' encoding='UTF-8'?><s:Envelope s:encodingStyle='http://schemas.xmlsoap.org/soap/encoding/' xmlns:s='http://schemas.xmlsoap.org/soap/envelope/'><s:Body><Auth xmlns='http://chomikuj.pl/'><name>topbarlogin</name><passHash>e10adc3949ba59abbe56e057f20f883e</passHash><ver>4</ver></Auth></s:Body></s:Envelope>",
"text/xml;charset=utf-8", "", "UTF-8", ZennoLab.InterfacesLibrary.Enums.Http.ResponceType.HeaderAndBody, 30000, "", "Mozilla/5.0", true, 1, string[] headers = new String[3]{ "a", "b", "c" }, "", false);
</code>```

I have problem with this:

```<code>string[] headers = new String[3]{ "a", "b", "c" }
</code>```

I still get the error and I don't know how to declare it.

答:
just delete "string[] headers = " part</p>

```<code>var resultHttpPost = ZennoPoster.HttpPost("http://box.chomikuj.pl/services/ChomikBoxService.svc","<?xml version='1.0' encoding='UTF-8'?><s:Envelope s:encodingStyle='http://schemas.xmlsoap.org/soap/encoding/' xmlns:s='http://schemas.xmlsoap.org/soap/envelope/'><s:Body><Auth xmlns='http://chomikuj.pl/'><name>topbarlogin</name><passHash>e10adc3949ba59abbe56e057f20f883e</passHash><ver>4</ver></Auth></s:Body></s:Envelope>", "text/xml;charset=utf-8", "", "UTF-8", ZennoLab.InterfacesLibrary.Enums.Http.ResponceType.HeaderAndBody, 30000, "", "Mozilla/5.0", true, 1, new String[3]{ "a", "b", "c" }, "", false);
</code>```

Title: can't declare array in C# POST request

Body:
var resultHttpPost = ZennoPoster.HttpPost("http://box.chomikuj.pl/services/ChomikBoxService.svc",
"<?xml version='1.0' encoding='UTF-8'?><s:Envelope s:encodingStyle='http://schemas.xmlsoap.org/soap/encoding/' xmlns:s='http://schemas.xmlsoap.org/soap/envelope/'><s:Body><Auth xmlns='http://chomikuj.pl/'><name>topbarlogin</name><passHash>e10adc3949ba59abbe56e057f20f883e</passHash><ver>4</ver></Auth></s:Body></s:Envelope>",
"text/xml;charset=utf-8", "", "UTF-8", ZennoLab.InterfacesLibrary.Enums.Http.ResponceType.HeaderAndBody, 30000, "", "Mozilla/5.0", true, 1, string[] headers = new String[3]{ "a", "b", "c" }, "", false);

I have problem with this:

string[] headers = new String[3]{ "a", "b", "c" }

I still get the error and I don't know how to declare it.

Body:
just delete "string[] headers = " part

var resultHttpPost = ZennoPoster.HttpPost("http://box.chomikuj.pl/services/ChomikBoxService.svc","<?xml version='1.0' encoding='UTF-8'?><s:Envelope s:encodingStyle='http://schemas.xmlsoap.org/soap/encoding/' xmlns:s='http://schemas.xmlsoap.org/soap/envelope/'><s:Body><Auth xmlns='http://chomikuj.pl/'><name>topbarlogin</name><passHash>e10adc3949ba59abbe56e057f20f883e</passHash><ver>4</ver></Auth></s:Body></s:Envelope>", "text/xml;charset=utf-8", "", "UTF-8", ZennoLab.InterfacesLibrary.Enums.Http.ResponceType.HeaderAndBody, 30000, "", "Mozilla/5.0", true, 1, new String[3]{ "a", "b", "c" }, "", false);


问:
Why is std::exchange not noexcept?
According to the Standard (N4659, §23.2.4, [utility.exchange]), std::exchange should do a std::move and a std::forward:

template <class T, class U = T> T exchange(T& obj, U&& new_val);

Effects: Equivalent to:

```<code>T old_val = std::move(obj);
obj = std::forward<U>(new_val);
return old_val;
</code>```

Both move and forward are marked as noexcept:

(N4659, §23.2.5, [forward]):

template <class T> constexpr T&& forward(remove_reference_t<T>& t) noexcept;
template <class T> constexpr T&& forward(remove_reference_t<T>&& t) noexcept;

Returns: static_cast<T&&>(t).

(...)

template <class T> constexpr remove_reference_t<T>&& move(T&& t) noexcept;

Returns: static_cast<remove_reference_t<T>&&>(t).

So why isn't exchange noexcept? Is there some other reason for this or did the committee simply overlook this? Is this being proposed or can I write one?

答: Unlike std::swap, which by default only relies on move constructors and therefore should usually be noexcept, std::exchange may allocate resources if the new value needs to be copied. While there could probably be a complicated expression for a conditional noexcept when new_val is a U&& and neither the move assignment nor the old value's move throw, it seems nobody has made such a proposal

Title: Why is std::exchange not noexcept?

Body:
According to the Standard (N4659, §23.2.4, [utility.exchange]), std::exchange should do a std::move and a std::forward:

template <class T, class U = T> T exchange(T& obj, U&& new_val);

Effects: Equivalent to:

T old_val = std::move(obj);
obj = std::forward(new_val);
return old_val;

Both move and forward are marked as noexcept:

(N4659, §23.2.5, [forward]):

template <class T> constexpr T&& forward(remove_reference_t<T>& t) noexcept;
template <class T> constexpr T&& forward(remove_reference_t<T>&& t) noexcept;

Returns: static_cast<T&&>(t).

(...)

template <class T> constexpr remove_reference_t<T>&& move(T&& t) noexcept;

Returns: static_cast<remove_reference_t<T>&&>(t).

So why isn't exchange noexcept? Is there some other reason for this or did the committee simply overlook this? Is this being proposed or can I write one?


问:
NSURLSessionDataTask on different thread destroys session cookies from UIWebView
I have a quite ugly problem with a subclassed UIWebView which is maintaining a user's web session with an online backend server, that will communicate with a session object, while the user is logged in to a specific service. From time to time, my app runs a data update service on a background thread with GDC and uses NSURLSessionDataTask to perform backend requests.

The background thread work somehow corrupts the web session object maintained by the UIWebView. In my understanding, that means that the NSHTTPCookieStorage gets corrupted … I don't know this exactly.

I think it would help, if the session maintained by the UIWebView would be shared with any other request done by a NSURLSessionDataTask running in any other thread.

In the past I suppressed the calls to the NSURLSessionDataTask work while the UIWebView session is active - but it seems that under some circumstances one of these calls still come through.

My question though is: How can I share the same session space used by the UIWebView with the NSURLSessionDataTask activities?

Unfortunately, due to the complexity of both implementations, I can't supply sample code…

答:
It mostly seems, that calling [NSURLSessionConfiguration defaultSessionConfiguration] as the web session used for the NSURLSessionDataTask breaks into the data of the UIWebView … at least it gets corrupted then and is no longer usable.

Using [NSURLSessionConfiguration ephemeralSessionConfiguration] instead does the trick and UIWebView's data stay intact pretty well.


问:
How to declare Classic COM Interface IBindCtx in C#?
I am currently poking around C# and COM interfaces.  COM Documentation in C# is sparse because C# came after COM (perhaps we at SO can fix).  I discovered the C# compiler can give informative error messages.  One can read the C# syntax version of the method signatures from the error messages and then add to your class.  This worked for IAdviseSink but does not work for IBindCtx.

I am getting error for the last method RevokeObjectParam(string a) the syntax in C++ is HRESULT RevokeObjectParam( [in] LPOLESTR pszKey ); and LPOLESTR is a null terminated 2 byte based string so using [MarshalAs(UnmanagedType.LPWStr)] should work.  But it doesn't, I get error messages

```<code>     * Class1.cs(25,14,25,40): error CS0539: 'IBindCtx.RevokeObjectParam' in explicit interface declaration is not a member of interface
     * Class1.cs(6,18,6,24): error CS0535: 'ComInterfacesInCSharp.Class1' does not implement interface member 'System.Runtime.InteropServices.ComTypes.IBindCtx.RevokeObjectParam(string)'
</code>```

So how do I amend this method signature to fix please?  Full code copyable into Visual Studio is below (create a Class Library project).

```<code>using System.Runtime.InteropServices.ComTypes;
using System.Runtime.InteropServices;

namespace ComInterfacesInCSharp
{
    public class Class1 : System.Runtime.InteropServices.ComTypes.IBindCtx
    {
        void IBindCtx.RegisterObjectBound(object obj) { }
        void IBindCtx.RevokeObjectBound(object obj) { }
        void IBindCtx.ReleaseBoundObjects() { }
        void IBindCtx.SetBindOptions(ref System.Runtime.InteropServices.ComTypes.BIND_OPTS opts) { }
        void IBindCtx.GetBindOptions(ref System.Runtime.InteropServices.ComTypes.BIND_OPTS opts) { }
        void IBindCtx.GetRunningObjectTable(out System.Runtime.InteropServices.ComTypes.IRunningObjectTable tab) { }
        void IBindCtx.RegisterObjectParam(string s, object obj) { }
        void IBindCtx.GetObjectParam(string s, out object obj) { }
        void IBindCtx.EnumObjectParam(out System.Runtime.InteropServices.ComTypes.IEnumString enumString) { }

        /* Problem here https://msdn.microsoft.com/en-us/library/windows/desktop/ms693771(v=vs.85).aspx
         * C++ Syntax is
         * HRESULT RevokeObjectParam( [in] LPOLESTR pszKey );
         * LPOLESTR is a null terminated 2 byte based string so UnmanagedType.LPWStr ought to work
         *
         */
        //void IBindCtx.RevokeObjectParam(string a) { }
        void IBindCtx.RevokeObjectParam([MarshalAs(UnmanagedType.LPWStr)] string a) { }

        /*
         * Compile errors are
         * Class1.cs(25,14,25,40): error CS0539: 'IBindCtx.RevokeObjectParam' in explicit interface declaration is not a member of interface
         * Class1.cs(6,18,6,24): error CS0535: 'ComInterfacesInCSharp.Class1' does not implement interface member 'System.Runtime.InteropServices.ComTypes.IBindCtx.RevokeObjectParam(string)'
         */
    }
}
</code>```

Incidentally, if you have a web resource detailing these interfaces in C# then that would be marvellous!

答:
the link you have given is superb! It answers my question which was what was correct method signature. Now I have definitively from Microsoft.

While you can find many of the source code definitions from Microsoft's Reference Source site, it is not your only option for discovering the signature for a method defined in an assembly.

Learn to use Visual Studio's Object Browser.  View Menu->Object Explorer (or press the F2 key).

In your particular case of implementing an interface, you can have Visual Studio auto implement the interface for you.  Right-Click on the interface name ad select "Implement Interface".

Body:
I am currently poking around C# and COM interfaces.  COM Documentation in C# is sparse because C# came after COM (perhaps we at SO can fix).  I discovered the C# compiler can give informative error messages.  One can read the C# syntax version of the method signatures from the error messages and then add to your class.  This worked for IAdviseSink but does not work for IBindCtx.

I am getting error for the last method RevokeObjectParam(string a) the syntax in C++ is HRESULT RevokeObjectParam( [in] LPOLESTR pszKey ); and LPOLESTR is a null terminated 2 byte based string so using [MarshalAs(UnmanagedType.LPWStr)] should work.  But it doesn't, I get error messages

     * Class1.cs(25,14,25,40): error CS0539: 'IBindCtx.RevokeObjectParam' in explicit interface declaration is not a member of interface
     * Class1.cs(6,18,6,24): error CS0535: 'ComInterfacesInCSharp.Class1' does not implement interface member 'System.Runtime.InteropServices.ComTypes.IBindCtx.RevokeObjectParam(string)'

So how do I amend this method signature to fix please?  Full code copyable into Visual Studio is below (create a Class Library project).

using System.Runtime.InteropServices.ComTypes;
using System.Runtime.InteropServices;

namespace ComInterfacesInCSharp
{
    public class Class1 : System.Runtime.InteropServices.ComTypes.IBindCtx
    {
        void IBindCtx.RegisterObjectBound(object obj) { }
        void IBindCtx.RevokeObjectBound(object obj) { }
        void IBindCtx.ReleaseBoundObjects() { }
        void IBindCtx.SetBindOptions(ref System.Runtime.InteropServices.ComTypes.BIND_OPTS opts) { }
        void IBindCtx.GetBindOptions(ref System.Runtime.InteropServices.ComTypes.BIND_OPTS opts) { }
        void IBindCtx.GetRunningObjectTable(out System.Runtime.InteropServices.ComTypes.IRunningObjectTable tab) { }
        void IBindCtx.RegisterObjectParam(string s, object obj) { }
        void IBindCtx.GetObjectParam(string s, out object obj) { }
        void IBindCtx.EnumObjectParam(out System.Runtime.InteropServices.ComTypes.IEnumString enumString) { }

        /* Problem here https://msdn.microsoft.com/en-us/library/windows/desktop/ms693771(v=vs.85).aspx
         * C++ Syntax is
         * HRESULT RevokeObjectParam( [in] LPOLESTR pszKey );
         * LPOLESTR is a null terminated 2 byte based string so UnmanagedType.LPWStr ought to work
         *
         */
        //void IBindCtx.RevokeObjectParam(string a) { }
        void IBindCtx.RevokeObjectParam([MarshalAs(UnmanagedType.LPWStr)] string a) { }

        /*
         * Compile errors are
         * Class1.cs(25,14,25,40): error CS0539: 'IBindCtx.RevokeObjectParam' in explicit interface declaration is not a member of interface
         * Class1.cs(6,18,6,24): error CS0535: 'ComInterfacesInCSharp.Class1' does not implement interface member 'System.Runtime.InteropServices.ComTypes.IBindCtx.RevokeObjectParam(string)'
         */
    }
}

Incidentally, if you have a web resource detailing these interfaces in C# then that would be marvellous!


问:
Angular2 function call from html element with no load event (or similiar)
I am new to Angular and have run into a problem that seems to have a javascript work around but they aren't very elegant.

I have a model with an array property. I ngfor the list property to build some html selection options. This is all working nicely. The problem comes when I am trying to set default value...the html elements don't have a load event.

I tried numerous html elements and they don't appear to have a load event either but I certainly could be doing it wrong.

I have seen a solution to put javascript tag right after the html and I could do that but I was really looking for a more elegant way in Angular.

I saw this SO post and thought that was my answer but there is a warning given that I agree with and thus it doesn't appear to be a good solution.
Regardless I tried it just to see if it would work and I got:

Failed to execute 'setAttribute' on 'Element': '{{loadDefaults()}}' is not a valid attribute name

```<code><span {{loadDefaults()}} ></span>
</code>```

So how can I fire an AS2 function in the component to load the default values?

HTML (btw this is NOT a full page load so there is no body tag):

```<code><tr>
   <td *ngFor="let loc of locOptions;">
      <span>{{loc.text}}</span>
      <input type="radio" name="radiogroup" [value]="loc.value" (change)="onSelectionChange(loc.value)">
  </td>
</tr>
</code>```

Edit

I thought perhaps mistakenly that ngoninit would fire too soon...before the html elements are rendered.

So perhaps what is being suggested is that I add a boolean is default to the model and bind THAT as the element is rendered.

答:
You should use ngOnInit to init you data, and call retrieve your data from your component :

```<code>defaults : any;

ngOnInit {
  this.defaults = loadDefaults();
}

loadDefaults() {
  //get data
}
</code>```

HTML :

```<code><span>{{defaults}}</span>
</code>```

Body:
I am new to Angular and have run into a problem that seems to have a javascript work around but they aren't very elegant.

I have a model with an array property. I ngfor the list property to build some html selection options. This is all working nicely. The problem comes when I am trying to set default value...the html elements don't have a load event.

I tried numerous html elements and they don't appear to have a load event either but I certainly could be doing it wrong.

I have seen a solution to put javascript tag right after the html and I could do that but I was really looking for a more elegant way in Angular.

I saw this SO post and thought that was my answer but there is a warning given that I agree with and thus it doesn't appear to be a good solution.
Regardless I tried it just to see if it would work and I got:

Failed to execute 'setAttribute' on 'Element': '{{loadDefaults()}}' is not a valid attribute name

So how can I fire an AS2 function in the component to load the default values?

HTML (btw this is NOT a full page load so there is no body tag):

      {{loc.text}}
      <input type="radio" name="radiogroup" [value]="loc.value" (change)="onSelectionChange(loc.value)">

Edit

I thought perhaps mistakenly that ngoninit would fire too soon...before the html elements are rendered.

So perhaps what is being suggested is that I add a boolean is default to the model and bind THAT as the element is rendered.

Body:
You should use ngOnInit to init you data, and call retrieve your data from your component :

defaults : any;

ngOnInit {
  this.defaults = loadDefaults();
}

loadDefaults() {
  //get data
}

HTML :

<span>{{defaults}}</span>


问:
CNPropertyNotFetchedException App Crashed
i want to get the all contacts list of phone with their name as well as phone numbers in swift 3.0 and xcode 8.0.
below is the code

```<code>func get_all_user_contacts()
{
    let status = CNContactStore.authorizationStatus(for: .contacts)
    if status == .denied || status == .restricted
    {
        presentSettingsActionSheet()
        return
    }

    // open it

    let store = CNContactStore()
    store.requestAccess(for: .contacts) { granted, error in
        guard granted else
        {
            DispatchQueue.main.async {
                self.presentSettingsActionSheet()
            }
            return
        }

        // get the contacts

        var contacts = [CNContact]()

        let request = CNContactFetchRequest(keysToFetch: [CNContactIdentifierKey as NSString, CNContactFormatter.descriptorForRequiredKeys(for: .fullName)])
        do
        {
            try store.enumerateContacts(with: request)
            { contact, stop in

                contacts.append(contact)
            }
        }
        catch
        {
            print(error)
        }

        // do something with the contacts array (e.g. print the names)

        let formatter = CNContactFormatter()
        formatter.style = .fullName
        for contact in contacts
        {
            let MobNumVar  = ((contact.phoneNumbers.first?.value)! as CNPhoneNumber).stringValue
            print(MobNumVar)
            print(formatter.string(from: contact) ?? "???")
        }
    }
}
</code>```

when i run this app it crashes and i don't know where i am getting wrong.
anyone can help me out.. it will be appreciated.

答:
You're requesting keys

```<code>• CNContactIdentifierKey
• CNContactFormatter.descriptorForRequiredKeys(for: .fullName)
</code>```

…but then you're trying to access contact.phoneNumber.

You can only access keys specified in keysToFetch, so you need to add CNContactPhoneNumbersKey to that array

Body:
i want to get the all contacts list of phone with their name as well as phone numbers in swift 3.0 and xcode 8.0.
below is the code

func get_all_user_contacts()
{
    let status = CNContactStore.authorizationStatus(for: .contacts)
    if status == .denied || status == .restricted
    {
        presentSettingsActionSheet()
        return
    }

    // open it

    let store = CNContactStore()
    store.requestAccess(for: .contacts) { granted, error in
        guard granted else
        {
            DispatchQueue.main.async {
                self.presentSettingsActionSheet()
            }
            return
        }

        // get the contacts

        var contacts = [CNContact]()

        let request = CNContactFetchRequest(keysToFetch: [CNContactIdentifierKey as NSString, CNContactFormatter.descriptorForRequiredKeys(for: .fullName)])
        do
        {
            try store.enumerateContacts(with: request)
            { contact, stop in

                contacts.append(contact)
            }
        }
        catch
        {
            print(error)
        }

        // do something with the contacts array (e.g. print the names)

        let formatter = CNContactFormatter()
        formatter.style = .fullName
        for contact in contacts
        {
            let MobNumVar  = ((contact.phoneNumbers.first?.value)! as CNPhoneNumber).stringValue
            print(MobNumVar)
            print(formatter.string(from: contact) ?? "???")
        }
    }
}

when i run this app it crashes and i don't know where i am getting wrong.
anyone can help me out.. it will be appreciated.

Body:
You're requesting keys

• CNContactIdentifierKey
• CNContactFormatter.descriptorForRequiredKeys(for: .fullName)

…but then you're trying to access contact.phoneNumber.

You can only access keys specified in keysToFetch, so you need to add CNContactPhoneNumbersKey to that array


问:
android setBackground animation
Currently I set background of a LinearLayout using

```<code>BitmapDrawable bd = new BitmapDrawable(getResources(), mBlurredMap);
mLytProfileCover.setBackground(bd);
</code>```

How can I animation this? For example, a fade-in animation where the background's alpha changes from 0 to 1 in 500ms.

Thanks.

答:
```<code>ObjectAnimator alphaAnimator = ObjectAnimator.ofFloat(mLytProfileCover, View.ALPHA, 0.0f, 1.0f);
alphaAnimator.addListener(new AnimatorListenerAdapter() {
    @Override
    public void onAnimationStart(final Animator animation) {
        mLytProfileCover.setBackground(bd);
    }
});
alphaAnimator.setDuration(500);
alphaAnimator.start();
</code>```

Title: android setBackground animation

Body:
Currently I set background of a LinearLayout using

BitmapDrawable bd = new BitmapDrawable(getResources(), mBlurredMap);
mLytProfileCover.setBackground(bd);

How can I animation this? For example, a fade-in animation where the background's alpha changes from 0 to 1 in 500ms.

Thanks.


问:
C read file & cut into 2D string array
I want to read in a .dat file and cut those information into 2 arrays:
pList is product list
eqList is equipment list

and the format of the file is as below:

```
productName equipment_a equipment_b
productName equipment_c equipment_d equipment_e
productName equipment_b equipment_d equipment_f
productName equipment_c
productName equipment_a equipment_f
```

What is the problem?

```<code>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#define lineLength 2048

int main()
{
    int a=0,b=0,c=0;
    char fileBuf[100], *pList[100], *eqList[100][100], *tempStr, delimilator[2] = " ";

    while ( fgets(fileBuf,lineLength,stdin) != NULL){
        tempStr = strtok(fileBuf,delimilator);
        pList[a] = malloc( strlen(tempStr) + 1);
        strcpy(pList[a], tempStr);

        for(b=0;tempStr != NULL;b++){
            tempStr = strtok(NULL,delimilator);
            eqList[a][b] = malloc( strlen(tempStr) + 1); //problem here
            strcpy(eqList[a][b], tempStr);               //problem here
        }
        a++;
    }

    return 0;
}
</code>```

答:
You are using strok returned value before to check if it is  != NULL. On last iteration it will invoke Undefined Behavior

Your loop could be like

```<code>while (fgets(fileBuf, sizeof(fileBuf), stdin) != NULL)
{
    tempStr = strtok(fileBuf,delimilator);
    pList[a] = malloc( strlen(tempStr) + 1);
    strcpy(pList[a], tempStr);

    tempStr = strtok(NULL,delimilator);

    b=0;

    while (tempStr != NULL)
    {
        eqList[a][b] = malloc( strlen(tempStr) + 1);
        strcpy(eqList[a][b], tempStr);

        tempStr = strtok(NULL,delimilator);

        b++;
    }

    a++;
}
</code>```

Title: C read file & cut into 2D string array

Body:
I want to read in a .dat file and cut those information into 2 arrays:
pList is product list
eqList is equipment list

and the format of the file is as below:

productName equipment_a equipment_b
productName equipment_c equipment_d equipment_e
productName equipment_b equipment_d equipment_f
productName equipment_c
productName equipment_a equipment_f

What is the problem?

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

#define lineLength 2048

int main()
{
    int a=0,b=0,c=0;
    char fileBuf[100], *pList[100], *eqList[100][100], *tempStr, delimilator[2] = " ";

    while ( fgets(fileBuf,lineLength,stdin) != NULL){
        tempStr = strtok(fileBuf,delimilator);
        pList[a] = malloc( strlen(tempStr) + 1);
        strcpy(pList[a], tempStr);

        for(b=0;tempStr != NULL;b++){
            tempStr = strtok(NULL,delimilator);
            eqList[a][b] = malloc( strlen(tempStr) + 1); //problem here
            strcpy(eqList[a][b], tempStr);               //problem here
        }
        a++;
    }

    return 0;
}

Body:
You are using strok returned value before to check if it is  != NULL. On last iteration it will invoke Undefined Behavior

Your loop could be like

while (fgets(fileBuf, sizeof(fileBuf), stdin) != NULL)
{
    tempStr = strtok(fileBuf,delimilator);
    pList[a] = malloc( strlen(tempStr) + 1);
    strcpy(pList[a], tempStr);

    tempStr = strtok(NULL,delimilator);

    b=0;

    while (tempStr != NULL)
    {
        eqList[a][b] = malloc( strlen(tempStr) + 1);
        strcpy(eqList[a][b], tempStr);

        tempStr = strtok(NULL,delimilator);

        b++;
    }

    a++;
}


问:
GMSMapViewDelegate idleAtCameraPosition is not triggered
I am using the Google Maps SDK for iOS in my app. I need to get the address when map moves. But idleAtCameraPosition is not triggered.

```<code> func vwGMap(vwGMap: GMSMapView!, idleAtCameraPosition position: GMSCameraPosition!) {
        print("changed position: \(vwGMap.camera.target)")
 }
</code>```

I have added delegate in viewDidLoad()

```<code>vwGMap.delegate = self
</code>```

and declared the map view

```<code>  @IBOutlet var vwGMap: GMSMapView!
</code>```

Why is idleAtCameraPosition not triggered?

Complete Code

```<code>class MapViewController: BaseViewController,CLLocationManagerDelegate, UISearchBarDelegate ,GMSMapViewDelegate, LocateOnTheMap,GMSAutocompleteFetcherDelegate {

    @IBOutlet var marker: UIImageView!

    @IBOutlet var fromaddress: kTextFiledPlaceHolder!

    @IBOutlet var toaddress: kTextFiledPlaceHolder!
    @IBOutlet var fromdummy: kTextFiledPlaceHolder!

    @IBOutlet var vwGMap: GMSMapView!
    var searchResultController: SearchResultsController!
    var resultsArray = [String]()
    var gmsFetcher: GMSAutocompleteFetcher!

    var locationManager = CLLocationManager()
    var didFindMyLocation = false

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.addSlideMenuButton()

        //Location Manager code to fetch current location
        self.locationManager.delegate = self
        self.locationManager.requestWhenInUseAuthorization()

        self.locationManager.startUpdatingLocation()

        vwGMap.delegate = self

         }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(true)

        searchResultController = SearchResultsController()
        searchResultController.delegate = self
        gmsFetcher = GMSAutocompleteFetcher()
        gmsFetcher.delegate = self

    }

    //Location Manager delegates
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
            let location = locations.last

               let camera = GMSCameraPosition.camera(withLatitude: (location?.coordinate.latitude)!, longitude:(location?.coordinate.longitude)!, zoom:16)
        vwGMap.animate(to: camera)

        CATransaction.begin()
        CATransaction.setValue(5, forKey: kCATransactionAnimationDuration)

        vwGMap.animate(toViewingAngle: 40)
        vwGMap.animate(toBearing: 80)

        //vwGMap.animate(toZoom: 18)

          CATransaction.commit()
        vwGMap.settings.myLocationButton = true
        vwGMap.isMyLocationEnabled = true

        vwGMap.delegate = self
        self.vwGMap.addSubview(toaddress)
        self.vwGMap.addSubview(fromdummy)
        self.vwGMap.addSubview(marker)

        self.locationManager.stopUpdatingLocation()

    }

    public func didFailAutocompleteWithError(_ error: Error) {
        //        resultText?.text = error.localizedDescription
    }

    /**
     * Called when autocomplete predictions are available.
     * @param predictions an array of GMSAutocompletePrediction objects.
     */
    public func didAutocomplete(with predictions: [GMSAutocompletePrediction]) {
        //self.resultsArray.count + 1
        print(predictions)
        for prediction in predictions {

            if let prediction = prediction as GMSAutocompletePrediction!{
                self.resultsArray.append(prediction.attributedFullText.string)
            }
        }
        self.searchResultController.reloadDataWithArray(self.resultsArray)
        //   self.searchResultsTable.reloadDataWithArray(self.resultsArray)
        print("check")
        print(resultsArray)
    }

    func locateWithLongitude(_ lon: Double, andLatitude lat: Double, andTitle title: String) {

        DispatchQueue.main.async { () -> Void in

            let position = CLLocationCoordinate2DMake(lat, lon)
            let marker = GMSMarker(position: position)

            let camera = GMSCameraPosition.camera(withLatitude: lat, longitude: lon, zoom: 10)
//            self.vwGMap.camera = camera
//
//            marker.title = "Address : \(title)"
//            marker.map = self.vwGMap
            CATransaction.begin()
            CATransaction.setValue(5, forKey: kCATransactionAnimationDuration)
            self.vwGMap.animate(to: camera)

             CATransaction.commit()

        }

    }
    func locate(_ lon: Double, andLatitude lat: Double) {

        DispatchQueue.main.async { () -> Void in

            let camera = GMSCameraPosition.camera(withLatitude: lat, longitude: lon, zoom: 10)
            //            self.vwGMap.camera = camera
            //
            //            marker.title = "Address : \(title)"
            //            marker.map = self.vwGMap
            CATransaction.begin()
            CATransaction.setValue(5, forKey: kCATransactionAnimationDuration)
            self.vwGMap.animate(to: camera)

            CATransaction.commit()

        }

    }

    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {

        //        let placeClient = GMSPlacesClient()
        //
        //
        //        placeClient.autocompleteQuery(searchText, bounds: nil, filter: nil)  {(results, error: Error?) -> Void in
        //           // NSError myerr = Error;
        //            print("Error @%",Error.self)
        //
        //            self.resultsArray.removeAll()
        //            if results == nil {
        //                return
        //            }
        //
        //            for result in results! {
        //                if let result = result as? GMSAutocompletePrediction {
        //                    self.resultsArray.append(result.attributedFullText.string)
        //                }
        //            }
        //
        //            self.searchResultController.reloadDataWithArray(self.resultsArray)
        //
        //        }

        print(searchText)

        self.resultsArray.removeAll()
        gmsFetcher?.sourceTextHasChanged(searchText)

    }

    func mapView(_ mapView: GMSMapView, idleAtCamera position: GMSCameraPosition) {
        print("changed position")
    }

}
</code>```

答:
Make sure to extend the class to GMSMapViewDelegate.

Sample code:

```<code>class Class-name : UIViewController,GMSMapViewDelegate
</code>```

change code in viewDidLoad:

```<code>vwGMap = GMSMapView()
vwGMap.delegate = self
</code>```

Use this method for tap marker event.

```<code>func mapView(_ mapView: GMSMapView, didTapAt coordinate: CLLocationCoordinate2D) {

 print("You tapped at \(coordinate.latitude), \(coordinate.longitude)")
}
</code>```

If map view is  scroll:

```<code>func mapView(_ mapView: GMSMapView, idleAt cameraPosition: GMSCameraPosition) {
   print("map scrolled.")
}
</code>```

Body:
I am using the Google Maps SDK for iOS in my app. I need to get the address when map moves. But idleAtCameraPosition is not triggered.

 func vwGMap(vwGMap: GMSMapView!, idleAtCameraPosition position: GMSCameraPosition!) {
        print("changed position: \(vwGMap.camera.target)")
 }

I have added delegate in viewDidLoad()

vwGMap.delegate = self

and declared the map view

  @IBOutlet var vwGMap: GMSMapView!

Why is idleAtCameraPosition not triggered?

Complete Code

class MapViewController: BaseViewController,CLLocationManagerDelegate, UISearchBarDelegate ,GMSMapViewDelegate, LocateOnTheMap,GMSAutocompleteFetcherDelegate {

    @IBOutlet var marker: UIImageView!

    @IBOutlet var fromaddress: kTextFiledPlaceHolder!

    @IBOutlet var toaddress: kTextFiledPlaceHolder!
    @IBOutlet var fromdummy: kTextFiledPlaceHolder!

    @IBOutlet var vwGMap: GMSMapView!
    var searchResultController: SearchResultsController!
    var resultsArray = [String]()
    var gmsFetcher: GMSAutocompleteFetcher!

    var locationManager = CLLocationManager()
    var didFindMyLocation = false

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.addSlideMenuButton()

        //Location Manager code to fetch current location
        self.locationManager.delegate = self
        self.locationManager.requestWhenInUseAuthorization()

        self.locationManager.startUpdatingLocation()

        vwGMap.delegate = self

         }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(true)

        searchResultController = SearchResultsController()
        searchResultController.delegate = self
        gmsFetcher = GMSAutocompleteFetcher()
        gmsFetcher.delegate = self

    }

    //Location Manager delegates
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
            let location = locations.last

               let camera = GMSCameraPosition.camera(withLatitude: (location?.coordinate.latitude)!, longitude:(location?.coordinate.longitude)!, zoom:16)
        vwGMap.animate(to: camera)

        CATransaction.begin()
        CATransaction.setValue(5, forKey: kCATransactionAnimationDuration)

        vwGMap.animate(toViewingAngle: 40)
        vwGMap.animate(toBearing: 80)

        //vwGMap.animate(toZoom: 18)

          CATransaction.commit()
        vwGMap.settings.myLocationButton = true
        vwGMap.isMyLocationEnabled = true

        vwGMap.delegate = self
        self.vwGMap.addSubview(toaddress)
        self.vwGMap.addSubview(fromdummy)
        self.vwGMap.addSubview(marker)

        self.locationManager.stopUpdatingLocation()

    }

    public func didFailAutocompleteWithError(_ error: Error) {
        //        resultText?.text = error.localizedDescription
    }

    /**
     * Called when autocomplete predictions are available.
     * @param predictions an array of GMSAutocompletePrediction objects.
     */
    public func didAutocomplete(with predictions: [GMSAutocompletePrediction]) {
        //self.resultsArray.count + 1
        print(predictions)
        for prediction in predictions {

            if let prediction = prediction as GMSAutocompletePrediction!{
                self.resultsArray.append(prediction.attributedFullText.string)
            }
        }
        self.searchResultController.reloadDataWithArray(self.resultsArray)
        //   self.searchResultsTable.reloadDataWithArray(self.resultsArray)
        print("check")
        print(resultsArray)
    }

    func locateWithLongitude(_ lon: Double, andLatitude lat: Double, andTitle title: String) {

        DispatchQueue.main.async { () -> Void in

            let position = CLLocationCoordinate2DMake(lat, lon)
            let marker = GMSMarker(position: position)

            let camera = GMSCameraPosition.camera(withLatitude: lat, longitude: lon, zoom: 10)
//            self.vwGMap.camera = camera
//
//            marker.title = "Address : \(title)"
//            marker.map = self.vwGMap
            CATransaction.begin()
            CATransaction.setValue(5, forKey: kCATransactionAnimationDuration)
            self.vwGMap.animate(to: camera)

             CATransaction.commit()

        }

    }
    func locate(_ lon: Double, andLatitude lat: Double) {

        DispatchQueue.main.async { () -> Void in

            let camera = GMSCameraPosition.camera(withLatitude: lat, longitude: lon, zoom: 10)
            //            self.vwGMap.camera = camera
            //
            //            marker.title = "Address : \(title)"
            //            marker.map = self.vwGMap
            CATransaction.begin()
            CATransaction.setValue(5, forKey: kCATransactionAnimationDuration)
            self.vwGMap.animate(to: camera)

            CATransaction.commit()

        }

    }

    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {

        //        let placeClient = GMSPlacesClient()
        //
        //
        //        placeClient.autocompleteQuery(searchText, bounds: nil, filter: nil)  {(results, error: Error?) -> Void in
        //           // NSError myerr = Error;
        //            print("Error @%",Error.self)
        //
        //            self.resultsArray.removeAll()
        //            if results == nil {
        //                return
        //            }
        //
        //            for result in results! {
        //                if let result = result as? GMSAutocompletePrediction {
        //                    self.resultsArray.append(result.attributedFullText.string)
        //                }
        //            }
        //
        //            self.searchResultController.reloadDataWithArray(self.resultsArray)
        //
        //        }

        print(searchText)

        self.resultsArray.removeAll()
        gmsFetcher?.sourceTextHasChanged(searchText)

    }

    func mapView(_ mapView: GMSMapView, idleAtCamera position: GMSCameraPosition) {
        print("changed position")
    }

}

Body:
Make sure to extend the class to GMSMapViewDelegate.

Sample code:

class Class-name : UIViewController,GMSMapViewDelegate

change code in viewDidLoad:

vwGMap = GMSMapView()
vwGMap.delegate = self

Use this method for tap marker event.

func mapView(_ mapView: GMSMapView, didTapAt coordinate: CLLocationCoordinate2D) {

 print("You tapped at \(coordinate.latitude), \(coordinate.longitude)")
}

If map view is  scroll:

func mapView(_ mapView: GMSMapView, idleAt cameraPosition: GMSCameraPosition) {
   print("map scrolled.")
}


问:
java H2 hanging on getLocalhost on arm32 device
My application works fine on Windows, OSX an, Ubuntu and other flavours of linux until now.

On an arm 32 machine using jdk-8u121-linux-arm32-vfp-hflt.tar.gz it is hanging for five minutes on trying to create a Hibernate database using pure java database H2 and then giving up

```<code>public static void recreateDatabase()
    {
        Configuration config;
        config =
                HibernateUtil.getInitializedConfigurationAndRebuildAuditTables();
        new SchemaExport(config).create(false,true);
        factory = config.buildSessionFactory();
    }
</code>```

I ran jstack during this period, of the relevent threads I think the key one is the 2nd one listed stuck at java.net.Inet4AddressImpl.lookupAllHostAddr but it just seem to be trying to get localhost , the machine is actually an embedded device and I wonder if that could mean it has weird networking that could be causing an issue ?

I have updated to the latest version of h2 (1.4.194), and the latest version of hibernate I could use without needing code changes (4.3.11.Final) due to changes they make to SchemaExport after that.

```<code>"main" #1 prio=5 os_prio=0 tid=0xb6105890 nid=0x7580 in Object.wait() [0xb6336000]
   java.lang.Thread.State: WAITING (on object monitor)
        at java.lang.Object.wait(Native Method)
        - waiting on <0x7c042900> (a com.mchange.v2.resourcepool.BasicResourcePool)
        at com.mchange.v2.resourcepool.BasicResourcePool.awaitAvailable(BasicResourcePool.java:1414)
        at com.mchange.v2.resourcepool.BasicResourcePool.prelimCheckoutResource(BasicResourcePool.java:606)
        - locked <0x7c042900> (a com.mchange.v2.resourcepool.BasicResourcePool)
        at com.mchange.v2.resourcepool.BasicResourcePool.checkoutResource(BasicResourcePool.java:526)
        at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutAndMarkConnectionInUse(C3P0PooledConnectionPool.java:755)
        at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:682)
        at com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource.getConnection(AbstractPoolBackedDataSource.java:140)
        at org.hibernate.c3p0.internal.C3P0ConnectionProvider.getConnection(C3P0ConnectionProvider.java:90)
        at org.hibernate.engine.jdbc.internal.JdbcServicesImpl$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcServicesImpl.java:279)
        at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:124)
        at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:111)
        at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:234)
        at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206)
        at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1887)
        at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1845)
        at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1930)
        at com.jthink.songlayer.hibernate.HibernateUtil.recreateDatabase(HibernateUtil.java:135)
        at com.jthink.songkong.cmdline.CmdCreateDatabase.start(CmdCreateDatabase.java:27)
        at com.jthink.songkong.cmdline.SongKong.cmdCheckDatabase(SongKong.java:1904)
        at com.jthink.songkong.cmdline.SongKong.cmdlineStart(SongKong.java:1574)
        at com.jthink.songkong.cmdline.SongKong.finish(SongKong.java:1699)
        at com.jthink.songkong.cmdline.SongKongForMelco.main(SongKongForMelco.java:33)
</code>```

Running jstack during this 5 minute period I see:

```<code>"C3P0PooledConnectionPoolManager[identityToken->tys5dp9n86d1sl8vqh|f278eb]-HelperThread-#0" #9 daemon prio=5 os_prio=0 tid=0x7a1747b8 nid=0x75d3 runnable [0x79d60000]
       java.lang.Thread.State: RUNNABLE
            at java.net.Inet4AddressImpl.lookupAllHostAddr(Native Method)
            at java.net.InetAddress$2.lookupAllHostAddr(InetAddress.java:928)
            at java.net.InetAddress.getAddressesFromNameService(InetAddress.java:1323)
            at java.net.InetAddress.getLocalHost(InetAddress.java:1500)
            - locked <0x8eddfe38> (a java.lang.Object)
            at org.h2.util.NetUtils.getLocalAddress(NetUtils.java:272)
            - locked <0x7c040f80> (a java.lang.Class for org.h2.util.NetUtils)
            at org.h2.store.FileLock.lockSocket(FileLock.java:380)
            at org.h2.store.FileLock.lock(FileLock.java:138)
            - locked <0x7be62750> (a org.h2.store.FileLock)
            at org.h2.engine.Database.open(Database.java:662)
            - locked <0x7bc23a90> (a org.h2.engine.Database)
            at org.h2.engine.Database.openDatabase(Database.java:276)
            at org.h2.engine.Database.<init>(Database.java:270)
            at org.h2.engine.Engine.openSession(Engine.java:64)
            at org.h2.engine.Engine.openSession(Engine.java:176)
            - locked <0x8ee8bc50> (a org.h2.engine.Engine)
            at org.h2.engine.Engine.createSessionAndValidate(Engine.java:154)
            at org.h2.engine.Engine.createSession(Engine.java:137)
            at org.h2.engine.Engine.createSession(Engine.java:27)
            at org.h2.engine.SessionRemote.connectEmbeddedOrServer(SessionRemote.java:354)
            at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:116)
            at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:100)
            at org.h2.Driver.connect(Driver.java:69)
            at com.mchange.v2.c3p0.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:146)
            at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:195)
            at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:184)
            at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.acquireResource(C3P0PooledConnectionPool.java:200)
            at com.mchange.v2.resourcepool.BasicResourcePool.doAcquire(BasicResourcePool.java:1086)
            at com.mchange.v2.resourcepool.BasicResourcePool.doAcquireAndDecrementPendingAcquiresWithinLockOnSuccess(BasicResourcePool.java:1073)
            at com.mchange.v2.resourcepool.BasicResourcePool.access$800(BasicResourcePool.java:44)
            at com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask.run(BasicResourcePool.java:1810)
            at com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:648)
</code>```

and then a number of threads with

```<code>"C3P0PooledConnectionPoolManager[identityToken->tys5dp9n86d1sl8vqh|f278eb]-HelperThread-#2" #11 daemon prio=5 os_prio=0 tid=0x7a312eb0 nid=0x75d5 waiting for monitor entry [0x79c]
   java.lang.Thread.State: BLOCKED (on object monitor)
        at org.h2.engine.Engine.openSession(Engine.java:169)
        - waiting to lock <0x8ee8bc50> (a org.h2.engine.Engine)
        at org.h2.engine.Engine.createSessionAndValidate(Engine.java:154)
        at org.h2.engine.Engine.createSession(Engine.java:137)
        at org.h2.engine.Engine.createSession(Engine.java:27)
        at org.h2.engine.SessionRemote.connectEmbeddedOrServer(SessionRemote.java:354)
        at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:116)
        at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:100)
        at org.h2.Driver.connect(Driver.java:69)
        at com.mchange.v2.c3p0.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:146)
        at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:195)
        at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:184)
        at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.acquireResource(C3P0PooledConnectionPool.java:200)
        at com.mchange.v2.resourcepool.BasicResourcePool.doAcquire(BasicResourcePool.java:1086)
        at com.mchange.v2.resourcepool.BasicResourcePool.doAcquireAndDecrementPendingAcquiresWithinLockOnSuccess(BasicResourcePool.java:1073)
        at com.mchange.v2.resourcepool.BasicResourcePool.access$800(BasicResourcePool.java:44)
        at com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask.run(BasicResourcePool.java:1810)
        at com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:648)
</code>```

Update with network info

```<code>more /etc/hosts

127.0.0.1       localhost

more /etc/resolv.conf

# Generated by dhcpcd for interface br0
nameserver 192.168.0.1
</code>```

Update

Just been pointed out to me the issue is with H2 not **Hibernate, can this be amended to use a different method, it is H2 that is making the call in its NetUtils class

答:
I fixed in by adding this h2 property to my HibernateUtil configuration

```<code>System.setProperty("h2.bindAddress", InetAddress.getLoopbackAddress().getHostAddress());
</code>```

I just hope it doesnt break any currenlty working installations !

Body:
My application works fine on Windows, OSX an, Ubuntu and other flavours of linux until now.

On an arm 32 machine using jdk-8u121-linux-arm32-vfp-hflt.tar.gz it is hanging for five minutes on trying to create a Hibernate database using pure java database H2 and then giving up

public static void recreateDatabase()
    {
        Configuration config;
        config =
                HibernateUtil.getInitializedConfigurationAndRebuildAuditTables();
        new SchemaExport(config).create(false,true);
        factory = config.buildSessionFactory();
    }

I ran jstack during this period, of the relevent threads I think the key one is the 2nd one listed stuck at java.net.Inet4AddressImpl.lookupAllHostAddr but it just seem to be trying to get localhost , the machine is actually an embedded device and I wonder if that could mean it has weird networking that could be causing an issue ?

I have updated to the latest version of h2 (1.4.194), and the latest version of hibernate I could use without needing code changes (4.3.11.Final) due to changes they make to SchemaExport after that.

"main" #1 prio=5 os_prio=0 tid=0xb6105890 nid=0x7580 in Object.wait() [0xb6336000]
   java.lang.Thread.State: WAITING (on object monitor)
        at java.lang.Object.wait(Native Method)
        - waiting on <0x7c042900> (a com.mchange.v2.resourcepool.BasicResourcePool)
        at com.mchange.v2.resourcepool.BasicResourcePool.awaitAvailable(BasicResourcePool.java:1414)
        at com.mchange.v2.resourcepool.BasicResourcePool.prelimCheckoutResource(BasicResourcePool.java:606)
        - locked <0x7c042900> (a com.mchange.v2.resourcepool.BasicResourcePool)
        at com.mchange.v2.resourcepool.BasicResourcePool.checkoutResource(BasicResourcePool.java:526)
        at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutAndMarkConnectionInUse(C3P0PooledConnectionPool.java:755)
        at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:682)
        at com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource.getConnection(AbstractPoolBackedDataSource.java:140)
        at org.hibernate.c3p0.internal.C3P0ConnectionProvider.getConnection(C3P0ConnectionProvider.java:90)
        at org.hibernate.engine.jdbc.internal.JdbcServicesImpl$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcServicesImpl.java:279)
        at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:124)
        at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:111)
        at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:234)
        at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206)
        at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1887)
        at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1845)
        at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1930)
        at com.jthink.songlayer.hibernate.HibernateUtil.recreateDatabase(HibernateUtil.java:135)
        at com.jthink.songkong.cmdline.CmdCreateDatabase.start(CmdCreateDatabase.java:27)
        at com.jthink.songkong.cmdline.SongKong.cmdCheckDatabase(SongKong.java:1904)
        at com.jthink.songkong.cmdline.SongKong.cmdlineStart(SongKong.java:1574)
        at com.jthink.songkong.cmdline.SongKong.finish(SongKong.java:1699)
        at com.jthink.songkong.cmdline.SongKongForMelco.main(SongKongForMelco.java:33)

Running jstack during this 5 minute period I see:

"C3P0PooledConnectionPoolManager[identityToken->tys5dp9n86d1sl8vqh|f278eb]-HelperThread-#0" #9 daemon prio=5 os_prio=0 tid=0x7a1747b8 nid=0x75d3 runnable [0x79d60000]
       java.lang.Thread.State: RUNNABLE
            at java.net.Inet4AddressImpl.lookupAllHostAddr(Native Method)
            at java.net.InetAddress$2.lookupAllHostAddr(InetAddress.java:928)
            at java.net.InetAddress.getAddressesFromNameService(InetAddress.java:1323)
            at java.net.InetAddress.getLocalHost(InetAddress.java:1500)
            - locked <0x8eddfe38> (a java.lang.Object)
            at org.h2.util.NetUtils.getLocalAddress(NetUtils.java:272)
            - locked <0x7c040f80> (a java.lang.Class for org.h2.util.NetUtils)
            at org.h2.store.FileLock.lockSocket(FileLock.java:380)
            at org.h2.store.FileLock.lock(FileLock.java:138)
            - locked <0x7be62750> (a org.h2.store.FileLock)
            at org.h2.engine.Database.open(Database.java:662)
            - locked <0x7bc23a90> (a org.h2.engine.Database)
            at org.h2.engine.Database.openDatabase(Database.java:276)
            at org.h2.engine.Database.<init>(Database.java:270)
            at org.h2.engine.Engine.openSession(Engine.java:64)
            at org.h2.engine.Engine.openSession(Engine.java:176)
            - locked <0x8ee8bc50> (a org.h2.engine.Engine)
            at org.h2.engine.Engine.createSessionAndValidate(Engine.java:154)
            at org.h2.engine.Engine.createSession(Engine.java:137)
            at org.h2.engine.Engine.createSession(Engine.java:27)
            at org.h2.engine.SessionRemote.connectEmbeddedOrServer(SessionRemote.java:354)
            at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:116)
            at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:100)
            at org.h2.Driver.connect(Driver.java:69)
            at com.mchange.v2.c3p0.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:146)
            at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:195)
            at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:184)
            at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.acquireResource(C3P0PooledConnectionPool.java:200)
            at com.mchange.v2.resourcepool.BasicResourcePool.doAcquire(BasicResourcePool.java:1086)
            at com.mchange.v2.resourcepool.BasicResourcePool.doAcquireAndDecrementPendingAcquiresWithinLockOnSuccess(BasicResourcePool.java:1073)
            at com.mchange.v2.resourcepool.BasicResourcePool.access$800(BasicResourcePool.java:44)
            at com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask.run(BasicResourcePool.java:1810)
            at com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:648)

and then a number of threads with

"C3P0PooledConnectionPoolManager[identityToken->tys5dp9n86d1sl8vqh|f278eb]-HelperThread-#2" #11 daemon prio=5 os_prio=0 tid=0x7a312eb0 nid=0x75d5 waiting for monitor entry [0x79c]
   java.lang.Thread.State: BLOCKED (on object monitor)
        at org.h2.engine.Engine.openSession(Engine.java:169)
        - waiting to lock <0x8ee8bc50> (a org.h2.engine.Engine)
        at org.h2.engine.Engine.createSessionAndValidate(Engine.java:154)
        at org.h2.engine.Engine.createSession(Engine.java:137)
        at org.h2.engine.Engine.createSession(Engine.java:27)
        at org.h2.engine.SessionRemote.connectEmbeddedOrServer(SessionRemote.java:354)
        at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:116)
        at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:100)
        at org.h2.Driver.connect(Driver.java:69)
        at com.mchange.v2.c3p0.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:146)
        at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:195)
        at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:184)
        at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.acquireResource(C3P0PooledConnectionPool.java:200)
        at com.mchange.v2.resourcepool.BasicResourcePool.doAcquire(BasicResourcePool.java:1086)
        at com.mchange.v2.resourcepool.BasicResourcePool.doAcquireAndDecrementPendingAcquiresWithinLockOnSuccess(BasicResourcePool.java:1073)
        at com.mchange.v2.resourcepool.BasicResourcePool.access$800(BasicResourcePool.java:44)
        at com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask.run(BasicResourcePool.java:1810)
        at com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:648)

Update with network info

more /etc/hosts

127.0.0.1       localhost

more /etc/resolv.conf

# Generated by dhcpcd for interface br0
nameserver 192.168.0.1

Update

Just been pointed out to me the issue is with H2 not **Hibernate, can this be amended to use a different method, it is H2 that is making the call in its NetUtils class

Body:
I fixed in by adding this h2 property to my HibernateUtil configuration

System.setProperty("h2.bindAddress", InetAddress.getLoopbackAddress().getHostAddress());

I just hope it doesnt break any currenlty working installations !


问:
VBA to complete a Internet form
I'm looking for a code to put values from an Excel to a Webpage.

```<code>Sub FillInternetForm()
  Dim IE As Object
  Set IE = CreateObject("InternetExplorer.Application")

  IE.navigate "http://xxxxxxxx/"
  IE.Visible = True
  While IE.Busy
    DoEvents
  Wend
  IE.document.getElementById("xxxxx").Value = "xxxx"
End Sub
</code>```

The error comes in on IE.document.getElementById("xxxxx").Value = "xxxx line and it says Method 'Document' of object 'IWebBrowser 2' failed.

I'm looking for suggstions to solve this question: I made a lot of research and nothing works :/

Thanks in advance :)

答:
Ana,
Here is a working example. You can easily customized this little bit of code to work for you. One time you must be aware of is that I added a reference to my project under TOOLS -> Preferences -> Microsoft Internet Controls. Also another word of caution is on this line Set Elements on this line, if you are looking for something that does not exists you will end up with an error. This working example I put together goes to stack overflow and finds the elements below  footer-menu.
Let me know if something does not make sense.

```<code>Sub TryInternetExplorer()
 'Reference to system32\shdocvw.dll  'Microsoft Internet Controls
Dim IEApp As InternetExplorer
Set IEApp = New InternetExplorer
IEApp.Visible = True
IEApp.Navigate "https://iam.pearson.com/auth/XUI/#login/"
While IEApp.ReadyState <> READYSTATE_COMPLETE And IEApp.ReadyState <> READYSTATE_LOADED
    DoEvents
Wend

'wait for the form to load
Do
Set form = IEApp.Document.getElementsByTagName("FORM")(0) '1st table
DoEvents
Loop While form Is Nothing

 IEApp.Document.getElementsByName("callback_0")(0).Value = "Miguel"
 IEApp.Document.getElementsByName("callback_1")(0).Value = "pass"
 IEApp.Document.getElementsByName("callback_2")(0).Click

Set Document = Nothing
Set IEApp = Nothing

 End Sub
</code>```

Title: VBA to complete a Internet form

Body:
I'm looking for a code to put values from an Excel to a Webpage.

Sub FillInternetForm()
  Dim IE As Object
  Set IE = CreateObject("InternetExplorer.Application")

  IE.navigate "http://xxxxxxxx/"
  IE.Visible = True
  While IE.Busy
    DoEvents
  Wend
  IE.document.getElementById("xxxxx").Value = "xxxx"
End Sub

The error comes in on IE.document.getElementById("xxxxx").Value = "xxxx line and it says Method 'Document' of object 'IWebBrowser 2' failed.

I'm looking for suggstions to solve this question: I made a lot of research and nothing works :/

Thanks in advance :)

Body:
Ana,
Here is a working example. You can easily customized this little bit of code to work for you. One time you must be aware of is that I added a reference to my project under TOOLS -> Preferences -> Microsoft Internet Controls. Also another word of caution is on this line Set Elements on this line, if you are looking for something that does not exists you will end up with an error. This working example I put together goes to stack overflow and finds the elements below  footer-menu.
Let me know if something does not make sense.

Sub TryInternetExplorer()
 'Reference to system32\shdocvw.dll  'Microsoft Internet Controls
Dim IEApp As InternetExplorer
Set IEApp = New InternetExplorer
IEApp.Visible = True
IEApp.Navigate "https://iam.pearson.com/auth/XUI/#login/"
While IEApp.ReadyState <> READYSTATE_COMPLETE And IEApp.ReadyState <> READYSTATE_LOADED
    DoEvents
Wend

'wait for the form to load
Do
Set form = IEApp.Document.getElementsByTagName("FORM")(0) '1st table
DoEvents
Loop While form Is Nothing

 IEApp.Document.getElementsByName("callback_0")(0).Value = "Miguel"
 IEApp.Document.getElementsByName("callback_1")(0).Value = "pass"
 IEApp.Document.getElementsByName("callback_2")(0).Click

Set Document = Nothing
Set IEApp = Nothing

 End Sub


问:
scikit learn: train_test_split, can I ensure same splits on different datasets
I understand that the train_test_split method splits a dataset into random train and test subsets. And using random_state=int can ensure we have the same splits on this dataset for each time the method is called.

My problem is slightly different.

I have two datasets, A and B, they contain identical sets of examples and the order of these examples appear in each dataset is also identical. But they key difference is that exmaples in each dataset uses a different sets of features.

I would like to test to see if the features used in A leads to better performance than features used in B. So I would like to ensure that when I call train_test_split on A and B, I can get the same splits on both datasets so that the comparison is meaningful.

Is this possible? Do I simply need to ensure the random_state in both method calls for both datasets are the same?

Thanks

答:
Looking at the code for the train_test_split function, it sets the random seed inside the function at every call. So it will result in the same split every time. We can check that this works pretty simply

```<code>X1 = np.random.random((200, 5))
X2 = np.random.random((200, 5))
y = np.arange(200)

X1_train, X1_test, y1_train, y1_test = model_selection.train_test_split(X1, y,
                                                                        test_size=0.1,
                                                                        random_state=42)
X2_train, X2_test, y2_train, y2_test = model_selection.train_test_split(X1, y,
                                                                        test_size=0.1,
                                                                        random_state=42)

print np.all(y1_train == y2_train)
print np.all(y1_test == y2_test)
</code>```

Which outputs:

```<code>True
True
</code>```

Which is good! Another way of doing this problem is to create one training and test split on all your features and then split your features up before training. However if you're in a weird situation where you need to do both at once (sometimes with similarity matrices you don't want test features in your training set), then you can use the StratifiedShuffleSplit function to return the indices of the data that belongs to each set. For example:

```<code>n_splits = 1
sss = model_selection.StratifiedShuffleSplit(n_splits=n_splits,
                                             test_size=0.1,
                                             random_state=42)
train_idx, test_idx = list(sss.split(X, y))[0]
</code>```

Body:
Looking at the code for the train_test_split function, it sets the random seed inside the function at every call. So it will result in the same split every time. We can check that this works pretty simply

X1 = np.random.random((200, 5))
X2 = np.random.random((200, 5))
y = np.arange(200)

X1_train, X1_test, y1_train, y1_test = model_selection.train_test_split(X1, y,
                                                                        test_size=0.1,
                                                                        random_state=42)
X2_train, X2_test, y2_train, y2_test = model_selection.train_test_split(X1, y,
                                                                        test_size=0.1,
                                                                        random_state=42)

print np.all(y1_train == y2_train)
print np.all(y1_test == y2_test)

Which outputs:

True
True

Which is good! Another way of doing this problem is to create one training and test split on all your features and then split your features up before training. However if you're in a weird situation where you need to do both at once (sometimes with similarity matrices you don't want test features in your training set), then you can use the StratifiedShuffleSplit function to return the indices of the data that belongs to each set. For example:

n_splits = 1
sss = model_selection.StratifiedShuffleSplit(n_splits=n_splits,
                                             test_size=0.1,
                                             random_state=42)
train_idx, test_idx = list(sss.split(X, y))[0]


问:
Is Task.Run appropriate here, wrapping network calls?
I'm studying a pretty popular c# proxy server.  In it there is code such as (I'm hiding the proxy server identity on purpose because I feel bad telling tales, if indeed it is wrong).

```<code>private void OnConnectionAccepted(TcpClient cl)
{
     ....
     Task.Run(async () =>
            {
               await HandleClientRequest();

            });
     Task.Run(async () =>
        {
            TcpClient cl = await listener.AcceptTcpClientAsync();
            OnConnectionAccepted(cl);
        });
}
</code>```

Where HandleClientRequest does some async network calls, such as reading the request from the client and repeating it to the server, like you'd expect a proxy to do.
listener.AcceptTcpClientAsync just waits for the next connection to come from a browser.

So it seems the point of the Task.Run is really just to allow AcceptTcpClientAsync to be called while HandleClientRequest is busy.

This seems to go against the recommendations I've been reading, eg. http://blog.stephencleary.com/2013/10/taskrun-etiquette-and-proper-usage.html because Task.Run is wrapping network, not CPU calls.

So how should it work instead, if this is wrong, should it use ThreadPool.QueueUserWorkerItem?

The context by the way would typically be a console app.

答:
I would propose refactoring this a little bit into one method accepting connections and another one dealing with incoming data. Finally a third one dealing with failed tasks.

```<code>public async Task Acceptor(TcpListener listener)
{
  for (;;)
  {
    TcpClient client = await listener.AcceptTcpClientAsync();
    OnConnectionAccepted(client).ContinueWith(task => { errorHandling }, OnlyOnFaulted);
    // some logic which will stop this loop if necessary
  }
}

private async Task OnConnectionAccepted(TcpClient client)
{
  await HandleClientRequest(client);
  // .. further logic
}
</code>```

"Acceptor" will throw when the listener cannot accept new connections anymore. "errorHandling" will be called when one particular connection cannot be processed. (You can also consider a try catch in OnConnectionAccepted and making it async void - which I personally would not prefer)

Stephen is right, there is hardly any case where Task.Run should be used. That is also because async/await and Task.Run work on different abstraction levels. Unless you are writing a library of some kind async/await should be always enough.

Body:
I'm studying a pretty popular c# proxy server.  In it there is code such as (I'm hiding the proxy server identity on purpose because I feel bad telling tales, if indeed it is wrong).

private void OnConnectionAccepted(TcpClient cl)
{
     ....
     Task.Run(async () =>
            {
               await HandleClientRequest();

            });
     Task.Run(async () =>
        {
            TcpClient cl = await listener.AcceptTcpClientAsync();
            OnConnectionAccepted(cl);
        });
}

Where HandleClientRequest does some async network calls, such as reading the request from the client and repeating it to the server, like you'd expect a proxy to do.
listener.AcceptTcpClientAsync just waits for the next connection to come from a browser.

So it seems the point of the Task.Run is really just to allow AcceptTcpClientAsync to be called while HandleClientRequest is busy.

This seems to go against the recommendations I've been reading, eg. http://blog.stephencleary.com/2013/10/taskrun-etiquette-and-proper-usage.html because Task.Run is wrapping network, not CPU calls.

So how should it work instead, if this is wrong, should it use ThreadPool.QueueUserWorkerItem?

The context by the way would typically be a console app.

Body:
I would propose refactoring this a little bit into one method accepting connections and another one dealing with incoming data. Finally a third one dealing with failed tasks.

public async Task Acceptor(TcpListener listener)
{
  for (;;)
  {
    TcpClient client = await listener.AcceptTcpClientAsync();
    OnConnectionAccepted(client).ContinueWith(task => { errorHandling }, OnlyOnFaulted);
    // some logic which will stop this loop if necessary
  }
}

private async Task OnConnectionAccepted(TcpClient client)
{
  await HandleClientRequest(client);
  // .. further logic
}

"Acceptor" will throw when the listener cannot accept new connections anymore. "errorHandling" will be called when one particular connection cannot be processed. (You can also consider a try catch in OnConnectionAccepted and making it async void - which I personally would not prefer)

Stephen is right, there is hardly any case where Task.Run should be used. That is also because async/await and Task.Run work on different abstraction levels. Unless you are writing a library of some kind async/await should be always enough.


问:
Declaring a Task Property and awaiting it
I'm stuck in something I thought so simple that it drives me out of myself.

I need to declare a Task in some point and run it later, I thought of:

```<code>Task T1 { get; set; }

public async Task CreateAndAwaitAsync()
{
    T1 = new Task(() => {
        // time consuming work like:
        System.Threading.Thread.Sleep(1000);
    }

    await T1;
}
</code>```

Of course the body of the lambda AND the method are just for the sake of this example (as I said I need to run it later), but no matter what, with await T1 I just cannot make it into the lambda! What am I missing?? I feel stupid because I have been using the async-await paradigm for quite the few years already that I didn't even imagine this wouldn't work!

答:
You are not starting the task.

Example:

```<code>public async Task DoSomething()
{
    await Task.Run(() => SomeMethod());
}
</code>```

Body:
I'm stuck in something I thought so simple that it drives me out of myself.

I need to declare a Task in some point and run it later, I thought of:

Task T1 { get; set; }

public async Task CreateAndAwaitAsync()
{
    T1 = new Task(() => {
        // time consuming work like:
        System.Threading.Thread.Sleep(1000);
    }

    await T1;
}

Of course the body of the lambda AND the method are just for the sake of this example (as I said I need to run it later), but no matter what, with await T1 I just cannot make it into the lambda! What am I missing?? I feel stupid because I have been using the async-await paradigm for quite the few years already that I didn't even imagine this wouldn't work!

Body:
You are not starting the task.

Example:

public async Task DoSomething()
{
    await Task.Run(() => SomeMethod());
}


问:
Qualtrics: javascript - text entry
I designed a Qualtrics survey which includes a text entry question. I used a form here and it contained 10 text entry boxes. I want participants to fill in  at least 5 boxes (any 5 boxes out the 10 is okay). I don't think validation is a good idea because there are so many possible cases when you complete at least 5 text boxes out of 10. For every text box, both filling in it and not filling it are okay, as long as the total competed text boxes are no less than 5.

So I tried to do this through javascript. And here is my code but it cannot work. Please tell me how to change it. Thanks!!

```<code>Qualtrics.SurveyEngine.addOnload(function()
{

    //disables the next button on the page
    this.disableNextButton();

    var choicesID=this.getQuestionInfo().Choices.Key

    while (1)
    {
        var t=0
        for (var i=0;i<choicesID.length;i++)
        {
            choicetext=this.getTextValue(choicesID[i])
            if (choicetext.length != 0)
            {
                t=t+1
            }
        }

        if (t<=4) continue;
    }

    this.enableNextButton();
});
</code>```

答:
Sorry to be the bearer of bad news, but you are way off.  Your script has a number of errors, but the biggest problem is that it attempts to check how many have been answered when the question loads, which doesn't do you any good. You would need to keep an on-going count using an event listener.

I suggest an alternative approach that doesn't require any JavaScript or custom validation.  Use a multiple choice, multiple select question with allow text entry / force response turned on for each answer option.  Then just set the minimum number of answers to 5.

Title: Qualtrics: javascript - text entry

Body:
I designed a Qualtrics survey which includes a text entry question. I used a form here and it contained 10 text entry boxes. I want participants to fill in  at least 5 boxes (any 5 boxes out the 10 is okay). I don't think validation is a good idea because there are so many possible cases when you complete at least 5 text boxes out of 10. For every text box, both filling in it and not filling it are okay, as long as the total competed text boxes are no less than 5.

So I tried to do this through javascript. And here is my code but it cannot work. Please tell me how to change it. Thanks!!

Qualtrics.SurveyEngine.addOnload(function()
{

    //disables the next button on the page
    this.disableNextButton();

    var choicesID=this.getQuestionInfo().Choices.Key

    while (1)
    {
        var t=0
        for (var i=0;i<choicesID.length;i++)
        {
            choicetext=this.getTextValue(choicesID[i])
            if (choicetext.length != 0)
            {
                t=t+1
            }
        }

        if (t<=4) continue;
    }

    this.enableNextButton();
});


问:
What are the disadvantages of using Visual Basic 6?
I hear that Visual Basic 6 is not good.

I want to make very generic program. Would Visual Basic 6 suffice?

答:
I have ever listen bad comments about Visual Basic 6 programming, I have written thousands of VB6 lines of code, in the same manner I have written code in object oriented languages (C++, C#, Java). But It seems to me that VB6 is a very good programming language, because it allows you to write powerful-simple applications. VB6 syntax is easier that C/C++ syntax but C#/Java aren't so much difficult that VB6. Also developing enterprise application is such new languages (Java, C#, VB.Net, Rubby) is easier that VB6 because they rely on Frameworks, every body can write C#/Java code that function, but it requires, tricks, good practices and some of imagination to write VB6 strong and rehusable code.

Many developers become quickly frustrating by using VB6 and then are happy programmers using C#/Java. All depends on practices and discipline there is no bad language, each language was designed with some purposes on mind, by selecting the appropriate language, problems solving could be easier.

ContentLicense: CC BY-SA 2.5


问:
Messenger Bot Webview not closing on IOS
I have a webview in my bot.
I have the following JS code to close it:

```<code>complete: function (data) {
                    MessengerExtensions.requestCloseBrowser(function success() {
                        }, function error(err) {
                            window.close()
                        });
                    console.log("post success");
                }
</code>```

The webview is being closed on ANDROID and WEB But NOT on IOS.

Any help would be appreciated.

答: You can search for related bugs here, i searched for a one related to your issue but there is none.</p>

Body:
I have a webview in my bot.
I have the following JS code to close it:

complete: function (data) {
                    MessengerExtensions.requestCloseBrowser(function success() {
                        }, function error(err) {
                            window.close()
                        });
                    console.log("post success");
                }

The webview is being closed on ANDROID and WEB But NOT on IOS.

Any help would be appreciated.


问:
Is there a way of making the following shape by CSS coding
Is there a way of making the following shape by CSS coding, without JavaScript?

答:
You have two choices :
Using SVG to draw your shape (The better way)

Using some simple shapes (circles and square) to get that
For example, a large circle blue, and inside a small circle white: You will get a circle (Else, you can get just one circle and put a blue border)
Then, two square with a 45° rotate, one at the left, and the other to the right

They are many ways like that to get this shape, but you should use svg.


问:
dismissViewControllerAnimated is called but ViewController is not dismissed
I am having a problems with the dismissViewControllerAnimated method not closing down the view.

What is happening in the app here is:

Cell in ItemViewController is selected.

View is pushed to ItemDetailViewControllerand details are sent through a delegate

User selects 'done' and the event is sent via a delegate to be closed in ItemViewController

All of this works except for the View is not dismissed, there are no errors. Can anyone see what is wrong?

```<code>- (void)itemDetailViewControllerDidFinish:(ItemDetailViewController *)controller
{
    NSLog(@"Controller: %@", controller);
    // Returns - Controller: <ItemDetailViewController: 0x6b68b60>

    [self dismissViewControllerAnimated:YES completion:nil];
}
</code>```

答:
Your Situation is -
ItemViewController -> ItemDetailViewController
                      (pushed on navigationController)
Self.dismissViewController(..) dismiss a view controller that is presented over self(in ur case it is ItemViewController). Here, u did not presented any VC over self, instead u pushed a new VC over navigation stack. So, Correct way to dismiss ItemDetailViewController would be

self.navigationController.popViewController(true). please read the description of dismissViewController(....) to get more clarity.

Body:
I am having a problems with the dismissViewControllerAnimated method not closing down the view.

What is happening in the app here is:

Cell in ItemViewController is selected.

View is pushed to ItemDetailViewControllerand details are sent through a delegate

User selects 'done' and the event is sent via a delegate to be closed in ItemViewController

All of this works except for the View is not dismissed, there are no errors. Can anyone see what is wrong?

- (void)itemDetailViewControllerDidFinish:(ItemDetailViewController *)controller
{
    NSLog(@"Controller: %@", controller);
    // Returns - Controller: <ItemDetailViewController: 0x6b68b60>

    [self dismissViewControllerAnimated:YES completion:nil];
}