问:
How to install Visual Studio 2015 in external hard drive
I need to install VS15 inside an external hard drive due to c drive memory ran out. I have read this, is actually same problem but the answer provided (create mklink) I not really understand how to work in the correct steps. Does anyone can provide me the steps to install? I tried to install but

1) I able to ran after I install but I need the cross platform Xamarin, so when I wanna modify the updates, it say required memory spaces in both drivers (C: & D:), which is not enough spaces.

2) Is that possible to install the whole VS15 inside the external hard drive?

答:
Your second question is a duplicate question for: How to install Visual Studio 2015 on a different drive.

As for your first question I think you mean to ask whether dependancies for Xamarin (Android SDK, Emulators) can be installed on a external drive - I suppose this is possible. You'd have to install all dependancies (Android NDK/SDK etc.) to your external drive and then configure Visual Studio to use those folders (Tools > Options > Xamarin > Android settings).

Keep in mind this is not ideal, due to the large number of I/O operations that are performed during building things like Android apps, not even taking an emulator into consideration.


来源: stackexchange

问:
Using a list of conditions to filter a DataFrame in Pandas
I wish to have a function which takes a list of conditions, of any length, and places an ampersand between all the conditions. Example code below.

```<code>df = pd.DataFrame(columns=['Sample', 'DP','GQ', 'AB'],
         data=[
               ['HG_12_34', 200, 35, 0.4],
               ['HG_12_34_2', 50, 45, 0.9],
               ['KD_89_9', 76, 67, 0.7],
               ['KD_98_9_2', 4, 78, 0.02],
               ['LG_3_45', 90, 3, 0.8],
               ['LG_3_45_2', 15, 12, 0.9]
               ])

def some_func(df, cond_list):

    # wrap ampersand between multiple conditions
    all_conds = ?

    return df[all_conds]

cond1 = df['DP'] > 40
cond2 = df['GQ'] > 40
cond3 = df['AB'] < 0.4

some_func(df, [cond1, cond2]) # should return df[cond1 & cond2]
some_func(df, [cond1, cond3, cond2]) # should return df[cond1 & cond3 & cond2]
</code>```

I would appreciate any help with this.

答:
You can use functools.reduce for that:

```<code><b>from functools import reduce</b>

def some_func(df, cond_list):
    return df[<b>reduce(lambda x,y: x&y</b>, cond_list<b>)</b>]</code>```

Or, like @AryaMcCarthy says, you can use and_ from the operator package:

```<code>from functools import reduce
<b>from operator import and_</b>

def some_func(df, cond_list):
    return df[reduce(<b>and_</b>, cond_list)]</code>```

or with numpy - like @ayhan says - which has also a logical and reduction:

```<code><b>from numpy import logical_and</b>

def some_func(df, cond_list):
    return df[<b>logical_and.reduce(</b>cond_list<b>)</b>]</code>```

All three versions produce - for your sample input - the following output:

```<code>>>> some_func(df, [cond1, cond2])
       Sample  DP  GQ   AB
1  HG_12_34_2  50  45  0.9
2     KD_89_9  76  67  0.7
>>> some_func(df, [cond1, cond2, cond3])
Empty DataFrame
Columns: [Sample, DP, GQ, AB]
Index: []
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I wish to have a function which takes a list of conditions, of any length, and places an ampersand between all the conditions. Example code below.

df = pd.DataFrame(columns=['Sample', 'DP','GQ', 'AB'],
         data=[
               ['HG_12_34', 200, 35, 0.4],
               ['HG_12_34_2', 50, 45, 0.9],
               ['KD_89_9', 76, 67, 0.7],
               ['KD_98_9_2', 4, 78, 0.02],
               ['LG_3_45', 90, 3, 0.8],
               ['LG_3_45_2', 15, 12, 0.9]
               ])

def some_func(df, cond_list):

    # wrap ampersand between multiple conditions
    all_conds = ?

    return df[all_conds]

cond1 = df['DP'] > 40
cond2 = df['GQ'] > 40
cond3 = df['AB'] < 0.4

some_func(df, [cond1, cond2]) # should return df[cond1 & cond2]
some_func(df, [cond1, cond3, cond2]) # should return df[cond1 & cond3 & cond2]

I would appreciate any help with this.

Body:
You can use functools.reduce for that:

from functools import reduce

def some_func(df, cond_list):
    return df[reduce(lambda x,y: x&y, cond_list)]

Or, like @AryaMcCarthy says, you can use and_ from the operator package:

from functools import reduce
from operator import and_

def some_func(df, cond_list):
    return df[reduce(and_, cond_list)]

or with numpy - like @ayhan says - which has also a logical and reduction:

from numpy import logical_and

def some_func(df, cond_list):
    return df[logical_and.reduce(cond_list)]

All three versions produce - for your sample input - the following output:

>>> some_func(df, [cond1, cond2])
       Sample  DP  GQ   AB
1  HG_12_34_2  50  45  0.9
2     KD_89_9  76  67  0.7
>>> some_func(df, [cond1, cond2, cond3])
Empty DataFrame
Columns: [Sample, DP, GQ, AB]
Index: []


问:
How do you go about batch processing poorly formatted text files?
People complain a lot about XML but, when compared to EDI and some of the proprietary file formats I've dealt with in my career, I think XML is bliss.  The work I did on importing data files from Automotive Comparative Raters, each with it's own creative and nightmarish file format, still gives me nightmares.

That being said I'm curious how other programmers approach automated parsing of poorly formatted text files.  Do you have a language preference?  Are there any automation tools that you find invaluable?  How do you make your code reusable?

答: Perl / Python, build up functionality slowly, keep the worse ones as test case, lots of coffee</p>

ContentLicense: CC BY-SA 2.5


问:
Group and identify busiest time periods
I have a log file that's just date in one column and time in the other. I'm trying to find the most popular time periods.

```<code>Date          Time
Jan/01/2017   08:23:45
Jan/01/2017   15:54:21
Jan/02/2017   04:02:39
Jan/03/2017   06:33:12
...
</code>```

I'm looking for an efficient way to group the data into 10-minute portions and then find the most popular 1-hour-intervals. So it's very likely the most popular hour-long-intervals would be consecutive like:

```<code>Interval               Count
08:10:00 - 09:10:00    586
08:20:00 - 09:20:00    565
08:30:00 - 09:30:00    544
...
</code>```

This has to scale up well to GB of data and I need to be able to find the most popular intervals preferably without sorting the entire table.

答:
You could convert to minutes since midnight, use integer division and a Counter. No need to sort the data, this should work fine and be efficient :

```<code>from collections import Counter

log = """Jan/01/2017   08:23:45
Jan/01/2017   15:54:21
Jan/01/2017   15:50:21
Jan/01/2017   15:52:21
Jan/02/2017   04:02:39
Jan/03/2017   06:33:12"""

portion = 10
interval = 60

counter = Counter()

