问:
relative path changed issue when my app is launched from another app
I face a confused issue, I have an app(let's named A.exe), in my app, it can launch another app(B.exe),  in my folder , A.exe and B.exe are in the same folder, so here the relative path of B.exe is "B.exe".

However, now another app(C.exe) can run the A.exe, C.exe is in another folder, so here comes the issue, if A.exe is launched from C.exe, it can never run the C.exe, as I get a error says it can't find C.exe.

So I think the relative path changed to current C.exe's folder, in C.exe folder, there is no B.exe.

Is any friends get this issue? or how can I get the right relative path in different state to fix this issue?

I use ShExecInfo to run my the c.exe, some code is as following:

```<code>QStringList paramList;
paramList.push_back("requiresAdmin");
QString paramsAsOneString = paramList.join(' ');
LPCWSTR szParams = reinterpret_cast<LPCWSTR>(paramsAsOneString.utf16());
LPCWSTR szAppName = reinterpret_cast<LPCWSTR>(appName.utf16());

SHELLEXECUTEINFO ShExecInfo = { 0 };
ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
ShExecInfo.hwnd = NULL;
ShExecInfo.lpVerb = L"runas";
ShExecInfo.lpFile = szAppName;
ShExecInfo.lpParameters = szParams;
ShExecInfo.lpDirectory = NULL;
ShExecInfo.nShow = SW_SHOW;
ShExecInfo.hInstApp = NULL;
</code>```

答:
If you launch an app from another app, you have to set up the folder too. I mean, if C is in PATH_C, and C launch the app A that is in the PATH_A, the process A run in the PATH_C, so when you try to run the process B, its not accesible.

You have to set up the folder too, for example. When you run nautilus in Ubuntu, you have to setup the folder too:

```<code>  user:~Documents/$: nautilus /home/user/
</code>```

If so, nautilus is opened in the given folder. If not, nautilus is opened in the folder of the process that launch it, in this case Documents folder.

To avoid the problem, if B.exe its allways in the same folder as A.exe, then use the relative path of the executable file to launch B.exe, by using GetModuleFileName function.

Body:
I face a confused issue, I have an app(let's named A.exe), in my app, it can launch another app(B.exe),  in my folder , A.exe and B.exe are in the same folder, so here the relative path of B.exe is "B.exe".

However, now another app(C.exe) can run the A.exe, C.exe is in another folder, so here comes the issue, if A.exe is launched from C.exe, it can never run the C.exe, as I get a error says it can't find C.exe.

So I think the relative path changed to current C.exe's folder, in C.exe folder, there is no B.exe.

Is any friends get this issue? or how can I get the right relative path in different state to fix this issue?

I use ShExecInfo to run my the c.exe, some code is as following:

QStringList paramList;
paramList.push_back("requiresAdmin");
QString paramsAsOneString = paramList.join(' ');
LPCWSTR szParams = reinterpret_cast<LPCWSTR>(paramsAsOneString.utf16());
LPCWSTR szAppName = reinterpret_cast<LPCWSTR>(appName.utf16());

SHELLEXECUTEINFO ShExecInfo = { 0 };
ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
ShExecInfo.hwnd = NULL;
ShExecInfo.lpVerb = L"runas";
ShExecInfo.lpFile = szAppName;
ShExecInfo.lpParameters = szParams;
ShExecInfo.lpDirectory = NULL;
ShExecInfo.nShow = SW_SHOW;
ShExecInfo.hInstApp = NULL;

Body:
If you launch an app from another app, you have to set up the folder too. I mean, if C is in PATH_C, and C launch the app A that is in the PATH_A, the process A run in the PATH_C, so when you try to run the process B, its not accesible.

You have to set up the folder too, for example. When you run nautilus in Ubuntu, you have to setup the folder too:

  user:~Documents/$: nautilus /home/user/

If so, nautilus is opened in the given folder. If not, nautilus is opened in the folder of the process that launch it, in this case Documents folder.

To avoid the problem, if B.exe its allways in the same folder as A.exe, then use the relative path of the executable file to launch B.exe, by using GetModuleFileName function.


来源: stackexchange

问:
Extract Json response Create dynamic variables and assign values
I want to extract values from a json response and assign the values to variables and use them in subsequent requests.

Request 1 Response

```<code>{
  "XXX":"Test Company 1",
  "YYY":"Test Company 2",
  "ZZZ":"Test Company 3"
}
</code>```

I want to create dynamic variables and values like below.

```<code>Company_Name_1 = "Test Company 1"
Company_Code_1 = "XXX"
Company_Name_2 = "Test Company 2"
Company_Code_2 = "YYY"
Company_Name_3 = "Test Company 3"
Company_Code_3 = "ZZZ"
</code>```

and use above variables in subsequent requests like below.

Request 2 Parameter

```<code>{
    "Date": "${MeetingDate}",
    "StartTime": "${StartTime}",
    "EndTime": "${EndTime}",
    "InvestorsByDate": [{
        "Name": "${Company_Name_1}",
        "Code": "${Company_Code_1}"
    },
    {
        "Name": "${Company_Name_2}",
        "Code": "${Company_Code_2}"
    },
    {
        "Name": "${Company_Name_3}",
        "Code": "${Company_Code_3}"
    }]
}
</code>```

Total number of companies is not a constant, its changing continuously. So i need to write a code to capture the dynamic values and assign them to dynamically created variables then use them in subsequent requests. I am totally new to scripting. Please help me to face this challenge. Your help is really appreciated.

答:
@Dmitri T Thank you, It's very useful, I did a modification and working as expected.

```<code>import groovy.json.JsonBuilder
import groovy.json.JsonSlurper

    def companies = new JsonSlurper().parse(prev.getResponseData())
    def jsonBuilder = new JsonBuilder()
    jsonBuilder {"InvestorsByDate"companies.collect{[IdString: it.getKey(),Name: it.getValue()]}
    }
    vars.put('InvestorsByDate', jsonBuilder.toString())
    vars.put('InvestorsByDate', vars.get('InvestorsByDate').substring(1))
    vars.put('InvestorsByDate', vars.get('InvestorsByDate').substring(0,vars.get('InvestorsByDate').length() - 1))

    log.info(vars.get('InvestorsByDate'))
</code>```

I need one more help, please do if possible. Is it possible to change company name like below.

```<code>"InvestorsByDate": [{
    "Name": "1. Company Name1",
    "Code": "Company_Code_1"
},
{
    "Name": "2. Company Name2",
    "Code": "Company_Code_2"
},
{
    "Name": "3. Company Name3",
    "Code": "Company_Code_3"
}]
</code>```

I want to concat number with company name. Is it possible in json builder?

ContentLicense: CC BY-SA 3.0

Body:
I want to extract values from a json response and assign the values to variables and use them in subsequent requests.

Request 1 Response

{
  "XXX":"Test Company 1",
  "YYY":"Test Company 2",
  "ZZZ":"Test Company 3"
}

I want to create dynamic variables and values like below.

Company_Name_1 = "Test Company 1"
Company_Code_1 = "XXX"
Company_Name_2 = "Test Company 2"
Company_Code_2 = "YYY"
Company_Name_3 = "Test Company 3"
Company_Code_3 = "ZZZ"

and use above variables in subsequent requests like below.

Request 2 Parameter

{
    "Date": "${MeetingDate}",
    "StartTime": "${StartTime}",
    "EndTime": "${EndTime}",
    "InvestorsByDate": [{
        "Name": "${Company_Name_1}",
        "Code": "${Company_Code_1}"
    },
    {
        "Name": "${Company_Name_2}",
        "Code": "${Company_Code_2}"
    },
    {
        "Name": "${Company_Name_3}",
        "Code": "${Company_Code_3}"
    }]
}

Total number of companies is not a constant, its changing continuously. So i need to write a code to capture the dynamic values and assign them to dynamically created variables then use them in subsequent requests. I am totally new to scripting. Please help me to face this challenge. Your help is really appreciated.

Body:
@Dmitri T Thank you, It's very useful, I did a modification and working as expected.

import groovy.json.JsonBuilder
import groovy.json.JsonSlurper

    def companies = new JsonSlurper().parse(prev.getResponseData())
    def jsonBuilder = new JsonBuilder()
    jsonBuilder {"InvestorsByDate"companies.collect{[IdString: it.getKey(),Name: it.getValue()]}
    }
    vars.put('InvestorsByDate', jsonBuilder.toString())
    vars.put('InvestorsByDate', vars.get('InvestorsByDate').substring(1))
    vars.put('InvestorsByDate', vars.get('InvestorsByDate').substring(0,vars.get('InvestorsByDate').length() - 1))

    log.info(vars.get('InvestorsByDate'))

I need one more help, please do if possible. Is it possible to change company name like below.

"InvestorsByDate": [{
    "Name": "1. Company Name1",
    "Code": "Company_Code_1"
},
{
    "Name": "2. Company Name2",
    "Code": "Company_Code_2"
},
{
    "Name": "3. Company Name3",
    "Code": "Company_Code_3"
}]

I want to concat number with company name. Is it possible in json builder?


问:
Material Design Bootstrap is not working in AngularJS single page application
I am working on MEAN Stack application. I want to use Bootstrap Material Design CSS styles to my single page application but routing is not working when using mdb.min.css .what is the solution to avoid this problem.

```<code>    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <title>Testing Application</title>
    <!-- STYLESHEETS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css">
    <link href="css/mdb.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

</head>

<body ng-app="myApp">

  <div ng-view></div>
  <!-- SCRIPTS -->
  <script type="text/javascript" src="js/jquery-3.1.1.min.js"></script>
  <script type="text/javascript" src="js/tether.min.js"></script>
  <script type="text/javascript" src="js/bootstrap.min.js"></script>
  <script type="text/javascript" src="js/mdb.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.js"></script>
  <script type="text/javascript" src="js/routingCtrl.js"></script>
  <script type="text/javascript" src="js/loginCtrl.js"></script>
</body>

</html>
</code>```

if i add mdb.min.css the routing page is not visible in ng-view.but if i remove mdb.min.css the page is visible without styling

答:
Try using the CDN by adding it to the head tags of your root index.html of your angular app like this.

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

```

If it doesn't work please make your issue more elaborate.

Body:
I am working on MEAN Stack application. I want to use Bootstrap Material Design CSS styles to my single page application but routing is not working when using mdb.min.css .what is the solution to avoid this problem.

    <!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <title>Testing Application</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css">
    <link href="css/mdb.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

if i add mdb.min.css the routing page is not visible in ng-view.but if i remove mdb.min.css the page is visible without styling

Body:
Try using the CDN by adding it to the head tags of your root index.html of your angular app like this.

<head>
   <!-- Latest compiled and minified CSS -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

    <!-- jQuery library -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

  <!-- Latest compiled JavaScript -->
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>

If it doesn't work please make your issue more elaborate.


问:
Issues getting JSON string for chart.js data
I'm getting the following error when trying to get a JSON data string for charts.js

```<code>Uncaught TypeError: Cannot create property 'datasets' on string '{"datasets":[{"label":"My First dataset","data":[{"x":"2017-01-01","y":35},{"x":"2017-01-15","y":28},{"x":"2017-01-31","y":42}]}]}'
</code>```

The JSON string I'm creating looks exactly the same like the one in an example. Also if I just copy and paste this string and set it as my data it's just working fine.

This is working:

```<code>            data: {"datasets":[{"label":"My First dataset","data":[{"x":"2017-01-01","y":35},{"x":"2017-01-15","y":28},{"x":"2017-01-31","y":42}]}]},
</code>```

This is not working:

```<code>.done(function( data ) {
    console.log(data);
        type: 'line',
        data: data });
</code>```

Any ideas what I am doing wrong here?

答: Data received is in string format. You should call JSON.parse(data) on received data in order to access dataset property.

Body:
I'm getting the following error when trying to get a JSON data string for charts.js

Uncaught TypeError: Cannot create property 'datasets' on string '{"datasets":[{"label":"My First dataset","data":[{"x":"2017-01-01","y":35},{"x":"2017-01-15","y":28},{"x":"2017-01-31","y":42}]}]}'

The JSON string I'm creating looks exactly the same like the one in an example. Also if I just copy and paste this string and set it as my data it's just working fine.

This is working:

            data: {"datasets":[{"label":"My First dataset","data":[{"x":"2017-01-01","y":35},{"x":"2017-01-15","y":28},{"x":"2017-01-31","y":42}]}]},

This is not working:

.done(function( data ) {
    console.log(data);
        type: 'line',
        data: data });

Any ideas what I am doing wrong here?


问:
The different constructor ways
I have write little class, now i see different ways to call constructors. Which way is the correct way? (Or the better way)

SharedKeys.h

```<code>#ifndef SHAREDKEYS_H
    #define SHAREDKEYS_H

    class SharedKeys
    {
    private:
        char keyCode;

    public:
        SharedKeys(char keycode)
        {
            keyCode = keycode;
        }
        ~SharedKeys() {}

        char getKeyCode() { return keyCode; };

    };

    #endif
</code>```

Main.cpp

My constructor call way:

```<code>SharedKeys* SK;
SK = new SharedKeys(*cstr); //Call contructor
</code>```

Other constructor call way:

```<code>// SharedKeys constructor
SharedKeys::SharedKeys(*cstr)
{
    keyCode = keycode;
}
</code>```

I am open to any suggestions for improvement. Thank you.

Main.cpp

SK must be a pointer here or? (this code works)

```<code>SharedKeys* SK;

    vector<SharedKeys> StoreSharedKeys;

string str = x;
char *cstr = new char[str.length() + 1];
strcpy(cstr, str.c_str());

SK = new SharedKeys(*cstr);
StoreSharedKeys.push_back(*SK);
delete[] cstr;
</code>```

Did I understand you correctly?

```<code>cout << "Key: " <<  x << " loaded." << endl;
string str = x;
char *cstr = new char[str.length() + 1];
strcpy(cstr, str.c_str());

SharedKeys SK(*cstr);
StoreSharedKeys.push_back(SK);
delete[] cstr;
</code>```

if im see that correct then this contructor call is the right way. So i dont must delete the objects. Correct?

答:
There are two ways to create an object:

```<code>SharedKeys   sk( 'a');
SharedKeys*  sk_ptr = new SharedKeys( 'a');
</code>```

The first line creates an object on the stack, and it will be deleted when it goes out of scope (e.g. end of function).

The second line creates an object dynamically, and the object will not be deleted once the scope is left. You have to delete it manually, using delete. Or, even better, use a smart pointer.

Which way you chose to create your objects depends on the use case, the size of the object (large objects should always be allocated dynamically), lifetime of the object etc. But both methods call the same constructor in the end.

Title: The different constructor ways

Body:
I have write little class, now i see different ways to call constructors. Which way is the correct way? (Or the better way)

SharedKeys.h

#ifndef SHAREDKEYS_H
    #define SHAREDKEYS_H

    class SharedKeys
    {
    private:
        char keyCode;

    public:
        SharedKeys(char keycode)
        {
            keyCode = keycode;
        }
        ~SharedKeys() {}

        char getKeyCode() { return keyCode; };

    };

    #endif

Main.cpp

My constructor call way:

SharedKeys* SK;
SK = new SharedKeys(*cstr); //Call contructor

Other constructor call way:

// SharedKeys constructor
SharedKeys::SharedKeys(*cstr)
{
    keyCode = keycode;
}

I am open to any suggestions for improvement. Thank you.

Main.cpp

SK must be a pointer here or? (this code works)

SharedKeys* SK;

    vector<SharedKeys> StoreSharedKeys;

string str = x;
char *cstr = new char[str.length() + 1];
strcpy(cstr, str.c_str());

SK = new SharedKeys(*cstr);
StoreSharedKeys.push_back(*SK);
delete[] cstr;

Did I understand you correctly?

cout << "Key: " <<  x << " loaded." << endl;
string str = x;
char *cstr = new char[str.length() + 1];
strcpy(cstr, str.c_str());

SharedKeys SK(*cstr);
StoreSharedKeys.push_back(SK);
delete[] cstr;

if im see that correct then this contructor call is the right way. So i dont must delete the objects. Correct?

Body:
There are two ways to create an object:

SharedKeys   sk( 'a');
SharedKeys*  sk_ptr = new SharedKeys( 'a');

The first line creates an object on the stack, and it will be deleted when it goes out of scope (e.g. end of function).

The second line creates an object dynamically, and the object will not be deleted once the scope is left. You have to delete it manually, using delete. Or, even better, use a smart pointer.

Which way you chose to create your objects depends on the use case, the size of the object (large objects should always be allocated dynamically), lifetime of the object etc. But both methods call the same constructor in the end.


问:
HTML table- Create pop up box for each  and display xml data
I am working on a project and I am trying to create a web application. So far, my code is like this example. I press the button and a table appears. As you can see in the example, this table contains data of an XML file. THE PROBLEM: I want by clicking each 'td', a popup box to appear. This box will contain different data for each 'td', from the same XML file. Specifically, it will contain an image and some text that refers to the 'td'. Actually, I want something like this. I tried adding this code to my code and I created a popup button in every 'td'. But clicking these buttons, nothing happens. It would be nice if you share your knowledge with me!

答:
i think its help full for your logic.</p>

```<code>  $('td').click(function () {
        $("#MyModal").modal("show");
    });
</code>```

Title: HTML table- Create pop up box for each <td> and display xml data

Body:
i think its help full for your logic.

  $('td').click(function () {
        $("#MyModal").modal("show");
    });


问:
Find pixels with given RGB colors
I would like to get all coordinates from the pixels with a given RGB color in Python. Here is the code that I'm using but it doesn't work. I want to find all pixels with a yellow color.

```<code>from PIL import Image
def find_rgb(imagename, r_query, g_query, b_query):
    img = Image.open(imagename)
    rgb = img.convert('RGB')
    for x in range(507):
        for y in range(337):
            r, g, b, = rgb.getpixel((x, y))
            if r >= r_query and g >= g_query and b <= b_query:
                return (x,y)
</code>```

And how can you do it that Python only gives the coordinates if there are at least three pixels with the same color? (They mustn't be the exact same color, they can be for example 156,173,87 and 155,173,87.)

答:
You are using return in the loop, so you will always have max one pixel returned, you can store the pixels in a set in order to return all yellow pixels.

```<code>def find_yellow_pixels(image_name):

    # Set the value you want for these variables
    r_min = 250
    r_max = 255
    g_min = 250
    g_max = 255
    b_min = 0
    b_max = 0

    yellow_pixels = set()

    img = Image.open(image_name)
    rgb = img.convert('rgb')
    for x in range(img.size[0]):
        for y in range(img.size[1]):
            r, g, b = rgb.getpixel((x, y))
            if r >= r_min and r <= r_max and b >= b_min and b <= b_max and g >= g_min and g <= g_max:
                yellow_pixels.add((x,y))

    return yellow_pixels
</code>```

Edit: fix, open( to Image.open(

Title: Find pixels with given RGB colors

Body:
I would like to get all coordinates from the pixels with a given RGB color in Python. Here is the code that I'm using but it doesn't work. I want to find all pixels with a yellow color.

from PIL import Image
def find_rgb(imagename, r_query, g_query, b_query):
    img = Image.open(imagename)
    rgb = img.convert('RGB')
    for x in range(507):
        for y in range(337):
            r, g, b, = rgb.getpixel((x, y))
            if r >= r_query and g >= g_query and b <= b_query:
                return (x,y)

And how can you do it that Python only gives the coordinates if there are at least three pixels with the same color? (They mustn't be the exact same color, they can be for example 156,173,87 and 155,173,87.)

Body:
You are using return in the loop, so you will always have max one pixel returned, you can store the pixels in a set in order to return all yellow pixels.

def find_yellow_pixels(image_name):

    # Set the value you want for these variables
    r_min = 250
    r_max = 255
    g_min = 250
    g_max = 255
    b_min = 0
    b_max = 0

    yellow_pixels = set()

    img = Image.open(image_name)
    rgb = img.convert('rgb')
    for x in range(img.size[0]):
        for y in range(img.size[1]):
            r, g, b = rgb.getpixel((x, y))
            if r >= r_min and r <= r_max and b >= b_min and b <= b_max and g >= g_min and g <= g_max:
                yellow_pixels.add((x,y))

    return yellow_pixels

Edit: fix, open( to Image.open(


问:
Using LINQ Where result in foreach: hidden if statement, double foreach?
```<code>foreach (Person criminal in people.Where(person => person.isCriminal)
{
    // do something
}
</code>```

I have this piece of code and want to know how does it actually work. Is it equivalent to an if statement nested inside the foreach iteration or does it first loop through the list of people and repeats the loop with selected values? I care to know more about this from the perspective of efficiency.

```<code>foreach (Person criminal in people)
{
    if (criminal.isCriminal)
    {
        // do something
    }
}
</code>```

答:
It depends on what people is.

If people is an IEnumerable object (like a collection, or the result of a method using yield) then the two pieces of code in your question are indeed equivalent.

A naïve Where could be implemented as:

```<code>public static IEnumerable<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
  // Error handling left out for simplicity.
  foreach (TSource item in source)
  {
    if (predicate(item))
    {
      yield return item;
    }
  }
}
</code>```

The actual code in Enumerable is a bit different to make sure that errors from passing a null source or predicate happen immediately rather than on the deferred execution, and to optimise for a few cases (e.g. source.Where(x => x.IsCriminal).Where(x => x.IsOnParole) is turned into the equivalent of source.Where(x => x.IsCriminal && x.IsOnParole) so that there's one fewer step in the chains of iterations), but that's the basic principle.

If however people is an IQueryable then things are different, and depend on the details of the query provider in question.

The simplest possibility is that the query provider can't do anything special with the Where and so it ends up just doing pretty much the above, because that will still work.

But often the query provider can do something else. Let's say people is a DbSet<Person> in Entity Framework assocated with a table in a database called people. If you do:

```<code>foreach(var person in people)
{
  DoSomething(person);
}
</code>```

Then Entity Framework will run SQL similar to:

```<code>SELECT *
FROM people
</code>```

And then create a Person object for each row returned. We could do the same filtering in about to implement Where but we can also do better.

If you do:

```<code>foreach (Person criminal in people.Where(person => person.isCriminal)
{
  DoSomething(person);
}
</code>```

Then Entity Framework will run SQL similar to:

```<code>SELECT *
FROM people
WHERE isCriminal = 1
</code>```

This means that the logic of deciding which elements to return is done in the database before it comes back to .NET. It allows for indices to be used in computing the WHERE which can be much more efficient, but even in the worse case of there being no useful indices and the database having to do a full scan it will still mean that those records we don't care about are never reported back from the database and there is no object created for them just to be thrown away again, so the difference in performance can be immense.

I care to know more about this from the perspective of efficiency

You are hopefully satisfied that there's no double pass as you suggested might happen, and happy to learn that it's even more efficient than the foreach … if you suggested when possible.

A bare foreach and if will still beat .Where() against an IEnumerable (but not against a database source) as there are a few overheads to Where that foreach and if don't have, but it's to a degree that is only worth caring about in very hot paths. Generally Where can be used with reasonable confidence in its efficiency.

Body:
foreach (Person criminal in people.Where(person => person.isCriminal)
{
    // do something
}

I have this piece of code and want to know how does it actually work. Is it equivalent to an if statement nested inside the foreach iteration or does it first loop through the list of people and repeats the loop with selected values? I care to know more about this from the perspective of efficiency.

foreach (Person criminal in people)
{
    if (criminal.isCriminal)
    {
        // do something
    }
}

Body:
It depends on what people is.

If people is an IEnumerable object (like a collection, or the result of a method using yield) then the two pieces of code in your question are indeed equivalent.

A naïve Where could be implemented as:

public static IEnumerable<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
  // Error handling left out for simplicity.
  foreach (TSource item in source)
  {
    if (predicate(item))
    {
      yield return item;
    }
  }
}

The actual code in Enumerable is a bit different to make sure that errors from passing a null source or predicate happen immediately rather than on the deferred execution, and to optimise for a few cases (e.g. source.Where(x => x.IsCriminal).Where(x => x.IsOnParole) is turned into the equivalent of source.Where(x => x.IsCriminal && x.IsOnParole) so that there's one fewer step in the chains of iterations), but that's the basic principle.

If however people is an IQueryable then things are different, and depend on the details of the query provider in question.

The simplest possibility is that the query provider can't do anything special with the Where and so it ends up just doing pretty much the above, because that will still work.

But often the query provider can do something else. Let's say people is a DbSet<Person> in Entity Framework assocated with a table in a database called people. If you do:

foreach(var person in people)
{
  DoSomething(person);
}

Then Entity Framework will run SQL similar to:

SELECT *
FROM people

And then create a Person object for each row returned. We could do the same filtering in about to implement Where but we can also do better.

If you do:

foreach (Person criminal in people.Where(person => person.isCriminal)
{
  DoSomething(person);
}

Then Entity Framework will run SQL similar to:

SELECT *
FROM people
WHERE isCriminal = 1

This means that the logic of deciding which elements to return is done in the database before it comes back to .NET. It allows for indices to be used in computing the WHERE which can be much more efficient, but even in the worse case of there being no useful indices and the database having to do a full scan it will still mean that those records we don't care about are never reported back from the database and there is no object created for them just to be thrown away again, so the difference in performance can be immense.

I care to know more about this from the perspective of efficiency

You are hopefully satisfied that there's no double pass as you suggested might happen, and happy to learn that it's even more efficient than the foreach … if you suggested when possible.

A bare foreach and if will still beat .Where() against an IEnumerable (but not against a database source) as there are a few overheads to Where that foreach and if don't have, but it's to a degree that is only worth caring about in very hot paths. Generally Where can be used with reasonable confidence in its efficiency.


问:
Import React in Node.js throws SyntaxError: Unexpected token export
I'm trying to implement SSR with Node.js and React following this example https://github.com/babel/example-node-server as advised in the official Babel docs here http://babeljs.io/docs/usage/cli/#babel-node

For development, I'm using babel-node; for production I want to transpile my server with babel and run it with node:

package.json

```<code>"scripts": {
  "start": "node ./dist/server/index.js",
  "dev:server": "nodemon ./src/server/index.js -x babel-node",
  "build:server": "babel ./src/server -d ./dist/server --copy-files -s inline"
},
"babel": {
  "presets": [
    "env",
    "react",
    "stage-2"
  ],
  "plugins": [
    "transform-decorators-legacy"
  ]
}
</code>```

The server is written with ES6 syntax:

src/server/index.js

```<code>import 'babel-polyfill'
import './config'
import Express from 'express'
import bootstrap from './bootstrap'

const app = Express()
bootstrap(app)

export default app
</code>```

Then in some route I import my React components to render it into HTML on request:

src/server/routes/admin.js

```<code>import { Router } from 'express'
import React from 'react'
import createHistory from 'history/createMemoryHistory'
import { renderToString } from 'react-dom/server'
import { Provider } from 'react-redux'
import { StaticRouter, matchPath } from 'react-router'
import configureStore from '../../../src/admin/store'
import routes from '../../../src/admin/routes'
import Root from '../../../src/admin/containers/Root'
// etc.
</code>```

The error is thrown when server tries to import React components

```<code>./src/admin/store/index.js:11
export default configureStore
^^^^^^

SyntaxError: Unexpected token export
</code>```

I tried using babel-register in the server, and it works, but it's not recommended to use it in production mode, so I would rather not do it.

Also, when inspecting the built server code, I find:

dist/server/routes/admin.js

```<code>var _store = require('../../../src/admin/store');
</code>```

It means that it's still referencing the src folder. Ideally I'd like to somehow incorporate those modules into the built server code, so I could safely remove the src folder from the production environment, leaving only dist.

Edit

Different from Babel 6 CLI: Unexpected token export?

答:
That's because you are transpiling only ./src/server and not ./src/admin. Then in ./src/server you have export keyword not translated by Babel and the export keyword is not supported by Node - to see why, see those answers:

Is it ok to use Babel npm package for node.js server application

javascript - Why is there a spec for sync and async modules?

Exporting Node module from promise result

You need to transpile all of the code that uses syntax that is not natively supported by Node, not only some of it.

Adding a script like this to your package.json might help, depending on how your ./src and ./dist is organized:

```<code>"build:all": "babel ./src -d ./dist --copy-files -s inline"
</code>```

Of course not knowing what you have in ./src apart from server and admin it's hard to give you a specific solution - but that's a good direction to start from.

Body:
I'm trying to implement SSR with Node.js and React following this example https://github.com/babel/example-node-server as advised in the official Babel docs here http://babeljs.io/docs/usage/cli/#babel-node

For development, I'm using babel-node; for production I want to transpile my server with babel and run it with node:

package.json

"scripts": {
  "start": "node ./dist/server/index.js",
  "dev:server": "nodemon ./src/server/index.js -x babel-node",
  "build:server": "babel ./src/server -d ./dist/server --copy-files -s inline"
},
"babel": {
  "presets": [
    "env",
    "react",
    "stage-2"
  ],
  "plugins": [
    "transform-decorators-legacy"
  ]
}

The server is written with ES6 syntax:

src/server/index.js

import 'babel-polyfill'
import './config'
import Express from 'express'
import bootstrap from './bootstrap'

const app = Express()
bootstrap(app)

export default app

Then in some route I import my React components to render it into HTML on request:

src/server/routes/admin.js

import { Router } from 'express'
import React from 'react'
import createHistory from 'history/createMemoryHistory'
import { renderToString } from 'react-dom/server'
import { Provider } from 'react-redux'
import { StaticRouter, matchPath } from 'react-router'
import configureStore from '../../../src/admin/store'
import routes from '../../../src/admin/routes'
import Root from '../../../src/admin/containers/Root'
// etc.

The error is thrown when server tries to import React components

./src/admin/store/index.js:11
export default configureStore
^^^^^^

SyntaxError: Unexpected token export

I tried using babel-register in the server, and it works, but it's not recommended to use it in production mode, so I would rather not do it.

Also, when inspecting the built server code, I find:

dist/server/routes/admin.js

var _store = require('../../../src/admin/store');

It means that it's still referencing the src folder. Ideally I'd like to somehow incorporate those modules into the built server code, so I could safely remove the src folder from the production environment, leaving only dist.

Edit

Different from Babel 6 CLI: Unexpected token export?

Body:
That's because you are transpiling only ./src/server and not ./src/admin. Then in ./src/server you have export keyword not translated by Babel and the export keyword is not supported by Node - to see why, see those answers:

Is it ok to use Babel npm package for node.js server application

javascript - Why is there a spec for sync and async modules?

Exporting Node module from promise result

You need to transpile all of the code that uses syntax that is not natively supported by Node, not only some of it.

Adding a script like this to your package.json might help, depending on how your ./src and ./dist is organized:

"build:all": "babel ./src -d ./dist --copy-files -s inline"

Of course not knowing what you have in ./src apart from server and admin it's hard to give you a specific solution - but that's a good direction to start from.


问:
Laravel error in /bootstrap/start.php: \Illuminate\Foundation\Application not found
So, I installed Laravel on a dev server (php5.5.3, standard installation, mcrypt installed), and I get the following error message:

```<code>Fatal error: Class 'Illuminate\Foundation\Application' not found in /[path_to_laravel_app]/bootstrap/start.php on line 14
</code>```

Quite odd, and I haven't seen a solution to this file, although I've seen plenty of similar errors. Any advice welcome. Thanks!

答:
Just Run the command

```<code>composer install --no-scripts
</code>```

Or,

```<code>composer update --no-scripts
</code>```

Body:
So, I installed Laravel on a dev server (php5.5.3, standard installation, mcrypt installed), and I get the following error message:

Fatal error: Class 'Illuminate\Foundation\Application' not found in /[path_to_laravel_app]/bootstrap/start.php on line 14

Quite odd, and I haven't seen a solution to this file, although I've seen plenty of similar errors. Any advice welcome. Thanks!

Body:
Just Run the command

composer install --no-scripts

Or,

composer update --no-scripts


问:
Can I change my android application style at runtime?
I want to change the manifest style when the user chooses a setting in the preferences file or settings. I have a setting in my apk which includes a list of preferences with three entries {Style_1, Style_2, Style_3}. I want to change the style color, like primaryColor, when the user clicks a style. How can I do this?

答:
I think, setting theme after a button click or option choosen could be harsh for an Activity to handle.
What I am suggesting you is to reload your activity on button click but before that simply save the style_name , the user want to apply in internal memory or Shared Preferences. You can apply shared preference simply looking at here.

At the start of onCreate of your activity, apply that fetching part of shared preferences and apply the theme as user has indicated. This would help you to preserve the theme for that user until s/he uninstall that application or clears the app data.
If s/he is using the application for first time, the stored style_name string would be null so load your application with default theme.

You can simply reload your activity on button click by using the below code:

```<code>public void onClick (View v){
    Intent intent = getIntent();
    finish();
    startActivity(intent);
}
</code>```

Hope it helps !!

Body:
I think, setting theme after a button click or option choosen could be harsh for an Activity to handle.
What I am suggesting you is to reload your activity on button click but before that simply save the style_name , the user want to apply in internal memory or Shared Preferences. You can apply shared preference simply looking at here.

At the start of onCreate of your activity, apply that fetching part of shared preferences and apply the theme as user has indicated. This would help you to preserve the theme for that user until s/he uninstall that application or clears the app data.
If s/he is using the application for first time, the stored style_name string would be null so load your application with default theme.

You can simply reload your activity on button click by using the below code:

public void onClick (View v){
    Intent intent = getIntent();
    finish();
    startActivity(intent);
}

Hope it helps !!


问:
Wordpress protected page, POST form on a other page
I,

I'm trying to add a form to a page, that send password to the wp-login.php?action=postpass via POST method, and then redirect the user to the protected page.

Problem is the action=postpass seems to look at the page currently used to send password via form for the redirection.

This form is on homepage and can be completed by anyone, only password is asked.

Is there a solution to do it ?

答:
Ok guys, i did make it

This is actually not a good solution to this problem, because you will need to override some wordpress files (wp-login.php).

1) Set your page private with a password

2) Insert this form in an other page (typique postpass wordpress form) :

```<code><form action="https://exemple.com/wp-login.php?action=postpass" class="post-password-form" method="post" id="go-pro-espace">
     <input name="post_password" id="exemple" type="password" size="20" /><br />
     <input type="submit" value="submit">
</form>
</code>```

3) Change your /wp-login.php file (root directory, at this time, this is located line 460) :

```<code>from:
wp_safe_redirect( wp_get_referer() );
to:
wp_safe_redirect( "https://exemple.fr/your-protected-page" );
</code>```

Body:
Ok guys, i did make it

This is actually not a good solution to this problem, because you will need to override some wordpress files (wp-login.php).

1) Set your page private with a password

2) Insert this form in an other page (typique postpass wordpress form) :

<form action="https://exemple.com/wp-login.php?action=postpass" class="post-password-form" method="post" id="go-pro-espace">
     <input name="post_password" id="exemple" type="password" size="20" /><br />
     <input type="submit" value="submit">
</form>

3) Change your /wp-login.php file (root directory, at this time, this is located line 460) :

from:
wp_safe_redirect( wp_get_referer() );
to:
wp_safe_redirect( "https://exemple.fr/your-protected-page" );


问:
Logging Framework for the ASP.NET application
My application needs to log informations about user actions (inserts, updates, deletes, etc) and exceptions and i want to store de log on Oracle10, so i'am searching some log framework to use.
I read a little bit about:

1 -Log4Net

2 - Logging Application Block

3 - Elmah

Whats your opinion about these log tools?
Whats a good framework (or way to implement) log on my application?

*After a discussion with the project manager, Logging Application Block
 will be our choice, but, lets comment about this =)

答:
I personally always create a wrapper anyway, so I have my own ILog implementation, that works with whichever of these that you choose.  This makes it easy to swap in or our implementations.

I tried #2 but it was kind of a pain; #1 would have worked out well for us but we didn't go for it, just went simple custom logging.  All I know about #3 is that I know of someone having trouble implementing it in their org.  Don't know why, but it actually looks pretty interesting.  I don't think you can go wrong with any personally.  It partially depends on the API that you like.

HTH.

ContentLicense: CC BY-SA 2.5


问:
Linq Query C# ( Multiple Occurrences in String array)
Guys I know this might be a naive Question but i got to ask.
I have array of string
List<string> lstPets = new List<string> { "dog", "cat","horse","parrot" };

And a string

string paragraph = "This is a test script to test whether a dog exists or not";

Now I have to write a linq query to find whether any occurrence of "lstPets" in "paragrah".

Thanks in advance. :)

答:
```<code>var lstPets = new List<string> { "dog", "cat","horse","parrot" };

string paragraph = "This is a test script to test whether a dog exists or not";
</code>```

```<code>var containsAny = lstPets.Any(paragraph.Contains);
</code>```

Or maybe more tolerant:

```<code>var containsAny = lstPets.Any(pet => paragraph.Contains(pet, StringComparison.OrdinalIgnoreCase));
</code>```

Body:
var lstPets = new List<string> { "dog", "cat","horse","parrot" };

string paragraph = "This is a test script to test whether a dog exists or not";

var containsAny = lstPets.Any(paragraph.Contains);

Or maybe more tolerant:

var containsAny = lstPets.Any(pet => paragraph.Contains(pet, StringComparison.OrdinalIgnoreCase));


问:
Python: time.clock() does not match real execution time
I am testing the execution time of a python script.
The script begins with

```<code>from time import clock
print clock()
</code>```

and ends with

```<code>print clock()
</code>```

My script executes much longer than the time difference I get with this method. I want to know why this happens? Is the processor time counted in a different way than I think?

Thanks for advice!

答: If what you need is real execution time rather than CPU time, use time.time instead of time.clock; also, you might be interested in timeit module.

Body:
I am testing the execution time of a python script.
The script begins with

from time import clock
print clock()

and ends with

print clock()

My script executes much longer than the time difference I get with this method. I want to know why this happens? Is the processor time counted in a different way than I think?

Thanks for advice!


问:
Symfony3 I have to show from a related entity
I have a question.

I have 2 entity

```<code>/**
 * @ORM\Entity
 * @ORM\Table(name="call_center")
 */
class Call {

    /**
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Id
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\OneToMany(targetEntity="Number", mappedBy="number")
     * @ORM\Column(type="string")
     */
    private $number;

    /**
     * @ORM\Column(type="string")
     */
      private $value;
......
    getters setters

/**
 * @ORM\Entity
 * @ORM\Table(name="number")
 */
class Number {

    /**
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Id
     * @ORM\Column(type="integer")
     *
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="Call", inversedBy="number")
     * @ORM\JoinColumn(nullable=false)
     */
    private $number;

    /**
     * @ORM\Column(type="string")
     */
    private $link;
</code>```

And I would like to show my data in controller.
This is my controller

```<code>class DefaultController extends Controller
{
    /**
     * @Route("/pl/", name="homepage")
     */
    public function indexAction(Request $request)
    {
        $em = $this->getDoctrine()->getRepository('AppBundle:Call')->findAll();

        foreach ($em as $name) {
        switch(1) {
            case $name->getNumber():
                echo $name->getValue();
                echo $name->getLink(); <----PROBLEME
                break;
            default:
                break;
        }
        }

        return $this->render('default/index.html.twig', array(
            'em' => $name
        ));
    }
}
</code>```

Data with entity call displayed but I don't know how dipsplay data from Number (getLink()). The problem is that I have a loop in which I have to display for a particular value relationship. Probably I have to create repository for entity?

```<code>Entity Call
/**
 * Get id
 *
 * @return integer
 */
public function getId()
{
    return $this->id;
}

/**
 * Set number
 *
 * @param string $number
 *
 * @return Call
 */
public function setNumber($number)
{
    $this->number = $number;

    return $this;
}

/**
 * Get number
 *
 * @return string
 */
public function getNumber()
{
    return $this->number;
}

/**
 * Set value
 *
 * @param string $value
 *
 * @return Call
 */
public function setValue($value)
{
    $this->value = $value;

    return $this;
}

/**
 * Get value
 *
 * @return string
 */
public function getValue()
{
    return $this->value;
}

entity Number

/**
     * Set number
     *
     * @param \AppBundle\Entity\Call $number
     *
     * @return Number
     */
    public function setNumber(\AppBundle\Entity\Call $number)
    {
        $this->number = $number;

        return $this;
    }

    /**
     * Get number
     *
     * @return \AppBundle\Entity\Call
     */
    public function getNumber()
    {
        return $this->number;
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set link
     *
     * @param string $link
     *
     * @return Number
     */
    public function setLink($link)
    {
        $this->link = $link;

        return $this;
    }

    /**
     * Get link
     *
     * @return string
     */
    public function getLink()
    {
        return $this->link;
    }
</code>```

答:
Have you tried to access it via   $name->getNumber()->getLink()  ?

as pointed out below, by tny,   you should fix your annotations, or the above will not work, as getNumber() is currently returning a string instead of a Number instance

Body:
I have a question.

I have 2 entity

/**
 * @ORM\Entity
 * @ORM\Table(name="call_center")
 */
class Call {

    /**
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Id
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\OneToMany(targetEntity="Number", mappedBy="number")
     * @ORM\Column(type="string")
     */
    private $number;

    /**
     * @ORM\Column(type="string")
     */
      private $value;
......
    getters setters

/**
 * @ORM\Entity
 * @ORM\Table(name="number")
 */
class Number {

    /**
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Id
     * @ORM\Column(type="integer")
     *
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="Call", inversedBy="number")
     * @ORM\JoinColumn(nullable=false)
     */
    private $number;

    /**
     * @ORM\Column(type="string")
     */
    private $link;

And I would like to show my data in controller.
This is my controller

class DefaultController extends Controller
{
    /**
     * @Route("/pl/", name="homepage")
     */
    public function indexAction(Request $request)
    {
        $em = $this->getDoctrine()->getRepository('AppBundle:Call')->findAll();

        foreach ($em as $name) {
        switch(1) {
            case $name->getNumber():
                echo $name->getValue();
                echo $name->getLink(); <----PROBLEME
                break;
            default:
                break;
        }
        }

        return $this->render('default/index.html.twig', array(
            'em' => $name
        ));
    }
}

Data with entity call displayed but I don't know how dipsplay data from Number (getLink()). The problem is that I have a loop in which I have to display for a particular value relationship. Probably I have to create repository for entity?

Entity Call
/**
 * Get id
 *
 * @return integer
 */
public function getId()
{
    return $this->id;
}

/**
 * Set number
 *
 * @param string $number
 *
 * @return Call
 */
public function setNumber($number)
{
    $this->number = $number;

    return $this;
}

/**
 * Get number
 *
 * @return string
 */
public function getNumber()
{
    return $this->number;
}

/**
 * Set value
 *
 * @param string $value
 *
 * @return Call
 */
public function setValue($value)
{
    $this->value = $value;

    return $this;
}

/**
 * Get value
 *
 * @return string
 */
public function getValue()
{
    return $this->value;
}

entity Number

/**
     * Set number
     *
     * @param \AppBundle\Entity\Call $number
     *
     * @return Number
     */
    public function setNumber(\AppBundle\Entity\Call $number)
    {
        $this->number = $number;

        return $this;
    }

    /**
     * Get number
     *
     * @return \AppBundle\Entity\Call
     */
    public function getNumber()
    {
        return $this->number;
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set link
     *
     * @param string $link
     *
     * @return Number
     */
    public function setLink($link)
    {
        $this->link = $link;

        return $this;
    }

    /**
     * Get link
     *
     * @return string
     */
    public function getLink()
    {
        return $this->link;
    }


问:
Why doesn't `Box::new` return an `Option` or `Result`?
I don't understand why Box::new doesn't return an Option or Result.

The allocation can fail because memory is not unlimited, or something else could happen; what is the behavior in such cases? I can't find any information about it.

答:
I found the following communication between the Rust developers regarding some of the lower-level functions in liballoc not returning Options: PR #14230.

Especially the following parts explain some of the reasons behind it:

huonw:

Hm... shouldn't the lowest level library not be triggering task
failure? Are we planning to have any lower-level libraries returning
Option or something?

alexcrichton:

I found that it was quite common to want to trigger task failure, much more so than I originally realized. I also found that all contexts have some form or notion of failure, although it's not always task failure.

huonw:

I was thinking from the perspective of task failure not being recoverable at the call site, i.e. a higher level library is free to fail, but the absolute lowest building blocks shouldn't, so that people can handle problems as they wish (even if it's just manually triggering task failure). If liballoc isn't designed to be the lowest level allocation library, failing is fine. (BTW, I think you may've misinterpreted my comment, because I wasn't talking about libcore, just liballoc.)

alexcrichton:

Oops, sorry! I believe that the core allocator interface (located in liballoc) will be specced to not fail!(), just the primitives on top of them (for example, the box operator).

Perhaps we could extend the box syntax to allow returning Option one day to accommodate this use case, because I'd definitely like to be able to re-use this code!


问:
Rails: Active Model explanation?
What's the difference from Active Resource and Active Record in Rails?</p>

答:
ActiveRecord: ORM to manage data in a relational database through SQL. read more..

ActiveResource: Manage data through a REST API on another server, no longer a part of Rails, but extracted as a gem. read more..

ActiveModel: Behavior (mixins) to make any Ruby object act like it's ActiveRecord or ActiveResource by adding validations, callbacks, naming conventions, tracking, etc. read more..

Title: Rails: Active Model explanation?


问:
Angular location search does not work with &
/course-home#/search?q=my%20lab%20%26%20mastering&%20kamal&ref=%2Ftab%2Factive

```<code>$scope.keyword = $location.search().q;
</code>```

In my angular app when I search for "my lab & mastering" $location.search().q returns only "my lab" and does not return full string. after the "&" it does not work properly. What is the best way to get query string from above URL ?

答:
Found the issue, and the issue was URL encoding not done properly.

```<code>$location.url('/search?q=' + searchText + '&ref=' + $location.$$path);
</code>```

To fix the issue need to encode the searchText variable

```<code>$location.url('/search?q=' + encodeURIComponent(searchText) + '&ref=' + $location.$$path);
</code>```

Body:
/course-home#/search?q=my%20lab%20%26%20mastering&%20kamal&ref=%2Ftab%2Factive

$scope.keyword = $location.search().q;

In my angular app when I search for "my lab & mastering" $location.search().q returns only "my lab" and does not return full string. after the "&" it does not work properly. What is the best way to get query string from above URL ?

Body:
Found the issue, and the issue was URL encoding not done properly.

$location.url('/search?q=' + searchText + '&ref=' + $location.$$path);

To fix the issue need to encode the searchText variable

$location.url('/search?q=' + encodeURIComponent(searchText) + '&ref=' + $location.$$path);


问:
jquery event delegation on static content doesn't work
JQuery event delegation not working on static content but work perfectly on dynamically added element. Alert('test') works perfectly on the dynamically added divs but not on static divs which are already present there.

$(document).ready(function() {
      $('.addPost').on('click', function() {
          console.log("hello");

          var dyanamicdiv =
          '
'+
          '
'+
          '          hello'+
          '
'+
          '
';

          $('.post-container').append(dyanamicdiv);

      });
      $('.post-container').on('click', '.click-delgated-event', function() {
        alert("test");
      });
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="post-container">
    <div>
        <div class="click-delgated-event">
            hello
        </div>
    </div>
</div>
<button class="addPost" type="button" name="button"> ADD POST </button></code>```

答:
add the - to your div class name

like below:

```<code><div class="click-delgated-event">
   hello
</div>
</code>```

you are by mistake - missing in your class name

so its work properly

Body:
JQuery event delegation not working on static content but work perfectly on dynamically added element. Alert('test') works perfectly on the dynamically added divs but not on static divs which are already present there.

$(document).ready(function() {
      $('.addPost').on('click', function() {
          console.log("hello");

          var dyanamicdiv =
          '
'+
          '
'+
          '          hello'+
          '
'+
          '
';

          $('.post-container').append(dyanamicdiv);

      });
      $('.post-container').on('click', '.click-delgated-event', function() {
        alert("test");
      });
  });

            hello

<button class="addPost" type="button" name="button"> ADD POST </button>

Body:
add the - to your div class name

like below:

<div class="click-delgated-event">
   hello
</div>

you are by mistake - missing in your class name

so its work properly


问:
Kill Process Excel C#
I have to 2 process excel. For example:

1) example1.xlsx
2) example2.xlsx

How to kill first "example1.xlsx"?

I use this code:

```<code>   foreach (Process clsProcess in Process.GetProcesses())
     if (clsProcess.ProcessName.Equals("EXCEL"))  //Process Excel?
          clsProcess.Kill();
</code>```

That kill a both.
I wanna kill just one...
Thank you.

答:
Copy and paste this. Its done! </p>

```<code> System.Diagnostics.Process[] process = System.Diagnostics.Process.GetProcessesByName("Excel");
     foreach (System.Diagnostics.Process p in process)
     {
         if (!string.IsNullOrEmpty(p.ProcessName))
         {
             try
             {
                 p.Kill();
             }
             catch { }
         }
     }
</code>```

Title: Kill Process Excel C#

Body:
I have to 2 process excel. For example:

1) example1.xlsx
2) example2.xlsx

How to kill first "example1.xlsx"?

I use this code:

   foreach (Process clsProcess in Process.GetProcesses())
     if (clsProcess.ProcessName.Equals("EXCEL"))  //Process Excel?
          clsProcess.Kill();

That kill a both.
I wanna kill just one...
Thank you.

Body:
Copy and paste this. Its done!

 System.Diagnostics.Process[] process = System.Diagnostics.Process.GetProcessesByName("Excel");
     foreach (System.Diagnostics.Process p in process)
     {
         if (!string.IsNullOrEmpty(p.ProcessName))
         {
             try
             {
                 p.Kill();
             }
             catch { }
         }
     }


问:
Load failed: Name cannot begin with the '<' character, hexadecimal value 0*3c. Line 610, position 3

Not able to open solution, I'n not getting how to resolve it any help appreciated,
Thank you,

答:
I found whats causing this error,
Xamarin.ios.commontargets file has that "<" at line 610,
I removed it it's working fine now.
Thank you</p>


问:
Load data from MongoDb to Elasticsearch through python
I have some json data loaded in MongoDb. e.g. doc1 = {"id": 1,"name": "x1"},doc2 = {"id": 2,"name": "x2"},doc3 = {"id": 3,"name": "x3"}. Now I want this data to import from MongoDb to Elasticsearch. I wrote this piece of code.

mgclient = MongoClient()
db = mgclient['light-test']
col = db['test']

es1 = Elasticsearch()
print ("Connected", es1.info())

es1.indices.create(index='light-test', ignore=400)

# Pull from mongo and dump into ES using bulk API
actions = []
for data in tqdm(col.find(), total=col.count()):
    data.pop('_id')
    action = {
        "_index": 'light-test',
        "_type": 'test',
        "_source": data
    }
    actions.append(action)
    print("complete")

# Dump x number of objects at a time
    if len(actions) >= 100:
        deque(parallel_bulk(es1, actions), maxlen=0)
        actions = []

print("done")

a = es1.search(index='light-test', body={
  'query': {
    'match_all': {
     }
  }
})
print(a)```

The problem is in the query returned. The hits shows blank whereas it should had returned the json files.
results

Help me in importing the data from MongoDb to Elasticsearch.

答:
app = Flask(__name__)

MONGO_URL = '...'
mgclient = MongoClient(MONGO_URL, ssl=True, ssl_cert_reqs=ssl.CERT_NONE)
db = mgclient['light']
col = db['task']

doc1 = {...}
doc2 = {...}
doc3 = {...}
post_id = col.insert_many([doc1, doc2, doc3])

print(col.count())

es1 = Elasticsearch(...)
ESinfo=(es1.info())

# Pull from mongo and dump into ES using bulk API
actions = []
for data in tqdm(col.find(), total=col.count()):
    data.pop('_id')
    action = {
            "index": {
                    "_index": 'light',
                    "_type": 'task',
                    }
    }
    actions.append(action)
    actions.append(data)

#delete = es1.indices.delete(index = 'light')
request_body = {
    "settings" : {
        "number_of_shards": 1,
        "number_of_replicas": 0
    }
}
es1.indices.create(index='light', body = request_body, ignore=400)
res = es1.bulk(index = 'light', body = actions, refresh = True)

result = col.find()
names = []
for obj in col.find():
    name = obj['name']
    names.append(name)
    print(names)

@app.route('/query')
def Query():
    a = es1.search(index='light', body={
      'query': {
        'match': {
          'name': '...',
         }
      }
    })
    return jsonify(query=a)

if __name__ == "__main__":
 app.run(host='0.0.0.0', port=1024)
  ```

This has helped. thank you :)

Body:
I have some json data loaded in MongoDb. e.g. doc1 = {"id": 1,"name": "x1"},doc2 = {"id": 2,"name": "x2"},doc3 = {"id": 3,"name": "x3"}. Now I want this data to import from MongoDb to Elasticsearch. I wrote this piece of code.

mgclient = MongoClient()
db = mgclient['light-test']
col = db['test']

es1 = Elasticsearch()
print ("Connected", es1.info())

es1.indices.create(index='light-test', ignore=400)

# Pull from mongo and dump into ES using bulk API
actions = []
for data in tqdm(col.find(), total=col.count()):
    data.pop('_id')
    action = {
        "_index": 'light-test',
        "_type": 'test',
        "_source": data
    }
    actions.append(action)
    print("complete")

# Dump x number of objects at a time
    if len(actions) >= 100:
        deque(parallel_bulk(es1, actions), maxlen=0)
        actions = []

print("done")

a = es1.search(index='light-test', body={
  'query': {
    'match_all': {
     }
  }
})
print(a)

The problem is in the query returned. The hits shows blank whereas it should had returned the json files.
results

Help me in importing the data from MongoDb to Elasticsearch.

Body:
app = Flask(__name__)

MONGO_URL = '...'
mgclient = MongoClient(MONGO_URL, ssl=True, ssl_cert_reqs=ssl.CERT_NONE)
db = mgclient['light']
col = db['task']

doc1 = {...}
doc2 = {...}
doc3 = {...}
post_id = col.insert_many([doc1, doc2, doc3])

print(col.count())

es1 = Elasticsearch(...)
ESinfo=(es1.info())

# Pull from mongo and dump into ES using bulk API
actions = []
for data in tqdm(col.find(), total=col.count()):
    data.pop('_id')
    action = {
            "index": {
                    "_index": 'light',
                    "_type": 'task',
                    }
    }
    actions.append(action)
    actions.append(data)

#delete = es1.indices.delete(index = 'light')
request_body = {
    "settings" : {
        "number_of_shards": 1,
        "number_of_replicas": 0
    }
}
es1.indices.create(index='light', body = request_body, ignore=400)
res = es1.bulk(index = 'light', body = actions, refresh = True)

result = col.find()
names = []
for obj in col.find():
    name = obj['name']
    names.append(name)
    print(names)

@app.route('/query')
def Query():
    a = es1.search(index='light', body={
      'query': {
        'match': {
          'name': '...',
         }
      }
    })
    return jsonify(query=a)

if __name__ == "__main__":
 app.run(host='0.0.0.0', port=1024)

This has helped. thank you :)


