问:
deleting windows update packages on date using powershell
I have an assignment that wants me to delete all windowsupdatepackages of a specific date.
I came as far as making a script to delete one package at a time using the given KB-numbers. I am stuck now and dont know what do, here's my code:</p>

```<code>function Uninstall-Hotfix {
    [cmdletbinding()]
    param(
        $computerName = $env:computername,
        [string] $hotFixId
    )

    $hotFixes = Get-WmiObject -ComputerName $computerName -Class Win32_QuickFixEngineering | select hotfixid

    $date = Get-Date

    Write-Host "deleted on '$date'"

    if ($hotFixes -match $hotFixId) {
        $hotFixId = $hotFixId.Replace("KB", "")
        Write-Host "found hotfix" + $hotFixId
        Write-Host "Uninstalling the hotflix"
        $uninstallString = "cmd.exe /c      wusa.exe /uninstall /KB:$hotFixId /quiet /norestart"
        ([WMICLASS]"\\$computerName\ROOT\CIMV2:win32_process").Create($uninstallString) | out-null

        while (@(Get-Process wusa -ComputerName $computerName -ErrorAction SilentlyContinue).Count -ne 0) {
            Start-Sleep 3
            Write-Host "Waiting for update removal to finish ..."
        }
        Write-Host "Completed uninstalling of $hotFixId"
    }
    else {
        Write-Host "Given hotfix($hotFixId) not found"
        return
    }
}
</code>```

答:
Instead of using a hotfixId string as a parameter, use a date object as an input parameter.  Then have the function compare the date supplied to the function to the dates of the $hotfixes.  The Win32_QuickFixEngineering class has an InstalledOn property that can be used for this comparison.  If the dates match, then uninstall the hotfix.  The exact details of how to do this are your homework, but if you get stuck on a specific point ask another question.

See the documentation on the Win32_QuickFixEngineering class:

https://msdn.microsoft.com/en-us/library/aa394391(v=vs.85).aspx

Body:
I have an assignment that wants me to delete all windowsupdatepackages of a specific date.
I came as far as making a script to delete one package at a time using the given KB-numbers. I am stuck now and dont know what do, here's my code:

function Uninstall-Hotfix {
    [cmdletbinding()]
    param(
        $computerName = $env:computername,
        [string] $hotFixId
    )

    $hotFixes = Get-WmiObject -ComputerName $computerName -Class Win32_QuickFixEngineering | select hotfixid

    $date = Get-Date

    Write-Host "deleted on '$date'"

    if ($hotFixes -match $hotFixId) {
        $hotFixId = $hotFixId.Replace("KB", "")
        Write-Host "found hotfix" + $hotFixId
        Write-Host "Uninstalling the hotflix"
        $uninstallString = "cmd.exe /c      wusa.exe /uninstall /KB:$hotFixId /quiet /norestart"
        ([WMICLASS]"\\$computerName\ROOT\CIMV2:win32_process").Create($uninstallString) | out-null

        while (@(Get-Process wusa -ComputerName $computerName -ErrorAction SilentlyContinue).Count -ne 0) {
            Start-Sleep 3
            Write-Host "Waiting for update removal to finish ..."
        }
        Write-Host "Completed uninstalling of $hotFixId"
    }
    else {
        Write-Host "Given hotfix($hotFixId) not found"
        return
    }
}


来源: stackexchange

问:
How do I make ordered list using javascript?
Lets say I have this

```<code><ol>
  <li>V1 One</li>
  <li>V1 Two</li>
  <li>V1 Three</li>
  <li>V1 Four</li>
</ol>`
</code>```

I want to make an ordered list using .js instead of using LI tags.
I was thinking the js. code could replace first V1 and call it 1. , replace second V1 and call it two and so on, in other words counting how many V1s there are and replacing them with ordered list.

Or maybe something like this

```<code><ol>
  <li>i++ V1 One</li>
  <li>i++ V1 Two</li>
  <li>i++ V1 Three</li>
  <li>i++ V1 Four</li>
</ol>
</code>```

Where i++ will be increased every time starting from 1

Yes, I know LI provide ordered list!

答:
Perhaps you want to loop through the children of
 and manipulate their innerHTML?

```<code>// Get the <ol> object from the DOM
var chillun = document.getElementById("yourOL").childNodes;

// Loop through the children of the <ol>
for(i=0;i<chillun.length;i++) {
  // Test that the node is indeed an <li>
  if(chillun[i].nodeName=='LI') {
    // Change this line to manipulate the text however you need
    chillun[i].innerHTML = i;
  }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Lets say I have this

V1 One

V1 Two

V1 Three

V1 Four

`

I want to make an ordered list using .js instead of using LI tags.
I was thinking the js. code could replace first V1 and call it 1. , replace second V1 and call it two and so on, in other words counting how many V1s there are and replacing them with ordered list.

Or maybe something like this

i++ V1 One

i++ V1 Two

i++ V1 Three

i++ V1 Four

Where i++ will be increased every time starting from 1

Yes, I know LI provide ordered list!

Body:
Perhaps you want to loop through the children of <ol> and manipulate their innerHTML?

// Get the <ol> object from the DOM
var chillun = document.getElementById("yourOL").childNodes;

// Loop through the children of the <ol>
for(i=0;i<chillun.length;i++) {
  // Test that the node is indeed an <li>
  if(chillun[i].nodeName=='LI') {
    // Change this line to manipulate the text however you need
    chillun[i].innerHTML = i;
  }
}


问:
React Native realtime get data
Im trying to build a real time feed with react native and I have limited request to the api given.

How should I get the data realtime with using a lot of requests.

I used to do that:

```<code>setInterval(() => {this.getfeed()},1000);
</code>```

Thanks

答: You need to check if the API gives you information about the rate limits in its responses headers (e.g. X-RateLimit-Limit, X-RateLimit-Remaining). With this in mind, you can optimize your polling timing. Otherwise you need to figure the API limits yourself and poll accordingly.

ContentLicense: CC BY-SA 3.0

Title: React Native realtime get data

Body:
Im trying to build a real time feed with react native and I have limited request to the api given.

How should I get the data realtime with using a lot of requests.

I used to do that:

setInterval(() => {this.getfeed()},1000);

Thanks


问:
OpenGL ARGB vs RGB and Texture Compression
I have a rendering context with a color depth of 32-bits. I will be using some alpha blending, but not much; so using 24-bit images for most of the textures I need will greatly reduce the memory requirements. My question is, can I use 24-bit RGB textures with a 32-bit rendering context and expect the same performance as a 32-bit ARGB texture? I understand that the internal format is probably neither to begin with, but the target format of the RC is 32-bit ARGB.

Also, I am planning on using some form of texture compression. The platform will be Windows, exclusively. Which would provide the best compression and widest-compatibility? I am also hoping to use 24-bit compressed textures since I won't be using the alpha bits; but the rendering context will remain 32-bits.

答:
It looks like DXT5 should work for you.

Here are the details for GL_EXT_texture_compression_s3tc


问:
Join three tables in mysql but have all data from one table
I have three tables named book (isbn, name, publisher, price, category, quantity), author (auth_id, auth_name) and written_by(isbn,auth_id). I am joining all three tables but in the result, I want all the books even whose author is not entered in the database. I have written the following query

```<code>select b.isbn, b.name, b.publisher, b.price, b.category, b.quantity,
group_concat(a.auth_name) as authors
from book b
left outer join written_by w on b.isbn=w.isbn
left outer join author a on a.auth_id=w.auth_id
group by b.isbn
having  authors like '%';
</code>```

The above query returns only the books who have authors linked to them in the written_by table. I want all the books including the ones with no authors in the database.
How do I join these three tables in such a way?
EDIT:
Sample Data
Book table

    isbn    name      publisher    price    category    quantity
 112345  It        New Lib      $10      Horror      2
 234562  The Hob   Puffin       $20      Fiction     5

Author table

    auth_id    auth_name
 1          Stephen King
 2          Tolkien

Written_by table

    isbn     auth_id
112345    1

Sample output

isbn    name      publisher    price    category    quantity    author
 112345  It        New Lib      $10      Horror      2           Stephen King
 234562  The Hob   Puffin       $20      Fiction     5           null

The above query will return only the book named "It" and will ignore "The Hobbit" since there is no author linked to that book in the written_by table, but I want both the books in the result table with author as null for the book that has no author linked to it

答:
Just remove this:

having  authors like '%'

It should be as following.

```<code>select b.isbn, b.name, b.publisher, b.price, b.category, b.quantity,
group_concat(a.auth_name) as authors
from book b
left outer join written_by w on b.isbn=w.isbn
left outer join author a on a.auth_id=w.auth_id
group by b.isbn;
</code>```

Body:
I have three tables named book (isbn, name, publisher, price, category, quantity), author (auth_id, auth_name) and written_by(isbn,auth_id). I am joining all three tables but in the result, I want all the books even whose author is not entered in the database. I have written the following query

select b.isbn, b.name, b.publisher, b.price, b.category, b.quantity,
group_concat(a.auth_name) as authors
from book b
left outer join written_by w on b.isbn=w.isbn
left outer join author a on a.auth_id=w.auth_id
group by b.isbn
having  authors like '%';

The above query returns only the books who have authors linked to them in the written_by table. I want all the books including the ones with no authors in the database.
How do I join these three tables in such a way?
EDIT:
Sample Data
Book table

    isbn    name      publisher    price    category    quantity
 112345  It        New Lib      $10      Horror      2
 234562  The Hob   Puffin       $20      Fiction     5

Author table

    auth_id    auth_name
 1          Stephen King
 2          Tolkien

Written_by table

    isbn     auth_id
112345    1

Sample output

isbn    name      publisher    price    category    quantity    author
 112345  It        New Lib      $10      Horror      2           Stephen King
 234562  The Hob   Puffin       $20      Fiction     5           null

The above query will return only the book named "It" and will ignore "The Hobbit" since there is no author linked to that book in the written_by table, but I want both the books in the result table with author as null for the book that has no author linked to it

Body:
Just remove this:

having  authors like '%'

It should be as following.

select b.isbn, b.name, b.publisher, b.price, b.category, b.quantity,
group_concat(a.auth_name) as authors
from book b
left outer join written_by w on b.isbn=w.isbn
left outer join author a on a.auth_id=w.auth_id
group by b.isbn;


问:
Difference between defer call a function directly and call it in an anonymous function?
I got some code like this.

```<code>import (
  "fmt"
)

func ShowResult(result []string) {
  fmt.Println(result)
}

func main() {
  result := []string{}
  defer func() {
    ShowResult(result)
  }()
  defer ShowResult(result)
  result = append(result, "test")
}
</code>```

And the result is:

```<code>[]
[test]
</code>```

So could anyone tell me what is difference between calling a function directly and calling it in an anonymous function when defer?

答:
The function arguments are evaluated when it is deferred. From the documentation

Each time a "defer" statement executes, the function value and parameters to the call are evaluated as usual and saved anew but the actual function is not invoked

When your deferred function is a closure, the ShowResult arguments are not evaluated until the closure is executed, which is immediately after the outer function returns and after the result value has been modified.

Body:
I got some code like this.

import (
  "fmt"
)

func ShowResult(result []string) {
  fmt.Println(result)
}

func main() {
  result := []string{}
  defer func() {
    ShowResult(result)
  }()
  defer ShowResult(result)
  result = append(result, "test")
}

And the result is:

[]
[test]

So could anyone tell me what is difference between calling a function directly and calling it in an anonymous function when defer?


问:
Error running android: Gradle project sync failed. Please fix your project and try again
Android Studio (1.2 RC0) keeps telling me
Error running android: Gradle project sync failed. Please fix your project and try again.
How can I find out what the problem is? Unfortunately the solutions from this SO thread did not help.

答:
Just ignore the error and try running the project anyway.
It will fail, but this time you will get a link in the error description. Clicking the link will trigger the automatic update/download of the outdated/missing component.

In my scenario, the project failed to launch two times, each time another API/SDK component being the culprit.

In my case I was just trying to launch a sample project I downloaded, having no clue what API level was being targeted or where to look for this information.

ContentLicense: CC BY-SA 4.0


问:
Overloading on std::function<...>
Given the following code :-

```<code>#include <algorithm>
#include <iostream>
#include <functional>
#include <string>

void func(std::function<void(void)> param)
{
    param();
}

void func(std::function<void(int)> param)
{
    param(5);
}

int main(int argc, char* argv[])
{
    func([] () { std::cout << "void(void)" << std::endl; });
    func([] (int i) { std::cout << "void(int): " << i << std::endl; });

    std::string line;
    std::getline(std::cin, line);
    return 0;
}
</code>```

Compile error from VS2010 :-

```<code>CppTest.cpp(18): error C2668: 'func' : ambiguous call to overloaded function
1>          CppTest.cpp(11): could be 'void func(std::tr1::function<_Fty>)'
1>          with
1>          [
1>              _Fty=void (int)
1>          ]
1>          CppTest.cpp(6): or       'void func(std::tr1::function<_Fty>)'
1>          with
1>          [
1>              _Fty=void (void)
1>          ]
1>          while trying to match the argument list '(`anonymous-namespace'::<lambda0>)'
1>CppTest.cpp(19): error C2668: 'func' : ambiguous call to overloaded function
1>          CppTest.cpp(11): could be 'void func(std::tr1::function<_Fty>)'
1>          with
1>          [
1>              _Fty=void (int)
1>          ]
1>          CppTest.cpp(6): or       'void func(std::tr1::function<_Fty>)'
1>          with
1>          [
1>              _Fty=void (void)
1>          ]
1>          while trying to match the argument list '(`anonymous-namespace'::<lambda1>)'
</code>```

Compile error from g++-4.5

```<code>program2.cpp: In function ‘int main(int, char**)’:
program2.cpp:18:68: error: call of overloaded ‘func(main(int, char**)::<lambda()>)’ is ambiguous
program2.cpp:6:10: note: candidates are: void func(std::function<void()>)
program2.cpp:11:10: note:                 void func(std::function<void(int)>)
program2.cpp:19:79: error: call of overloaded ‘func(main(int, char**)::<lambda(int)>)’ is ambiguous
program2.cpp:6:10: note: candidates are: void func(std::function<void()>)
program2.cpp:11:10: note:                 void func(std::function<void(int)>)
</code>```

So it seems the compiler can't figure out that a lambda [] () -> void can only be assigned to a std::function<void(void)>, and a lambda [] (int) -> void can only be assigned to a std::function<void(int)>. Is this supposed to happen or just a deficiency in the compilers?

答:
Is this supposed to happen or just a deficiency in the compilers?

This is supposed to happen.  std::function has a constructor template that can take an argument of any type.  The compiler can't know until after a constructor template is selected and instantiated that it's going to run into errors, and it has to be able to select an overload of your function before it can do that.

The most straightforward fix is to use a cast or to explicitly construct a std::function object of the correct type:

```<code>func(std::function<void()>([](){}));
func(std::function<void(int)>([](int){}));
</code>```

If you have a compiler that supports the captureless-lambda-to-function-pointer conversion and your lambda doesn't capture anything, you can use raw function pointers:

```<code>void func(void (*param)()) { }
void func(void (*param)(int)) { }
</code>```

(It looks like you are using Visual C++ 2010, which does not support this conversion.  The conversion was not added to the specification until just before Visual Studio 2010 shipped, too late to add it in.)

To explain the problem in a bit more detail, consider the following:

```<code>template <typename T>
struct function {