for line in log.split("\n"):
    time = line.split()[-1]
    hour, minute, second = map(int, time.split(':'))
    since_midnight = hour * 60 + minute
    counter[since_midnight // portion] += 1

for slot, count in counter.most_common():
    print("%02d:%02d -> %02d:%02d - %d" % ((slot * portion) / 60,
                                           (slot * portion) % 60,
                                           ((slot + 1) * portion) / 60,
                                           ((slot + 1) * portion) % 60,
                                           count))
</code>```

It outputs :

```<code>15:50 -> 16:00 - 3
04:00 -> 04:10 - 1
08:20 -> 08:30 - 1
06:30 -> 06:40 - 1
</code>```

Since you didn't write any code, I'll leave an exercise to you : for a given 10-minute portion, increment the counter of every 60-min interval containing this portion. A simple for loop should do.

Also, you should read the file line by line. The split("\n") was just for a simple example.

Title: Group and identify busiest time periods

Body:
I have a log file that's just date in one column and time in the other. I'm trying to find the most popular time periods.

Date          Time
Jan/01/2017   08:23:45
Jan/01/2017   15:54:21
Jan/02/2017   04:02:39
Jan/03/2017   06:33:12
...

I'm looking for an efficient way to group the data into 10-minute portions and then find the most popular 1-hour-intervals. So it's very likely the most popular hour-long-intervals would be consecutive like:

Interval               Count
08:10:00 - 09:10:00    586
08:20:00 - 09:20:00    565
08:30:00 - 09:30:00    544
...

This has to scale up well to GB of data and I need to be able to find the most popular intervals preferably without sorting the entire table.

Body:
You could convert to minutes since midnight, use integer division and a Counter. No need to sort the data, this should work fine and be efficient :

from collections import Counter

log = """Jan/01/2017   08:23:45
Jan/01/2017   15:54:21
Jan/01/2017   15:50:21
Jan/01/2017   15:52:21
Jan/02/2017   04:02:39
Jan/03/2017   06:33:12"""

portion = 10
interval = 60

counter = Counter()

for line in log.split("\n"):
    time = line.split()[-1]
    hour, minute, second = map(int, time.split(':'))
    since_midnight = hour * 60 + minute
    counter[since_midnight // portion] += 1

for slot, count in counter.most_common():
    print("%02d:%02d -> %02d:%02d - %d" % ((slot * portion) / 60,
                                           (slot * portion) % 60,
                                           ((slot + 1) * portion) / 60,
                                           ((slot + 1) * portion) % 60,
                                           count))

It outputs :

15:50 -> 16:00 - 3
04:00 -> 04:10 - 1
08:20 -> 08:30 - 1
06:30 -> 06:40 - 1

Since you didn't write any code, I'll leave an exercise to you : for a given 10-minute portion, increment the counter of every 60-min interval containing this portion. A simple for loop should do.

Also, you should read the file line by line. The split("\n") was just for a simple example.


问:
Trying to create a JSONObject ends with a Cannot evaluate org.json.JSONObject.toString()
I've been following a tutorial (honestly, I was copy pasting, therefore I don't know why it doesn't work as I didn't change a thing) and I have this String response that I need to convert into a Json Object.

response =

Config.php\r\n{"error":false,"user":{"name":"test","surname":"test","address":"test","email":"test"}}

Right after the try at JSONObject jObj = new JSONObject(response); my program jumps to the exception with a message:

Method threw 'java.lang.NullPointerException' exception. Cannot
  evaluate org.json.JSONObject.toString()

Is it the structure of response or something?

Here's where I use it:

```<code>@Override
            public void onResponse(String response) {
                Log.d(TAG, "Login Response: " + response.toString());
                hideDialog();

                try {
                    JSONObject jObj = new JSONObject(response);
                    boolean error = jObj.getBoolean("error");

                    // Check for error node in json
                    if (!error) {
                        // user successfully logged in
                        // Create login session
                        session.setLogin(true);

                        // Now store the user in SQLite

                        JSONObject user = jObj.getJSONObject("user");
                        String name = user.getString("name");
                        String surname = user.getString("surname");
                        String address = user.getString("address");
                        String email = user.getString("email");

                        // Inserting row in users table
                        db.addUser(name, surname, address, email);

                        // Launch main activity
                        Intent intent = new Intent(LoginScreen.this,
                                MainMenu.class);
                        startActivity(intent);
                        finish();
                    } else {
                        // Error in login. Get the error message
                        String errorMsg = jObj.getString("error_msg");
                        Toast.makeText(getApplicationContext(),
                                errorMsg, Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    // JSON error
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                }

            }
</code>```

答:
Your response is not a valid json string.

See RFC 7159.

Also you can verify your json with online json formatter

Body:
I've been following a tutorial (honestly, I was copy pasting, therefore I don't know why it doesn't work as I didn't change a thing) and I have this String response that I need to convert into a Json Object.

response =

Config.php\r\n{"error":false,"user":{"name":"test","surname":"test","address":"test","email":"test"}}

Right after the try at JSONObject jObj = new JSONObject(response); my program jumps to the exception with a message:

Method threw 'java.lang.NullPointerException' exception. Cannot
  evaluate org.json.JSONObject.toString()

Is it the structure of response or something?

Here's where I use it:

@Override
            public void onResponse(String response) {
                Log.d(TAG, "Login Response: " + response.toString());
                hideDialog();

                try {
                    JSONObject jObj = new JSONObject(response);
                    boolean error = jObj.getBoolean("error");

                    // Check for error node in json
                    if (!error) {
                        // user successfully logged in
                        // Create login session
                        session.setLogin(true);

                        // Now store the user in SQLite

                        JSONObject user = jObj.getJSONObject("user");
                        String name = user.getString("name");
                        String surname = user.getString("surname");
                        String address = user.getString("address");
                        String email = user.getString("email");

                        // Inserting row in users table
                        db.addUser(name, surname, address, email);

                        // Launch main activity
                        Intent intent = new Intent(LoginScreen.this,
                                MainMenu.class);
                        startActivity(intent);
                        finish();
                    } else {
                        // Error in login. Get the error message
                        String errorMsg = jObj.getString("error_msg");
                        Toast.makeText(getApplicationContext(),
                                errorMsg, Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    // JSON error
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                }

            }


问:
Balanced Binary Tree Vs Balanced Binary Search Tree
For each of these operations would a balanced binary search tree complete the task in a faster big oh time than a balanced binary tree?

Finding the smallest item in the tree.

I think balanced BST would have a faster big oh time than a balanced Binary Tree since you can just keep traversing left and find the smallest item. I think it would be O(log n).

Creating a list of all elements in the tree that are smaller than some value v.

For 2 could someone offer me an explanation about which one would have a faster big oh time?

答:
You also have to take into account best, average and worst case scenarios in time complexity performance, keeping in mind what the value of n represents:

1. Balanced Binary Search Tree representation

```<code>           25             // Level 1
        20    36          // Level 2
      10 22  30 40        // Level 3
  .. .. .. .. .. .. ..
.. .. .. .. .. .. .. ..   // Level n
</code>```

2. Binary Search Tree representation

```<code>           10           // Level 1
          9  11         // Level 2
         7 . . 20       // Level 3
        8 . . . 15 24
       6 . . . . . . .  // Level n
</code>```

Finding the smallest item in the tree.

This is a search operation.

1) The time complexity in here is O(log n), even in worst case scenario, because the tree is balanced. The minimum value is 10.

2) The time complexity here in the worst case scenario is O(n). The minimum value is 6. You can picture from the representation that the root's left tree (branch) behaves like a linked list. This is because the tree is unbalanced. [1]

Creating a list of all elements in the tree that are smaller than some value v.

This would be an insertion operation.

1) This would be O(log n), because as the tree is traversed it is balanced so you don't get 2)'s scenario.

2) This would be O(n), because in the worst case scenario your insertion will resemble insertion of a linked list.

In conclusion:
A Balanced Binary Search Tree guarantees O(log n) in all cases of search, insertion and deletion of nodes, where as a typical BST does not.

Citations

Best, worst and average case [1]

Body:
You also have to take into account best, average and worst case scenarios in time complexity performance, keeping in mind what the value of n represents:

1. Balanced Binary Search Tree representation

           25             // Level 1
        20    36          // Level 2
      10 22  30 40        // Level 3
  .. .. .. .. .. .. ..
.. .. .. .. .. .. .. ..   // Level n

2. Binary Search Tree representation

           10           // Level 1
          9  11         // Level 2
         7 . . 20       // Level 3
        8 . . . 15 24
       6 . . . . . . .  // Level n

Finding the smallest item in the tree.

This is a search operation.

1) The time complexity in here is O(log n), even in worst case scenario, because the tree is balanced. The minimum value is 10.

2) The time complexity here in the worst case scenario is O(n). The minimum value is 6. You can picture from the representation that the root's left tree (branch) behaves like a linked list. This is because the tree is unbalanced. [1]

Creating a list of all elements in the tree that are smaller than some value v.

This would be an insertion operation.

1) This would be O(log n), because as the tree is traversed it is balanced so you don't get 2)'s scenario.

2) This would be O(n), because in the worst case scenario your insertion will resemble insertion of a linked list.

In conclusion:
A Balanced Binary Search Tree guarantees O(log n) in all cases of search, insertion and deletion of nodes, where as a typical BST does not.

Citations

Best, worst and average case [1]


问:
Stuck in multiline edit mode when importing module in Node.js REPL
I'm on node v7.5.0. I run node and then:

```<code>> import moment from 'moment';
... moment();
...
</code>```

I get stuck in multiline mode as you can see. How do I use import in Node REPL?

答:
Node does not support the module import/export syntax yet. You will have to stick with this for now:</p>

```<code>moment = require('moment')
</code>```

Body:
I'm on node v7.5.0. I run node and then:

> import moment from 'moment';
... moment();
...

I get stuck in multiline mode as you can see. How do I use import in Node REPL?

Body:
Node does not support the module import/export syntax yet. You will have to stick with this for now:

moment = require('moment')


问:
NSUserDefaults write to disk?
I am writing an index for the currently selected UITabBar to [NSUserDefaults standardUserDefaults] but I am getting the odd situation where the index is not writen to disk. I am using

```<code>// TO WRITE
NSNumber *selectedTab = [NSNumber numberWithInt:[tabBarController selectedIndex]];
[[NSUserDefaults standardUserDefaults] setObject:selectedTab forKey:@"selectedTab"];
</code>```

and ...

```<code>// TO READ
NSNumber *selectTab = [[NSUserDefaults standardUserDefaults] objectForKey:@"selectedTab"];
NSLog(@"SelectTab: %@", selectTab);
[tabController setSelectedIndex:[selectTab intValue]];
</code>```

Can anyone tell me if setObject:forKey: does the actual write to disk, or do I need to force the write using something like synchronize ?

答: You need to call synchronize, although it does get called automatically periodically (at least according to the documentation).  A good time to call it is in the app delegate's applicationWillEnterBackground: and applicationWillTerminate:.

Title: NSUserDefaults write to disk?

Body:
I am writing an index for the currently selected UITabBar to [NSUserDefaults standardUserDefaults] but I am getting the odd situation where the index is not writen to disk. I am using

// TO WRITE
NSNumber *selectedTab = [NSNumber numberWithInt:[tabBarController selectedIndex]];
[[NSUserDefaults standardUserDefaults] setObject:selectedTab forKey:@"selectedTab"];

and ...

// TO READ
NSNumber *selectTab = [[NSUserDefaults standardUserDefaults] objectForKey:@"selectedTab"];
NSLog(@"SelectTab: %@", selectTab);
[tabController setSelectedIndex:[selectTab intValue]];

Can anyone tell me if setObject:forKey: does the actual write to disk, or do I need to force the write using something like synchronize ?


问:
How to access text from a webpage where url does not change after choosing a dropdown value?
I have a website - http://kjc-sv013.kjc.uni-heidelberg.de/dcs/index.php?contents=texte

Upon selecting a text from the dropdown menu, the text appears on screen but the url does not update.

How do I get this text using beautiful soup?

答:
When you select a dropdown on that website it makes a request to a separate url to get the data.  If you make similar requests to those urls you'll get the data you are trying to gather.</p>

```<code>curl 'http://kjc-sv013.kjc.uni-heidelberg.de/dcs/ajax-php/ajax-text-handler-wrapper.php' -H 'Cookie: PHPSESSID=r864nj78198tr9ukeg8nuulkg0' -H 'Origin: http://kjc-sv013.kjc.uni-heidelberg.de' -H 'Accept-Encoding: gzip, deflate' -H 'Accept-Language: en-US,en;q=0.8' -H 'User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.110 Safari/537.36' -H 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8' -H 'Accept: */*' -H 'Referer: http://kjc-sv013.kjc.uni-heidelberg.de/dcs/index.php?contents=texte' -H 'X-Requested-With: XMLHttpRequest' -H 'Connection: keep-alive' --data 'mode=printsentences&chapterid=7032' --compressed
</code>```

Body:
When you select a dropdown on that website it makes a request to a separate url to get the data.  If you make similar requests to those urls you'll get the data you are trying to gather.

curl 'http://kjc-sv013.kjc.uni-heidelberg.de/dcs/ajax-php/ajax-text-handler-wrapper.php' -H 'Cookie: PHPSESSID=r864nj78198tr9ukeg8nuulkg0' -H 'Origin: http://kjc-sv013.kjc.uni-heidelberg.de' -H 'Accept-Encoding: gzip, deflate' -H 'Accept-Language: en-US,en;q=0.8' -H 'User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.110 Safari/537.36' -H 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8' -H 'Accept: */*' -H 'Referer: http://kjc-sv013.kjc.uni-heidelberg.de/dcs/index.php?contents=texte' -H 'X-Requested-With: XMLHttpRequest' -H 'Connection: keep-alive' --data 'mode=printsentences&chapterid=7032' --compressed


问:
AS3: How to access children of children of children?
Is there a better (quicker, shorter or neater) way to access a child sprite (object) 3 layers or more deep? If the children have all been given names and you know the names. Is there a better way to do it than the code I made below?

var mySprite:DisplayObjectContainer = layerASprite.getChildByName("layerA") as DisplayObjectContainer;

mySprite = mySprite.getChildByName("layerB") as DisplayObjectContainer;

mySprite.getChildByName("layerC").y = 200;

答:
As I'm not a big fan of static properties so I would also propose recursive search:

```<code>public function findChild(d:DisplayObject, n:String):DisplayObject {
    var dc:DisplayObjectContainer = d as DisplayObjectContainer; if (!dc) return null;
    for (var i:int = 0; i < dc.numChildren; i++){
        var ch:DisplayObject = dc.getChildAt(i);
        if (ch.name == n || (ch = findChild(ch, n))) return ch;
    }return null;
}
</code>```

and than you can simply type this:

```<code> var d:DisplayObject = findChild(stage, "childName");
</code>```

to find first child with childName name anywhere on stage.

I just wrote it and tested it once, but I hope it fine.

Advantages:

You don't need to make any additional steps to work with this method. You don't even need to name containers of child you search for.

You can start search at any DisplayObjectContainer you want.

If you decide at some point that you need you need to move your child form container A to container B no change in code is needed if it's still part of the same branch and has unique name.

Disadvantages:

It could be expensive, especially if you have extensive branch.

You need to make sure name of your child is unique across searched branch.

More sophisticated version

As searched children could usually be direct child of given container or be on closer level you could possibly search for child one level at time though it's bit tricky. For example my alpha version:

```<code>/**
 * Perform parallel/sprial recursive search in this container to find child with given name.
 * This means that this function will first check names of all child of this container and and then go to deeper level.
 * In other words, no element will be tested on level x+1 if not all elements were tested on level x.
 * This is true for all levels until whole tree is exhausted. This method is using token argument for such functionallity.
 * @param   n name of child element to be found.
 * @param   t token passed internally for sipral search. You should not specify this if you want the function to search a whole tree.
 * The token has only single value which is basically a desired level at which child should be searched for.
 * Level 1 means this function will only check its own childrens, level 2 means that only childs of childs of this container will be checked and so one.
 * However note that if you specify a token with some level, only that single level will be searched.
 * On the other hand if given token is null, this will check childs on level 1, then level 2, 3... and it will countinue until deepest level has been reached.
 * @return nearest child with specified name or null if no child with given name found.
 */
public function findChild(n:String, t:SearchToken = null, ind:String = ""):SGLElement {
    ind += "    ";
    var r:Boolean = (t) ? false : true; //is this call root of search.
    t = (t) ? t.offL( -1) : new SearchToken(0); //create new token if not given or decrement current token value.
    //trace(ind + "F", this.name, ":", t);
    //if (!t) t = new SearchToken(0);
    //--t.l;
    var cl:SearchToken = new SearchToken(t.l); //current search level.
    var exc:int = 0; //exhausted childrens.
    if(t.l == 0){//search own children
        for (var i:int = 0; i < _childs.length; i++) { //trace(ind + "  c", _childs[i].name);
            if (_childs[i].name == n) return _childs[i]; }
        if (r) ++cl.l; else return null;
    }
    while( cl.l > 0){
        if (exc >= _childs.length) { t.l = -1; return null;}
        for (i = 0; i < _childs.length; i++) {
            //trace(ind + "ch", t,":", i, _childs[i].name, _childs[i]);
            if (!(_childs[i] as SGLElementContainer)) continue;
            //trace(ind + "t", t, i);
            t.l = cl.l;
            var e:SGLElement = SGLElementContainer(_childs[i]).findChild(n, t, ind);
            //++cl.l;
            if (e) return e;
            else if (t.l < 0) exc++;
        }
        //trace(ind + "END_LEVEL>>>>", t);
        if (!r) return null;
        //t.l = cl.l;
        ++cl.l;
    }
    return null;
}
</code>```

token class

```<code>package adnss.common.utils
{
    public class SearchToken
    {
        /**Current level**/
        public var l:int;

        public function SearchToken(levelValue:int) {l = levelValue;}

        public function toString():String {return String(l);}

        /**Set level value and return this token instance.**/
        public function setL(v:int):SearchToken { l = v; return this; }

        /**Add given offset value to level value and return this token instance.**/
        public function offL(v:int):SearchToken { l += v; return this;}
    }

}
</code>```

I note I don't know what is technical name for such search so I gave it my own name and this method is not used for display list so you would need to adapt it. It's bit hard to explain this but if you have some question about it feel free to ask.

Body:
As I'm not a big fan of static properties so I would also propose recursive search:

public function findChild(d:DisplayObject, n:String):DisplayObject {
    var dc:DisplayObjectContainer = d as DisplayObjectContainer; if (!dc) return null;
    for (var i:int = 0; i < dc.numChildren; i++){
        var ch:DisplayObject = dc.getChildAt(i);
        if (ch.name == n || (ch = findChild(ch, n))) return ch;
    }return null;
}

and than you can simply type this:

 var d:DisplayObject = findChild(stage, "childName");

to find first child with childName name anywhere on stage.

I just wrote it and tested it once, but I hope it fine.

Advantages:

You don't need to make any additional steps to work with this method. You don't even need to name containers of child you search for.

You can start search at any DisplayObjectContainer you want.

If you decide at some point that you need you need to move your child form container A to container B no change in code is needed if it's still part of the same branch and has unique name.

Disadvantages:

It could be expensive, especially if you have extensive branch.

You need to make sure name of your child is unique across searched branch.

More sophisticated version

As searched children could usually be direct child of given container or be on closer level you could possibly search for child one level at time though it's bit tricky. For example my alpha version:

/**
 * Perform parallel/sprial recursive search in this container to find child with given name.
 * This means that this function will first check names of all child of this container and and then go to deeper level.
 * In other words, no element will be tested on level x+1 if not all elements were tested on level x.
 * This is true for all levels until whole tree is exhausted. This method is using token argument for such functionallity.
 * @param   n name of child element to be found.
 * @param   t token passed internally for sipral search. You should not specify this if you want the function to search a whole tree.
 * The token has only single value which is basically a desired level at which child should be searched for.
 * Level 1 means this function will only check its own childrens, level 2 means that only childs of childs of this container will be checked and so one.
 * However note that if you specify a token with some level, only that single level will be searched.
 * On the other hand if given token is null, this will check childs on level 1, then level 2, 3... and it will countinue until deepest level has been reached.
 * @return nearest child with specified name or null if no child with given name found.
 */
public function findChild(n:String, t:SearchToken = null, ind:String = ""):SGLElement {
    ind += "    ";
    var r:Boolean = (t) ? false : true; //is this call root of search.
    t = (t) ? t.offL( -1) : new SearchToken(0); //create new token if not given or decrement current token value.
    //trace(ind + "F", this.name, ":", t);
    //if (!t) t = new SearchToken(0);
    //--t.l;
    var cl:SearchToken = new SearchToken(t.l); //current search level.
    var exc:int = 0; //exhausted childrens.
    if(t.l == 0){//search own children
        for (var i:int = 0; i < _childs.length; i++) { //trace(ind + "  c", _childs[i].name);
            if (_childs[i].name == n) return _childs[i]; }
        if (r) ++cl.l; else return null;
    }
    while( cl.l > 0){
        if (exc >= _childs.length) { t.l = -1; return null;}
        for (i = 0; i < _childs.length; i++) {
            //trace(ind + "ch", t,":", i, _childs[i].name, _childs[i]);
            if (!(_childs[i] as SGLElementContainer)) continue;
            //trace(ind + "t", t, i);
            t.l = cl.l;
            var e:SGLElement = SGLElementContainer(_childs[i]).findChild(n, t, ind);
            //++cl.l;
            if (e) return e;
            else if (t.l < 0) exc++;
        }
        //trace(ind + "END_LEVEL>>>>", t);
        if (!r) return null;
        //t.l = cl.l;
        ++cl.l;
    }
    return null;
}

token class

package adnss.common.utils
{
    public class SearchToken
    {
        /**Current level**/
        public var l:int;

        public function SearchToken(levelValue:int) {l = levelValue;}

        public function toString():String {return String(l);}

        /**Set level value and return this token instance.**/
        public function setL(v:int):SearchToken { l = v; return this; }

        /**Add given offset value to level value and return this token instance.**/
        public function offL(v:int):SearchToken { l += v; return this;}
    }

}

I note I don't know what is technical name for such search so I gave it my own name and this method is not used for display list so you would need to adapt it. It's bit hard to explain this but if you have some question about it feel free to ask.


问:
How does hgearman worker work?
I asked a question how does hgearman-client work? three weeks ago. With some help I wrote a simple client application and I'm working on the worker side now. The worker implementation below compiles well and runs without any exception. The only trouble is that W.runWorker gc (return g) will not be executed. If I understand it correctly, it's the result of Haskell laziness and return t Monad wrapping. But I haven't faintest idea how to get rid of the issue. Could some one help?

```<code>import qualified Control.Monad.State as S
import qualified Data.ByteString.Char8 as B
import qualified Network.Gearman.Client as C
import qualified Network.Gearman.Worker as W
import Network.Gearman.Internal (Function, Port)
import Network.Socket (HostName)

main :: IO ()
main = do
  c <- connect
  case c of
    Left e -> error $ B.unpack e
    Right gc -> do
      (res, _) <- flip S.runStateT gc $ do
        g <- (W.registerWorker name func)
        let t = W.runWorker gc (return g)
        return t >> return ()

      return res
  where
    connect = C.connectGearman (B.pack "i") host port
    host = "localhost"::HostName
    port =  4730::Port
    name = (B.pack "foo")::Function
    func _ = B.pack "bar"
</code>```

Unfortunately an attempt to bind t <- W.runWorker ends in compiler exception. If I change the code in this way:

```<code>Right gc -> do
  (res, _) <- flip S.runStateT gc $ do
    g <- (W.registerWorker name func)
    t <- W.runWorker gc (return ())
    return t >> return  ()

  return res
</code>```

The compilation fails with exception:

```<code>Couldn't match expected type `S.StateT
                                Network.Gearman.Internal.GearmanClient IO a0'
                with actual type `IO GHC.Conc.Sync.ThreadId'
    In a stmt of a 'do' block: t <- W.runWorker gc (return ())
    In the second argument of `($)', namely
      `do { g <- (W.registerWorker name func);
            t <- W.runWorker gc (return ());
            return t >> return () }'
</code>```

IO GHC.Conc.Sync.ThreadId is the result of runWorker.

答:
A value of type Gearman a for some a is an action, a recipe to do something.  You can bind together such recipes to make bigger recipes, until you have constructed the main recipe which is the one that gets run.

Practically speaking, it means if you are running a do-block that looks like this:

```<code>do ...
   foo
   ...
</code>```

then foo will be run.  If you have a do-block that looks like this:

```<code>do ...
   ret <- foo
   ...
</code>```

then foo will be run and the result of running foo will be stored in ret.  Those two syntaxes are binds.  However if you are running a do-block that looks like this:

```<code>do ...
   let ret = foo
   ...
</code>```

then foo will not be run -- instead you are just asking for the variable ret to be shorthand for foo, so foo and ret are afterwards interchangeable.

So now you can see, in:

```<code>do g <- W.registerWorker name func
   let t = W.runWorker gc (return g)
   return t >> return ()
</code>```

the second line does not actually run a worker, it just lets t be a shorthand for running a worker.  Returning an action does not bind it either.  You need to bind:

```<code>   t <- W.runWorker gc (return g)
</code>```

By the way, I've been looking at the documentation and it looks like registerWorker returns a Gearman (), which means that the result of running the action is (), or "nothing interesting".  So g is nothing interesting, you could get rid of it and say

```<code>do W.registerWorker name func
   t <- W.runWorker gc (return ())
   return t >> return ()
</code>```

Presumably in place of that return () in the second line you would put an action that you wanted to run in the worker.  Like:

```<code>   t <- W.runWorker gc $ do
       ... the things you want the worker to do ...
   return t >> return ()
</code>```

And finally that last line: return t >> return (), also written

```<code>do return t
   return ()
</code>```

is exactly the same thing as return ().  return x constructs an action with no side-effects, which is only used for the result.  Then when you use >> (or don't bind the result in a do block) you run an action only for its side-effects and discard its result.  So the first return does nothing whatsoever.

Title: How does hgearman worker work?

Body:
I asked a question how does hgearman-client work? three weeks ago. With some help I wrote a simple client application and I'm working on the worker side now. The worker implementation below compiles well and runs without any exception. The only trouble is that W.runWorker gc (return g) will not be executed. If I understand it correctly, it's the result of Haskell laziness and return t Monad wrapping. But I haven't faintest idea how to get rid of the issue. Could some one help?

import qualified Control.Monad.State as S
import qualified Data.ByteString.Char8 as B
import qualified Network.Gearman.Client as C
import qualified Network.Gearman.Worker as W
import Network.Gearman.Internal (Function, Port)
import Network.Socket (HostName)

main :: IO ()
main = do
  c <- connect
  case c of
    Left e -> error $ B.unpack e
    Right gc -> do
      (res, _) <- flip S.runStateT gc $ do
        g <- (W.registerWorker name func)
        let t = W.runWorker gc (return g)
        return t >> return ()

      return res
  where
    connect = C.connectGearman (B.pack "i") host port
    host = "localhost"::HostName
    port =  4730::Port
    name = (B.pack "foo")::Function
    func _ = B.pack "bar"

Unfortunately an attempt to bind t <- W.runWorker ends in compiler exception. If I change the code in this way:

Right gc -> do
  (res, _) <- flip S.runStateT gc $ do
    g <- (W.registerWorker name func)
    t <- W.runWorker gc (return ())
    return t >> return  ()

  return res

The compilation fails with exception:

Couldn't match expected type `S.StateT
                                Network.Gearman.Internal.GearmanClient IO a0'
                with actual type `IO GHC.Conc.Sync.ThreadId'
    In a stmt of a 'do' block: t <- W.runWorker gc (return ())
    In the second argument of `($)', namely
      `do { g <- (W.registerWorker name func);
            t <- W.runWorker gc (return ());
            return t >> return () }'

IO GHC.Conc.Sync.ThreadId is the result of runWorker.

Body:
A value of type Gearman a for some a is an action, a recipe to do something.  You can bind together such recipes to make bigger recipes, until you have constructed the main recipe which is the one that gets run.

Practically speaking, it means if you are running a do-block that looks like this:

do ...
   foo
   ...

then foo will be run.  If you have a do-block that looks like this:

do ...
   ret <- foo
   ...

then foo will be run and the result of running foo will be stored in ret.  Those two syntaxes are binds.  However if you are running a do-block that looks like this:

do ...
   let ret = foo
   ...

then foo will not be run -- instead you are just asking for the variable ret to be shorthand for foo, so foo and ret are afterwards interchangeable.

So now you can see, in:

do g <- W.registerWorker name func
   let t = W.runWorker gc (return g)
   return t >> return ()

the second line does not actually run a worker, it just lets t be a shorthand for running a worker.  Returning an action does not bind it either.  You need to bind:

   t <- W.runWorker gc (return g)

By the way, I've been looking at the documentation and it looks like registerWorker returns a Gearman (), which means that the result of running the action is (), or "nothing interesting".  So g is nothing interesting, you could get rid of it and say

do W.registerWorker name func
   t <- W.runWorker gc (return ())
   return t >> return ()

Presumably in place of that return () in the second line you would put an action that you wanted to run in the worker.  Like:

   t <- W.runWorker gc $ do
       ... the things you want the worker to do ...
   return t >> return ()

And finally that last line: return t >> return (), also written

do return t
   return ()

is exactly the same thing as return ().  return x constructs an action with no side-effects, which is only used for the result.  Then when you use >> (or don't bind the result in a do block) you run an action only for its side-effects and discard its result.  So the first return does nothing whatsoever.


问:
How to create an array from two columns in pandas
suppose I have a DataFrame similar to this:

```<code>d = {'col1': [0, 2, 4], 'col2': [1, 3, 5], 'col3': [2, 4, 8]}
df = pd.DataFrame(d)

   col1  col2  col3
0     0     1     2
1     2     3     4
2     4     5     8
</code>```

How can I select col1 and col2 and turn them into this array?

```<code>array([[0, 1],
       [2, 3],
       [4, 5]])
</code>```

答:
You can also achieve the same output with the below code.</p>

```<code>import numpy as np
np.array(df[['col1','col2']])
Out[60]:
array([[0, 1],
       [2, 3],
       [4, 5]])
</code>```

Body:
suppose I have a DataFrame similar to this:

d = {'col1': [0, 2, 4], 'col2': [1, 3, 5], 'col3': [2, 4, 8]}
df = pd.DataFrame(d)

   col1  col2  col3
0     0     1     2
1     2     3     4
2     4     5     8

How can I select col1 and col2 and turn them into this array?

array([[0, 1],
       [2, 3],
       [4, 5]])

Body:
You can also achieve the same output with the below code.

import numpy as np
np.array(df[['col1','col2']])
Out[60]:
array([[0, 1],
       [2, 3],
       [4, 5]])


问:
Heap corruption when using delete/new in extra function
In the following code sample Visual Studio gives me the error "A heap has been corrupted". At first the for-loop seems to work fine, but after 1 or 2 iterations it just crashes.

I feel that my function myReAllocate facilitates some sort of memory leak where it shouldn't (because when I comment it out, everything works fine). What exactly is going on? It seems like a very subtle error.

```<code>#include <iostream>
using namespace std;

class myClass{};

void myReAllocate(myClass* c)
{
    delete c;
    c = new myClass();
}

int main(void)
{
    myClass *cc[10];

    for (int i = 0; i < 10; i++){
        cout << i << " attempt" << endl;
        cc[i] = new myClass();
        myReAllocate(cc[i]);
        delete cc[i];
    }

    return 0;
}
</code>```

I have tried adding a operator= but it didn't help either.

```<code>myClass operator=(myClass& right) {
    myClass temp = right;
    return *this;
}
</code>```

答:
I would go for reference instead of pointer as parameter:

```<code>void myReAllocate(myClass*& c)
{
    delete c;
    c = new myClass();
}
</code>```

as this would not require client code change. Goswin's proposal requires the call to myReAllocate to be:

```<code>myReAllocate(&cc[i]);
</code>```

while references allow it to be called without a change.

Body:
In the following code sample Visual Studio gives me the error "A heap has been corrupted". At first the for-loop seems to work fine, but after 1 or 2 iterations it just crashes.

I feel that my function myReAllocate facilitates some sort of memory leak where it shouldn't (because when I comment it out, everything works fine). What exactly is going on? It seems like a very subtle error.

#include <iostream>
using namespace std;

class myClass{};

void myReAllocate(myClass* c)
{
    delete c;
    c = new myClass();
}

int main(void)
{
    myClass *cc[10];

    for (int i = 0; i < 10; i++){
        cout << i << " attempt" << endl;
        cc[i] = new myClass();
        myReAllocate(cc[i]);
        delete cc[i];
    }

    return 0;
}

I have tried adding a operator= but it didn't help either.

myClass operator=(myClass& right) {
    myClass temp = right;
    return *this;
}

Body:
I would go for reference instead of pointer as parameter:

void myReAllocate(myClass*& c)
{
    delete c;
    c = new myClass();
}

as this would not require client code change. Goswin's proposal requires the call to myReAllocate to be:

myReAllocate(&cc[i]);

while references allow it to be called without a change.


问:
Understanding 2d arrays in C
All i am trying with the following source code, is to understand in depth how 2d arrays (tables) works in C. The code bellow may seems much but as you can see its nothing but simple prints and assignments.

Code:

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

int main(int argc, char* argv[]){

char** as = (char **)malloc(2 * sizeof(char *));
for (int i=0; i<2; i++){
    as[i] = (char *)malloc(3 * sizeof(char));
}

strcpy(&as[0][0],"a");
strcpy(&as[0][1],"b");
strcpy(&as[0][2],"c");
strcpy(&as[1][0],"aa");
strcpy(&as[1][1],"bb");
strcpy(&as[1][2],"cc");

printf("as[0][0] <%s>\n",&as[0][0]);
printf("as[0][1] <%s>\n",&as[0][1]);
printf("as[0][2] <%s>\n",&as[0][2]);
printf("as[1][0] <%s>\n",&as[1][0]);
printf("as[1][1] <%s>\n",&as[1][1]);
printf("as[1][2] <%s>\n",&as[1][2]);

for (int i=0; i<2; i++){
    free(as[i]);
}
free(as);

/*************** PART 2 **********************/
as = (char **)malloc(2 * sizeof(int));
for (int i=0; i<2; i++){
    as[i] = (char *)malloc(3 * sizeof(int));
}

printf("enter:as[0][0]: "); scanf("%s",&as[0][0]); // Input: a
printf("enter:as[0][1]: "); scanf("%s",&as[0][1]); // Input: b
printf("enter:as[0][2]: "); scanf("%s",&as[0][2]); // Input: c
printf("enter:as[1][0]: "); scanf("%s",&as[1][0]); // Input: aa
printf("enter:as[1][1]: "); scanf("%s",&as[1][1]); // Input: bb
printf("enter:as[1][2]: "); scanf("%s",&as[1][2]); // Input: cc

printf("as[0][0] <%s>\n",&as[0][0]);
printf("as[0][1] <%s>\n",&as[0][1]);
printf("as[0][2] <%s>\n",&as[0][2]);
printf("as[1][0] <%s>\n",&as[1][0]);
printf("as[1][1] <%s>\n",&as[1][1]);
printf("as[1][2] <%s>\n",&as[1][2]);

for (int i=0; i<2; i++){
    free(as[i]);
}
free(as);

return 0;
}
</code>```

The result i am excepting is something like the tab on the left but all i am getting into ./a.out is the tab on the right

```<code>as[0][0] <a>  }                           as[0][0] <abc>  }
as[0][1] <b>  }                           as[0][1] <bc>   }
as[0][2] <c>  }                           as[0][2] <c>    }
as[1][0] <aa> }  Excepted Result          as[1][0] <abcc> }  Final Result
as[1][1] <bb> }                           as[1][1] <bcc>  }
as[1][2] <cc> }                           as[1][2] <cc>   }
</code>```

My first thought is that i am not using correctly strcpy(). That's why /PART2/ exists in the code, but gives out the same results.

I know there is lot of same issue topics explaining 2d arrays and i did my fair research getting around the above subject.
A

答:
First: you don't actually have  a 2D array.

```<code>char** as = (char **)malloc(2 * sizeof(char *));
for (int i=0; i<2; i++){
    as[i] = (char *)malloc(3 * sizeof(char));
}
</code>```

This allocates a 1D array, and points as to it. Then, for each element, it allocates space and assigns the pointer to that space to the element. So what you have is a 1D array where each element is a pointer to another 1D array; let's call this a "2 level array" although I'm not sure if there's a better term available.

For a 2D array, you would instead write:

```<code>char (*as)[2][3] = malloc(2 * 3 * sizeof(char));
</code>```

However, if you want the array to hold strings (as char *) instead of individual characters then your declaration would need to be:

```<code>char *(*as)[2][3] = malloc(2 * 3 * sizeof(char));
</code>```

Alternatively, your original code could be changed for a 2 level array of char *:

```<code>char*** as = malloc(2 * sizeof(char **));
for (int i=0; i<2; i++){
    as[i] = malloc(3 * sizeof(char *));
}
</code>```

In both cases, you also need to allocate storage for the strings themselves. Instead of:

```<code>strcpy(&as[0][0],"a");
</code>```

you should probably use:

```<code> as[0][0] = strdup("a");
</code>```

So, what actually happened with your code to give you the results you got? well, here:

```<code>strcpy(&as[0][0],"a");
strcpy(&as[0][1],"b");
strcpy(&as[0][2],"c");
strcpy(&as[1][0],"aa");
strcpy(&as[1][1],"bb");
strcpy(&as[1][2],"cc");
</code>```

If as is a char **, then as[0] is a char * and as[0][0] is a simple char. You are then taking the address of this and copying an entire string to it. At best, this is odd; at worst, particularly for that last line, it's undefined behaviour - because you are copying past the end of an allocated array.

That is:

```<code>strcpy(&as[1][2],"cc");
</code>```

You are copying to the 3rd and "4th" character of as[1] (that is, positions 2 and 3). But you only allocated space for 3:

```<code>as[i] = (char *)malloc(3 * sizeof(char));
</code>```

(In fact, an additional two lines above have the same issue, because copying a string also copies the "nul terminator" byte at the end of the string).

When you print the strings, you print the result of the previous strcpy invocations. Consider, for as[0]:

```<code>strcpy(&as[0][0],"a");
</code>```

Ok, as[0] now contains "a", represented as 'a' in as[0][0] and '\0', the string terminator, in as[0][1].

```<code>strcpy(&as[0][1],"b");
</code>```

Now, you have 'b' in as[0][1] and '\0' in as[0][2].

```<code>strcpy(&as[0][2],"c");
</code>```

As explained before, this is invalid; but supposing we ignore that for now, you end up with:

as[0][0] = 'a'
   as[0][1] = 'b'
   as[0][2] = 'c'

However, now you are printing:

```<code>printf("as[0][0] <%s>\n",&as[0][0]);
</code>```

... and you say that you expect "a" as the output. However, the string as[0] contains "abc", (and is nul terminated only due to an accident of behaviour) so that is what you get when you print it.

To clarify:

as[0] and as[1] are string pointers

as[0][i], for any i, is a character within the string pointed to by as[0]

When you take the address of a character within a string, and copy another string to that address, you copy over the containing string starting at that particular character.

Title: Understanding 2d arrays in C

Body:
All i am trying with the following source code, is to understand in depth how 2d arrays (tables) works in C. The code bellow may seems much but as you can see its nothing but simple prints and assignments.

Code:

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

int main(int argc, char* argv[]){

char** as = (char **)malloc(2 * sizeof(char *));
for (int i=0; i<2; i++){
    as[i] = (char *)malloc(3 * sizeof(char));
}

strcpy(&as[0][0],"a");
strcpy(&as[0][1],"b");
strcpy(&as[0][2],"c");
strcpy(&as[1][0],"aa");
strcpy(&as[1][1],"bb");
strcpy(&as[1][2],"cc");

printf("as[0][0] <%s>\n",&as[0][0]);
printf("as[0][1] <%s>\n",&as[0][1]);
printf("as[0][2] <%s>\n",&as[0][2]);
printf("as[1][0] <%s>\n",&as[1][0]);
printf("as[1][1] <%s>\n",&as[1][1]);
printf("as[1][2] <%s>\n",&as[1][2]);

for (int i=0; i<2; i++){
    free(as[i]);
}
free(as);

/*************** PART 2 **********************/
as = (char **)malloc(2 * sizeof(int));
for (int i=0; i<2; i++){
    as[i] = (char *)malloc(3 * sizeof(int));
}

printf("enter:as[0][0]: "); scanf("%s",&as[0][0]); // Input: a
printf("enter:as[0][1]: "); scanf("%s",&as[0][1]); // Input: b
printf("enter:as[0][2]: "); scanf("%s",&as[0][2]); // Input: c
printf("enter:as[1][0]: "); scanf("%s",&as[1][0]); // Input: aa
printf("enter:as[1][1]: "); scanf("%s",&as[1][1]); // Input: bb
printf("enter:as[1][2]: "); scanf("%s",&as[1][2]); // Input: cc

printf("as[0][0] <%s>\n",&as[0][0]);
printf("as[0][1] <%s>\n",&as[0][1]);
printf("as[0][2] <%s>\n",&as[0][2]);
printf("as[1][0] <%s>\n",&as[1][0]);
printf("as[1][1] <%s>\n",&as[1][1]);
printf("as[1][2] <%s>\n",&as[1][2]);

for (int i=0; i<2; i++){
    free(as[i]);
}
free(as);

return 0;
}

The result i am excepting is something like the tab on the left but all i am getting into ./a.out is the tab on the right

as[0][0]   }                           as[0][0] <abc>  }
as[0][1]   }                           as[0][1] <bc>   }
as[0][2] <c>  }                           as[0][2] <c>    }
as[1][0] <aa> }  Excepted Result          as[1][0] <abcc> }  Final Result
as[1][1] <bb> }                           as[1][1] <bcc>  }
as[1][2] <cc> }                           as[1][2] <cc>   }