问:
Summary table (using tables or xtable package) with counts at 3 level of depth
I am using the tabular function from tables package to get a summary table of the "df" dataframe. I need to get an output that can be processed to get a Latex table with multirow-cells capability.

Here below is the dummy "df" dataframe:

```<code>age <- c(62, 60, 63, 59, 63, 67, 71, 64, 65, 66, 68, 66, 71, 67, 68, 68, 56, 62, 60, 61, 63, 64, 63, 59)
L3 <- factor(rep(paste(LETTERS[7:16], LETTERS[7:16], LETTERS[7:16], sep=""), c(1,3,2,1,3,5,1,1,6,1)))
L2 <- factor(rep(paste(LETTERS[3:6], LETTERS[3:6], sep=""), c(4,6,6,8)))
L1 <- factor(rep(LETTERS[1:2], c(10,14)))
df <- data.frame(Top=L1, Mid=L2, Low=L3, Age=age, stringsAsFactors=F)
</code>```

I use the following R command line to produce the summary table:

```<code>tabular( (Top*Mid*Low*DropEmpty()) ~ (CL3=1) + (Age)*(Format(digits=2, latex=T)*mean + Format(digits=3, latex=T)*sd), data=df)
</code>```

The summary table generated with this command line is the following:

```<code>                 Age
 Top Mid Low CL3 mean sd
 A   CC  GGG 1   62     NA
         HHH 3   61   2.08
     DD  III 2   65   2.83
         JJJ 1   71     NA
         KKK 3   65   1.00
 B   EE  LLL 5   68   1.87
         MMM 1   68     NA
     FF  NNN 1   56     NA
         OOO 6   62   1.47
         PPP 1   59     NA
</code>```