    template <typename U>
    function(U f) { }
};
</code>```

This is basically what the std::function constructor in question looks like:  You can call it with any argument, even if the argument doesn't make sense and would cause an error somewhere else.  For example, function<int()> f(42); would invoke this constructor template with U = int.

In your specific example, the compiler finds two candidate functions during overload resolution:

```<code>void func(std::function<void(void)>)
void func(std::function<void(int)>)
</code>```

The argument type, some unutterable lambda type name that we will refer to as F, doesn't match either of these exactly, so the compiler starts looking at what conversions it can do to F to try and make it match one of these candidate functions.  When looking for conversions, it finds the aforementioned constructor template.

All the compiler sees at this point is that it can call either function because

it can convert F to std::function<void(void)> using its converting constructor with U = F and

it can convert F to std::function<void(int)> using its converting constructor with U = F.

In your example it is obvious that only one of these will succeed without error, but in the general case that isn't true.  The compiler can't do anything further.  It has to report the ambiguity and fail.  It can't pick one because both conversions are equally good and neither overload is better than the other.

Title: Overloading on std::function<...>

Body:
Given the following code :-

#include <algorithm>
#include <iostream>
#include <functional>
#include <string>

void func(std::function<void(void)> param)
{
    param();
}

void func(std::function<void(int)> param)
{
    param(5);
}

int main(int argc, char* argv[])
{
    func([] () { std::cout << "void(void)" << std::endl; });
    func([] (int i) { std::cout << "void(int): " << i << std::endl; });

    std::string line;
    std::getline(std::cin, line);
    return 0;
}

Compile error from VS2010 :-

CppTest.cpp(18): error C2668: 'func' : ambiguous call to overloaded function
1>          CppTest.cpp(11): could be 'void func(std::tr1::function<_Fty>)'
1>          with
1>          [
1>              _Fty=void (int)
1>          ]
1>          CppTest.cpp(6): or       'void func(std::tr1::function<_Fty>)'
1>          with
1>          [
1>              _Fty=void (void)
1>          ]
1>          while trying to match the argument list '(`anonymous-namespace'::<lambda0>)'
1>CppTest.cpp(19): error C2668: 'func' : ambiguous call to overloaded function
1>          CppTest.cpp(11): could be 'void func(std::tr1::function<_Fty>)'
1>          with
1>          [
1>              _Fty=void (int)
1>          ]
1>          CppTest.cpp(6): or       'void func(std::tr1::function<_Fty>)'
1>          with
1>          [
1>              _Fty=void (void)
1>          ]
1>          while trying to match the argument list '(`anonymous-namespace'::<lambda1>)'

Compile error from g++-4.5

program2.cpp: In function ‘int main(int, char**)’:
program2.cpp:18:68: error: call of overloaded ‘func(main(int, char**)::<lambda()>)’ is ambiguous
program2.cpp:6:10: note: candidates are: void func(std::function<void()>)
program2.cpp:11:10: note:                 void func(std::function<void(int)>)
program2.cpp:19:79: error: call of overloaded ‘func(main(int, char**)::<lambda(int)>)’ is ambiguous
program2.cpp:6:10: note: candidates are: void func(std::function<void()>)
program2.cpp:11:10: note:                 void func(std::function<void(int)>)

So it seems the compiler can't figure out that a lambda [] () -> void can only be assigned to a std::function<void(void)>, and a lambda [] (int) -> void can only be assigned to a std::function<void(int)>. Is this supposed to happen or just a deficiency in the compilers?

Body:
Is this supposed to happen or just a deficiency in the compilers?

This is supposed to happen.  std::function has a constructor template that can take an argument of any type.  The compiler can't know until after a constructor template is selected and instantiated that it's going to run into errors, and it has to be able to select an overload of your function before it can do that.

The most straightforward fix is to use a cast or to explicitly construct a std::function object of the correct type:

func(std::function<void()>([](){}));
func(std::function<void(int)>([](int){}));

If you have a compiler that supports the captureless-lambda-to-function-pointer conversion and your lambda doesn't capture anything, you can use raw function pointers:

void func(void (*param)()) { }
void func(void (*param)(int)) { }

(It looks like you are using Visual C++ 2010, which does not support this conversion.  The conversion was not added to the specification until just before Visual Studio 2010 shipped, too late to add it in.)

To explain the problem in a bit more detail, consider the following:

template <typename T>
struct function {

    template <typename U>
    function(U f) { }
};

This is basically what the std::function constructor in question looks like:  You can call it with any argument, even if the argument doesn't make sense and would cause an error somewhere else.  For example, function<int()> f(42); would invoke this constructor template with U = int.

In your specific example, the compiler finds two candidate functions during overload resolution:

void func(std::function<void(void)>)
void func(std::function<void(int)>)

The argument type, some unutterable lambda type name that we will refer to as F, doesn't match either of these exactly, so the compiler starts looking at what conversions it can do to F to try and make it match one of these candidate functions.  When looking for conversions, it finds the aforementioned constructor template.

All the compiler sees at this point is that it can call either function because

it can convert F to std::function<void(void)> using its converting constructor with U = F and

it can convert F to std::function<void(int)> using its converting constructor with U = F.

In your example it is obvious that only one of these will succeed without error, but in the general case that isn't true.  The compiler can't do anything further.  It has to report the ambiguity and fail.  It can't pick one because both conversions are equally good and neither overload is better than the other.


问:
Display places 2 weeks or older with Ruby on Rails + PostgresQL
This topic has been covered before, but I am new and trying to understand. My app is designed to store the locations of an item and since time matters, I wanted to create a link for a view that would ONLY show places that are two weeks or older. I understand I should create a method in the model similar to what's below, but I am just confused on this code. I have been trying to find material to read to understand better. The homepage shows all the places, but I want a link to also show 2 weeks or older.