My first thought is that i am not using correctly strcpy(). That's why /PART2/ exists in the code, but gives out the same results.

I know there is lot of same issue topics explaining 2d arrays and i did my fair research getting around the above subject.
A

Body:
First: you don't actually have  a 2D array.

char** as = (char **)malloc(2 * sizeof(char *));
for (int i=0; i<2; i++){
    as[i] = (char *)malloc(3 * sizeof(char));
}

This allocates a 1D array, and points as to it. Then, for each element, it allocates space and assigns the pointer to that space to the element. So what you have is a 1D array where each element is a pointer to another 1D array; let's call this a "2 level array" although I'm not sure if there's a better term available.

For a 2D array, you would instead write:

char (*as)[2][3] = malloc(2 * 3 * sizeof(char));

However, if you want the array to hold strings (as char *) instead of individual characters then your declaration would need to be:

char *(*as)[2][3] = malloc(2 * 3 * sizeof(char));

Alternatively, your original code could be changed for a 2 level array of char *:

char*** as = malloc(2 * sizeof(char **));
for (int i=0; i<2; i++){
    as[i] = malloc(3 * sizeof(char *));
}

In both cases, you also need to allocate storage for the strings themselves. Instead of:

strcpy(&as[0][0],"a");

you should probably use:

 as[0][0] = strdup("a");