Caption: with CL3 which is a just short names meaning "Count at Level 3" (i.e : for Top-Mid-Low combination).

But I would like to get this (2 extra count columns (CL1 and CL2) respectively at level "Top" and "Mid"):

```<code>                 Age
 Top CL1 Mid CL2 Low CL3 mean sd
 A   10  CC  4   GGG 1   62     NA
                 HHH 3   61   2.08
         DD  6   III 2   65   2.83
                 JJJ 1   71     NA
                 KKK 3   65   1.00
 B   14  EE  6   LLL 5   68   1.87
                 MMM 1   68     NA
         FF  8   NNN 1   56     NA
                 OOO 6   62   1.47
                 PPP 1   59     NA
</code>```

Caption: with CL1, CL2, CL3 which are just short names meaning "Count at Level x" (with x standing for Top, Top-Mid, Top-Mid-Low combination).

So, could you help me to figure out how I can get this with the tabular function of the tables package? I need to use this function, or at least any others that can output Latex code handling multirow-cells capability (ex: xtable, or bytable of taRifx package) because I want to output a picture (.EMF or .SVG or .JPG) of this table with verticaly centered multirow cells.

答:
Here's one using dplyr and (my) huxtable package:

```<code>library(huxtable)
library(dplyr)

# prepare summaries:
df_sum <- df %>%
      group_by(Top) %>% mutate(CL1 = n()) %>%
      group_by(Mid, add = TRUE) %>% mutate(CL2 = n()) %>%
      group_by(Low, add = TRUE) %>% mutate(CL3 = n()) %>%
      summarize(
        mean = mean(Age),
        sd   = sd(Age),
        CL1  = CL1[1],
        CL2  = CL2[1],
        CL3  = CL3[1]
      ) %>%
      select(Top, CL1, Mid, CL2, Low, CL3, mean, sd)

# format for LaTeX/HTML output:
hux_sum <- as_hux(df_sum)
rowspan(hux_sum)[c(1,6), 1:2] <- 5
rowspan(hux_sum)[c(1,3,6,8), 3:4] <- c(2,3,2,3)
number_format(hux_sum)[, 1:6] <- 0
hux_sum
</code>```