Along with help, I would love any good reads to help me understand better. Thanks so much SO!

```<code>def self.recent_places
  Place.select("p.*, COUNT(v.id) AS count").where("post.created_at >= 2.week.ago.utc")
end
</code>```

This is a link to the GitHub.
https://github.com/Mbartlett413/DumpStack

答:
I would recommend using scope over class method though two are mostly the same:

```<code>scope :older_than, ->(time) { where("created_at < ?", time) }
</code>```

Using:

```<code>Post.older_than(2.weeks.ago)
Post.older_than(1.month.ago)
</code>```

Here you go: http://guides.rubyonrails.org/active_record_querying.html#passing-in-arguments

Body:
This topic has been covered before, but I am new and trying to understand. My app is designed to store the locations of an item and since time matters, I wanted to create a link for a view that would ONLY show places that are two weeks or older. I understand I should create a method in the model similar to what's below, but I am just confused on this code. I have been trying to find material to read to understand better. The homepage shows all the places, but I want a link to also show 2 weeks or older.

Along with help, I would love any good reads to help me understand better. Thanks so much SO!

def self.recent_places
  Place.select("p.*, COUNT(v.id) AS count").where("post.created_at >= 2.week.ago.utc")
end

This is a link to the GitHub.
https://github.com/Mbartlett413/DumpStack

Body:
I would recommend using scope over class method though two are mostly the same:

scope :older_than, ->(time) { where("created_at < ?", time) }

Using:

Post.older_than(2.weeks.ago)
Post.older_than(1.month.ago)

Here you go: http://guides.rubyonrails.org/active_record_querying.html#passing-in-arguments


问:
Read value of Hidden Field inside ng-repeat in html table binding
I have a html table and data is binding from angular js.
The structure is like that

```<code><tr ng-repeat="item in List| filter: { MachineType: 'Physical' }">

     <td>{{item.MachineType}}</td>

</tr>
</code>```

I want to pass the filter value dynamically from html hidden field which is set dynamically.

How I read the Html hidden field value here and pass in filter..

Thanks

答:
I'm assuming you want to filter some data based on another dynamic field.

Here is an example of how you would filter based on search query.

```<code><p><input type="hidden" ng-model="test"></p>
<ul>
  <li ng-repeat="x in names | filter : test">
    {{ x }}
  </li>
</ul>
</code>```

You can make custom filters as well. The question you proposed was a little broad so I think this link can help with a myriad of filter queries.

Body:
I have a html table and data is binding from angular js.
The structure is like that

     {{item.MachineType}}

I want to pass the filter value dynamically from html hidden field which is set dynamically.

How I read the Html hidden field value here and pass in filter..

Thanks

Body:
I'm assuming you want to filter some data based on another dynamic field.

Here is an example of how you would filter based on search query.

<p><input type="hidden" ng-model="test"></p>
<ul>
  <li ng-repeat="x in names | filter : test">
    {{ x }}
  </li>
</ul>

You can make custom filters as well. The question you proposed was a little broad so I think this link can help with a myriad of filter queries.


问:
Antipattern error when react child component updating parent
I am getting the error Uncaught RangeError: Maximum call stack size exceeded. How do I eliminate this recursive function in my child (Typewriter) component? I believe I am getting this error because I am calling a function constantly in the ComponentWillUpdate() ? How do I fix this? I thought that by adding in the if condition, this should be fixed?
 Please see the snippet below. Thanks!

class Parent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      typing: true,
    };
    this.interval = null;
    this.handleTyping = this.handleTyping.bind(this);
  }

  handleTyping(doneTyping) {
    if (doneTyping) {
      this.setState({ typing: !this.state.typing });
    }
  }

  render() {
    return (

{this.state.typing ? "TRUE" : "FALSE"}

        <Typewriter text={"typewriter_testing"} typeSpeed={50} handleTyping={this.handleTyping}/>

    );
  }
}

class Typewriter extends React.Component {
  constructor() {
    super();
    this.state = {
      finalText: '',
      doneTyping: false,
    }
    this.typeWriter = this.typeWriter.bind(this);
  }

  typeWriter(text, n) {
    if (n < (text.length)) {
      if (n + 1 == (text.length)) {
        let j = text.substring(0, n+1);
        this.setState({ finalText: j, doneTyping: !this.state.doneTyping });
        n++;
      }
      else {
        let k = text.substring(0, n+1) + '|';
        this.setState({ finalText: k });
        n++;
      }
      setTimeout( () => { this.typeWriter(text, n) }, this.props.typeSpeed );
    }
  }

  componentDidMount() {
    this.typeWriter(this.props.text, 0);
  }

  componentWillUpdate(nextProps, nextState) {
    if (nextState.doneTyping) {
      nextProps.handleTyping(nextState.doneTyping);
    }
  }

  render() {
    return (

        { this.state.finalText }

    );
  }
}

ReactDOM.render(<Parent />, app);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="app"></div></code>```

答:
this component need to run nextProps.handleTyping(nextState.doneTyping); on exact time when doneTyping is changed only.
add another condition in componentWillUpdate and check it out:

```<code>componentWillUpdate(nextProps, nextState) {
    if (nextState.doneTyping && (nextState.doneTyping !== this.state.doneTyping)) {
      nextProps.handleTyping(nextState.doneTyping);
    }
  }
</code>```

Code:

class Parent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      typing: true,
    };
    this.interval = null;
    this.handleTyping = this.handleTyping.bind(this);
  }

  handleTyping(doneTyping) {
    if (doneTyping) {
      this.setState({ typing: !this.state.typing });
    }
  }

  render() {
    return (

{this.state.typing ? "TRUE" : "FALSE"}

        <Typewriter text={"typewriter_testing"} typeSpeed={50} handleTyping={this.handleTyping}/>

    );
  }
}

class Typewriter extends React.Component {
  constructor() {
    super();
    this.state = {
      finalText: '',
      doneTyping: false,
    }
    this.typeWriter = this.typeWriter.bind(this);
  }

  typeWriter(text, n) {
    if (n < (text.length)) {
      if (n + 1 == (text.length)) {
        let j = text.substring(0, n+1);
        this.setState({ finalText: j, doneTyping: !this.state.doneTyping });
        n++;
      }
      else {
        let k = text.substring(0, n+1) + '|';
        this.setState({ finalText: k });
        n++;
      }
      setTimeout( () => { this.typeWriter(text, n) }, this.props.typeSpeed );
    }
  }

  componentDidMount() {
    this.typeWriter(this.props.text, 0);
  }

  componentWillUpdate(nextProps, nextState) {
    if (nextState.doneTyping && (nextState.doneTyping !== this.state.doneTyping)) {
      nextProps.handleTyping(nextState.doneTyping);
    }
  }

  render() {
    return (

        { this.state.finalText }

    );
  }
}

ReactDOM.render(<Parent />, app);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="app"></div></code>```

Body:
this component need to run nextProps.handleTyping(nextState.doneTyping); on exact time when doneTyping is changed only.
add another condition in componentWillUpdate and check it out:

componentWillUpdate(nextProps, nextState) {
    if (nextState.doneTyping && (nextState.doneTyping !== this.state.doneTyping)) {
      nextProps.handleTyping(nextState.doneTyping);
    }
  }

Code:

class Parent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      typing: true,
    };
    this.interval = null;
    this.handleTyping = this.handleTyping.bind(this);
  }

  handleTyping(doneTyping) {
    if (doneTyping) {
      this.setState({ typing: !this.state.typing });
    }
  }

  render() {
    return (
      <div>
        <h3>{this.state.typing ? "TRUE" : "FALSE"}</h3>
        <Typewriter text={"typewriter_testing"} typeSpeed={50} handleTyping={this.handleTyping}/>
      </div>
    );
  }
}

class Typewriter extends React.Component {
  constructor() {
    super();
    this.state = {
      finalText: '',
      doneTyping: false,
    }
    this.typeWriter = this.typeWriter.bind(this);
  }

  typeWriter(text, n) {
    if (n < (text.length)) {
      if (n + 1 == (text.length)) {
        let j = text.substring(0, n+1);
        this.setState({ finalText: j, doneTyping: !this.state.doneTyping });
        n++;
      }
      else {
        let k = text.substring(0, n+1) + '|';
        this.setState({ finalText: k });
        n++;
      }
      setTimeout( () => { this.typeWriter(text, n) }, this.props.typeSpeed );
    }
  }

  componentDidMount() {
    this.typeWriter(this.props.text, 0);
  }

  componentWillUpdate(nextProps, nextState) {
    if (nextState.doneTyping && (nextState.doneTyping !== this.state.doneTyping)) {
      nextProps.handleTyping(nextState.doneTyping);
    }
  }

  render() {
    return (
      <div>
        { this.state.finalText }
      </div>
    );
  }
}

ReactDOM.render(<Parent />, app);

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="app"></div>


问:
SQL Server: Why CLR Function is faster than CLR Stored Procedure?
I came across the debate of CLR function may be faster than T-SQL scalar function for some people or the other way round for another group of people.

And I also read about comparing CLR function with CLR stored procedure and I learn that CLR function is faster than CLR stored procedure. Can someone explain to me, in technical, why a CLR function is faster?

I'm new to CLR and currently developing a CLR stored procedure in C# to be used in SQL Server. The CLR execution basically consume 0 seconds even after many tried. I haven't tried implementing into an actual T-SQL stored procedure yet but I need to do that to produce the expected result. So I want to understand the execution part and determine which method to use

答:
I don't think that a SQLCLR Scalar User-Defined Function (UDF) is necessarily faster than a SQLCLR Stored Procedure. I think it would depend on what the operation is and how it is being used. One advantage that some SQLCLR UDFs have the ability to make use of is, if there is no data access (and sometimes, though not always, if IsDeterministic is set to true), then they can participate in parallel plans. This is not something that T-SQL UDFs can do. So, for operations that can be done in a UDF (not all can be, some require being done in a Stored Procedure), that do not do any data access, and that are being called repetitively in a single query, this can provide a performance improvement over Stored Procedures, which cannot be called in set-based fashion.

For more information on working with SQLCLR in general, please see the series of articles I am writing on the topic on SQL Server Central: Stairway to SQLCLR

P.S. If you are going to state that you "came across a debate" and then "read about" some topic, you really should provide the links to those discussions and articles / posts, assuming that they are not in private forums or on a corporate intranet. It really helps to have the context of what is being said, especially to help ensure that you weren't simply misreading / misunderstanding what you have found (and yes, that has happened).


问:
Can't launch application through Android Studio (logcat [DEAD])
For the last two days the app I'm working on is showing up as [DEAD] in logcat and when I try to launch the app through the run button in Android Studio all seems fine, except the app never start and leaves no error message in Android Studio, except for [DEAD]. Any idea what this is?