So, what actually happened with your code to give you the results you got? well, here:

strcpy(&as[0][0],"a");
strcpy(&as[0][1],"b");
strcpy(&as[0][2],"c");
strcpy(&as[1][0],"aa");
strcpy(&as[1][1],"bb");
strcpy(&as[1][2],"cc");

If as is a char **, then as[0] is a char * and as[0][0] is a simple char. You are then taking the address of this and copying an entire string to it. At best, this is odd; at worst, particularly for that last line, it's undefined behaviour - because you are copying past the end of an allocated array.

That is:

strcpy(&as[1][2],"cc");

You are copying to the 3rd and "4th" character of as[1] (that is, positions 2 and 3). But you only allocated space for 3:

as[i] = (char *)malloc(3 * sizeof(char));

(In fact, an additional two lines above have the same issue, because copying a string also copies the "nul terminator" byte at the end of the string).

When you print the strings, you print the result of the previous strcpy invocations. Consider, for as[0]:

strcpy(&as[0][0],"a");

Ok, as[0] now contains "a", represented as 'a' in as[0][0] and '\0', the string terminator, in as[0][1].

strcpy(&as[0][1],"b");

Now, you have 'b' in as[0][1] and '\0' in as[0][2].

strcpy(&as[0][2],"c");

As explained before, this is invalid; but supposing we ignore that for now, you end up with:

as[0][0] = 'a'
   as[0][1] = 'b'
   as[0][2] = 'c'

However, now you are printing:

printf("as[0][0] <%s>\n",&as[0][0]);

... and you say that you expect "a" as the output. However, the string as[0] contains "abc", (and is nul terminated only due to an accident of behaviour) so that is what you get when you print it.

To clarify:

as[0] and as[1] are string pointers

as[0][i], for any i, is a character within the string pointed to by as[0]

When you take the address of a character within a string, and copy another string to that address, you copy over the containing string starting at that particular character.


问:
How to mount network location in docker
I am using docker (1.12.3) in my Ubuntu machine. I am running a python script which will send its output to a windows network path (\\my_win_path\c). I am able to execute the python script. Can someone help me with the second part (i.e. sending the output(its a text file) to network location).

This network location is access restricted (only few ids/people have access) and is there anyway that I do not create any dependency on the host machine, as the image I will be creating will be used by lot of other people and they will be using different machines to run the image?

答:
First Mount the Network Path to your Ubuntu machine.

Again mount(Mounted Network Path Directory) to the Docker container which can be done by adding -v parameter with docker run command. For example if you have mounted the Network drive to /mnt of your Ubuntu machine.

```<code>docker run --privileged -v /mnt:/opt <rest/of/the/parameters>
</code>```

Now Redirect the output file to /opt inside the container.

Title: How to mount network location in docker

Body:
First Mount the Network Path to your Ubuntu machine.

Again mount(Mounted Network Path Directory) to the Docker container which can be done by adding -v parameter with docker run command. For example if you have mounted the Network drive to /mnt of your Ubuntu machine.

docker run --privileged -v /mnt:/opt <rest/of/the/parameters>

Now Redirect the output file to /opt inside the container.


问:
Python: Frequency Analysis of Sound Files
I am generating some sound files that play tones at various frequencies with a certain number of harmonics.

Ultimately, these sounds will be played on a device with a small speaker.

I have the frequency response curve of the speaker and want to do the following in Python:

Plot the frequency spectrum of sound file. I need a take the FFT of the file and plot it with gnuplot

Apply a nonlinear transfer function based on the frequency response curve in the data sheet.

Plot the result after the function is applied.

Does anyone know :

What the simplest way to do this would be?

or of an Application (GNU/Linux based) that could do this for me?

答: scipy has an FFT and hooks nicely into gnuplot. You should be able to use the signal module to do the math.</p>


问:
Ionic : how to detect bottom scroll?
For a chat app, I wanted to know if my ion-content is scrolled at bottom, to scroll down again after adding a message only if the user is already at bottom.

It it any possibility to easily detect when the content is scrolled?

答:
we can use on-scroll or on-scroll-complete events on content then we need to call function in controller like below

```<code> $scope.checkScroll = function() {
     var currentTop = $ionicScrollDelegate.getScrollPosition().top;
     var maxTop = $ionicScrollDelegate.getScrollView().__maxScrollTop;
     if (currentTop >= maxTop) {
     // hit the bottom

    }
};
</code>```

Complete tutorial is given here http://freakyjolly.com/detect-ionic-view-page-bottom-load-infinite-data/

Title: Ionic : how to detect bottom scroll?

Body:
we can use on-scroll or on-scroll-complete events on content then we need to call function in controller like below

 $scope.checkScroll = function() {
     var currentTop = $ionicScrollDelegate.getScrollPosition().top;
     var maxTop = $ionicScrollDelegate.getScrollView().__maxScrollTop;
     if (currentTop >= maxTop) {
     // hit the bottom

    }
};

Complete tutorial is given here http://freakyjolly.com/detect-ionic-view-page-bottom-load-infinite-data/


问:
Unit testing in java using mockito and powermockito
I have a method

```<code>public TaskProperty addTask()
{
     /*some operations
     *
     */
     mapToProperty();
 }

private TaskProperty mapToProperty()
{
    /**some op's**/
}
</code>```

How to write unit test case for the addTask() without allowing the control to go inside mapToProperty() method.

How to mock the private method mapToProperty()?

答:
The fact that you want to do this ... doesn't make it a good idea:

private methods represent "internal implementation" details. Excluding them from a test ... means that your test needs to know about this private method. But your tests shouldn't know anything about your private implementation details. They should not need to care.

In other words: your unit tests should only care about the public interface of your class(es). Thus: you try to write all your code in a way that you can test those public methods without the need to "disable" something other in the class you are testing. Meaning: either try to rewrite your private method so that you can call it from any unit test; or if that is not possible, move the corresponding behavior into another class; and then provide a mocked instance of that class to your method under test.