Body:
I am using the tabular function from tables package to get a summary table of the "df" dataframe. I need to get an output that can be processed to get a Latex table with multirow-cells capability.

Here below is the dummy "df" dataframe:

age <- c(62, 60, 63, 59, 63, 67, 71, 64, 65, 66, 68, 66, 71, 67, 68, 68, 56, 62, 60, 61, 63, 64, 63, 59)
L3 <- factor(rep(paste(LETTERS[7:16], LETTERS[7:16], LETTERS[7:16], sep=""), c(1,3,2,1,3,5,1,1,6,1)))
L2 <- factor(rep(paste(LETTERS[3:6], LETTERS[3:6], sep=""), c(4,6,6,8)))
L1 <- factor(rep(LETTERS[1:2], c(10,14)))
df <- data.frame(Top=L1, Mid=L2, Low=L3, Age=age, stringsAsFactors=F)

I use the following R command line to produce the summary table:

tabular( (Top*Mid*Low*DropEmpty()) ~ (CL3=1) + (Age)*(Format(digits=2, latex=T)*mean + Format(digits=3, latex=T)*sd), data=df)

The summary table generated with this command line is the following:

                 Age
 Top Mid Low CL3 mean sd
 A   CC  GGG 1   62     NA
         HHH 3   61   2.08
     DD  III 2   65   2.83
         JJJ 1   71     NA
         KKK 3   65   1.00
 B   EE  LLL 5   68   1.87
         MMM 1   68     NA
     FF  NNN 1   56     NA
         OOO 6   62   1.47
         PPP 1   59     NA