Update:
I have been able to remove the [DEAD] thing from the logcat by:

Removing the app from the device

Restarting the device (Should not have been this because it was just started befor it happened, but just in case)

Invalidate caches and restart in Android Studio

Re-run the app from the toolbar in Android Studio

This might help to get you going again, but my question stays.

What is this?

Why does it happen?

And whats the correct way of solving it?

答:
My solution: replace the debugging equipment.
I've had this problem recently, and I've been struggling with it for a long time.
I use as 3.0, the computer i7+16G+ SSD, the configuration will not be a problem.
During the period, I tried to restart as, the computer, have no effect.The online method tried some, but it didn't work.
I always thought it was the as problem, and then I was able to debug the machine.
The debug phone is a 7.0 system. After root, it enters the adb shell and finds that the command line does not respond. The phone shell has been stuck and the card dies and the card dies.
The as run is going to be directly stuck there.
The key as interface is not clickable, and the bug should be given to as.</p>


问:
How to get the current logged in user ID in ASP.NET Core?
I've done this before with MVC5 using User.Identity.GetUserId() but that doesn't seem to work here.
The User.Identity doesn't have the GetUserId() method.

I am using Microsoft.AspNet.Identity.

答:
you have to import Microsoft.AspNetCore.Identity & System.Security.Claims</p>

```<code>// to get current user ID
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);

// to get current user info
var user = await _userManager.FindByIdAsync(userId);
</code>```

Body:
you have to import Microsoft.AspNetCore.Identity & System.Security.Claims

// to get current user ID
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);

// to get current user info
var user = await _userManager.FindByIdAsync(userId);


问:
Javascript uncaught type error; property can't be read, undefined variable
I am trying to fetch the value from text input in HTML to a variable in javascript.
An uncaught type error had appeared.
The following are my HTML code:

```<code> <form name="purchaseform" id="formma">
 KJW M700 <br>
 <input name='buyM700' type='text' id='1234'>
 <input name='caller' type='button' value='click here' onClick='call()'>
 </form>
</code>```

The following are my Javascript code:

```<code>var m700 =  document.purchaseform.buyM700.value;
function call() {
  confirm (m700);
};
</code>```

Thank you for helping me in advance.

答:
You can access the form via the forms HTMLCollection of the document</p>

```<code>var m700 =  document.forms.purchaseform.buyM700.value;
function call() {
  confirm (m700);
};
</code>```

Body:
I am trying to fetch the value from text input in HTML to a variable in javascript.
An uncaught type error had appeared.
The following are my HTML code:

 <form name="purchaseform" id="formma">
 KJW M700

 <input name='buyM700' type='text' id='1234'>
 <input name='caller' type='button' value='click here' onClick='call()'>
 </form>

The following are my Javascript code:

var m700 =  document.purchaseform.buyM700.value;
function call() {
  confirm (m700);
};

Thank you for helping me in advance.

Body:
You can access the form via the forms HTMLCollection of the document

var m700 =  document.forms.purchaseform.buyM700.value;
function call() {
  confirm (m700);
};


问:
how can I get just a single div to refresh on submit as apposed to the entire page?
I am working  with a dynamically  generated page written in PHP. The divon the page contain contents listed  FancyBox  links that open editing screens.
Once editing is complete and the user closes the FancyBox modal the changes
need to be reflected on the parent page.

Right, so I was able to find a solution that refreshes the entire page on submit
using

```<code>  parent.location.reload (true);
</code>```

to refresh the entire parent page. But, that causes a browser prompt
that is confusing to users and a bit of over kill as I really only
need the information edited to refresh.

how can I get just a single div to refresh on submit  as
apposed to the entire page??????

答:
```<code>jQuery('#id_of_div').load('/url/to/updated/html');
</code>```

See jQuery docs for load()

Body:
I am working  with a dynamically  generated page written in PHP. The divon the page contain contents listed  FancyBox  links that open editing screens.
Once editing is complete and the user closes the FancyBox modal the changes
need to be reflected on the parent page.

Right, so I was able to find a solution that refreshes the entire page on submit
using

  parent.location.reload (true);

to refresh the entire parent page. But, that causes a browser prompt
that is confusing to users and a bit of over kill as I really only
need the information edited to refresh.

how can I get just a single div to refresh on submit  as
apposed to the entire page??????

Body:
jQuery('#id_of_div').load('/url/to/updated/html');

See jQuery docs for load()


问:
visual studio 2017 remote debugging azure api app: "The breakpoint will not currently be hit. No symbols have been loaded for this document."
I'm trying to remote debug an asp.net core 1.1 api app (targeting .net framework 4.5.2) that's running on Azure.

I attach the debugger via Server Explorer. The debugger attaches to the correct process. But any breakpoint I set has the message "The breakpoint will not currently be hit. No symbols have been loaded for this document."

All answers I've seen to such a problem assume that the modules window shows all modules loaded by my project, but in my case the modules window is empty!

I'm on VS2017 15.4.

If I remember correctly, I was previously able to remote debug the same project with version 15.2. The problem started occurring when I updated to 15.3 but I didn't pursue it at the time.

答:
I submitted the problem on the MS forums:  Can't remote debug Azure API app

and now I have received an official reply that it is indeed a bug in VS, and a fix will be available in the pending release (15.6).

They also suggested a workaround, which I tried and indeed worked:  Manually Attach a Debugger to Azure Web Apps

Which involves:

Going to the web app Application settings in the Azure portal, and making sure that Remote debugging is enabled,

In the VS menu: Debug > Attach to Process..., entering the web app url with the debugging port, e.g.:

```<code>myapp.azurewebsites.net:4022
</code>```

Then in the credentials that appears, entering the username & password that are available in the app's Publish Profile, which can be downloaded from the portal. If the username is $myapp, it should be entered like this:

```<code>$myappp\$myapp
</code>```

Then choosing Managed(v4.6, v4.5, v4.0) code and then the name of the Core app.

Actually, I had found and unsuccessfully tried similar approaches before. The key for me was step 3. The others had suggested entering the username as .\$myapp, or myapp\$myapp. So make sure to enter it as written above.

BTW, seeing that the above blog post is from almost 2 years ago (Feb 2016), whereas the problem I'm experiencing was introduced only a few months ago, it seems to be a cure-all, and it is therefore worthwhile, for anyone who has to deal with remote debugging Azure apps, to save this information for future reference.

UPDATE:
After updating VS 2017 to version 15.5.2 the problem seems to have been fixed.

Body:
I submitted the problem on the MS forums:  Can't remote debug Azure API app

and now I have received an official reply that it is indeed a bug in VS, and a fix will be available in the pending release (15.6).

They also suggested a workaround, which I tried and indeed worked:  Manually Attach a Debugger to Azure Web Apps

Which involves:

Going to the web app Application settings in the Azure portal, and making sure that Remote debugging is enabled,

In the VS menu: Debug > Attach to Process..., entering the web app url with the debugging port, e.g.:

myapp.azurewebsites.net:4022

Then in the credentials that appears, entering the username & password that are available in the app's Publish Profile, which can be downloaded from the portal. If the username is $myapp, it should be entered like this:

$myappp\$myapp

Then choosing Managed(v4.6, v4.5, v4.0) code and then the name of the Core app.

Actually, I had found and unsuccessfully tried similar approaches before. The key for me was step 3. The others had suggested entering the username as .\$myapp, or myapp\$myapp. So make sure to enter it as written above.

BTW, seeing that the above blog post is from almost 2 years ago (Feb 2016), whereas the problem I'm experiencing was introduced only a few months ago, it seems to be a cure-all, and it is therefore worthwhile, for anyone who has to deal with remote debugging Azure apps, to save this information for future reference.

UPDATE:
After updating VS 2017 to version 15.5.2 the problem seems to have been fixed.


问:
Ansible Playbook to copy a file to a remote host - Permission denied - How to send credentials?
I'm trying to copy a file, local, to a remote host using a simple Ansible playbook:

```<code>    ---
   - name: Transfer file to remote host device
     hosts: remotehost
     connection: local

     tasks:
          - name: Send file to remote host
            copy:
              src: /home/plc/cert.pfx
              dest: /root/certificates
</code>```

But I'm getting permission denied. What's the User/Password that's being used when trying to send the file to the remote host? Can I specify it?

Error I'm getting as follow:

fatal: [remotehost]: FAILED! => {"failed": true, "msg": "Failed to get information on remote file (/root/certificates): Permission denied"}

答:
Given the destination path is /root/certificates, you must either:

connect as root (not recommended), or

use privilege escalation with become: true.

Your connecting account must be configured to be able to do so — all that is well documented, so learn and apply.

Besides, you have an unnecessary connection: local in your play definition which prevents from connecting to the target server. Remove it.

Considering that, maybe you should start with Getting Started chapter of Ansible documentation.

Body:
I'm trying to copy a file, local, to a remote host using a simple Ansible playbook:

    ---
   - name: Transfer file to remote host device
     hosts: remotehost
     connection: local

     tasks:
          - name: Send file to remote host
            copy:
              src: /home/plc/cert.pfx
              dest: /root/certificates

But I'm getting permission denied. What's the User/Password that's being used when trying to send the file to the remote host? Can I specify it?

Error I'm getting as follow:

fatal: [remotehost]: FAILED! => {"failed": true, "msg": "Failed to get information on remote file (/root/certificates): Permission denied"}


问:
I am trying to execute this facebook api but it is not working....can you suggest any corrections
```<code>function getalbum(){
    FB.api(
        '/me',
        'GET',
        {"fields":"albums{name,link}"},
        function(response) {
            var album=response.data[1]
            document.getElementById("photo").innerHTML=album.link;
        }
  )};
</code>```

Whenever I am trying to print the album link it shows error cannot read the property '1' of unknown

答:
From the facebook documentation:

So your code should be:

```<code>function getalbum(){
   FB.api(
       '/me',
       'GET',
       {"fields":"albums{name,link}"},
       function(response) {
           if (response.error) {
              console.log(error);
           } else {
              if (response.albums.length > 0) {
                  var album=response.albums[0]
                  document.getElementById("photo").innerHTML=album.link;
              }
           }
       }
)};
</code>```

Note that your albums property is directly accessible on the response object.

You need to use the data of the response object only when the results are paginated, as explained in the documentation

Body:
function getalbum(){
    FB.api(
        '/me',
        'GET',
        {"fields":"albums{name,link}"},
        function(response) {
            var album=response.data[1]
            document.getElementById("photo").innerHTML=album.link;
        }
  )};

Whenever I am trying to print the album link it shows error cannot read the property '1' of unknown