Long story short: your question implies that you want to fix a "bad design" by using the "mocking framework hammer" to "massage" the symptom. But it a symptom; and the underlying problem is still there, and affects your code base. So spend your time fixing the real problem; instead of working around it!

And just in case you still prefer to mock that private method; I would rather suggest to look into a mockito spy to do that (although PowerMock also allows for such kind of test, see here)

Body:
I have a method

public TaskProperty addTask()
{
     /*some operations
     *
     */
     mapToProperty();
 }

private TaskProperty mapToProperty()
{
    /**some op's**/
}

How to write unit test case for the addTask() without allowing the control to go inside mapToProperty() method.

How to mock the private method mapToProperty()?


问:
Angular2 - Pass parameters to a dynamically generated component?
I have a simple demo app which I'm simulating  manually insert / fetch data from DB and injecting new components - according to the num entered.

Plunker

So if I click the "manual " button twice :

And if I set "3" in the text and click "fetch from db" - I get the expected delay(simulate db) and then :

This all works as expected.

The "parent" component is :

```<code>//src/MainPage.ts
@Component({
  selector: 'my-app',
  template: `
    <button (click)="putInMyHtml()">Insert component manually</button>
    <p> # Items to fetch  : <input type="text" style='width:40px'  [(ngModel)]="dbNumItems" name="dbNumItems"/> <input type='button' value='fetch from db' (click)='fetchItems($event)'/></p>
    <div #myDiv>
       <template #target></template>
    </div>
  `
})
export class MainPage {
  @ViewChild('target', { read: ViewContainerRef }) target: ViewContainerRef;
  dbNumItems: string;
  constructor(private cfr: ComponentFactoryResolver) {}

  fetchItems(){
        var p= new Promise((resolve, reject) => { //simulate db
        setTimeout(()=>resolve(this.dbNumItems),2000)
    });

  p.then(v=>{

    for (let i =0;i<v;i++)
    {
         this.putInMyHtml() ;// inject "v" times
    }
  })

}

  putInMyHtml() {
   // this.target.clear();
   let compFactory = this.cfr.resolveComponentFactory(TestPage);
    this.target.createComponent(compFactory);
  }
}
</code>```

This is the Injected component :

```<code>//src/TestPage.ts
@Component({
  selector: 'test-component',
  template: '<b>Content  : Name={{user.Name}} Age={{user.Age}}</b><br/>',
})
export class TestPage {
    @Input
     User:Person;

}
</code>```

So where is the problem ?

As you can see , in the injected component I have :

```<code>@Input
User:Person;
</code>```

which means that I want the parent component to pass a Person object to each injection.

In other words :

Question

Looking at the "after db stage" , How can I pass a customized person to each injection ?

```<code>  p.then(v=>{

    for (let i =0;i<v;i++)
    {
         let p = new Person();
         p.Name = "name"+i;
         p.Age = i;

         this.putInMyHtml() ; //how to I pass `p` ???

    }
  })

}
</code>```

Expected output   :

NB
I don't want to use ngFor because I don't need to hold an Array at the back end. this is an app which injects new articles periodically.and I will be glad to know if there's a better way of doing it.

答:
You can do it with the instance property of component ref like this:

```<code>putInMyHtml(p) {
   // this.target.clear();

    let compFactory = this.cfr.resolveComponentFactory(TestPage);

    let ref = this.target.createComponent(compFactory);
    ref.instance.user = p;
}
</code>```

-Fixed the @Input() binding, syntax was wrong.

-Added a safe-navigation operator (?) for the template to do the null checks for the async input.

Fixed plunker: https://plnkr.co/edit/WgWFZQLxt9RFoZLR46HH?p=preview

Body:
I have a simple demo app which I'm simulating  manually insert / fetch data from DB and injecting new components - according to the num entered.

Plunker

So if I click the "manual " button twice :

And if I set "3" in the text and click "fetch from db" - I get the expected delay(simulate db) and then :

This all works as expected.

The "parent" component is :

//src/MainPage.ts
@Component({
  selector: 'my-app',
  template: `
    <button (click)="putInMyHtml()">Insert component manually</button>

 # Items to fetch  : <input type="text" style='width:40px'  [(ngModel)]="dbNumItems" name="dbNumItems"/> <input type='button' value='fetch from db' (click)='fetchItems($event)'/>

       <template #target></template>

  `
})
export class MainPage {
  @ViewChild('target', { read: ViewContainerRef }) target: ViewContainerRef;
  dbNumItems: string;
  constructor(private cfr: ComponentFactoryResolver) {}

  fetchItems(){
        var p= new Promise((resolve, reject) => { //simulate db
        setTimeout(()=>resolve(this.dbNumItems),2000)
    });

  p.then(v=>{

    for (let i =0;i<v;i++)
    {
         this.putInMyHtml() ;// inject "v" times
    }
  })

}

  putInMyHtml() {
   // this.target.clear();
   let compFactory = this.cfr.resolveComponentFactory(TestPage);
    this.target.createComponent(compFactory);
  }
}

This is the Injected component :

//src/TestPage.ts
@Component({
  selector: 'test-component',
  template: 'Content  : Name={{user.Name}} Age={{user.Age}}
',
})
export class TestPage {
    @Input
     User:Person;

}

So where is the problem ?

As you can see , in the injected component I have :

@Input
User:Person;

which means that I want the parent component to pass a Person object to each injection.

In other words :

Question

Looking at the "after db stage" , How can I pass a customized person to each injection ?

  p.then(v=>{

    for (let i =0;i<v;i++)
    {
         let p = new Person();
         p.Name = "name"+i;
         p.Age = i;

         this.putInMyHtml() ; //how to I pass `p` ???

    }
  })

}

Expected output   :

NB
I don't want to use ngFor because I don't need to hold an Array at the back end. this is an app which injects new articles periodically.and I will be glad to know if there's a better way of doing it.

Body:
You can do it with the instance property of component ref like this:

putInMyHtml(p) {
   // this.target.clear();

    let compFactory = this.cfr.resolveComponentFactory(TestPage);

    let ref = this.target.createComponent(compFactory);
    ref.instance.user = p;
}

-Fixed the @Input() binding, syntax was wrong.

-Added a safe-navigation operator (?) for the template to do the null checks for the async input.

Fixed plunker: https://plnkr.co/edit/WgWFZQLxt9RFoZLR46HH?p=preview


问:
Zend_Controller_Router_Route issue
I need to trim the first part of my url

Example /param1/12234/module/controller/action
would become /module/controller/action/param1/12234

I tried with

$router->addRoute('appid', new
  Zend_Controller_Router_Route('appid/:appid/:module/:controller/:action/',
  array(), array(2=> "module", 3=> "controller", 4=> "action")));

but won't works!

some helps?

答:
Try:

```<code><?php

   //-------------------------
   // Get router from front
   // controller
   $router = $this->frontController->getRouter();

   //-------------------------
   // Create route
   $route = new Zend_Controller_Router_Route(
      'controller/action/:appid/:param1',
      array(
         'module' => default',
         'controller' => 'index',
         'action' => 'index',
         'appid' => '',
         'param1' => 'default_value'
      ),

      //-------------------------
      // You can even add a regex
      // to parameters. Example,
      // appid can only be an integer
      array(
         'appid' => '\d+'
      )
   );

   //-------------------------
   // Add route to Router
   $router->addRoute('appid', $route);
?>
</code>```

Of'course, you'll need to substitute a few things (module, controller, action and parameters).  If you're not using modules, simply delete it from the array.

Finally, to use the route in the view, you can use:

```<code>$this->url(array('appid' => 1, 'param1' => 'custom_value'),'appid');
</code>```

UPDATE:

You can try the following in your

```<code><VirtualHost>

   RewriteEngine On
   RewriteRule ^/appid/(.*) /module/controller/action/$1 [R=301,L]
</VirtualHost>
</code>```

If you don't need to use a permanent 301 redirect, you can drop the R

Title: Zend_Controller_Router_Route issue

Body:
Try:

<?php

   //-------------------------
   // Get router from front
   // controller
   $router = $this->frontController->getRouter();

   //-------------------------
   // Create route
   $route = new Zend_Controller_Router_Route(
      'controller/action/:appid/:param1',
      array(
         'module' => default',
         'controller' => 'index',
         'action' => 'index',
         'appid' => '',
         'param1' => 'default_value'
      ),

      //-------------------------
      // You can even add a regex
      // to parameters. Example,
      // appid can only be an integer
      array(
         'appid' => '\d+'
      )
   );

   //-------------------------
   // Add route to Router
   $router->addRoute('appid', $route);
?>

Of'course, you'll need to substitute a few things (module, controller, action and parameters).  If you're not using modules, simply delete it from the array.

Finally, to use the route in the view, you can use:

$this->url(array('appid' => 1, 'param1' => 'custom_value'),'appid');

UPDATE:

You can try the following in your

<VirtualHost>

   RewriteEngine On
   RewriteRule ^/appid/(.*) /module/controller/action/$1 [R=301,L]
</VirtualHost>

If you don't need to use a permanent 301 redirect, you can drop the R


问:
Ansible task fails, when creating extensions
While provisioning via Vagrant and Ansible I keep running into this issue.

TASK [postgresql : Create extensions] ******************************************

  failed: [myapp] (item=postgresql_extensions) => {"changed": true, "cmd": "psql myapp -c 'CREATE EXTENSION IF NOT EXISTS postgresql_extensions;'", "delta": "0:00:00.037786", "end": "2017-04-01 08:37:34.805325", "failed": true, "item": "postgresql_extensions", "rc": 1, "start": "2017-04-01 08:37:34.767539", "stderr": "ERROR:  could not open extension control file \"/usr/share/postgresql/9.3/extension/postgresql_extensions.control\": No such file or directory", "stdout": "", "stdout_lines": [], "warnings": []}

I'm using a railsbox.io generated playbook.

答:
Turns out that railsbox.io is still using a deprecated syntax in the task.

```<code>- name: Create extensions
  sudo_user: '{{ postgresql_admin_user }}'
  shell: "psql {{ postgresql_db_name }} -c 'CREATE EXTENSION IF NOT EXISTS {{ item }};'"
  with_items: postgresql_extensions
  when: postgresql_extensions
</code>```

The last line should use full jinja2 syntax.

```<code>when: '{{postgresql_extensions}}'
</code>```

Body:
Turns out that railsbox.io is still using a deprecated syntax in the task.

- name: Create extensions
  sudo_user: '{{ postgresql_admin_user }}'
  shell: "psql {{ postgresql_db_name }} -c 'CREATE EXTENSION IF NOT EXISTS {{ item }};'"
  with_items: postgresql_extensions
  when: postgresql_extensions

The last line should use full jinja2 syntax.

when: '{{postgresql_extensions}}'


问:
Jquery 'mouseover' only before content is loaded
I have a function that should detect what you hover over only in a certain iframe.
The code

```<code>$(document).ready(function(){
    editor();
});
function editor(){
    var iframe = document.getElementById("iframe")
    var doc = iframe.contentDocument || iframe.contentWindow.document;
    $(doc).on('mouseover',function(e){
      console.log("hey");
      //further code non-related
    });
}
</code>```