Caption: with CL3 which is a just short names meaning "Count at Level 3" (i.e : for Top-Mid-Low combination).

But I would like to get this (2 extra count columns (CL1 and CL2) respectively at level "Top" and "Mid"):

                 Age
 Top CL1 Mid CL2 Low CL3 mean sd
 A   10  CC  4   GGG 1   62     NA
                 HHH 3   61   2.08
         DD  6   III 2   65   2.83
                 JJJ 1   71     NA
                 KKK 3   65   1.00
 B   14  EE  6   LLL 5   68   1.87
                 MMM 1   68     NA
         FF  8   NNN 1   56     NA
                 OOO 6   62   1.47
                 PPP 1   59     NA

Caption: with CL1, CL2, CL3 which are just short names meaning "Count at Level x" (with x standing for Top, Top-Mid, Top-Mid-Low combination).

So, could you help me to figure out how I can get this with the tabular function of the tables package? I need to use this function, or at least any others that can output Latex code handling multirow-cells capability (ex: xtable, or bytable of taRifx package) because I want to output a picture (.EMF or .SVG or .JPG) of this table with verticaly centered multirow cells.

Body:
Here's one using dplyr and (my) huxtable package:

library(huxtable)
library(dplyr)

# prepare summaries:
df_sum <- df %>%
      group_by(Top) %>% mutate(CL1 = n()) %>%
      group_by(Mid, add = TRUE) %>% mutate(CL2 = n()) %>%
      group_by(Low, add = TRUE) %>% mutate(CL3 = n()) %>%
      summarize(
        mean = mean(Age),
        sd   = sd(Age),
        CL1  = CL1[1],
        CL2  = CL2[1],
        CL3  = CL3[1]
      ) %>%
      select(Top, CL1, Mid, CL2, Low, CL3, mean, sd)