Body:
From the facebook documentation:

So your code should be:

function getalbum(){
   FB.api(
       '/me',
       'GET',
       {"fields":"albums{name,link}"},
       function(response) {
           if (response.error) {
              console.log(error);
           } else {
              if (response.albums.length > 0) {
                  var album=response.albums[0]
                  document.getElementById("photo").innerHTML=album.link;
              }
           }
       }
)};

Note that your albums property is directly accessible on the response object.

You need to use the data of the response object only when the results are paginated, as explained in the documentation


问:
What is it called when JS is used to show only a certain part of a png?
Let's say you have a png and it contains all of the icons that are to be used on one page, what is the process of using JS to select and display on a certain icon in that image? I've always seen it being done, but it seems to evade me what it is, and how to do it.

答: Sprites, but you would probably use CSS rather than Javascript.</p>


问:
Angular HttpClient request with retry and delay is sending an extra request then canceling it
Am trying to use the Angulars HttpClient service to make a request with a number of tries and a delay in between. The code works, but i noticed in the devTools network tap that in the end an extra request is sent and canceled. What am I doing wrong here is the code:

```<code>return this.http.post<LoginSuccessPayload>('/api/auth/signin', payload).pipe(
  retryWhen(errors => {
    return errors.pipe(
      mergeMap((er: any) => {
        if (er.status === 504 || er.status === 503) {
          return of(er.status).pipe(delay(1000));
        }
        return _throw({message: er.error.message || 'Notification.Core.loginError'});
      }),
      take(3),
      concat(_throw({message: 'Notification.Core.networkError'}))
    );
  })
);
</code>```

Here is an Image of Firefox and Chrome network tab, there should be three request but its making four and canceling the last one

答:
Here is how I solved it. now three tries with a second delay per request and no extra canceled request</p>

```<code> return this.http.post<LoginSuccessPayload>('/api/auth/signin', payload).pipe(
  retryWhen(errors => errors.pipe(
    switchMap((error) => {
      if (error.status === 504 || error.status === 503) {
        return of(error.status);
      }
      return _throw({message: error.error.message || 'Notification.Core.loginError'});
    }),
    scan(acc => acc + 1, 0),
    takeWhile(acc => acc < 3),
    delay(1000),
    concat(_throw({message: 'Notification.Core.networkError'}))
  ))
);
</code>```

Body:
Am trying to use the Angulars HttpClient service to make a request with a number of tries and a delay in between. The code works, but i noticed in the devTools network tap that in the end an extra request is sent and canceled. What am I doing wrong here is the code:

return this.http.post<LoginSuccessPayload>('/api/auth/signin', payload).pipe(
  retryWhen(errors => {
    return errors.pipe(
      mergeMap((er: any) => {
        if (er.status === 504 || er.status === 503) {
          return of(er.status).pipe(delay(1000));
        }
        return _throw({message: er.error.message || 'Notification.Core.loginError'});
      }),
      take(3),
      concat(_throw({message: 'Notification.Core.networkError'}))
    );
  })
);

Here is an Image of Firefox and Chrome network tab, there should be three request but its making four and canceling the last one

Body:
Here is how I solved it. now three tries with a second delay per request and no extra canceled request

 return this.http.post<LoginSuccessPayload>('/api/auth/signin', payload).pipe(
  retryWhen(errors => errors.pipe(
    switchMap((error) => {
      if (error.status === 504 || error.status === 503) {
        return of(error.status);
      }
      return _throw({message: error.error.message || 'Notification.Core.loginError'});
    }),
    scan(acc => acc + 1, 0),
    takeWhile(acc => acc < 3),
    delay(1000),
    concat(_throw({message: 'Notification.Core.networkError'}))
  ))
);


问:
Avoiding Repetitive View Code in ASP.NET MVC
This is for an ASP.NET MVC 4 application in a Razor view. I am passing a model to a partial view and am trying to iterate through a given list of properties contained in the model to be displayed as a table.

Given something like List<string> propertyNames, in this table, I would like to output the DisplayNameFor and the value of the property in a structure like so:

```<code><tr>
    <th>@Html.DisplayNameFor(Model.property)</th>
    <td>@Model.property</td>
</tr>
</code>```

I'll have to do this a few times in the partial because different properties correspond to different div elements in the partial where different tables will be inserted so I've created a helper and this is where I get hung up. First, the only way I know how to do this is reflection, and I have read that reflection is expensive especially for just doing one property at a time. Also, using this method, I can't get @Html.DisplayNameFor to work correctly because, using reflection, I don't quite know the syntax:

```<code>@helper IterateDetailPropertyNames(List<string> propertyNames) {
    foreach (var property in propertyNames)
    {
        <tr>
            <th>
                @Html.DisplayNameFor(m => m.GetType().GetProperty(property).GetValue(Model, null));
                @*Error: Templates can be used only with field access, property access...*@
            </th>
            <td>
                @Model.GetType().GetProperty(property).GetValue(Model, null)
            </td>
        </tr>
    }
}
</code>```

How can I make this work and improve this?

答:
A models ModelMetadata gives you the data you need to generate your table. It contains the model value in additional to properties such as the DisplayName, DisplayFormatString, NullDisplayText etc that are determined from annotations applied to your properties.

For more information of ModelMetadata, refer the documentation and ASP.NET MVC 2 Templates, Part 2: ModelMetadata.

To generate your table, you could write the following HtmlHelper extension method

```<code>public static class TableHelper
{

    public static MvcHtmlString DisplayTableFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression)
    {
        // Get the ModelMetadata for the model
        ModelMetadata metaData = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
        StringBuilder html = new StringBuilder();
        // Loop through the ModelMetadata of each property in the model
        foreach (ModelMetadata property in metaData.Properties)
        {
            var x = metaData.DisplayFormatString;
            string label = property.DisplayName;
            string value = null;
            if (property.Model == null)
            {
                value = metaData.NullDisplayText;
            }
            else if (metaData.DisplayFormatString != null)
            {
                value = string.Format(metaData.DisplayFormatString, property.Model);
            }
            else
            {
                value = property.Model.ToString();
            }
            TagBuilder labelCell = new TagBuilder("td");
            labelCell.InnerHtml = label;
            TagBuilder valueCell = new TagBuilder("td");
            valueCell.InnerHtml = value;
            StringBuilder innerHtml = new StringBuilder();
            innerHtml.Append(labelCell.ToString());
            innerHtml.Append(valueCell.ToString());
            TagBuilder row = new TagBuilder("tr");
            row.InnerHtml = innerHtml.ToString();
            html.Append(row.ToString());
        }
        TagBuilder table = new TagBuilder("table");
        table.InnerHtml = html.ToString();
        return new MvcHtmlString(table.ToString());
    }
}
</code>```

and in the view

```<code>@using YourAssembly.TableHelper
....
@Html.DisplayTableFor(m => m)
</code>```

You can also include the assembly in your web.config file so that the @using statement is not required in the view

As s side note,
 elements are for tabular data and should not be used for layout. Instead consider using styled
 elements

Body:
This is for an ASP.NET MVC 4 application in a Razor view. I am passing a model to a partial view and am trying to iterate through a given list of properties contained in the model to be displayed as a table.

Given something like List<string> propertyNames, in this table, I would like to output the DisplayNameFor and the value of the property in a structure like so:

    @Html.DisplayNameFor(Model.property)
    @Model.property

I'll have to do this a few times in the partial because different properties correspond to different div elements in the partial where different tables will be inserted so I've created a helper and this is where I get hung up. First, the only way I know how to do this is reflection, and I have read that reflection is expensive especially for just doing one property at a time. Also, using this method, I can't get @Html.DisplayNameFor to work correctly because, using reflection, I don't quite know the syntax:

@helper IterateDetailPropertyNames(List<string> propertyNames) {
    foreach (var property in propertyNames)
    {

                @Html.DisplayNameFor(m => m.GetType().GetProperty(property).GetValue(Model, null));
                @*Error: Templates can be used only with field access, property access...*@

                @Model.GetType().GetProperty(property).GetValue(Model, null)

    }
}

How can I make this work and improve this?

Body:
A models ModelMetadata gives you the data you need to generate your table. It contains the model value in additional to properties such as the DisplayName, DisplayFormatString, NullDisplayText etc that are determined from annotations applied to your properties.

For more information of ModelMetadata, refer the documentation and ASP.NET MVC 2 Templates, Part 2: ModelMetadata.

To generate your table, you could write the following HtmlHelper extension method

public static class TableHelper
{

    public static MvcHtmlString DisplayTableFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression)
    {
        // Get the ModelMetadata for the model
        ModelMetadata metaData = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
        StringBuilder html = new StringBuilder();
        // Loop through the ModelMetadata of each property in the model
        foreach (ModelMetadata property in metaData.Properties)
        {
            var x = metaData.DisplayFormatString;
            string label = property.DisplayName;
            string value = null;
            if (property.Model == null)
            {
                value = metaData.NullDisplayText;
            }
            else if (metaData.DisplayFormatString != null)
            {
                value = string.Format(metaData.DisplayFormatString, property.Model);
            }
            else
            {
                value = property.Model.ToString();
            }
            TagBuilder labelCell = new TagBuilder("td");
            labelCell.InnerHtml = label;
            TagBuilder valueCell = new TagBuilder("td");
            valueCell.InnerHtml = value;
            StringBuilder innerHtml = new StringBuilder();
            innerHtml.Append(labelCell.ToString());
            innerHtml.Append(valueCell.ToString());
            TagBuilder row = new TagBuilder("tr");
            row.InnerHtml = innerHtml.ToString();
            html.Append(row.ToString());
        }
        TagBuilder table = new TagBuilder("table");
        table.InnerHtml = html.ToString();
        return new MvcHtmlString(table.ToString());
    }
}

and in the view

@using YourAssembly.TableHelper
....
@Html.DisplayTableFor(m => m)

You can also include the assembly in your web.config file so that the @using statement is not required in the view

As s side note, <table> elements are for tabular data and should not be used for layout. Instead consider using styled <div> elements


问:
ASP.Net Core 2.0 MVC dynamic model updating
I'm trying to build a dynamic view, where I can pass a list of properties that need to be filled in by the user.

The collection of properties is dynamic, so I can't build the view that displays specific properties.

I've been able to display the property names and their initial values, and the user can change the values on the screen, but those updated values don't make it to the controller action that would update the model.

I've tried using a dynamic model, as well as a list of key/value pairs.

I'm thinking that it has something to do with the over-posting protection.  Since the properties are dynamic, I can't list them in the Bind attribute in the update action.

Here's the controller action methods:

```<code>public IActionResult Test()
{
    dynamic testObj = new ExpandoObject();
    testObj.IntProperty = 100;
    testObj.StringProperty = "A String Value";
    return View(testObj);
}

[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Test(ExpandoObject model)
{
    return Ok();
}
</code>```

Here's the view:

```<code>@model dynamic

@{
    ViewData["Title"] = "Test";
}

<form asp-action="Test" method="post">
    <div class="form-horizontal">
        @foreach (var propertyName in ((System.Collections.Generic.IDictionary<string, object>)Model).Keys)
        {
            <div class="form-group">
                <label class="col-md-2 control-label">@propertyName</label>
                <div class="col-md-10">
                    @Html.TextBox(propertyName, ((System.Collections.Generic.IDictionary<string, object>)Model)[propertyName])
                </div>
            </div>
        }
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Save" class="btn btn-default" />
            </div>
        </div>
    </div>
</form>
</code>```

This is a new application, and I'm doing code-first - so the model can be changed somewhat.  All I really need to do is to be able to have different properties that can be updated.

Thanks in advance.

答:
I recommend that you do not rely on the IModelBinder for this purpose at all and why I recommend this is because the form data that is passed between the controller and view is dynamic in terms of structure. A better, yet more troublesome, solution would be to get the form data directly out of the HttpContext.Request.Form. This type has an indexer which allows you to access the posted values by their names. For example

```<code>var name = HttpContext.Request.Form["name"].FirstOrDefault();
</code>```

The .FirstOrDefault() (or SingleOrDefault(), this throws an exception when finding more than a value that meets a condition in a collection) is called assuming that there would be a single value (or a single value that meets a  condition) for the "Name" input. However, when you have an array of those, you can get the values either in a foreach loop, or using linq methods, or directly by an index. For example:

```<code> var name = HttpContext.Request.Form["name"].FirstOrDefault(x=> x.ToString().StartsWith("x"));
 var name = HttpContext.Request.Form["name"][0];
</code>```

Body:
I'm trying to build a dynamic view, where I can pass a list of properties that need to be filled in by the user.

The collection of properties is dynamic, so I can't build the view that displays specific properties.

I've been able to display the property names and their initial values, and the user can change the values on the screen, but those updated values don't make it to the controller action that would update the model.

I've tried using a dynamic model, as well as a list of key/value pairs.

I'm thinking that it has something to do with the over-posting protection.  Since the properties are dynamic, I can't list them in the Bind attribute in the update action.

Here's the controller action methods:

public IActionResult Test()
{
    dynamic testObj = new ExpandoObject();
    testObj.IntProperty = 100;
    testObj.StringProperty = "A String Value";
    return View(testObj);
}