It should fire when I move my mouse and I have my mouse over this certain iframe, but it only does it once when I load it and my mouse is in the iframe. Is there an update I am not aware of or? So, when I move my mouse over this iframe nothing happens, which is kind of upsetting and the problem.

The target

So, the initial goal is to have an iframe on a page and when I move my mouse over that iframe I want to be able to see what item in the iframe I'm hovering over. This is only when the mouse is in the iframe. I want to get that message when I'm hovering over the items in that iframe I suppose....

When it does work

It works, without content. As you can see here. Butttt... when content is loaded in, the whole operations shuts down and is not working anymore.

答:
Bind the event on the IFRAME DIRECTLY

function editor(){
    $("iframe").on('mouseover',function(e){
      alert("hey");
      //further code non-related
    });
}

editor();```
<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>
<iframe src="https://www.youtube.com/embed/NMBNZspmn7I">

</iframe></code>```

Body:
I have a function that should detect what you hover over only in a certain iframe.
The code

$(document).ready(function(){
    editor();
});
function editor(){
    var iframe = document.getElementById("iframe")
    var doc = iframe.contentDocument || iframe.contentWindow.document;
    $(doc).on('mouseover',function(e){
      console.log("hey");
      //further code non-related
    });
}

It should fire when I move my mouse and I have my mouse over this certain iframe, but it only does it once when I load it and my mouse is in the iframe. Is there an update I am not aware of or? So, when I move my mouse over this iframe nothing happens, which is kind of upsetting and the problem.

The target

So, the initial goal is to have an iframe on a page and when I move my mouse over that iframe I want to be able to see what item in the iframe I'm hovering over. This is only when the mouse is in the iframe. I want to get that message when I'm hovering over the items in that iframe I suppose....

When it does work

It works, without content. As you can see here. Butttt... when content is loaded in, the whole operations shuts down and is not working anymore.

Body:
Bind the event on the IFRAME DIRECTLY

function editor(){
    $("iframe").on('mouseover',function(e){
      alert("hey");
      //further code non-related
    });
}

editor();

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<iframe src="https://www.youtube.com/embed/NMBNZspmn7I">

</iframe>


问:
how to display pic with slider from json source?
I have a JSON file which contains the address of pics, I used get JSON for connect to JSON file, and also I am using a plugin called"lightslider" to show the pictures, my problem is when I run the HTML noting show but after refreshing the page it shows. and other problem is it is work only on fire fox. and also in server not working on server. please give me some easy and possible way to show my pic on slider from JSON file which is works on all browser. thanks.</p>

```<code><!DOCTYPE html>
<html lang="en">
    <head>
    <title>link3</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet"  href="lightslider.css"/>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script src="lightslider.js"></script>
    <script>
         $(document).ready(function() {
            $('#image-gallery').lightSlider({
                item:1,
                speed:500,
                auto:true,
                loop:true,
                pause: 3000,
                pauseOnHover:true,
                thumbItem:9,
                slideMargin: 0,
                autoWidth:true,
                onSliderLoad: function() {
                    $('#image-gallery').removeClass('cS-hidden');
                }
            });
        });
    </script>
    <script>
    $(document).ready( function(){

    $.getJSON('slides.json', function(data) {
    $("h2").html(data[0].title);
            $.each(data, function (i, f) {
                if(i>0){
                    $("#image-gallery").append("<li><img src=" + f.content + "/></li>");
                }
            });
       });
    });
    </script>
</head>
    <body>
        <h2 style="text-align: center; font-weight: bolder;">
        </h2>
        <div class="clearfix container" style="max-width:900px;" >
            <ul id="image-gallery" class="gallery list-unstyled cS-hidden">
            </ul>
        </div>
    </body>
</html>
</code>```

答: regarding your problem on JavaScript only working after refreshing try to wrap your code in window.onload = function(){} so that your code is loaded after DOM is fully loaded.

Body:
I have a JSON file which contains the address of pics, I used get JSON for connect to JSON file, and also I am using a plugin called"lightslider" to show the pictures, my problem is when I run the HTML noting show but after refreshing the page it shows. and other problem is it is work only on fire fox. and also in server not working on server. please give me some easy and possible way to show my pic on slider from JSON file which is works on all browser. thanks.

<!DOCTYPE html>

    <title>link3</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet"  href="lightslider.css"/>


问:
MS Paint registry settings not working
Years ago, I wrote a C program that would open Microsoft Paint with a 0x0 pixel palette.  It wrote values in the registry before spawning Paint.  I have created a C# version:

```<code>using System;
using Microsoft.Win32;

namespace PaintZeroCanvas
{
    class Program
    {
        static void Main(string[] args)
        {
            const string userRoot = "HKEY_CURRENT_USER";
            const string subkey = "Software\\Microsoft\\Windows\\CurrentVersion\\Applets\\Paint\\View";
            const string keyName = userRoot + "\\" + subkey;

            Registry.SetValue(keyName, "BMPWidth", 0);
            Registry.SetValue(keyName, "BMPHeight", 0);
            Registry.CurrentUser.Flush();

            System.Diagnostics.Process.Start(Environment.SystemDirectory + "\\mspaint.exe");
        }
    }
}
</code>```

The registry is modified, but Paint opens in the previously saved size.  These key names also appear in HKEY_USERS, but do not work there either.  I have administrative privileges, have FullControl access to both locations and have tried running the app with Administrative Privileges.

If I manually start Paint, change the palette size and close it, the values are written to these two locations.

I am running 64 bit Windows 10 and using Visual Studio 2015 Community version, and using .NET Framework 4.5.2.

答:
I think you need to open the 64bit Registry, like here:

Registry access with C# and "BUILD x86" on a 64bit machine

Note: the code below is untested!

```<code>using System;
using Microsoft.Win32;

namespace PaintZeroCanvas
{
    class Program
    {
        static void Main(string[] args)
        {
            const string userRoot = "HKEY_CURRENT_USER";
            const string subkey = "Software\\Microsoft\\Windows\\CurrentVersion\\Applets\\Paint\\View";
            const string keyName = userRoot + "\\" + subkey;

            RegistryKey registryKey =
            RegistryKey.OpenBaseKey(RegistryHive.LocalMachine,
            RegistryView.Registry64).OpenSubKey(keyName);

            registryKey.SetValue("BMPWidth", 0);
            registryKey.SetValue("BMPHeight", 0);

            System.Diagnostics.Process.Start(Environment.SystemDirectory + "\\mspaint.exe");
        }
    }
}
</code>```

Title: MS Paint registry settings not working

Body:
Years ago, I wrote a C program that would open Microsoft Paint with a 0x0 pixel palette.  It wrote values in the registry before spawning Paint.  I have created a C# version:

using System;
using Microsoft.Win32;

namespace PaintZeroCanvas
{
    class Program
    {
        static void Main(string[] args)
        {
            const string userRoot = "HKEY_CURRENT_USER";
            const string subkey = "Software\\Microsoft\\Windows\\CurrentVersion\\Applets\\Paint\\View";
            const string keyName = userRoot + "\\" + subkey;

            Registry.SetValue(keyName, "BMPWidth", 0);
            Registry.SetValue(keyName, "BMPHeight", 0);
            Registry.CurrentUser.Flush();

            System.Diagnostics.Process.Start(Environment.SystemDirectory + "\\mspaint.exe");
        }
    }
}

The registry is modified, but Paint opens in the previously saved size.  These key names also appear in HKEY_USERS, but do not work there either.  I have administrative privileges, have FullControl access to both locations and have tried running the app with Administrative Privileges.

If I manually start Paint, change the palette size and close it, the values are written to these two locations.

I am running 64 bit Windows 10 and using Visual Studio 2015 Community version, and using .NET Framework 4.5.2.

Body:
I think you need to open the 64bit Registry, like here:

Registry access with C# and "BUILD x86" on a 64bit machine

Note: the code below is untested!

using System;
using Microsoft.Win32;

namespace PaintZeroCanvas
{
    class Program
    {
        static void Main(string[] args)
        {
            const string userRoot = "HKEY_CURRENT_USER";
            const string subkey = "Software\\Microsoft\\Windows\\CurrentVersion\\Applets\\Paint\\View";
            const string keyName = userRoot + "\\" + subkey;

            RegistryKey registryKey =
            RegistryKey.OpenBaseKey(RegistryHive.LocalMachine,
            RegistryView.Registry64).OpenSubKey(keyName);

            registryKey.SetValue("BMPWidth", 0);
            registryKey.SetValue("BMPHeight", 0);

            System.Diagnostics.Process.Start(Environment.SystemDirectory + "\\mspaint.exe");
        }
    }
}


问:
DataGridVIew row to e-mail
I have DataGridView control where I want cell values from every selected row to be send as an e-mail body text as one string line:

```<code>        private void buttonReport_Click(object sender, EventArgs e)
    {
        MailAddress from = new MailAddress("hi@greetings.com", "Hello");
        MailAddress to = new MailAddress("hi1234@gmail.com", "Hi");
        string join;

        foreach (DataGridViewRow row in dgvTest.Rows)
        {
            List<string> email = new List<string>();
            {
                if (Convert.ToBoolean(row.Cells[cbSelect.Name].Value) == true)
                {
                    foreach (DataGridViewCell cell in row.Cells)
                    {
                        if (cell.Value != null)
                        {
                            email.Add(cell.Value.ToString());
                        }
                    }
                }
            }
            foreach (string items in email.Skip(1).Take(4))
            {
                join = String.Join(", ", items.ToString());
                SendEmail("Hi!", from, to, join);
            }
        }
    }
</code>```

This is the code, however I am getting 4 mails now because the SendMail() is in the foreach loop, if I take it out, the local variable join is not accessible..? how to work around this? I am using the email.Skip(1).Take(4) to omit some unnecessary values? Thanks in advance

答:
Move declaration List<string> email = new List<string>(); outside foreach. Not sure why you need Skip(1).Take(4)

I suggest following code:

```<code>//declared somewhere above
List<string> CellsForReport = new List<string>{ "item1", "item2", "item3", "item4" }

//code inside buttonReport_Click
List<string> emails = new List<string>();
foreach (DataGridViewRow row in dgvTest.Rows)
{
  if (Convert.ToBoolean(row.Cells[cbSelect.Name].Value) == true)
  {
    //list to collect current row items
    var currentMailItems = new List<string>()
    foreach (var cellName in CellsForReport )
    {
       //this can throw exception if you specified wrong name above
       var cell = row.Cells[cellName];
       if (cell.Value != null)
       {
         currentMailItems.Add(cell.Value.ToString());
       }
    }
    //construct email text from row
    var finalEmailText = string.Join(", ", currentMailItems);
    emails.Add(finalEmailText);
  }
}
//sending 1 email per row
foreach (var email in emails)
{
  SendEmail("Hi!", from, to, email);
}
</code>```

Title: DataGridVIew row to e-mail

Body:
I have DataGridView control where I want cell values from every selected row to be send as an e-mail body text as one string line:

        private void buttonReport_Click(object sender, EventArgs e)
    {
        MailAddress from = new MailAddress("hi@greetings.com", "Hello");
        MailAddress to = new MailAddress("hi1234@gmail.com", "Hi");
        string join;

        foreach (DataGridViewRow row in dgvTest.Rows)
        {
            List<string> email = new List<string>();
            {
                if (Convert.ToBoolean(row.Cells[cbSelect.Name].Value) == true)
                {
                    foreach (DataGridViewCell cell in row.Cells)
                    {
                        if (cell.Value != null)
                        {
                            email.Add(cell.Value.ToString());
                        }
                    }
                }
            }
            foreach (string items in email.Skip(1).Take(4))
            {
                join = String.Join(", ", items.ToString());
                SendEmail("Hi!", from, to, join);
            }
        }
    }