# format for LaTeX/HTML output:
hux_sum <- as_hux(df_sum)
rowspan(hux_sum)[c(1,6), 1:2] <- 5
rowspan(hux_sum)[c(1,3,6,8), 3:4] <- c(2,3,2,3)
number_format(hux_sum)[, 1:6] <- 0
hux_sum


问:
Could not load file or assembly 'Owin, Version=1.0.0.0, Culture=neutral, PublicKeyToken=f0ebd12fd5e55cc5'

Description: An unhanded exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.

Exception Details: System.IO.FileNotFoundException: Could not load
file or assembly 'Owin, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=f0ebd12fd5e55cc5' or one of its dependencies. The
system cannot find the file specified.

Source Error:

An unhandled exception was generated during the execution of the
current web request. Information regarding the origin and location
of the exception can be identified using the exception stack trace
below.

Assembly Load Trace: The following information can be helpful to
determine why the assembly 'Owin, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=f0ebd12fd5e55cc5' could not be loaded.

=== Pre-bind state information === LOG: DisplayName = Owin, Version=1.0.0.0, Culture=neutral, PublicKeyToken=f0ebd12fd5e55cc5
(Fully-specified) LOG: Appbase = file:///E:/Working
File/V1/V1/InfraERP/Infra.AuditWS/ LOG: Initial PrivatePath =
E:\Working File\V1\V1\InfraERP\Infra.AuditWS\bin Calling assembly :
Microsoft.Owin.Host.SystemWeb, Version=3.0.1.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35.
=== LOG: This bind starts in default load context. LOG: Using application configuration file: E:\Working
File\V1\V1\InfraERP\Infra.AuditWS\web.config LOG: Using host
configuration file:
C:\Users\Infra04\Documents\IISExpress\config\aspnet.config LOG:
Using machine configuration file from
C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
LOG: Post-policy reference: Owin, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=f0ebd12fd5e55cc5 LOG: Attempting download of new URL
file:///C:/Users/Infra04/AppData/Local/Temp/Temporary ASP.NET
Files/root/b2eb5b6f/c83c34d7/Owin.DLL. LOG: Attempting download of
new URL file:///C:/Users/Infra04/AppData/Local/Temp/Temporary
ASP.NET Files/root/b2eb5b6f/c83c34d7/Owin/Owin.DLL. LOG: Attempting
download of new URL file:///E:/Working
File/V1/V1/InfraERP/Infra.AuditWS/bin/Owin.DLL. LOG: Attempting
download of new URL file:///E:/Working
File/V1/V1/InfraERP/Infra.AuditWS/bin/Owin/Owin.DLL. LOG: Attempting
download of new URL
file:///C:/Users/Infra04/AppData/Local/Temp/Temporary ASP.NET
Files/root/b2eb5b6f/c83c34d7/Owin.EXE. LOG: Attempting download of
new URL file:///C:/Users/Infra04/AppData/Local/Temp/Temporary
ASP.NET Files/root/b2eb5b6f/c83c34d7/Owin/Owin.EXE. LOG: Attempting
download of new URL file:///E:/Working
File/V1/V1/InfraERP/Infra.AuditWS/bin/Owin.EXE. LOG: Attempting
download of new URL file:///E:/Working
File/V1/V1/InfraERP/Infra.AuditWS/bin/Owin/Owin.EXE.