[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Test(ExpandoObject model)
{
    return Ok();
}

Here's the view:

@model dynamic

@{
    ViewData["Title"] = "Test";
}

<form asp-action="Test" method="post">

        @foreach (var propertyName in ((System.Collections.Generic.IDictionary<string, object>)Model).Keys)
        {

                @propertyName

                    @Html.TextBox(propertyName, ((System.Collections.Generic.IDictionary<string, object>)Model)[propertyName])

        }

                <input type="submit" value="Save" class="btn btn-default" />

</form>

This is a new application, and I'm doing code-first - so the model can be changed somewhat.  All I really need to do is to be able to have different properties that can be updated.

Thanks in advance.

Body:
I recommend that you do not rely on the IModelBinder for this purpose at all and why I recommend this is because the form data that is passed between the controller and view is dynamic in terms of structure. A better, yet more troublesome, solution would be to get the form data directly out of the HttpContext.Request.Form. This type has an indexer which allows you to access the posted values by their names. For example

var name = HttpContext.Request.Form["name"].FirstOrDefault();

The .FirstOrDefault() (or SingleOrDefault(), this throws an exception when finding more than a value that meets a condition in a collection) is called assuming that there would be a single value (or a single value that meets a  condition) for the "Name" input. However, when you have an array of those, you can get the values either in a foreach loop, or using linq methods, or directly by an index. For example:

 var name = HttpContext.Request.Form["name"].FirstOrDefault(x=> x.ToString().StartsWith("x"));
 var name = HttpContext.Request.Form["name"][0];


答:
It's done with CSS, not JavaScript, and it's called sprites.

http://css-tricks.com/css-sprites/

Title: What is it called when JS is used to show only a certain part of a png?

Body: Let's say you have a png and it contains all of the icons that are to be used on one page, what is the process of using JS to select and display on a certain icon in that image? I've always seen it being done, but it seems to evade me what it is, and how to do it.


问:
android studio 3 emulator, how to enable microphone input for speech recognition
I am unsure how to enable microphone input in my emulator.  It is greyed out.  Is there some code that I can write that will let the microphone detect speech in the android studio (3.0) emulator?

My app works on a real phone, but I need to simulate other devices too. I can't buy all of the real devices.  Thank you!

答: You can use Genymotion as an alternative. It is no longer free for personal use and has builtin webcam and microphone set up for you. Most of the android developers use this as it is faster than AVD. There is also a plugin for android studio.</p>


问:
gdb dump memory as specific type
I'm trying to debug a memory problem in my application.

I want to dump a memory region to a file as unsigned int

This is the print command of what I want to dump

p/x *((unsigned int*)0x800@8

Can I dump the memory to a file and keep it as unsigned int and not hex\binary?

答:
Can I dump the memory to a file and keep it as unsigned int and not hex\binary?

It's hard to tell precisely what you want to achieve.

If you simply want to save the output from p/x *((unsigned int*)0x800@8 in a file, you could do this:

```<code>(gdb) set logging on
(gdb) p/x *((unsigned int*)0x800@8
(gdb) set logging off
</code>```

Title: gdb dump memory as specific type

Body:
Can I dump the memory to a file and keep it as unsigned int and not hex\binary?

It's hard to tell precisely what you want to achieve.

If you simply want to save the output from p/x *((unsigned int*)0x800@8 in a file, you could do this:

(gdb) set logging on
(gdb) p/x *((unsigned int*)0x800@8
(gdb) set logging off


问:
Rterm.,exe and tcl86.dll
Godd morning!

On friday while I was doing some tests using parallel processing (with doParallel, compiler and foreach packages) suddenly I began to have repeteadly the following message

Message error

which traduced says:

"It was not possible to find the access point (or point of entry) to the proccedure deflateSetHeader in the dynamic link library C:PROGRA~1\R\R-3.4~1.2\Tcl\bin64\tcl86.dll "

The R version I was using when it started was the prior 3.3.3

I thought that, may be I didn't realize any inconsistency with that version and the packages I mentioned.

I reinstalled everything (R - the most recent version and RStudio, also, the most recent version) and the problem continues even in its most basic installation state (with no extra package installed). And now the message appears even when I just open RStudio but I'm not running anything.

Is anyone having this trouble? how can I solve it?

If any other info is needed I'll be glad to give you. I appreciate any help sice it's been a long weekend trying to solve it.

答:
The issue got resolved by reinstalling R and R studio latest update. Currently using this version
RStudio-1.1.383
R-3.4.2-win

enter image description here

Title: Rterm.,exe and tcl86.dll


问:
FATAL Flags parsing error:Unknown command line flag 'logtostderr'
System information

OS Platform and Distribution: Windows 10 64 Bit

TensorFlow installed from (source or binary): binary

TensorFlow version:1.5.0-dev20171115'

Python version 3.5.2(v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55)

GPU: nVidia GeForce 755M 2GB

CPU: Intel x64-64 Intel Core i5-4200M CPU @ 2.50Ghz, 8GB memory

Describe the problem:

Initially, the problem I had was is described here: https://github.com/tensorflow/models/issues/2653

The solution given in that is to try and install tf nightly. I did that as shown :
tfnightly

However, now when I try to run the following command:

```<code>C:\Users\kannan\Documents\MDLearning\models\research\object_detection>train.py --logtostderr --train_dir=training/ --
pipeline_config_path=training/ssd_mobilenet_v1_pets.config
</code>```

I get the following Error:

FATAL Flags parsing error: Unknown command line flag 'logtostderr'
  Pass --helpshort or --helpfull to see help on flags.

Any idea how to solve this?

EDIT:
I omitted --logtostderr and tried the same command. I probably ended up with a memory allocation error from the looks of it as seen here in the PDF attached below. I know it is really long. To make it easy, I have highlighted the important errors: Page 1, 2, 106, 107, 111 and 115.

PDF-Memory Error

Any idea how to get around this? I am using a batch size of 1 and it possibly can't go any lower. I have used around 187 images with two classes labelled in each image. All my images are 960 by 720 pixels each. My GPU compute capability is 3.0

答: --logtostderr is not a supported flag see this issue

Body:
System information

OS Platform and Distribution: Windows 10 64 Bit

TensorFlow installed from (source or binary): binary

TensorFlow version:1.5.0-dev20171115'

Python version 3.5.2(v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55)

GPU: nVidia GeForce 755M 2GB

CPU: Intel x64-64 Intel Core i5-4200M CPU @ 2.50Ghz, 8GB memory

Describe the problem:

Initially, the problem I had was is described here: https://github.com/tensorflow/models/issues/2653

The solution given in that is to try and install tf nightly. I did that as shown :
tfnightly

However, now when I try to run the following command:

C:\Users\kannan\Documents\MDLearning\models\research\object_detection>train.py --logtostderr --train_dir=training/ --
pipeline_config_path=training/ssd_mobilenet_v1_pets.config

I get the following Error:

FATAL Flags parsing error: Unknown command line flag 'logtostderr'
  Pass --helpshort or --helpfull to see help on flags.

Any idea how to solve this?

EDIT:
I omitted --logtostderr and tried the same command. I probably ended up with a memory allocation error from the looks of it as seen here in the PDF attached below. I know it is really long. To make it easy, I have highlighted the important errors: Page 1, 2, 106, 107, 111 and 115.

PDF-Memory Error

Any idea how to get around this? I am using a batch size of 1 and it possibly can't go any lower. I have used around 187 images with two classes labelled in each image. All my images are 960 by 720 pixels each. My GPU compute capability is 3.0


问:
Axios POST request 413 (Payload Too Large)
This is an axios POST request in my React project. labelIDs is a long array whose length is around 8000.

```<code>    axios.post('http://localhost:3000/api/filter', {
      'ids': labelIDs,
      'like_ratio_range': ["0", "1"]
    })
</code>```

I've tried body-parserbut it didn't solve the problem. Any idea how to config axios post body limit?

Or should this API be better designed?

答:
The solution to this problem lies within body parser and how your middleware is set up. Body-parser's limit option will only take in effect if your content-type and type option match. It looks like you're sending regular json to the server, your bodyparser middleware should look something like this.

```<code>var express = require("express");
var bodyParser = require("body-parser");
var app = express();
app.use(bodyParser.json({limit: '100kb'}));
</code>```

If the payload is still too large, increment the bodyParser.json() limit option. Try '200kb', try '300kb'. 100kb shoudld be enough though.

Body:
This is an axios POST request in my React project. labelIDs is a long array whose length is around 8000.

    axios.post('http://localhost:3000/api/filter', {
      'ids': labelIDs,
      'like_ratio_range': ["0", "1"]
    })

I've tried body-parserbut it didn't solve the problem. Any idea how to config axios post body limit?

Or should this API be better designed?

Body:
The solution to this problem lies within body parser and how your middleware is set up. Body-parser's limit option will only take in effect if your content-type and type option match. It looks like you're sending regular json to the server, your bodyparser middleware should look something like this.

var express = require("express");
var bodyParser = require("body-parser");
var app = express();
app.use(bodyParser.json({limit: '100kb'}));

If the payload is still too large, increment the bodyParser.json() limit option. Try '200kb', try '300kb'. 100kb shoudld be enough though.


问:
EF Core 2.0.0 Query Filter is Caching TenantId (Updated for 2.0.1+)
I'm building a multi-tenant application, and am running into difficulties with what I think is EF Core caching the tenant id across requests. The only thing that seems to help is constantly rebuilding the application as I sign in and out of tenants.

I thought it may have something to do with the IHttpContextAccessor instance being a singleton, but it can't be scoped, and when I sign in and out without rebuilding I can see the tenant's name change at the top of the page, so it's not the issue.

The only other thing I can think of is that EF Core is doing some sort of query caching. I'm not sure why it would be considering that it's a scoped instance and it should be getting rebuild on every request, unless I'm wrong, which I probably am. I was hoping it would behave like a scoped instance so I could simply inject the tenant id at model build time on each instance.

I'd really appreciate it if someone could point me in the right direction. Here's my current code:

TenantProvider.cs

```<code>public sealed class TenantProvider :
    ITenantProvider {
    private readonly IHttpContextAccessor _accessor;

    public TenantProvider(
        IHttpContextAccessor accessor) {
        _accessor = accessor;
    }

    public int GetId() {
        return _accessor.HttpContext.User.GetTenantId();
    }
}
</code>```

...which is injected into TenantEntityConfigurationBase.cs where I use it to setup a global query filter.

```<code>internal abstract class TenantEntityConfigurationBase<TEntity, TKey> :
    EntityConfigurationBase<TEntity, TKey>
    where TEntity : TenantEntityBase<TKey>
    where TKey : IEquatable<TKey> {
    protected readonly ITenantProvider TenantProvider;

    protected TenantEntityConfigurationBase(
        string table,
        string schema,
        ITenantProvider tenantProvider) :
        base(table, schema) {
        TenantProvider = tenantProvider;
    }

    protected override void ConfigureFilters(
        EntityTypeBuilder<TEntity> builder) {
        base.ConfigureFilters(builder);

        builder.HasQueryFilter(
            e => e.TenantId == TenantProvider.GetId());
    }

    protected override void ConfigureRelationships(
        EntityTypeBuilder<TEntity> builder) {
        base.ConfigureRelationships(builder);

        builder.HasOne(
            t => t.Tenant).WithMany().HasForeignKey(
            k => k.TenantId);
    }
}
</code>```

...which is then inherited by all other tenant entity configurations. Unfortunately it doesn't seem to work as I had planned.

I have verified that the tenant id being returned by the user principal is changing depending on what tenant user is logged in, so that's not the issue. Thanks in advance for any help!

Update

For a solution when using EF Core 2.0.1+, look at the not-accepted answer from me.

Update 2

Also look at Ivan's update for 2.0.1+, it proxies in the filter expression from the DbContext which restores the ability to define it once in a base configuration class. Both solutions have their pros and cons. I've opted for Ivan's again because I just want to leverage my base configurations as much as possible.

答:
Answer for 2.0.1+

So, the day I got it work, EF Core 2.0.1 was released. As soon as I updated, this solution came crashing down. After a very long thread over here, it turned out that it was really a fluke that it was working in 2.0.0.

Officially for 2.0.1 and beyond any query filters that depend on an outside value, like the tenant id in my case, must be defined in the OnModelCreating method and must reference a property on the DbContext. The reason is because on first run of the app or first call into EF all EntityTypeConfiguration classes are processed and their results are cached regardless of how many times the DbContext is instanced.

That's why defining the query filters in the OnModelCreating method works because it's a fresh instance and the filter lives and dies with it.

```<code>public class MyDbContext : DbContext {
    private readonly ITenantService _tenantService;

    private int TenantId => TenantService.GetId();

    public DbSet<User> Users { get; set; }

    public MyDbContext(
        DbContextOptions options,
        ITenantService tenantService) {
        _tenantService = tenantService;
    }

    protected override void OnModelCreating(
        ModelBuilder modelBuilder) {
        modelBuilder.Entity<User>().HasQueryFilter(
            u => u.TenantId == TenantId);
    }
}
</code>```

Body:
I'm building a multi-tenant application, and am running into difficulties with what I think is EF Core caching the tenant id across requests. The only thing that seems to help is constantly rebuilding the application as I sign in and out of tenants.

I thought it may have something to do with the IHttpContextAccessor instance being a singleton, but it can't be scoped, and when I sign in and out without rebuilding I can see the tenant's name change at the top of the page, so it's not the issue.

The only other thing I can think of is that EF Core is doing some sort of query caching. I'm not sure why it would be considering that it's a scoped instance and it should be getting rebuild on every request, unless I'm wrong, which I probably am. I was hoping it would behave like a scoped instance so I could simply inject the tenant id at model build time on each instance.

I'd really appreciate it if someone could point me in the right direction. Here's my current code:

TenantProvider.cs

public sealed class TenantProvider :
    ITenantProvider {
    private readonly IHttpContextAccessor _accessor;

    public TenantProvider(
        IHttpContextAccessor accessor) {
        _accessor = accessor;
    }

    public int GetId() {
        return _accessor.HttpContext.User.GetTenantId();
    }
}

...which is injected into TenantEntityConfigurationBase.cs where I use it to setup a global query filter.

internal abstract class TenantEntityConfigurationBase<TEntity, TKey> :
    EntityConfigurationBase<TEntity, TKey>
    where TEntity : TenantEntityBase<TKey>
    where TKey : IEquatable<TKey> {
    protected readonly ITenantProvider TenantProvider;

    protected TenantEntityConfigurationBase(
        string table,
        string schema,
        ITenantProvider tenantProvider) :
        base(table, schema) {
        TenantProvider = tenantProvider;
    }

    protected override void ConfigureFilters(
        EntityTypeBuilder<TEntity> builder) {
        base.ConfigureFilters(builder);

        builder.HasQueryFilter(
            e => e.TenantId == TenantProvider.GetId());
    }

    protected override void ConfigureRelationships(
        EntityTypeBuilder<TEntity> builder) {
        base.ConfigureRelationships(builder);

        builder.HasOne(
            t => t.Tenant).WithMany().HasForeignKey(
            k => k.TenantId);
    }
}

...which is then inherited by all other tenant entity configurations. Unfortunately it doesn't seem to work as I had planned.

I have verified that the tenant id being returned by the user principal is changing depending on what tenant user is logged in, so that's not the issue. Thanks in advance for any help!

Update

For a solution when using EF Core 2.0.1+, look at the not-accepted answer from me.

Update 2

Also look at Ivan's update for 2.0.1+, it proxies in the filter expression from the DbContext which restores the ability to define it once in a base configuration class. Both solutions have their pros and cons. I've opted for Ivan's again because I just want to leverage my base configurations as much as possible.

Body:
Answer for 2.0.1+

So, the day I got it work, EF Core 2.0.1 was released. As soon as I updated, this solution came crashing down. After a very long thread over here, it turned out that it was really a fluke that it was working in 2.0.0.

Officially for 2.0.1 and beyond any query filters that depend on an outside value, like the tenant id in my case, must be defined in the OnModelCreating method and must reference a property on the DbContext. The reason is because on first run of the app or first call into EF all EntityTypeConfiguration classes are processed and their results are cached regardless of how many times the DbContext is instanced.

That's why defining the query filters in the OnModelCreating method works because it's a fresh instance and the filter lives and dies with it.

public class MyDbContext : DbContext {
    private readonly ITenantService _tenantService;

    private int TenantId => TenantService.GetId();

    public DbSet<User> Users { get; set; }

    public MyDbContext(
        DbContextOptions options,
        ITenantService tenantService) {
        _tenantService = tenantService;
    }

    protected override void OnModelCreating(
        ModelBuilder modelBuilder) {
        modelBuilder.Entity<User>().HasQueryFilter(
            u => u.TenantId == TenantId);
    }
}


问:
iOS TestFlight - how to provide 1024x1024 icon?
Because the 1024x1024 icon size isn't actually needed by the app, I haven't included it in the build.  I uploaded the build and then uploaded the icon on the app store submission page in iTunes Connect, which seems to have worked for the app store submission.

However, I'm now trying to submit for public testing via TestFlight, but when I try to create a group, I get a message complaining that I haven't uploaded a 1024x1024 icon and that I can do so via iTunes Connect.  How do I do this?

答:
If you submit an ipa generated through Xcode 9, iTunes Connect throws the below error:

```<code>Missing App Store Icon - iOS Apps must include a 1024x1024px App Store Icon in PNG
format. Without providing the icon in the Asset Catalog or via iTunes Connect, apps
cannot be submitted for App Review or Beta App Review. Refer to
https://developer.apple.com/ios/human-interface-guidelines/icons-and-images/app-icon/ for more information.
</code>```

The same will be applicable only for the apps generated though Xcode 9+. If you want to avoid this, you still can generate the ipa using Xcode 8.

In Xcode 9, under App Icon section, there is a provision to add 1024*1024 icon.

Go to Images folder in your project

Navigate to Image.xcassets

Click on AppIcon

Navigate to bottom, there you will see App Store iOS 1024pt (1x)

Screenshot of the app icon image asset with 1024*1024 icon available here

Body:
If you submit an ipa generated through Xcode 9, iTunes Connect throws the below error:

Missing App Store Icon - iOS Apps must include a 1024x1024px App Store Icon in PNG
format. Without providing the icon in the Asset Catalog or via iTunes Connect, apps
cannot be submitted for App Review or Beta App Review. Refer to
https://developer.apple.com/ios/human-interface-guidelines/icons-and-images/app-icon/ for more information.

The same will be applicable only for the apps generated though Xcode 9+. If you want to avoid this, you still can generate the ipa using Xcode 8.

In Xcode 9, under App Icon section, there is a provision to add 1024*1024 icon.

Go to Images folder in your project

Navigate to Image.xcassets

Click on AppIcon

Navigate to bottom, there you will see App Store iOS 1024pt (1x)

Screenshot of the app icon image asset with 1024*1024 icon available here


答:
Try following code, your variable declare before call the function when field is empty:</p>

```<code>function call() {
  var m700 =  document.purchaseform.buyM700.value;
  confirm (m700);
};
</code>```

Title: Javascript uncaught type error; property can't be read, undefined variable

Body:
I am trying to fetch the value from text input in HTML to a variable in javascript.
An uncaught type error had appeared.
The following are my HTML code:

 <form name="purchaseform" id="formma">
 KJW M700

 <input name='buyM700' type='text' id='1234'>
 <input name='caller' type='button' value='click here' onClick='call()'>
 </form>

The following are my Javascript code:

var m700 =  document.purchaseform.buyM700.value;
function call() {
  confirm (m700);
};

Thank you for helping me in advance.

Body:
Try following code, your variable declare before call the function when field is empty:

function call() {
  var m700 =  document.purchaseform.buyM700.value;
  confirm (m700);
};


问:
document.body not working in IE
I am trying to create a simple on click function, but IE isn't cooperating.
This works when I use it in chrome. When I call this function in IE, the function doesn't execute.
IE version: 11

```<code><script language="JavaScript">
AJS.$(document).ready(function($) {

AJS.$(document.body).on("click", "#Test-button", function() {

    });

});
</script>
</code>```

Thanks in advance.

答:
document.body not work in IE, remove the body and only use document

Just change your code to :

```<code><script language="JavaScript">
AJS.$(document).ready(function($) {

AJS.$(document).on("click", "#Test-button", function() {

});

});
</script>
</code>```

https://jsfiddle.net/tLa4mxgp/

Title: document.body not working in IE

Body:
I am trying to create a simple on click function, but IE isn't cooperating.
This works when I use it in chrome. When I call this function in IE, the function doesn't execute.
IE version: 11

Thanks in advance.

Body:
document.body not work in IE, remove the body and only use document

Just change your code to :

<script language="JavaScript">
AJS.$(document).ready(function($) {

AJS.$(document).on("click", "#Test-button", function() {

});

});
</script>

https://jsfiddle.net/tLa4mxgp/


问:
How to get the values from Dictionary type SESSION Variable in C#
I am using C#.

I have got below format values in my SESSION variable ["FROMDATA"], I am using DICTIONARY to store the FORM Posted Data. Please see the related question.

Below are the some values in my SESSION Variable.

```<code>1) key - "skywardsNumber" value-"99999039t"
2) key - "password" value-"a2222222"
3) key - "ctl00$MainContent$ctl22$FlightSchedules1$ddlDepartureAirport-suggest" value-"London"
4) key - "ctl00$MainContent$ctl22$ctl07$txtPromoCode" value-"AEEGIT9"
.
.
....so on
</code>```

Now I want to create a CLASS with METHOD in it, in which I will just pass the "KEY" and it will first check it for NULL OR EMPTY and then it will return its value from the SESSION Variable ["FROMDATA"].

Please suggest using C#.

答:
Try this: you'll have to tweak it a bit for it to complie. But you'll get the basic idea</p>

```<code>public class Session
    {

        private const string _skyWardsNumber = "skyWardsNumber";
        // Add other keys here

        public string SkyWardsNumber
        {
            get
            {
                object str = (ReadFromDictionary(_skyWardsNumber);
                if (str != null)
                {
                    return (string) str;
                }
                else
                {
                    return string.Empty;
                }

            }
            set
            {
                WriteToDictionary(_skyWardsNumber, value);
            }
        }

        public object ReadFromDictionary(string key)
        {
            IDictionary dictionary = (ReadFromContext("Dictionary") as IDictionary);
            if (dictionary != null && dictionary.ContainsKey(key))
            {
               return dictionary[key];
            }
            else
            {
               return null;
            }
        }

        public object WriteFromDictionary(string key, object value)
        {
            IDictionary dictionary = (ReadFromContext("Dictionary") as IDictionary);

            if(dictionary == null)
                 WriteToContext("Dictionary", new Dictionary<string, string>())

            dictionary = (ReadFromContext("Dictionary") as IDictionary);

            if (dictionary.ContainsKey(key))
            {
               dictionary[key] = value;
            }
            else
            {
               dictionary.Add(//add new keyvaluepair.);
            }
        }

        private static void WriteToContext(string key, object value)
        {
            HttpContext.Current.Session[key] = value;
        }

        private static object ReadFromContext(string key)
        {
            if(HttpContext.Current.Session[key] != null)
                return HttpContext.Current.Session[key] as object;

             return null;
        }

    }
</code>```

Body:
I am using C#.

I have got below format values in my SESSION variable ["FROMDATA"], I am using DICTIONARY to store the FORM Posted Data. Please see the related question.

Below are the some values in my SESSION Variable.

1) key - "skywardsNumber" value-"99999039t"
2) key - "password" value-"a2222222"
3) key - "ctl00$MainContent$ctl22$FlightSchedules1$ddlDepartureAirport-suggest" value-"London"
4) key - "ctl00$MainContent$ctl22$ctl07$txtPromoCode" value-"AEEGIT9"
.
.
....so on

Now I want to create a CLASS with METHOD in it, in which I will just pass the "KEY" and it will first check it for NULL OR EMPTY and then it will return its value from the SESSION Variable ["FROMDATA"].

Please suggest using C#.

Body:
Try this: you'll have to tweak it a bit for it to complie. But you'll get the basic idea

public class Session
    {

        private const string _skyWardsNumber = "skyWardsNumber";
        // Add other keys here

        public string SkyWardsNumber
        {
            get
            {
                object str = (ReadFromDictionary(_skyWardsNumber);
                if (str != null)
                {
                    return (string) str;
                }
                else
                {
                    return string.Empty;
                }

            }
            set
            {
                WriteToDictionary(_skyWardsNumber, value);
            }
        }

        public object ReadFromDictionary(string key)
        {
            IDictionary dictionary = (ReadFromContext("Dictionary") as IDictionary);
            if (dictionary != null && dictionary.ContainsKey(key))
            {
               return dictionary[key];
            }
            else
            {
               return null;
            }
        }

        public object WriteFromDictionary(string key, object value)
        {
            IDictionary dictionary = (ReadFromContext("Dictionary") as IDictionary);

            if(dictionary == null)
                 WriteToContext("Dictionary", new Dictionary<string, string>())

            dictionary = (ReadFromContext("Dictionary") as IDictionary);

            if (dictionary.ContainsKey(key))
            {
               dictionary[key] = value;
            }
            else
            {
               dictionary.Add(//add new keyvaluepair.);
            }
        }

        private static void WriteToContext(string key, object value)
        {
            HttpContext.Current.Session[key] = value;
        }

        private static object ReadFromContext(string key)
        {
            if(HttpContext.Current.Session[key] != null)
                return HttpContext.Current.Session[key] as object;

             return null;
        }

    }


问:
golang regular expression ReplaceAllString
I am writing a chatbot program in the Go programming language.
In this function it reads in a user string checks for a regular expression and then is supposed to remove the expression and replace with another string if found. It is successful in finding a match but will not append it to the string

```<code>input = "I am feeling happy"
pattern2 := []string{`.*i am.*`, `.*I AM.*`, `.*I'm.*`, `.*i'm.*`, `.*im.*`, `.*I am.*`}

// loop through pattern2 array
//if pattern is found extract substring
//set response

for _, checkPattern := range pattern2 {
    re := regexp.MustCompile(checkPattern)
    if re.MatchString(input) {
        match := re.ReplaceAllString(input, "How do you know you are $1 ?")
        response = "output : " + match
        return response
    } //if re.MatchString
} //for pattern2
</code>```

my output for response is "how do you know you are"

my intended output "how do you know you are feeling happy"

答:
You can actually rewrite the regular expression to avoid having to loop. The following is an illustration of what @mypetlion is talking about:

```<code>package main

import (
    "fmt"
    "regexp"
)

func main() {
    input := "I AM feeling happy"
    re := regexp.MustCompile("(?i)(i[' a]*m) (.*)")
    if re.MatchString(input) {
        match := re.ReplaceAllString(input, "How do you know you are $2?")
        fmt.Println("output: " + match)
    } else {
        fmt.Println("There is no match")
    }
}
</code>```

The expression (?i)(i[' a]*m) (.*) basically captures two groups of characters present in the string. The first group is the various formats of I am. This should work for the other variants, as well. The second matches the remaining of the string after I am. Please note that we are using (?i) to make the regular expression case-insensitive.

Once we have compiled the expression, we move on to using the matched string from second group as our replacement.

You should get the following for all variations of I am:

```<code>output: How do you know you are feeling happy?
</code>```

I hope this helps.

Body:
I am writing a chatbot program in the Go programming language.
In this function it reads in a user string checks for a regular expression and then is supposed to remove the expression and replace with another string if found. It is successful in finding a match but will not append it to the string

input = "I am feeling happy"
pattern2 := []string{`.*i am.*`, `.*I AM.*`, `.*I'm.*`, `.*i'm.*`, `.*im.*`, `.*I am.*`}

// loop through pattern2 array
//if pattern is found extract substring
//set response

for _, checkPattern := range pattern2 {
    re := regexp.MustCompile(checkPattern)
    if re.MatchString(input) {
        match := re.ReplaceAllString(input, "How do you know you are $1 ?")
        response = "output : " + match
        return response
    } //if re.MatchString
} //for pattern2

my output for response is "how do you know you are"

my intended output "how do you know you are feeling happy"

Body:
You can actually rewrite the regular expression to avoid having to loop. The following is an illustration of what @mypetlion is talking about:

package main

import (
    "fmt"
    "regexp"
)

func main() {
    input := "I AM feeling happy"
    re := regexp.MustCompile("(?i)(i[' a]*m) (.*)")
    if re.MatchString(input) {
        match := re.ReplaceAllString(input, "How do you know you are $2?")
        fmt.Println("output: " + match)
    } else {
        fmt.Println("There is no match")
    }
}

The expression (?i)(i[' a]*m) (.*) basically captures two groups of characters present in the string. The first group is the various formats of I am. This should work for the other variants, as well. The second matches the remaining of the string after I am. Please note that we are using (?i) to make the regular expression case-insensitive.

Once we have compiled the expression, we move on to using the matched string from second group as our replacement.

You should get the following for all variations of I am:

output: How do you know you are feeling happy?

I hope this helps.