This is the code, however I am getting 4 mails now because the SendMail() is in the foreach loop, if I take it out, the local variable join is not accessible..? how to work around this? I am using the email.Skip(1).Take(4) to omit some unnecessary values? Thanks in advance

Body:
Move declaration List<string> email = new List<string>(); outside foreach. Not sure why you need Skip(1).Take(4)

I suggest following code:

//declared somewhere above
List<string> CellsForReport = new List<string>{ "item1", "item2", "item3", "item4" }

//code inside buttonReport_Click
List<string> emails = new List<string>();
foreach (DataGridViewRow row in dgvTest.Rows)
{
  if (Convert.ToBoolean(row.Cells[cbSelect.Name].Value) == true)
  {
    //list to collect current row items
    var currentMailItems = new List<string>()
    foreach (var cellName in CellsForReport )
    {
       //this can throw exception if you specified wrong name above
       var cell = row.Cells[cellName];
       if (cell.Value != null)
       {
         currentMailItems.Add(cell.Value.ToString());
       }
    }
    //construct email text from row
    var finalEmailText = string.Join(", ", currentMailItems);
    emails.Add(finalEmailText);
  }
}
//sending 1 email per row
foreach (var email in emails)
{
  SendEmail("Hi!", from, to, email);
}


问:
Layout adapting depending on Screen size
I have a problem with Android Studio when I have to adapt my application to different screen sizes. I tried creating diferent layouts depending on the screen size (small, normal, large, xlarge), but it doesn't work and I don't know why. No matter what the screen size of the mobile is, it uses the normal screen size layout. Here I leave you 2 screenshots: The first one is the res folder in the explorer, and the second one the folders in android studio.

Res folder

Android Studio folder

答:
Try this approach:

```<code>//create a folder structure like this

/layout
/layout-sw300dp
/layout-sw400dp
/layout-sw600dp
/layout-sw800dp
</code>```

Now you can place the respective layout files in the corresponding folders!

I hope this helps! Good luck!

Body:
Try this approach:

//create a folder structure like this

/layout
/layout-sw300dp
/layout-sw400dp
/layout-sw600dp
/layout-sw800dp

Now you can place the respective layout files in the corresponding folders!

I hope this helps! Good luck!


问:
jquery .html load external file through object data is not working
I am trying the demo solution like below

```<code>$("#loadExtPage01").html(<object data="https://system.netsuite.com/pages/customerlogin.jsp?country=US" />);
</code>```

It is working instead of the object data, when i try to use my own external file url its not working(loading)?

i.e:

```<code>$("#loadExtPage01").html(<object data="http://gmovdevk2pocapp:81/Runtime/Runtime/Form/MarketingServiceTicketCreateEditForm?FarmId=1&ServiceTicketTaskId=21&ServiceTicketId=7&ServiceTypeId=2" />);
</code>```

Any ideas / solutions ?

答:
what is also important is that you allow iframing.

apache will block iframing when the security is set like this:

```<code> Header append X-FRAME-OPTIONS DENY
</code>```

use this instead:

```<code>X-Frame-Options: SAMEORIGIN
</code>```

Body:
I am trying the demo solution like below

$("#loadExtPage01").html(<object data="https://system.netsuite.com/pages/customerlogin.jsp?country=US" />);

It is working instead of the object data, when i try to use my own external file url its not working(loading)?

i.e:

$("#loadExtPage01").html(<object data="http://gmovdevk2pocapp:81/Runtime/Runtime/Form/MarketingServiceTicketCreateEditForm?FarmId=1&ServiceTicketTaskId=21&ServiceTicketId=7&ServiceTypeId=2" />);

Any ideas / solutions ?

Body:
what is also important is that you allow iframing.

apache will block iframing when the security is set like this:

 Header append X-FRAME-OPTIONS DENY

use this instead:

X-Frame-Options: SAMEORIGIN


问:
php add html element inside while loop
Hello here is my code :

```<code><table class="table table-hover table-bordered">
<tr>
<th class="well" style="text-align:center">ID</th>
<th class="well" style="text-align:center">Email</th>
<th class="well" style="text-align:center">User level</th>
</tr>';

<?
$code_sql = "SELECT user_id, user_email,user_level FROM users ORDER BY user_id ASC ";
$code_query = mysql_query($code_sql) or die(error_sql(mysql_error(),__LINE__,__FILE__));
$sql_rows = mysql_num_rows($code_query);
if($sql_rows > 0){
while($rows = mysql_fetch_object($code_query)){
$user_id = intval($rows->user_id);
$user_level= intval($rows->user_level);
$user_email = htmlspecialchars($rows->user_email);
echo '      <tr>
<td>'.$user_id.'</td>
<td>'.$user_email.'</td>
<td>'.$user_level.'</td>
</tr>';
}
mysql_free_result($code_query);
}else{
echo '<tr>
<td>
<font color="red">no data found</font>
</td>
</tr>';
}
echo '</table>';
?>
</code>```

the output of the code will be like .

```<code><table class="table table-hover table-bordered">
<tr>
<th class="well" style="text-align:center">ID</th>
<th class="well" style="text-align:center">Email</th>
<th class="well" style="text-align:center">User level</th>
</tr>
<tr>
<td>1</td>
<td>test1@gmail.com</td>
<td>1</td>
</tr>
<tr>
<td>2</td>
<td>test2@gmail.com</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>test3@gmail.com</td>
<td>2</td>
</tr>
<tr>
<td>4</td>
<td>test4@gmail.com</td>
<td>1</td>
</tr>
</table>
</code>```

(1 = normal user , and 2 = admin for user level) but what I want is something .like that

```<code><table class="table table-hover table-bordered">
<tr>
<th class="well" style="text-align:center">ID</th>
<th class="well" style="text-align:center">Email</th>
<th class="well" style="text-align:center">User level</th>
</tr>
<div id="users">
<tr>
<td>1</td>
<td>test1@gmail.com</td>
<td>1</td>
</tr>
<tr>
<td>4</td>
<td>test4@gmail.com</td>
<td>1</td>
</tr>
</div>
<div id="admins">
<tr>
<td>2</td>
<td>test2@gmail.com</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>test3@gmail.com</td>
<td>2</td>
</tr>
</div>
</table>
</code>```

I want to add a div id="users" that will contain all users from database that have user_level = 1 and another div id="admins" for user_level = 2.

答:
try the following code, you need to create div's based on conditions like if the iteration number 1 then insert div(open) before content and after content(close)...and the if iteration number is 3 then again insert the div(open) before content an after content(close)</p>

```<code>   <table class="table table-hover table-bordered">
    <tr>
    <th class="well" style="text-align:center">ID</th>
    <th class="well" style="text-align:center">Email</th>
    <th class="well" style="text-align:center">User level</th>
    </tr>

    <?php
    $code_sql = "SELECT user_id, user_email,user_level FROM users ORDER BY user_id ASC ";
    $code_query = mysql_query($code_sql) or die(error_sql(mysql_error(),__LINE__,__FILE__));
    $sql_rows = mysql_num_rows($code_query);
    if($sql_rows > 0){
        $i=0;
    while($rows = mysql_fetch_object($code_query)){
      $user_id = intval($rows->user_id);
      $user_level= intval($rows->user_level);
      $user_email = htmlspecialchars($rows->user_email);
      if($i==0){?><div id='users'><?php }elseif($i==2){?><div id='admins'><?php }
      echo '      <tr>
      <td>'.$user_id.'</td>
      <td>'.$user_email.'</td>
      <td>'.$user_level.'</td>
      </tr>';
      if($i==0){?></div><?php }elseif($i==2){?></div><?php }
       $i++;
      }
      mysql_free_result($code_query);
      }else{
    echo '<tr>
    <td>
    <font color="red">no data found</font>
    </td>
    </tr>';
    }
    echo '</table>';
    ?>
</code>```

Title: php add html element inside while loop

Body:
Hello here is my code :

ID
Email
User level

';

<?
$code_sql = "SELECT user_id, user_email,user_level FROM users ORDER BY user_id ASC ";
$code_query = mysql_query($code_sql) or die(error_sql(mysql_error(),__LINE__,__FILE__));
$sql_rows = mysql_num_rows($code_query);
if($sql_rows > 0){
while($rows = mysql_fetch_object($code_query)){
$user_id = intval($rows->user_id);
$user_level= intval($rows->user_level);
$user_email = htmlspecialchars($rows->user_email);
echo '

'.$user_id.'
'.$user_email.'
'.$user_level.'

';
}
mysql_free_result($code_query);
}else{
echo '

no data found

';
}
echo '
';
?>

the output of the code will be like .

ID
Email
User level

1
test1@gmail.com
1

2
test2@gmail.com
2

3
test3@gmail.com
2

4
test4@gmail.com
1

(1 = normal user , and 2 = admin for user level) but what I want is something .like that

ID
Email
User level

1
test1@gmail.com
1

4
test4@gmail.com
1

2
test2@gmail.com
2

3
test3@gmail.com
2

I want to add a div id="users" that will contain all users from database that have user_level = 1 and another div id="admins" for user_level = 2.

Body:
try the following code, you need to create div's based on conditions like if the iteration number 1 then insert div(open) before content and after content(close)...and the if iteration number is 3 then again insert the div(open) before content an after content(close)

   <table class="table table-hover table-bordered">
    <tr>
    <th class="well" style="text-align:center">ID</th>
    <th class="well" style="text-align:center">Email</th>
    <th class="well" style="text-align:center">User level</th>
    </tr>

    <?php
    $code_sql = "SELECT user_id, user_email,user_level FROM users ORDER BY user_id ASC ";
    $code_query = mysql_query($code_sql) or die(error_sql(mysql_error(),__LINE__,__FILE__));
    $sql_rows = mysql_num_rows($code_query);
    if($sql_rows > 0){
        $i=0;
    while($rows = mysql_fetch_object($code_query)){
      $user_id = intval($rows->user_id);
      $user_level= intval($rows->user_level);
      $user_email = htmlspecialchars($rows->user_email);
      if($i==0){?><div id='users'><?php }elseif($i==2){?><div id='admins'><?php }
      echo '      <tr>
      <td>'.$user_id.'</td>
      <td>'.$user_email.'</td>
      <td>'.$user_level.'</td>
      </tr>';
      if($i==0){?></div><?php }elseif($i==2){?></div><?php }
       $i++;
      }
      mysql_free_result($code_query);
      }else{
    echo '<tr>
    <td>
    <font color="red">no data found</font>
    </td>
    </tr>';
    }
    echo '</table>';
    ?>


问:
How to make your desktop Java app looks like Open Office or Eclipse etc.?
How to make your desktop Java app looks like Open Office or Eclipse  etc ?
Installation process looks like any Windpws app. installation. There is no Java logo on the to on a app window. You run it by .exe file. How it is done? Is this jar->exe conversion?
Is there any free tool to do that?</p>

答: The question is a little unclear, but I think that what you're after is making your java app behave like a native app (stuff like running it when an icon is double-clicked, etc...). There is an excellent tutorial on this here.</p>