Stack Trace:

[FileNotFoundException: Could not load file or assembly 'Owin,
Version=1.0.0.0, Culture=neutral, PublicKeyToken=f0ebd12fd5e55cc5'
or one of its dependencies. The system cannot find the file
specified.]

Microsoft.Owin.Host.SystemWeb.OwinHttpModule.InitializeBlueprint()
+0    System.Threading.LazyInitializer.EnsureInitializedCore(T& target, Boolean& initialized, Object& syncLock, Func`1 valueFactory)
+115    Microsoft.Owin.Host.SystemWeb.OwinHttpModule.Init(HttpApplication
context) +106

System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr
appContext, HttpContext context, MethodInfo[] handlers) +536

System.Web.HttpApplication.InitSpecial(HttpApplicationState state,
MethodInfo[] handlers, IntPtr appContext, HttpContext context) +172
System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr
appContext, HttpContext context) +336

System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr
appContext) +296

[HttpException (0x80004005): Could not load file or assembly 'Owin,
Version=1.0.0.0, Culture=neutral, PublicKeyToken=f0ebd12fd5e55cc5'
or one of its dependencies. The system cannot find the file
specified.]    System.Web.HttpRuntime.FirstRequestInit(HttpContext
context) +9963856

答:
```<code>Please change in the line "bindingRedirect " your web.config if your version of microsoft.owin is 3.0.0

<runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</code>```


问:
does try catch clause affect performance?
does try/catch affects performance if no exception thrown in try block?

how about try/catch/finally?

答:
No, a try/catch block does not incur any performance cost when an exception is not thrown.

Read a great MSDN article about this here:
http://msdn.microsoft.com/en-us/library/ms973839.aspx


问:
how to get second highest salary department wise without using analytical functions?
Suppose we have 3 employees in each department.we have total 3 departments . Below is the sample source table

```<code>Emp deptno salary
A    10     1000
B    10     2000
C    10     3000
D    20     7000
E    20     9000
F    20     8000
G    30     17000
H    30     15000
I    30     30000
</code>```

Output

```<code>B    10     2000
F    20     8000
G    30     17000
</code>```

With using analytic function dense_rank we can achive the second highest salary dept wise.

Can we achieve this without using ANY analytic function ???

Is Max() is also analytic function ??

Body:
Suppose we have 3 employees in each department.we have total 3 departments . Below is the sample source table

Emp deptno salary
A    10     1000
B    10     2000
C    10     3000
D    20     7000
E    20     9000
F    20     8000
G    30     17000
H    30     15000
I    30     30000

Output

B    10     2000
F    20     8000
G    30     17000

With using analytic function dense_rank we can achive the second highest salary dept wise.

Can we achieve this without using ANY analytic function ???

Is Max() is also analytic function ??

Body:
CREATE TABLE Employee
    ([Name] varchar(1), [Dept] varchar(1), [Salary] int)
;

INSERT INTO Employee
    ([Name], [Dept], [Salary])
VALUES
    ('a', 'M', 20),
    ('b', 'M', 25),
    ('c', 'M', 30),
    ('d', 'C', 44),
    ('e', 'C', 45),
    ('f', 'C', 46),
    ('g', 'H', 20)


问:
Multiple drop down questions selection in angular js

<!DOCTYPE html>

                Consumer's Choices

            <select ng-model="selectedName" ng-options="x for x in questions" class="form-control">
                    </select>

                    <input type="text" class="form-control" placeholder="Answer">

            <select ng-model="selectedName" ng-options="x for x in questions" class="form-control">
                    </select>

                    <input type="text" class="form-control" placeholder="Answer">

            <select ng-model="selectedName" ng-options="x for x in questions" class="form-control">
                    </select>

                    <input type="text" class="form-control" placeholder="Answer">

```

I'm developing multiple security questions in the dropdown and its answers using angular js. The problem is that these questions come from an array inside the controller and on clicking on drop down, all the other dropdowns are also changing and first selected option should not be displayed in the other drop downs.I need to avoid it.I don't know where I'm making the mistake.

答:
please set different names for different select tags

You cannot use same model for different select tags.

Body:
<!DOCTYPE html>

                Consumer's Choices

            <select ng-model="selectedName" ng-options="x for x in questions" class="form-control">
                    </select>

                    <input type="text" class="form-control" placeholder="Answer">

            <select ng-model="selectedName" ng-options="x for x in questions" class="form-control">
                    </select>

                    <input type="text" class="form-control" placeholder="Answer">

            <select ng-model="selectedName" ng-options="x for x in questions" class="form-control">
                    </select>

                    <input type="text" class="form-control" placeholder="Answer">

I'm developing multiple security questions in the dropdown and its answers using angular js. The problem is that these questions come from an array inside the controller and on clicking on drop down, all the other dropdowns are also changing and first selected option should not be displayed in the other drop downs.I need to avoid it.I don't know where I'm making the mistake.


问:
Why iOS coordinate system is difficult to understand?? only me?
I'm studying iOS' UIView!
And I found that I can't understand how bounds works.

For example,

Please run this code ... and see red box's moving.
The red box goes up! and white root view is static!

Why!? why red box goes up! ?? please let me know OTL!

```<code>class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let childView : UIView = UIView(frame: CGRect(x: 50, y: 50, width: 200, height: 200) )
        childView.backgroundColor = UIColor.red

        self.view.addSubview(childView)

    }

    override func viewDidAppear(_ animated: Bool) {

        UIView.animate(withDuration: 8, animations: {

          // I cannot unnerstand how bounds works!!
          self.view.bounds = CGRect(x: 0, y: -300, width:self.view.bounds.width, height: 700)

          //I can understand how frame works
          self.view.frame = CGRect(x: 200, y: 0, width: self.view.bounds.width, height: self.view.frame.height)
      })

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
      // Dispose of any resources that can be recreated.
    }

}
</code>```

I read this article, but I can not understand

```<code>CompositedPosition.x = View.frame.origin.x - Superview.bounds.origin.x;
CompositedPosition.y = View.frame.origin.y - Superview.bounds.origin.y;
</code>```

HERE! this is right ( according to what I tested, it was right. ) but, I don't know why. Why not "View.frame.origin.x + Superview.bounds.origin.x" ?

If we change the origin of view's bounds and the view moves on screen , what is the difference between "bounds" and "frame" in perspective of origin(or position) ? Is there a difference other than simply acting in reverse?

答:
Basically, The bounds of an UIView is the rectangle, expressed as a location (x,y) and size (width,height) relative to its own coordinate system (0,0).

The frame of an UIView is the rectangle, expressed as a location (x,y) and size (width,height) relative to the superview it is contained within.

Please follow this link for clear example. Cocoa: What's the difference between the frame and the bounds?

Body:
I'm studying iOS' UIView!
And I found that I can't understand how bounds works.

For example,

Please run this code ... and see red box's moving.
The red box goes up! and white root view is static!

Why!? why red box goes up! ?? please let me know OTL!

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let childView : UIView = UIView(frame: CGRect(x: 50, y: 50, width: 200, height: 200) )
        childView.backgroundColor = UIColor.red

        self.view.addSubview(childView)

    }

    override func viewDidAppear(_ animated: Bool) {

        UIView.animate(withDuration: 8, animations: {

          // I cannot unnerstand how bounds works!!
          self.view.bounds = CGRect(x: 0, y: -300, width:self.view.bounds.width, height: 700)

          //I can understand how frame works
          self.view.frame = CGRect(x: 200, y: 0, width: self.view.bounds.width, height: self.view.frame.height)
      })

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
      // Dispose of any resources that can be recreated.
    }

}

I read this article, but I can not understand

CompositedPosition.x = View.frame.origin.x - Superview.bounds.origin.x;
CompositedPosition.y = View.frame.origin.y - Superview.bounds.origin.y;

HERE! this is right ( according to what I tested, it was right. ) but, I don't know why. Why not "View.frame.origin.x + Superview.bounds.origin.x" ?

If we change the origin of view's bounds and the view moves on screen , what is the difference between "bounds" and "frame" in perspective of origin(or position) ? Is there a difference other than simply acting in reverse?


答:
At
 you missed - it should be

```<code><div class="post-container">
    <div>
        <div class="click-delgated-event">
            hello
        </div>
    </div>
</div>
</code>```

Title: jquery event delegation on static content doesn't work

Body:
At <div class="click-delgated event"> you missed - it should be

<div class="post-container">
    <div>
        <div class="click-delgated-event">
            hello
        </div>
    </div>
</div>