问:
Find the version of an installed npm package
How can I find the version of an installed Node.js or npm package?

This prints the version of npm itself:

```<code>npm -v <package-name>
</code>```

This prints a cryptic error:

```<code>npm version <package-name>
</code>```

This prints the package version on the registry (i.e., the latest version available):

```<code>npm view <package-name> version
</code>```

How do I get the installed version?

答:
I added this to my .bashrc file:

```<code>function npmv {
    case $# in # Number of arguments passed
    0) v="$(npm -v)" ; # Store output from npm -v in variable
        echo "NPM version is: $v"; # Can't use single quotes
                                   # ${v} would also work
    ;;
    1) s="$(npm list --depth=0 $1 | grep $1 | cut -d @ -f 2)";
       echo "$s";
    ;;
    2) case "$2" in # Second argument
        g) #global| # Syntax to compare bash string to literal
             s="$(npm list --depth=0 -g $1 | grep $1 | cut -d @ -f 2)";
        echo "$s";
        ;;
        l) #Latest
             npm view $1 version; # 'npm info $1 version' does the same thing
       ;;
       *) echo 'Invalid arguments';
       ;;
       esac;
    ;;
    *) echo 'Invalid arguments';
    ;;
    esac;
}
export -f npmv
</code>```

Now all I have to do is type:

npmv for the version of npm, for example, NPM version is: 4.2.0

npmv <package-name> for the local version, for example, 0.8.08

npmv <package-name> g for global version, for example, 0.8.09

npmv <package-name> l for latest version, for example, 0.8.10

Note -d on the cut command means delimit by, followed by @, and then f means field. The '2' means the second field since there will be one either side of the @ symbol.

Body:
How can I find the version of an installed Node.js or npm package?

This prints the version of npm itself:

npm -v <package-name>

This prints a cryptic error:

npm version <package-name>

This prints the package version on the registry (i.e., the latest version available):

npm view <package-name> version

How do I get the installed version?

Body:
I added this to my .bashrc file:

function npmv {
    case $# in # Number of arguments passed
    0) v="$(npm -v)" ; # Store output from npm -v in variable
        echo "NPM version is: $v"; # Can't use single quotes
                                   # ${v} would also work
    ;;
    1) s="$(npm list --depth=0 $1 | grep $1 | cut -d @ -f 2)";
       echo "$s";
    ;;
    2) case "$2" in # Second argument
        g) #global| # Syntax to compare bash string to literal
             s="$(npm list --depth=0 -g $1 | grep $1 | cut -d @ -f 2)";
        echo "$s";
        ;;
        l) #Latest
             npm view $1 version; # 'npm info $1 version' does the same thing
       ;;
       *) echo 'Invalid arguments';
       ;;
       esac;
    ;;
    *) echo 'Invalid arguments';
    ;;
    esac;
}
export -f npmv

Now all I have to do is type:

npmv for the version of npm, for example, NPM version is: 4.2.0

npmv <package-name> for the local version, for example, 0.8.08

npmv <package-name> g for global version, for example, 0.8.09

npmv <package-name> l for latest version, for example, 0.8.10

Note -d on the cut command means delimit by, followed by @, and then f means field. The '2' means the second field since there will be one either side of the @ symbol.


来源: stackexchange

问:
How to sign in second user in incognito window to test actioncable
I'm trying to sign in a 2nd user to see if ActionCable is working.  I have my app open in a regular Chrome window on localhost:3000 and I also have it open in an incognito window also localhost:3000

From https://github.com/rails/actioncable-examples:

Open two browsers with separate cookie spaces (like a regular session and an incognito session).

Login as different people in each browser.
3  Go to the same message.

Add comments in either browser and see them appear real-time on the counterpart screen.

However, when I sign in the 2nd user in the incognito window, the 1st user gets logged out.

I'm using ng-token-auth and devise_token_auth for authentication.

Also, I have an ng-click that toggles the navbar to collapse

```<code><button type="button" class="navbar-toggle" ng-click="isNavCollapsed = !isNavCollapsed">
  <i class="fa fa-bars" aria-hidden="true"></i>
</button>
</code>```

When I click the hamburger button in either the regular window or the incognito window, the navbar collapses in both windows.

I thought an incognito window would give me a completely separate cookie jar and therefore separate $scopes but I guess not.

I hope someone can tell me what is going one.

答:
When using Incognito mode, your Sesssion stays active on every tab/window as long as you do not close each and every one of them as stated on the Incognito start page:

Pages you view in incognito tabs won't stick around in your browser's history, cookie store, or search history after you've closed all of your incognito tabs. Any files you download or bookmarks you create will be kept.

Having stated this, your session is completely different from the one in a normal tab/window, so the action cable test should work.

This may fail if by any means your logic overrides the logged in user when a new user gets logged in.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to sign in a 2nd user to see if ActionCable is working.  I have my app open in a regular Chrome window on localhost:3000 and I also have it open in an incognito window also localhost:3000

From https://github.com/rails/actioncable-examples:

Open two browsers with separate cookie spaces (like a regular session and an incognito session).

Login as different people in each browser.
3  Go to the same message.

Add comments in either browser and see them appear real-time on the counterpart screen.

However, when I sign in the 2nd user in the incognito window, the 1st user gets logged out.

I'm using ng-token-auth and devise_token_auth for authentication.

Also, I have an ng-click that toggles the navbar to collapse

<button type="button" class="navbar-toggle" ng-click="isNavCollapsed = !isNavCollapsed">

</button>

When I click the hamburger button in either the regular window or the incognito window, the navbar collapses in both windows.

I thought an incognito window would give me a completely separate cookie jar and therefore separate $scopes but I guess not.

I hope someone can tell me what is going one.


问:
Getting tag name from xml
I have file with such structure:

```<code><pwACL>
The gateway only supports upto 10 rules.
</pwACL>

<cmn53>
Batch Number
</cmn53>
</code>```

I want to get tag name and data between tags. I tried to use BeatifulSoup HTMLParser library, but it automatically converts tag name to lowercase. I found that there was a possibility to use html5lib creating tree with beatifulsoup tree builder like this:

```<code>parser = html5lib.HTMLParser(tree=treebuilders.getTreeBuilder("beatifulsoup"))
</code>```

but it seems like html5lib does not support beatifulsoup anymore. Is there any other way?

答:
It's mentioned in BeautisulSoup documentation - Other parsers problems:

Because HTML tags and attributes are case-insensitive, all three HTML
  parsers convert tag and attribute names to lowercase. That is, the
  markup <TAG></TAG> is converted to <tag></tag>. If you want to
  preserve mixed-case or uppercase tags and attributes, you’ll need to
  parse the document as XML.

Parsing XML:

By default, Beautiful Soup parses documents as HTML. To parse a
  document as XML, pass in “xml” as the second argument to the
  BeautifulSoup constructor:

```<code>soup = BeautifulSoup(markup, "xml")
</code>```

You’ll need to have lxml installed.

```<code>>>> markup = '''<pwACL>
... The gateway only supports upto 10 rules.
... </pwACL>'''
>>> soup = BeautifulSoup(markup, 'xml')
>>> soup.find_all()
[<pwACL>\nThe gateway only supports upto 10 rules.\n</pwACL>]
</code>```

Title: Getting tag name from xml

Body:
I have file with such structure:

<pwACL>
The gateway only supports upto 10 rules.
</pwACL>

<cmn53>
Batch Number
</cmn53>

I want to get tag name and data between tags. I tried to use BeatifulSoup HTMLParser library, but it automatically converts tag name to lowercase. I found that there was a possibility to use html5lib creating tree with beatifulsoup tree builder like this:

parser = html5lib.HTMLParser(tree=treebuilders.getTreeBuilder("beatifulsoup"))

but it seems like html5lib does not support beatifulsoup anymore. Is there any other way?

Body:
It's mentioned in BeautisulSoup documentation - Other parsers problems:

Because HTML tags and attributes are case-insensitive, all three HTML
  parsers convert tag and attribute names to lowercase. That is, the
  markup <TAG></TAG> is converted to <tag></tag>. If you want to
  preserve mixed-case or uppercase tags and attributes, you’ll need to
  parse the document as XML.

Parsing XML:

By default, Beautiful Soup parses documents as HTML. To parse a
  document as XML, pass in “xml” as the second argument to the
  BeautifulSoup constructor:

soup = BeautifulSoup(markup, "xml")

You’ll need to have lxml installed.

>>> markup = '''<pwACL>
... The gateway only supports upto 10 rules.
... </pwACL>'''
>>> soup = BeautifulSoup(markup, 'xml')
>>> soup.find_all()
[<pwACL>\nThe gateway only supports upto 10 rules.\n</pwACL>]


问:
AdMob add ad unit does not work
It's my first time using AdMob.  When I hit ADD AD UNIT button. It's constantly just loading and does not proceed to the next page. Any of you know what's happening? My app isn't published to the Playstore yet.

答: Just disable all the extensions from your browser and try reloading that page or by logging out and then logging in and you'll get the access to ad units.  </p>

Title: AdMob add ad unit does not work


问:
How to run through mysql loop when also using group by
I have the following four tables:

members

```<code>agent   |   memberid   |   firstname   |   lastname
===================================================
123     |    444       |  john         |    smith
123     |    555       |  sarah        |    stevens
123     |    777       |   harry       |    tabor
</code>```

where agent refers to the selling agent id, member id is unique to every customer, first and last names associated with the member

selections

```<code>id   |   memberid   |   programid
=================================
1    |      444     |     1
2    |      444     |     2
3    |      444     |     3
4    |      555     |     1
5    |      555     |     2
6    |      555     |     3
7    |      777     |     1
8    |      777     |     2
9    |      777     |     3
</code>```

which details the selections made by each member, for simplicity sake, each of the members listed above in this example selected to be a part of programID's 1, 2, and 3.

groups

```<code>programID  |   cost   |   type
===================================
  1        |   20.00  |     7
  2        |   30.00  |     8
  3        |   40.00  |     9
</code>```

this table details the cost and system type for each unique programID

comp_levels

```<code>level  |   type1   |   type2   |   type3
============================================
   1   |   0.25    |   0.15    |  0.1
   2   |   0.3     |   0.18    |  0.11
   3   |   0.35    |   0.2     |  0.12
   4   |   0.4     |   0.225   |  0.15
   5   |   0.425   |   0.25    |  0.17
   6   |   0.45    |   0.27    |  0.2
   7   |   0.47    |   0.28    |  0.22
   8   |   0.5     |   0.3     |  0.24
</code>```

this table highlights the sales commission structure for each particular agent based on their level and using the system type from GROUPS above.

For this example, we will assume Agent 123 is at commission level 2.

Ultimately, I am trying to build a reporting system which would detail the commission structure for both a single agent and a group of agents based on their sales, respective commission level, and the type of sale they brought in.

My current sql statement (which does not satisfy my need), is:

```<code>select
    a.memberid,
    a.firstname,
    a.lastname,
    sum(c.cost) as Cost,
CASE
    when c.type = '5' THEN (SUM(c.cost) * d.type1)
    when c.type = '6' THEN (SUM(c.cost) * d.type2)
    when c.type = '7' THEN (SUM(c.cost) * d.type3)
END as Commission
FROM
    members a
left join selections b using(memberid)
left join groups c using(programid)
left join comp_levels d on d.level = '2'
where agent = '123'
GROUP BY a.memberid;
</code>```

the results of this query are:

```<code>memberid   |  firstname   | lastname   |   Cost   |   Commission
================================================================
   444     |   john       | smith      |   60.00  |   27.00
   555     |   sarah      | stevens    |   60.00  |   27.00
   666     |   harry      | tabor      |   60.00  |   27.00
</code>```

The issue I face is the resultset is taking the first CASE match and applying to several rows returned when it should in fact only apply to each row, THEN group the results.

In the example above, the commission for each particular member SHOULD be $15.18 (30% of $20 + 18% of $30 + 11% of $40) but it is instead taking case 1 and applying the 30% commission to every result (30% of $90).

I have played around with several variations but am unable to figure out how to combine what I am trying to do within a single query ( this query is ONLY run from a mysql gui so using any programming language is not acceptable.

答:
I think the primary problem is that you're using a CASE improperly in a GROUP BY. I think most SQL platforms would complain if you try something like that, but MySQL will just give you bunk/random results and smile.

At any rate, I think you have to use a subquery to get what you want due to the unusual schema.  Something like this

```<code>SELECT
    sq.memberid, sq.firstname, sq.lastname,
    SUM(sq.cost) AS total_cost, SUM(sq.commission) AS total_commission
FROM
(
    SELECT
    m.memberid, m.firstname, m.lastname, g.cost,
    CASE
        WHEN g.type = '7' THEN (g.cost * cl.type1)
        WHEN g.type = '8' THEN (g.cost * cl.type2)
        WHEN g.type = '9' THEN (g.cost * cl.type3)
    END as commission
    FROM members m
    LEFT JOIN selections s USING(memberid)
    LEFT JOIN groups g USING(programid)
    LEFT JOIN comp_levels cl ON cl.level = '2'
    WHERE m.agent = '123'
) sq GROUP BY sq.memberid
</code>```

You can run the subquery by itself to trace what's going on.

Using your data, it gives the result

```<code>+----------+-----------+----------+------------+------------------+
| memberid | firstname | lastname | total_cost | total_commission |
+----------+-----------+----------+------------+------------------+
|      444 | john      | smith    |      90.00 |           15.800 |
|      555 | sarah     | stevens  |      90.00 |           15.800 |
|      777 | harry     | tabour   |      90.00 |           15.800 |
+----------+-----------+----------+------------+------------------+
</code>```

NB: due to the unusual (lack of) normalization, i.e. mapping the types (7,8,9) to type fields (type1,type2,type3), this an awkward problem to wrap a head around.  Moreover, I think you might have had some typos in your test data description; i.e. the type values in your SQL, and the total cost in your query output and desired result.

ContentLicense: CC BY-SA 2.5

Body:
I have the following four tables:

members

agent   |   memberid   |   firstname   |   lastname
===================================================
123     |    444       |  john         |    smith
123     |    555       |  sarah        |    stevens
123     |    777       |   harry       |    tabor

where agent refers to the selling agent id, member id is unique to every customer, first and last names associated with the member

selections

id   |   memberid   |   programid
=================================
1    |      444     |     1
2    |      444     |     2
3    |      444     |     3
4    |      555     |     1
5    |      555     |     2
6    |      555     |     3
7    |      777     |     1
8    |      777     |     2
9    |      777     |     3

which details the selections made by each member, for simplicity sake, each of the members listed above in this example selected to be a part of programID's 1, 2, and 3.

groups

programID  |   cost   |   type
===================================
  1        |   20.00  |     7
  2        |   30.00  |     8
  3        |   40.00  |     9

this table details the cost and system type for each unique programID

comp_levels

level  |   type1   |   type2   |   type3
============================================
   1   |   0.25    |   0.15    |  0.1
   2   |   0.3     |   0.18    |  0.11
   3   |   0.35    |   0.2     |  0.12
   4   |   0.4     |   0.225   |  0.15
   5   |   0.425   |   0.25    |  0.17
   6   |   0.45    |   0.27    |  0.2
   7   |   0.47    |   0.28    |  0.22
   8   |   0.5     |   0.3     |  0.24

this table highlights the sales commission structure for each particular agent based on their level and using the system type from GROUPS above.

For this example, we will assume Agent 123 is at commission level 2.

Ultimately, I am trying to build a reporting system which would detail the commission structure for both a single agent and a group of agents based on their sales, respective commission level, and the type of sale they brought in.

My current sql statement (which does not satisfy my need), is:

select
    a.memberid,
    a.firstname,
    a.lastname,
    sum(c.cost) as Cost,
CASE
    when c.type = '5' THEN (SUM(c.cost) * d.type1)
    when c.type = '6' THEN (SUM(c.cost) * d.type2)
    when c.type = '7' THEN (SUM(c.cost) * d.type3)
END as Commission
FROM
    members a
left join selections b using(memberid)
left join groups c using(programid)
left join comp_levels d on d.level = '2'
where agent = '123'
GROUP BY a.memberid;

the results of this query are:

memberid   |  firstname   | lastname   |   Cost   |   Commission
================================================================
   444     |   john       | smith      |   60.00  |   27.00
   555     |   sarah      | stevens    |   60.00  |   27.00
   666     |   harry      | tabor      |   60.00  |   27.00

The issue I face is the resultset is taking the first CASE match and applying to several rows returned when it should in fact only apply to each row, THEN group the results.

In the example above, the commission for each particular member SHOULD be $15.18 (30% of $20 + 18% of $30 + 11% of $40) but it is instead taking case 1 and applying the 30% commission to every result (30% of $90).

I have played around with several variations but am unable to figure out how to combine what I am trying to do within a single query ( this query is ONLY run from a mysql gui so using any programming language is not acceptable.

Body:
I think the primary problem is that you're using a CASE improperly in a GROUP BY. I think most SQL platforms would complain if you try something like that, but MySQL will just give you bunk/random results and smile.

At any rate, I think you have to use a subquery to get what you want due to the unusual schema.  Something like this

SELECT
    sq.memberid, sq.firstname, sq.lastname,
    SUM(sq.cost) AS total_cost, SUM(sq.commission) AS total_commission
FROM
(
    SELECT
    m.memberid, m.firstname, m.lastname, g.cost,
    CASE
        WHEN g.type = '7' THEN (g.cost * cl.type1)
        WHEN g.type = '8' THEN (g.cost * cl.type2)
        WHEN g.type = '9' THEN (g.cost * cl.type3)
    END as commission
    FROM members m
    LEFT JOIN selections s USING(memberid)
    LEFT JOIN groups g USING(programid)
    LEFT JOIN comp_levels cl ON cl.level = '2'
    WHERE m.agent = '123'
) sq GROUP BY sq.memberid

You can run the subquery by itself to trace what's going on.

Using your data, it gives the result

+----------+-----------+----------+------------+------------------+
| memberid | firstname | lastname | total_cost | total_commission |
+----------+-----------+----------+------------+------------------+
|      444 | john      | smith    |      90.00 |           15.800 |
|      555 | sarah     | stevens  |      90.00 |           15.800 |
|      777 | harry     | tabour   |      90.00 |           15.800 |
+----------+-----------+----------+------------+------------------+

NB: due to the unusual (lack of) normalization, i.e. mapping the types (7,8,9) to type fields (type1,type2,type3), this an awkward problem to wrap a head around.  Moreover, I think you might have had some typos in your test data description; i.e. the type values in your SQL, and the total cost in your query output and desired result.


问:
Developing for Android vs developing for IOS
I have been working some time with Android and now considering a new job on iOS, so I was wondering how many new concepts would have to learn. I know iOS is another planet but this is just to clear a bit more the whole picture.

So, what are the similitudes and differences between developing an Android app and an iOS app?

答:
Similitudes

Both use object oriented programming and have great IDEs with UI design implementation, nice features and the possibility of adding new ones.

Differences

Sources

General information:

http://www.androidauthority.com/developing-for-android-vs-ios-697304/

And some interest and more specific answers:

https://www.quora.com/How-does-Android-development-compare-to-iOS-development

I don't have much experience on iOS, so if something is wrong let me know and if you see an important missing similitude or difference, write it down as a new answer please!


问:
How to add tableview xcode
I am using Xcode 8.3.2. I am following https://www.raywenderlich.com/77974/making-a-gesture-driven-to-do-list-app-like-clear-in-swift-part-1, and it says to "add a table view".

I can't find it when I follow the steps. I also followed https://www.youtube.com/watch?v=fFpMiSsynXM and am not seeing any table view. I don't understand why my xcode doesn't offer this. Am I missing a plugin?

答:
You need to select the object library` here:

Also make sure you have your Main.storyboard file open

ContentLicense: CC BY-SA 4.0

Title: How to add tableview xcode


答:
The list you are looking at is file templates. You need to:

start editing a storyboard

pick the third item in the toolbar for the section you are typing into, which is where all the view templates are located.

Now you should find the table view you’re after and drag it into the storyboard.

Title: How to add tableview xcode

Body:
I am using Xcode 8.3.2. I am following https://www.raywenderlich.com/77974/making-a-gesture-driven-to-do-list-app-like-clear-in-swift-part-1, and it says to "add a table view".

I can't find it when I follow the steps. I also followed https://www.youtube.com/watch?v=fFpMiSsynXM and am not seeing any table view. I don't understand why my xcode doesn't offer this. Am I missing a plugin?


问:
Read from configuration kafkalistener
I have a spring boot application which has the listener as follows:

```<code>@KafkaListener(id = "demo", topics = "demo",
            containerFactory = "retryKafkaListenerContainerFactory")
    public void receive(ConsumerRecord<String, String> consumerRecord, Acknowledgment acknowledgment) throws Exception {

}
</code>```

I have apache configuration object which I want to use to read topics from properties. I know that I can use property placeholders to do that. But the configuration I use has some logic inside so want to read only from that configuration object. It is as follows:

```<code>@Inject
private Configuration configuration
</code>```

I can get topics as configuration.getString("kafka.consumer.topic"). I tried using like this: topics = "#{configuration.getString('kafka-generic.consumer.topics')}" in topics field of KafkaListener annotation but getting the following errors.

```<code>Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1008E: Property or field 'configuration' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext' - maybe not public?
    at org.springframework.expression.spel.ast.PropertyOrFieldReference.readProperty(PropertyOrFieldReference.java:224)
    at org.springframework.expression.spel.ast.PropertyOrFieldReference.getValueInternal(PropertyOrFieldReference.java:94)
    at org.springframework.expression.spel.ast.PropertyOrFieldReference.getValueInternal(PropertyOrFieldReference.java:81)
    at org.springframework.expression.spel.ast.CompoundExpression.getValueRef(CompoundExpression.java:51)
    at org.springframework.expression.spel.ast.CompoundExpression.getValueInternal(CompoundExpression.java:87)
    at org.springframework.expression.spel.ast.SpelNodeImpl.getValue(SpelNodeImpl.java:120)
    at org.springframework.expression.spel.standard.SpelExpression.getValue(SpelExpression.java:242)
    at org.springframework.context.expression.StandardBeanExpressionResolver.evaluate(StandardBeanExpressionResolver.java:161)
    ... 23 common frames omitted
</code>```

Can someone tell me how to use configuration.getString("kafka.consumer.topic") in topics field of KafkaListener annotation?

答:
getting errors.

That is never enough for for a question like this; you have to show the actual error.

You can use SpEL topics = "#{@somebean.someProperty}" ortopics = "#{@somebean.getString('...')}".

Title: Read from configuration kafkalistener

Body:
I have a spring boot application which has the listener as follows:

@KafkaListener(id = "demo", topics = "demo",
            containerFactory = "retryKafkaListenerContainerFactory")
    public void receive(ConsumerRecord<String, String> consumerRecord, Acknowledgment acknowledgment) throws Exception {

}

I have apache configuration object which I want to use to read topics from properties. I know that I can use property placeholders to do that. But the configuration I use has some logic inside so want to read only from that configuration object. It is as follows:

@Inject
private Configuration configuration

I can get topics as configuration.getString("kafka.consumer.topic"). I tried using like this: topics = "#{configuration.getString('kafka-generic.consumer.topics')}" in topics field of KafkaListener annotation but getting the following errors.

Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1008E: Property or field 'configuration' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext' - maybe not public?
    at org.springframework.expression.spel.ast.PropertyOrFieldReference.readProperty(PropertyOrFieldReference.java:224)
    at org.springframework.expression.spel.ast.PropertyOrFieldReference.getValueInternal(PropertyOrFieldReference.java:94)
    at org.springframework.expression.spel.ast.PropertyOrFieldReference.getValueInternal(PropertyOrFieldReference.java:81)
    at org.springframework.expression.spel.ast.CompoundExpression.getValueRef(CompoundExpression.java:51)
    at org.springframework.expression.spel.ast.CompoundExpression.getValueInternal(CompoundExpression.java:87)
    at org.springframework.expression.spel.ast.SpelNodeImpl.getValue(SpelNodeImpl.java:120)
    at org.springframework.expression.spel.standard.SpelExpression.getValue(SpelExpression.java:242)
    at org.springframework.context.expression.StandardBeanExpressionResolver.evaluate(StandardBeanExpressionResolver.java:161)
    ... 23 common frames omitted

Can someone tell me how to use configuration.getString("kafka.consumer.topic") in topics field of KafkaListener annotation?


问:
Add white space to image using Laravel 5 intervention image to make square image
Assume I have a favourite square size, and in this case it has 2236 px width and height.

I need to save my images in this size on my server using php intervention package.

It's not important that what is user's image size, but the point is that the image have to save with new size but the user image have to be center and middle of the square and if the picture is smaller than my favourite dimensions, it have to be stretch and if the image is bigger, it have to be compress to my dimension.

Please take a look at this picture:

And these are some real examples:

Does anyone any experience in this situation and do you know how can I do that?

Thanks in Advance

答:
```<code><?php
$width = 2236;
$height = 2236;

$img = Image::make('image.jpg');

// we need to resize image, otherwise it will be cropped
if ($img->width() > $width) {
    $img->resize($width, null, function ($constraint) {
        $constraint->aspectRatio();
    });
}

if ($img->height() > $height) {
    $img->resize(null, $height, function ($constraint) {
        $constraint->aspectRatio();
    });
}

$img->resizeCanvas($width, $height, 'center', false, '#ffffff');
$img->save('out.jpg');
</code>```


问:
Differences in print output/format
New to python and trying to figure out why the following 2 lists generate different output formats

```<code>n=5
mylist = "*" * n
print(mylist)
mylist = ["\*", "\*", "\*", "\*", "\*"]
print(mylist)
</code>```

Output:

*****
['\*', '\*', '\*', '\*', '\*']
```

答:
My output is

```<code>*****
['\\*', '\\*', '\\*', '\\*', '\\*']
</code>```

Obviously,"*" * n is a string,["\*", "\*", "\*", "\*", "\*"] is a list. If you want to create a list, please set a list first.

Title: Differences in print output/format

Body:
New to python and trying to figure out why the following 2 lists generate different output formats

n=5
mylist = "*" * n
print(mylist)
mylist = ["\*", "\*", "\*", "\*", "\*"]
print(mylist)

Output:

*****
['\*', '\*', '\*', '\*', '\*']

Body:
My output is

*****
['\\*', '\\*', '\\*', '\\*', '\\*']

Obviously,"*" * n is a string,["\*", "\*", "\*", "\*", "\*"] is a list. If you want to create a list, please set a list first.


问:
Pygame player movement stops when too many keys are pressed at the same time
When I try to move my character and press any other key at the same time, the movement suddenly stops. For example, the space key in my code is used to shoot a tiny orb out of the spaceship. Every time I press space and I am moving left and right quickly, the orb will shoot out but the player movement will be frozen for a second or two.

I have tried to switch to different ways of handling the way keys are input, but all of them seem to lead to this same problem. pygame.key.get_pressed() also has this problem when in my code.

I am not quite sure if this is a problem with my laptop keyboard or something in the code, so the code for the entire file is below.

```<code>import pygame, sys, decimal

# Screen Size
SCREEN_X = 400
SCREEN_Y = 400

# Loading Images
backgroundImg = pygame.image.load('StarBackground.png')
menuBar = pygame.image.load('Menu_Bar.png')
shipImg = pygame.image.load('PowerShip.png')
orb = pygame.image.load('Orb00.png')

class Ship(pygame.sprite.Sprite):
    # Movement rate of change
    change_x = 0

    # Methods
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)

        self.image = shipImg.convert_alpha()

        self.rect = self.image.get_rect()

        self.rect.x = SCREEN_X / 2 - 8
        self.rect.y = SCREEN_Y - 40

    def move(self, speed):
        self.change_x = speed

    def stop(self):
        self.change_x = 0

    def update(self, screen):
        self.rect.x += self.change_x

        if self.rect.x < 0:
            self.rect.x = 0
        elif self.rect.right > SCREEN_X:
            self.rect.x -= 1

        screen.blit(self.image, self.rect)

class MenuBar(pygame.sprite.Sprite):

    def __init__(self):
        pygame.sprite.Sprite.__init__(self)

        self.image = menuBar.convert_alpha()

        self.rect = self.image.get_rect()

        self.rect.x = 10
        self.rect.y = 0

    def update(self, screen):

        screen.blit(self.image,self.rect)

class Bullet1(pygame.sprite.Sprite):

    def __init__(self,x,y):
        pygame.sprite.Sprite.__init__(self)

        self.image = orb.convert_alpha()
        self.rect = self.image.get_rect()

        self.rect.x = x
        self.rect.y = y
        self.alive = True

    def update(self):
        if self.alive == True:
            self.rect.y -= 1

        if self.alive == False:
            self.rect.y = -10000

class HealthBar(pygame.sprite.Sprite):
    pass

class EnergyBar(pygame.sprite.Sprite):
    pass

class PointsBar(pygame.sprite.Sprite):
    pass

class Background(pygame.sprite.Sprite):

    def __init__(self):
        pygame.sprite.Sprite.__init__(self)

        self.image = backgroundImg.convert_alpha()

        self.rect = self.image.get_rect()

        self.rect.x = 0
        self.rect.y = 0

    def update(self, screen):
        if self.rect.top > 0:
            self.rect.y = SCREEN_Y * -1

        self.rect.y += 1

        screen.blit(self.image, self.rect)

def main():
    pygame.init()

    size = [SCREEN_X, SCREEN_Y]
    screen = pygame.display.set_mode(size, pygame.DOUBLEBUF)    # Set the height and width of the screen

    pygame.display.set_caption("Space Adventure")               # Setting the game name in the title bar

    background = Background()       # Creating the game objects
    menubar = MenuBar()
    ship = Ship()
    finished = False                # Close button exit code

    bullet1Enabled = True
    bullet1Count = 1
    spacePressed = False

    clock = pygame.time.Clock()     # Manages the frames per second

    lastkey = None                  # Variable that stores the last key pressed

    bulletlist = []

    # Game loop
    while not finished:
        for event in pygame.event.get():
            print(lastkey)
            if event.type == pygame.QUIT:
                finished = True

            pygame.event.set_blocked(pygame.MOUSEMOTION)

            if event.type == pygame.KEYDOWN:

                if lastkey != pygame.K_SPACE:
                    lastkey = event.key

                if event.key == pygame.K_SPACE:
                    spacePressed = True
                    if bullet1Enabled == True:
                        bullet1 = Bullet1(ship.rect.x, ship.rect.y)
                        bulletlist.append(bullet1)
                        bullet1Count = 1
                else:
                    spacePressed = False

            if event.type == pygame.KEYUP:

                if event.key == pygame.K_RIGHT and lastkey != pygame.K_LEFT:
                    lastkey = None
                    ship.move(0)
                if event.key == pygame.K_LEFT and lastkey != pygame.K_RIGHT:
                    lastkey = None
                    ship.move(0)

                if event.key == pygame.K_RIGHT or lastkey == pygame.K_LEFT:
                    spacePressed = False

                if event.key == pygame.K_LEFT or lastkey == pygame.K_RIGHT:
                    spacePressed = False

            #Bullet Delay

            if spacePressed == True:
                 bullet1Count = True
            if spacePressed == False:
                bullet1Count =  False

            if lastkey == pygame.K_RIGHT:
                ship.move(1)
            if lastkey == pygame.K_LEFT:
                ship.move(-1)

        clock.tick(240)             # Frames per second

        background.update(screen)   # Background update
       # Menu Bar update
        ship.update(screen)         # Ship update

        for b in bulletlist:
            if b.rect.bottom <= 0:
                b.alive = False

            b.update()

            screen.blit(b.image, b.rect)

        menubar.update(screen)

        pygame.display.flip()       # Updates the display for everything

    pygame.quit() # Clean shutdown on IDLE

if __name__ == "__main__":
    main()
</code>```

答:
The problem occurs because you don't reset lastkey to None after you release the space bar, so you have to press left or right twice.

```<code>if event.type == pygame.KEYUP:
    if event.key == pygame.K_SPACE:
        lastkey = None
</code>```

I don't see why you need the lastkey variable at all. I'd remove these lines from the main loop,

```<code>if lastkey == pygame.K_RIGHT:
    ship.move(1)
if lastkey == pygame.K_LEFT:
    ship.move(-1)
</code>```

insert them in the event loop and change lastkey to event.key:

```<code>if event.type == pygame.KEYDOWN:
    if event.key == pygame.K_RIGHT:
        ship.move(1)
    if event.key == pygame.K_LEFT:
        ship.move(-1)
</code>```

Now you should be able to remove the lastkey completely.

Body:
When I try to move my character and press any other key at the same time, the movement suddenly stops. For example, the space key in my code is used to shoot a tiny orb out of the spaceship. Every time I press space and I am moving left and right quickly, the orb will shoot out but the player movement will be frozen for a second or two.

I have tried to switch to different ways of handling the way keys are input, but all of them seem to lead to this same problem. pygame.key.get_pressed() also has this problem when in my code.

I am not quite sure if this is a problem with my laptop keyboard or something in the code, so the code for the entire file is below.

import pygame, sys, decimal

# Screen Size
SCREEN_X = 400
SCREEN_Y = 400

# Loading Images
backgroundImg = pygame.image.load('StarBackground.png')
menuBar = pygame.image.load('Menu_Bar.png')
shipImg = pygame.image.load('PowerShip.png')
orb = pygame.image.load('Orb00.png')

class Ship(pygame.sprite.Sprite):
    # Movement rate of change
    change_x = 0

    # Methods
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)

        self.image = shipImg.convert_alpha()

        self.rect = self.image.get_rect()

        self.rect.x = SCREEN_X / 2 - 8
        self.rect.y = SCREEN_Y - 40

    def move(self, speed):
        self.change_x = speed

    def stop(self):
        self.change_x = 0

    def update(self, screen):
        self.rect.x += self.change_x

        if self.rect.x < 0:
            self.rect.x = 0
        elif self.rect.right > SCREEN_X:
            self.rect.x -= 1

        screen.blit(self.image, self.rect)

class MenuBar(pygame.sprite.Sprite):

    def __init__(self):
        pygame.sprite.Sprite.__init__(self)

        self.image = menuBar.convert_alpha()

        self.rect = self.image.get_rect()

        self.rect.x = 10
        self.rect.y = 0

    def update(self, screen):

        screen.blit(self.image,self.rect)

class Bullet1(pygame.sprite.Sprite):

    def __init__(self,x,y):
        pygame.sprite.Sprite.__init__(self)

        self.image = orb.convert_alpha()
        self.rect = self.image.get_rect()

        self.rect.x = x
        self.rect.y = y
        self.alive = True

    def update(self):
        if self.alive == True:
            self.rect.y -= 1

        if self.alive == False:
            self.rect.y = -10000

class HealthBar(pygame.sprite.Sprite):
    pass

class EnergyBar(pygame.sprite.Sprite):
    pass

class PointsBar(pygame.sprite.Sprite):
    pass

class Background(pygame.sprite.Sprite):

    def __init__(self):
        pygame.sprite.Sprite.__init__(self)

        self.image = backgroundImg.convert_alpha()

        self.rect = self.image.get_rect()

        self.rect.x = 0
        self.rect.y = 0

    def update(self, screen):
        if self.rect.top > 0:
            self.rect.y = SCREEN_Y * -1

        self.rect.y += 1

        screen.blit(self.image, self.rect)

def main():
    pygame.init()

    size = [SCREEN_X, SCREEN_Y]
    screen = pygame.display.set_mode(size, pygame.DOUBLEBUF)    # Set the height and width of the screen

    pygame.display.set_caption("Space Adventure")               # Setting the game name in the title bar

    background = Background()       # Creating the game objects
    menubar = MenuBar()
    ship = Ship()
    finished = False                # Close button exit code

    bullet1Enabled = True
    bullet1Count = 1
    spacePressed = False

    clock = pygame.time.Clock()     # Manages the frames per second

    lastkey = None                  # Variable that stores the last key pressed

    bulletlist = []

    # Game loop
    while not finished:
        for event in pygame.event.get():
            print(lastkey)
            if event.type == pygame.QUIT:
                finished = True

            pygame.event.set_blocked(pygame.MOUSEMOTION)

            if event.type == pygame.KEYDOWN:

                if lastkey != pygame.K_SPACE:
                    lastkey = event.key

                if event.key == pygame.K_SPACE:
                    spacePressed = True
                    if bullet1Enabled == True:
                        bullet1 = Bullet1(ship.rect.x, ship.rect.y)
                        bulletlist.append(bullet1)
                        bullet1Count = 1
                else:
                    spacePressed = False

            if event.type == pygame.KEYUP:

                if event.key == pygame.K_RIGHT and lastkey != pygame.K_LEFT:
                    lastkey = None
                    ship.move(0)
                if event.key == pygame.K_LEFT and lastkey != pygame.K_RIGHT:
                    lastkey = None
                    ship.move(0)

                if event.key == pygame.K_RIGHT or lastkey == pygame.K_LEFT:
                    spacePressed = False

                if event.key == pygame.K_LEFT or lastkey == pygame.K_RIGHT:
                    spacePressed = False

            #Bullet Delay

            if spacePressed == True:
                 bullet1Count = True
            if spacePressed == False:
                bullet1Count =  False

            if lastkey == pygame.K_RIGHT:
                ship.move(1)
            if lastkey == pygame.K_LEFT:
                ship.move(-1)

        clock.tick(240)             # Frames per second

        background.update(screen)   # Background update
       # Menu Bar update
        ship.update(screen)         # Ship update

        for b in bulletlist:
            if b.rect.bottom <= 0:
                b.alive = False

            b.update()

            screen.blit(b.image, b.rect)

        menubar.update(screen)

        pygame.display.flip()       # Updates the display for everything

    pygame.quit() # Clean shutdown on IDLE

if __name__ == "__main__":
    main()

Body:
The problem occurs because you don't reset lastkey to None after you release the space bar, so you have to press left or right twice.

if event.type == pygame.KEYUP:
    if event.key == pygame.K_SPACE:
        lastkey = None

I don't see why you need the lastkey variable at all. I'd remove these lines from the main loop,

if lastkey == pygame.K_RIGHT:
    ship.move(1)
if lastkey == pygame.K_LEFT:
    ship.move(-1)

insert them in the event loop and change lastkey to event.key:

if event.type == pygame.KEYDOWN:
    if event.key == pygame.K_RIGHT:
        ship.move(1)
    if event.key == pygame.K_LEFT:
        ship.move(-1)

Now you should be able to remove the lastkey completely.


问:
How do I calculate the percent chance from using Int(Rnd()) in VB.NET?
```<code>If Int(Rnd() * 5) >= 4
</code>```

The line of code above is supposed to give a 40% chance of something happening. However, I do not understand how this 40% is calculated. Would Int(Rnd()*2.5) = 1 also give 40%?

I would very much appreciate if someone could explain how calculate percentages using this function.

答:
Rnd returns a number from zero to just less than 1 (in a Single data type).

Int(Rnd() * 5) would return a value 0 to 4 (indeed 5 distinct values).

So, to give a 40% chance, compare the result < 2 (0 or 1), or the result > 2 (3 or 4).

I think you might have been confused by the result being zero-based.

Hope that helps.

Body:
If Int(Rnd() * 5) >= 4

The line of code above is supposed to give a 40% chance of something happening. However, I do not understand how this 40% is calculated. Would Int(Rnd()*2.5) = 1 also give 40%?

I would very much appreciate if someone could explain how calculate percentages using this function.


问:
php - why the id automatically turn into 0?
it just set my id into 0 after i inserted some data into the table

then, I get this kind of error:

Duplicate entry '0' for key 'PRIMARY'.

can someone help me identify the problem?

```<code>$query = mysql_query("INSERT INTO customer VALUES('', '$name', '$phone', '$address', '$email_add')") or die(mysql_error());

            $i=1;
            foreach($_SESSION as $namee => $value)
            {
            if($value > 0)
            {
            if(substr($namee, 0, 5) == 'cart_')
                {
        $id = substr($namee, 5, (strlen($namee)-5));
        $get = mysql_query("SELECT * FROM product WHERE code='$id'");
        while($get_row = mysql_fetch_assoc($get)){
        $sub = $get_row['price'] * $value;

        echo '<p>'.$i.' '.$get_row['code'].' '.$get_row['name_nl'].' '.$value.' SubTotal : RM '.$sub.'</p>                              ';

        $getCustomer = mysql_query("SELECT customer.id_customer, customer.name, customer.address, product.code, product.name_nl FROM customer, product WHERE name='$name' AND address='$address'" ) or die(mysql_error());

        $data = mysql_fetch_array($getCustomer);
        $pemb = $data['id_customer'];
        $na = $data['name'];
        $al = $data['address'];
        $ib = $get_row['code'];
        $nb = $get_row['name_nl'];

                        $i++;
                    }
            }

mysql_query("INSERT INTO book VALUES('', '$pemb', '$na', '$al', '$ib', '$nb', '$value', '$sub', now()) ") or die(mysql_error());
        }
    }
</code>```

答:
Primary key fields must have different values.

To resolve this, you must set this field to AUTO_INCREMENT, so each time a new record is entered, the primary key field is incremented automatically.

Body:
it just set my id into 0 after i inserted some data into the table

then, I get this kind of error:

Duplicate entry '0' for key 'PRIMARY'.

can someone help me identify the problem?

$query = mysql_query("INSERT INTO customer VALUES('', '$name', '$phone', '$address', '$email_add')") or die(mysql_error());

            $i=1;
            foreach($_SESSION as $namee => $value)
            {
            if($value > 0)
            {
            if(substr($namee, 0, 5) == 'cart_')
                {
        $id = substr($namee, 5, (strlen($namee)-5));
        $get = mysql_query("SELECT * FROM product WHERE code='$id'");
        while($get_row = mysql_fetch_assoc($get)){
        $sub = $get_row['price'] * $value;

        echo '
'.$i.' '.$get_row['code'].' '.$get_row['name_nl'].' '.$value.' SubTotal : RM '.$sub.'
                              ';

        $getCustomer = mysql_query("SELECT customer.id_customer, customer.name, customer.address, product.code, product.name_nl FROM customer, product WHERE name='$name' AND address='$address'" ) or die(mysql_error());

        $data = mysql_fetch_array($getCustomer);
        $pemb = $data['id_customer'];
        $na = $data['name'];
        $al = $data['address'];
        $ib = $get_row['code'];
        $nb = $get_row['name_nl'];

                        $i++;
                    }
            }

mysql_query("INSERT INTO book VALUES('', '$pemb', '$na', '$al', '$ib', '$nb', '$value', '$sub', now()) ") or die(mysql_error());
        }
    }


问:
In Javascript, how do I generate a random element out of a list?
Suppose I have a list of strings. How do I generate a random one?</p>

答:
You mean, get a random array member?

```<code>var strings = ['a', 'b', 'c'];

var randomIndex = Math.floor(Math.random() * strings.length);

var randomString = strings[randomIndex];
</code>```

See it on jsFiddle.

If you mean a random string, it is a little different.

```<code>var randomStrLength = 16,
    pool = 'abcdefghijklmnopqrstuvwxyz0123456789',
    randomStr = '';

for (var i = 0; i < randomStrLength; i++) {
     var randomChar = pool.charAt(Math.floor(Math.random() * pool.length));
     randomStr += randomChar;
}
</code>```

See it on jsFiddle.

Of course, you can skip the pool variable and do String.fromCharCode() with a random number between 97 ('a'.charCodeAt(0)) and 122 ('z'.charCodeAt(0)) for lowercase letters, etc. But depending on the range you want (lowercase and uppercase, plus special characters), using a pool is less complex.

Body:
You mean, get a random array member?

var strings = ['a', 'b', 'c'];

var randomIndex = Math.floor(Math.random() * strings.length);

var randomString = strings[randomIndex];

See it on jsFiddle.

If you mean a random string, it is a little different.

var randomStrLength = 16,
    pool = 'abcdefghijklmnopqrstuvwxyz0123456789',
    randomStr = '';

for (var i = 0; i < randomStrLength; i++) {
     var randomChar = pool.charAt(Math.floor(Math.random() * pool.length));
     randomStr += randomChar;
}

See it on jsFiddle.

Of course, you can skip the pool variable and do String.fromCharCode() with a random number between 97 ('a'.charCodeAt(0)) and 122 ('z'.charCodeAt(0)) for lowercase letters, etc. But depending on the range you want (lowercase and uppercase, plus special characters), using a pool is less complex.


问:
Building error with setuptools: RuntimeError
I've been using cxFreeze to build my Python code for some time and had no issue, until today.  I'm not sure the problem comes from cxFreeze, though.  Although there are some RuntimeError exceptions on the web, they don't exactly match what I obtain.

```<code>$ python2.7 setup.py build
running build
running build_exe
Traceback (most recent call last):
  File "setup.py", line 79, in <module>
    executables = [client, updater, dbg_updater]
  File "C:\python27\lib\site-packages\cx_Freeze\dist.py", line 362, in setup
    distutils.core.setup(**attrs)
  File "C:\python27\lib\distutils\core.py", line 151, in setup
    dist.run_commands()
  File "C:\python27\lib\distutils\dist.py", line 953, in run_commands
    self.run_command(cmd)
  File "C:\python27\lib\distutils\dist.py", line 972, in run_command
    cmd_obj.run()
  File "C:\python27\lib\distutils\command\build.py", line 127, in run
    self.run_command(cmd_name)
  File "C:\python27\lib\distutils\cmd.py", line 326, in run_command
    self.distribution.run_command(command)
  File "C:\python27\lib\distutils\dist.py", line 972, in run_command
    cmd_obj.run()
  File "C:\python27\lib\site-packages\cx_Freeze\dist.py", line 232, in run
    freezer.Freeze()
  File "C:\python27\lib\site-packages\cx_Freeze\freezer.py", line 619, in Freeze
    self.finder = self._GetModuleFinder()
  File "C:\python27\lib\site-packages\cx_Freeze\freezer.py", line 378, in _GetModuleFinder
    finder.IncludePackage(name)
  File "C:\python27\lib\site-packages\cx_Freeze\finder.py", line 686, in IncludePackage
    module = self._ImportModule(name, deferredImports)
  File "C:\python27\lib\site-packages\cx_Freeze\finder.py", line 346, in _ImportModule
    deferredImports, namespace = namespace)
  File "C:\python27\lib\site-packages\cx_Freeze\finder.py", line 419, in _InternalImportModule
    namespace = namespace)
  File "C:\python27\lib\site-packages\cx_Freeze\finder.py", line 436, in _InternalImportModule
    parentModule, namespace)
  File "C:\python27\lib\site-packages\cx_Freeze\finder.py", line 448, in _LoadModule
    namespace)
  File "C:\python27\lib\site-packages\cx_Freeze\finder.py", line 513, in _LoadPackage
    self._LoadModule(name, fp, path, info, deferredImports, parent)
  File "C:\python27\lib\site-packages\cx_Freeze\finder.py", line 502, in _LoadModule
    self._ScanCode(module.code, module, deferredImports)
  File "C:\python27\lib\site-packages\cx_Freeze\finder.py", line 601, in _ScanCode
    module, relativeImportIndex)
......................................
  File "C:\python27\lib\site-packages\cx_Freeze\finder.py", line 356, in _ImportModule
    deferredImports, namespace = namespace)
  File "C:\python27\lib\site-packages\cx_Freeze\finder.py", line 436, in _InternalImportModule
    parentModule, namespace)
  File "C:\python27\lib\site-packages\cx_Freeze\finder.py", line 502, in _LoadModule
    self._ScanCode(module.code, module, deferredImports)
  File "C:\python27\lib\site-packages\cx_Freeze\finder.py", line 601, in _ScanCode
    module, relativeImportIndex)
  File "C:\python27\lib\site-packages\cx_Freeze\finder.py", line 356, in _ImportModule
    deferredImports, namespace = namespace)
  File "C:\python27\lib\site-packages\cx_Freeze\finder.py", line 436, in _InternalImportModule
    parentModule, namespace)
  File "C:\python27\lib\site-packages\cx_Freeze\finder.py", line 449, in _LoadModule
    module = self._AddModule(name)
  File "C:\python27\lib\site-packages\cx_Freeze\finder.py", line 213, in _AddModule
    module = self._modules[name] = Module(name)
RuntimeError: maximum recursion depth exceeded while calling a Python object
</code>```

No idea what is creating the bug.  I didn't add in any new module and just fixed some errors in my program.  I have the most recent version of pip and setuptools.  Does anyone know what this error mean?

If you want to see the code, it's here: https://github.com/vlegoff/cocomud/blob/master/src/setup.py

Thanks in advance!

EDIT:
It turned out all the fuss was because of the parse module (pypi.python.org/pypi/parse), although it's not included in the project I was trying to freeze. I removed it with pip uninstall and it worked when I tried to freeze my project. No idea why, I did it because I remember having installed two new packages to try them out.

答: It turned out all the fuss was because of the parse module (pypi.python.org/pypi/parse), although it's not included in the project I was trying to freeze. I removed it with pip uninstall and it worked when I tried to freeze my project. No idea why, I did it because I remember having installed two new packages to try them out.</p>

Body:
I've been using cxFreeze to build my Python code for some time and had no issue, until today.  I'm not sure the problem comes from cxFreeze, though.  Although there are some RuntimeError exceptions on the web, they don't exactly match what I obtain.

$ python2.7 setup.py build
running build
running build_exe
Traceback (most recent call last):
  File "setup.py", line 79, in <module>
    executables = [client, updater, dbg_updater]
  File "C:\python27\lib\site-packages\cx_Freeze\dist.py", line 362, in setup
    distutils.core.setup(**attrs)
  File "C:\python27\lib\distutils\core.py", line 151, in setup
    dist.run_commands()
  File "C:\python27\lib\distutils\dist.py", line 953, in run_commands
    self.run_command(cmd)
  File "C:\python27\lib\distutils\dist.py", line 972, in run_command
    cmd_obj.run()
  File "C:\python27\lib\distutils\command\build.py", line 127, in run
    self.run_command(cmd_name)
  File "C:\python27\lib\distutils\cmd.py", line 326, in run_command
    self.distribution.run_command(command)
  File "C:\python27\lib\distutils\dist.py", line 972, in run_command
    cmd_obj.run()
  File "C:\python27\lib\site-packages\cx_Freeze\dist.py", line 232, in run
    freezer.Freeze()
  File "C:\python27\lib\site-packages\cx_Freeze\freezer.py", line 619, in Freeze
    self.finder = self._GetModuleFinder()
  File "C:\python27\lib\site-packages\cx_Freeze\freezer.py", line 378, in _GetModuleFinder
    finder.IncludePackage(name)
  File "C:\python27\lib\site-packages\cx_Freeze\finder.py", line 686, in IncludePackage
    module = self._ImportModule(name, deferredImports)
  File "C:\python27\lib\site-packages\cx_Freeze\finder.py", line 346, in _ImportModule
    deferredImports, namespace = namespace)
  File "C:\python27\lib\site-packages\cx_Freeze\finder.py", line 419, in _InternalImportModule
    namespace = namespace)
  File "C:\python27\lib\site-packages\cx_Freeze\finder.py", line 436, in _InternalImportModule
    parentModule, namespace)
  File "C:\python27\lib\site-packages\cx_Freeze\finder.py", line 448, in _LoadModule
    namespace)
  File "C:\python27\lib\site-packages\cx_Freeze\finder.py", line 513, in _LoadPackage
    self._LoadModule(name, fp, path, info, deferredImports, parent)
  File "C:\python27\lib\site-packages\cx_Freeze\finder.py", line 502, in _LoadModule
    self._ScanCode(module.code, module, deferredImports)
  File "C:\python27\lib\site-packages\cx_Freeze\finder.py", line 601, in _ScanCode
    module, relativeImportIndex)
......................................
  File "C:\python27\lib\site-packages\cx_Freeze\finder.py", line 356, in _ImportModule
    deferredImports, namespace = namespace)
  File "C:\python27\lib\site-packages\cx_Freeze\finder.py", line 436, in _InternalImportModule
    parentModule, namespace)
  File "C:\python27\lib\site-packages\cx_Freeze\finder.py", line 502, in _LoadModule
    self._ScanCode(module.code, module, deferredImports)
  File "C:\python27\lib\site-packages\cx_Freeze\finder.py", line 601, in _ScanCode
    module, relativeImportIndex)
  File "C:\python27\lib\site-packages\cx_Freeze\finder.py", line 356, in _ImportModule
    deferredImports, namespace = namespace)
  File "C:\python27\lib\site-packages\cx_Freeze\finder.py", line 436, in _InternalImportModule
    parentModule, namespace)
  File "C:\python27\lib\site-packages\cx_Freeze\finder.py", line 449, in _LoadModule
    module = self._AddModule(name)
  File "C:\python27\lib\site-packages\cx_Freeze\finder.py", line 213, in _AddModule
    module = self._modules[name] = Module(name)
RuntimeError: maximum recursion depth exceeded while calling a Python object

No idea what is creating the bug.  I didn't add in any new module and just fixed some errors in my program.  I have the most recent version of pip and setuptools.  Does anyone know what this error mean?

If you want to see the code, it's here: https://github.com/vlegoff/cocomud/blob/master/src/setup.py

Thanks in advance!

EDIT:
It turned out all the fuss was because of the parse module (pypi.python.org/pypi/parse), although it's not included in the project I was trying to freeze. I removed it with pip uninstall and it worked when I tried to freeze my project. No idea why, I did it because I remember having installed two new packages to try them out.


问:
Creating a streaming Conduit Source with postgresql-simple
postgresql-simple provides functions for streaming queries, e.g.

```<code>fold
  :: (FromRow row, ToRow params)
  => Connection -> Query -> params -> a -> (a -> row -> IO a) -> IO a
</code>```

I want to create a conduit source which takes full advantage of streaming.

```<code>mySource :: (FromRow row, Monad m) => Source m row
</code>```

Unfortunately, because IO appears in a contravariant position (I think?) in fold, I'm really struggling with the types. The following type-checks, but folds the entire stream before yielding values.

```<code>getConduit :: Connection -> IO (C.ConduitM () Event IO ())
getConduit conn = fold_ conn queryEventRecord CL.sourceNull foo
  where
    foo :: C.ConduitM () Event IO () -> Event -> IO (C.ConduitM () Event IO ())
    foo cond evt = pure (cond >> C.yield evt)
</code>```

Any pointers on how to implement this would be greatly appreciated! Thanks!

答:
Here's a modification of Alec's above that compiles and runs. mkPgSource is the general function that Alec referred to at the end of his post.

```<code>import Database.PostgreSQL.Simple
import Database.PostgreSQL.Simple.FromRow
import Database.PostgreSQL.Simple.ToRow
import Control.Monad.IO.Class (MonadIO)
import Data.Conduit.TMChan (sourceTMChan)
import Control.Concurrent.STM.TMChan (newTMChanIO, writeTMChan,
closeTMChan, TMChan)
import GHC.Conc (atomically, forkIO)
import Conduit

--closes the channel after action is done to terminate the source
mkPgSource :: (MonadIO m, FromRow r) => ((r -> IO ()) -> IO ()) -> IO (Source m r)
mkPgSource action = do
  chan <- newTMChanIO
  _ <- forkIO $ do action $ atomically . (writeTMChan chan)
               atomically $ closeTMChan chan
  pure $ sourceTMChan chan

sourceQuery :: (ToRow params, FromRow r, MonadIO m) =>
     Connection -> Query -> params -> IO (Source m r)
sourceQuery conn q params = mkPgSource $ forEach conn q params

sourceQuery_ :: (FromRow r, MonadIO m) => Connection -> Query -> IO
(Source m r)
sourceQuery_ conn q = mkPgSource $ forEach_ conn q
</code>```

Body:
postgresql-simple provides functions for streaming queries, e.g.

fold
  :: (FromRow row, ToRow params)
  => Connection -> Query -> params -> a -> (a -> row -> IO a) -> IO a

I want to create a conduit source which takes full advantage of streaming.

mySource :: (FromRow row, Monad m) => Source m row

Unfortunately, because IO appears in a contravariant position (I think?) in fold, I'm really struggling with the types. The following type-checks, but folds the entire stream before yielding values.

getConduit :: Connection -> IO (C.ConduitM () Event IO ())
getConduit conn = fold_ conn queryEventRecord CL.sourceNull foo
  where
    foo :: C.ConduitM () Event IO () -> Event -> IO (C.ConduitM () Event IO ())
    foo cond evt = pure (cond >> C.yield evt)

Any pointers on how to implement this would be greatly appreciated! Thanks!

Body:
Here's a modification of Alec's above that compiles and runs. mkPgSource is the general function that Alec referred to at the end of his post.

import Database.PostgreSQL.Simple
import Database.PostgreSQL.Simple.FromRow
import Database.PostgreSQL.Simple.ToRow
import Control.Monad.IO.Class (MonadIO)
import Data.Conduit.TMChan (sourceTMChan)
import Control.Concurrent.STM.TMChan (newTMChanIO, writeTMChan,
closeTMChan, TMChan)
import GHC.Conc (atomically, forkIO)
import Conduit

--closes the channel after action is done to terminate the source
mkPgSource :: (MonadIO m, FromRow r) => ((r -> IO ()) -> IO ()) -> IO (Source m r)
mkPgSource action = do
  chan <- newTMChanIO
  _ <- forkIO $ do action $ atomically . (writeTMChan chan)
               atomically $ closeTMChan chan
  pure $ sourceTMChan chan

sourceQuery :: (ToRow params, FromRow r, MonadIO m) =>
     Connection -> Query -> params -> IO (Source m r)
sourceQuery conn q params = mkPgSource $ forEach conn q params

sourceQuery_ :: (FromRow r, MonadIO m) => Connection -> Query -> IO
(Source m r)
sourceQuery_ conn q = mkPgSource $ forEach_ conn q


问:
C#: get text and printing it with webdriver
I have this page: http://services.ce3c.be/ciprg/?countrys=ANGUILLA

I' m trying to get the text(country and IPs) and print it with:

```<code>var content = driver.FindElement(By.XPath(@"/html/body/pre/text()")).Text;
Console.WriteLine(content);
</code>```

but it seems that doesn't work. How can I do this?

答:
Remove the "/text()"
from the XPATH. You cannot point to text nodes in Selenium.

This works:

```<code>var content = driver.FindElement(By.XPath(@"/html/body/pre")).Text;
Console.WriteLine(content);
</code>```

Body:
I have this page: http://services.ce3c.be/ciprg/?countrys=ANGUILLA

I' m trying to get the text(country and IPs) and print it with:

var content = driver.FindElement(By.XPath(@"/html/body/pre/text()")).Text;
Console.WriteLine(content);

but it seems that doesn't work. How can I do this?

Body:
Remove the "/text()"
from the XPATH. You cannot point to text nodes in Selenium.

This works:

var content = driver.FindElement(By.XPath(@"/html/body/pre")).Text;
Console.WriteLine(content);


问:
Handsontable remove settings [especially width and height]
I am working with handsontable [JavaScript Spreadsheet
library] and want to toggle settings with a bootstrap-styled-checkbox. The first thing was, to set a specific width and height to the table when the box is checked and to undo this fixed size (so it automatically resizes again) when uncheck the box.
Here is my current code:

```<code>$('#mycheckbox').click(function() {
  if($('#mycheckbox').prop("checked") == true){
    handsontable_table.updateSettings({
       width: 725,
       height:100
    })
  }else{
  handsontable_table.updateSettings({
        // missing :(

        //UPDATE:
         width: null,
         height: null
  })
 }
});
</code>```

At first, my handsontable-table is automatically sized to the correct size. When I check the checkbox, the table resizes to the given width and height. But I don't know how to remove this width- and height-settings. I tried to set them to 'false' or 0 or remove these settings with jQuery-.removeProp(), but none of them does what I want. And I can't find something right in the handsontable-docs (or other sites).

I very appreciate your help!

EDIT

I found a solution: You just have to set the width and height to null. See edit above.
But there is something strange going on when I minimize my table and maximize it again - at first, my div below the table slides up to the new bottom of my table, but when it gets big again, the div doesn't move anymore, its overlapping with the table...

However, I still don't know how to remove settings from a handsontable...

答:
As you mentioned in your edit, by updating the value to null it appears to be one way to reset a setting with in Handsontables options. It my experience you do not want to set the height and width to null, but instead update it to a new value.

If you were clearing out a setting like nestedHeaders for example; you would just set the value to null to stop using the nestedHeaders feature. However, that doesn't work for every option.

If you are trying to expand and collapse a handsontable then setting the height and width to null or zero is not going to be the best solution. You should update the parent div to display null using jQuery(handsontable's parent selector).hide() or .show().

Body:
I am working with handsontable [JavaScript Spreadsheet
library] and want to toggle settings with a bootstrap-styled-checkbox. The first thing was, to set a specific width and height to the table when the box is checked and to undo this fixed size (so it automatically resizes again) when uncheck the box.
Here is my current code:

$('#mycheckbox').click(function() {
  if($('#mycheckbox').prop("checked") == true){
    handsontable_table.updateSettings({
       width: 725,
       height:100
    })
  }else{
  handsontable_table.updateSettings({
        // missing :(

        //UPDATE:
         width: null,
         height: null
  })
 }
});

At first, my handsontable-table is automatically sized to the correct size. When I check the checkbox, the table resizes to the given width and height. But I don't know how to remove this width- and height-settings. I tried to set them to 'false' or 0 or remove these settings with jQuery-.removeProp(), but none of them does what I want. And I can't find something right in the handsontable-docs (or other sites).

I very appreciate your help!

EDIT

I found a solution: You just have to set the width and height to null. See edit above.
But there is something strange going on when I minimize my table and maximize it again - at first, my div below the table slides up to the new bottom of my table, but when it gets big again, the div doesn't move anymore, its overlapping with the table...

However, I still don't know how to remove settings from a handsontable...


问:
Zsh returning `<function>:<linenumber> = not found`
I used the have the following tmux shortcut function defined in a separate script and aliased, which worked fine but was messy. I decided to move it to my .zshrc where it naturally belongs, and encountered a problem I wasn't able to figure out.

```<code>function t () {re='^[0-9]+$'
if [ "$1" == "kill" ]
then
        tmux kill-session -t $2
elif [[ "$1" =~ "$re" ]]
then
        tmux attach-session -d -t $1
fi}
</code>```

I source my .zshrc, call the function, and get:

```<code>t:1: = not found
</code>```

I know the function is defined:

```<code>╭─bennett@Io [~] using
╰─○ which t
t () {
    re='^[0-9]+$'
    if [ "$1" == "kill" ]
    then
            tmux kill-session -t $2
    elif [[ "$1" =~ "$re" ]]
    then
            tmux attach-session -d -t $1
    fi
}
</code>```

I'm assuming this is complaining about the first line of the function. I've tried shifting the first line of the function down several lines, which doesn't change anything except which line the error message refers to. Any clue what's going on? I haven't found anything relating to this specific issue on SO.

答:
Wrapping the first conditional in a second set of square-brackets seemed to resolve the issue.

More information on single vs double brackets here:
Is [[ ]] preferable over [ ] in bash scripts?

Body:
I used the have the following tmux shortcut function defined in a separate script and aliased, which worked fine but was messy. I decided to move it to my .zshrc where it naturally belongs, and encountered a problem I wasn't able to figure out.

function t () {re='^[0-9]+$'
if [ "$1" == "kill" ]
then
        tmux kill-session -t $2
elif [[ "$1" =~ "$re" ]]
then
        tmux attach-session -d -t $1
fi}

I source my .zshrc, call the function, and get:

t:1: = not found

I know the function is defined:

╭─bennett@Io [~] using
╰─○ which t
t () {
    re='^[0-9]+$'
    if [ "$1" == "kill" ]
    then
            tmux kill-session -t $2
    elif [[ "$1" =~ "$re" ]]
    then
            tmux attach-session -d -t $1
    fi
}

I'm assuming this is complaining about the first line of the function. I've tried shifting the first line of the function down several lines, which doesn't change anything except which line the error message refers to. Any clue what's going on? I haven't found anything relating to this specific issue on SO.


问:
How do you document your development?
I am building my first complex app (in RoR) and as I think about passing it on to new programmers, I have been thinking about the best ways to document what I'm building.

How do you like to document your work?

Are there softwares or websites that allow one to easily accumulate sections of documentation, perhaps with tagging for easy reference later on?

答:
I add lots of comments; everywhere. I took the time to write out what logic is happening in human-readable form for every single line of my 500 line music-generation algorithm, and it saved me so much time, and my other friends who were helping.

Here's what I did (as a start):

```<code>def __init__(self):
  self.chromatic = ['C', ['C#', 'Db'], 'D', ['D#', 'Eb'], 'E', 'F', ['F#', 'Gb'], 'G', ['G#', 'Ab'], 'A',  ['A#', 'Bb'], 'B']

  self.steps = {}
  self.steps['major']                 = [2, 2, 1, 2, 2, 2, 1]
  self.steps['natural minor']         = [2, 1, 2, 2, 1, 2, 2]
  self.steps['harmonic minor']        = [2, 1, 2, 2, 1, 3]
  self.steps['melodic minor up']      = [2, 1, 2, 2, 2, 2, 1]
  self.steps['melodic minor down']    = [2, 2, 1, 2, 2, 1, 2]
  self.steps['dorian']                = [2, 1, 2, 2, 2, 1, 2]
  self.steps['mixolydian']            = [2, 2, 1, 2, 2, 1, 2]
  self.steps['ahava raba']            = [1, 3, 1, 2, 1, 2, 2]
  self.steps['minor penatonic blues'] = [3, 2, 2, 3, 2]

  self.list = []

def scale(self, note, name):                          # Function to generate a scale from the required base note.
  if re.sub('[^0-9]', '', note) == '':                # Checks for nonexistent octave number
    octave = 5                                        # Defaults to 5
  else:                                               # If octave number exists
    octave = int(re.sub('[^0-9]', '', note))          # Extracts octave number from note

  note = re.sub('[0-9]', '', note)                    # Strips all numbers from note
  scale = []                                          # Initializes the scale to be empty

  for i in rlen(self.chromatic):                      # Loops through all elements of the Chromatic scale
    if self.chromatic[i] is not list:                 # If the note is just a natural
      if note == self.chromatic[i]: scale = [i + 1]   # Check if the note is in the chromatic. If it is, add it.
    else:
      if note in self.chromatic[i]: scale = [i + 1]   # If the note is in a key of the chromatic, add it too. It is a sharp/flat.

  for i in rlen(self.steps[name]):                    # Loops through desired scale
    scale.append(self.steps[name][i] + scale[i])      # Adds string notes following the algorithm of the scale
    scale[i + 1] = scale[i + 1] % len(self.chromatic) # Modulo length of Chromatic scale
</code>```

It's a start (and an example with cruddy code), but it helps me debug code really quickly.

Title: How do you document your development?

Body:
I add lots of comments; everywhere. I took the time to write out what logic is happening in human-readable form for every single line of my 500 line music-generation algorithm, and it saved me so much time, and my other friends who were helping.

Here's what I did (as a start):

def __init__(self):
  self.chromatic = ['C', ['C#', 'Db'], 'D', ['D#', 'Eb'], 'E', 'F', ['F#', 'Gb'], 'G', ['G#', 'Ab'], 'A',  ['A#', 'Bb'], 'B']

  self.steps = {}
  self.steps['major']                 = [2, 2, 1, 2, 2, 2, 1]
  self.steps['natural minor']         = [2, 1, 2, 2, 1, 2, 2]
  self.steps['harmonic minor']        = [2, 1, 2, 2, 1, 3]
  self.steps['melodic minor up']      = [2, 1, 2, 2, 2, 2, 1]
  self.steps['melodic minor down']    = [2, 2, 1, 2, 2, 1, 2]
  self.steps['dorian']                = [2, 1, 2, 2, 2, 1, 2]
  self.steps['mixolydian']            = [2, 2, 1, 2, 2, 1, 2]
  self.steps['ahava raba']            = [1, 3, 1, 2, 1, 2, 2]
  self.steps['minor penatonic blues'] = [3, 2, 2, 3, 2]

  self.list = []

def scale(self, note, name):                          # Function to generate a scale from the required base note.
  if re.sub('[^0-9]', '', note) == '':                # Checks for nonexistent octave number
    octave = 5                                        # Defaults to 5
  else:                                               # If octave number exists
    octave = int(re.sub('[^0-9]', '', note))          # Extracts octave number from note

  note = re.sub('[0-9]', '', note)                    # Strips all numbers from note
  scale = []                                          # Initializes the scale to be empty

  for i in rlen(self.chromatic):                      # Loops through all elements of the Chromatic scale
    if self.chromatic[i] is not list:                 # If the note is just a natural
      if note == self.chromatic[i]: scale = [i + 1]   # Check if the note is in the chromatic. If it is, add it.
    else:
      if note in self.chromatic[i]: scale = [i + 1]   # If the note is in a key of the chromatic, add it too. It is a sharp/flat.

  for i in rlen(self.steps[name]):                    # Loops through desired scale
    scale.append(self.steps[name][i] + scale[i])      # Adds string notes following the algorithm of the scale
    scale[i + 1] = scale[i + 1] % len(self.chromatic) # Modulo length of Chromatic scale

It's a start (and an example with cruddy code), but it helps me debug code really quickly.


问:
Keep the lifespan of variable after multiple function calls?
Assuming:

```<code>def myfunc(x):
    my_list  = []
    list.append(x)
</code>```

is there a keyword to stop a variable(my_list) from being reassigned?
Let's suppose that NA is the keyword:

```<code>def myfunc(x):
    NA listv  = []
    list.append(x)
</code>```

in such way that the line will be read and not reassigned but the variable still active appending new values for every function call. I know about the GLOBAL variable, but I just want to know is the keyword exists!

答:
You can declare the variable globally as in C/C++ and use global keyword in python to refer them as variable in global data section.
Some of references about them:

https://docs.python.org/3/faq/programming.html#what-are-the-rules-for-local-and-global-variables-in-python

http://www.geeksforgeeks.org/global-local-variables-python/

Use of "global" keyword in Python

Body:
Assuming:

def myfunc(x):
    my_list  = []
    list.append(x)

is there a keyword to stop a variable(my_list) from being reassigned?
Let's suppose that NA is the keyword:

def myfunc(x):
    NA listv  = []
    list.append(x)

in such way that the line will be read and not reassigned but the variable still active appending new values for every function call. I know about the GLOBAL variable, but I just want to know is the keyword exists!


问:
Resizing a control in WPF
I have a set of user controls in my wpf form and want to give ability to user to resize them. Whenever a user clicks on a control total 8 boundary rectangles should appear and then by dragging any of them, the user must be able to resize the control. Please help me on this.</p>

答:
I made a library that applies resize grips to any control.

Homepage has a quick gif video showing it in-action.

Very simple, just call one line of code.

```<code>//Set max resize to 200px max height, 300px max width.
new CResizeAdorner(button1, 200, 300);
</code>```

OwnerDisplayName: Sanjeet Kumar

Title: Resizing a control in WPF

Body:
I made a library that applies resize grips to any control.

Homepage has a quick gif video showing it in-action.

Very simple, just call one line of code.

//Set max resize to 200px max height, 300px max width.
new CResizeAdorner(button1, 200, 300);


问:
Get Current Thread Handle
I have problem in Delphi application with determining current application (current Thread) handle. I know that I can get Current Thread ID with Windows API function GetCurrentThreadID, but I need current Thread handle to use as param for another Windows API function that is SuspendThread.

Actually what I am trying to do is to make one of my old dll's made for hooking API functions located in kernel32.dll like OpenProcess or TerminateProcessto also do hook for SuspendProcess. Hook is located in dll file and using SetWindowsHookEx to be injected in running processes then finding base address of target functions.
I had no problem with hooking functions like TerminateProcess because it needs process ID as param that is easy to obtain in main application using GetCurrentProcessID. To make similar hook for SuspendThread function i need to pass thread handle as param.

Only place where I found thread handle is PROCESS_INFORMATION structure that contains

```<code>typedef struct _PROCESS_INFORMATION { // pi
    HANDLE hProcess;
    HANDLE hThread;
    DWORD dwProcessId;
    DWORD dwThreadId;
} PROCESS_INFORMATION;
</code>```

but problem is that this structure is available only after creating process with CreateProcess API function. Main goal is to prevent program users to use different tools available online like ProcessExplorer etc to terminate process. I acheived that with success hooking TerminateProcess API calls and preventing that way closing my app but Suspend option in those process exploring tools can Suspend my process. It is internet kiosk application and it is vital that users can't close that application. Applications is currently running in Windows XP and it has to be run on administrator account because other apps that users are using after logging in my application requires administrator account to operate, so I can't simply run my application under restricted user.

Is there any way that I can get my main application main thread handle in Delphi ?

Thanks in advance

答:
If you have the thread ID, you can get a handle for it using OpenThread:</p>

```<code>HANDLE WINAPI OpenThread(
  __in  DWORD dwDesiredAccess,
  __in  BOOL bInheritHandle,
  __in  DWORD dwThreadId
);
</code>```

Title: Get Current Thread Handle

Body:
I have problem in Delphi application with determining current application (current Thread) handle. I know that I can get Current Thread ID with Windows API function GetCurrentThreadID, but I need current Thread handle to use as param for another Windows API function that is SuspendThread.

Actually what I am trying to do is to make one of my old dll's made for hooking API functions located in kernel32.dll like OpenProcess or TerminateProcessto also do hook for SuspendProcess. Hook is located in dll file and using SetWindowsHookEx to be injected in running processes then finding base address of target functions.
I had no problem with hooking functions like TerminateProcess because it needs process ID as param that is easy to obtain in main application using GetCurrentProcessID. To make similar hook for SuspendThread function i need to pass thread handle as param.

Only place where I found thread handle is PROCESS_INFORMATION structure that contains

typedef struct _PROCESS_INFORMATION { // pi
    HANDLE hProcess;
    HANDLE hThread;
    DWORD dwProcessId;
    DWORD dwThreadId;
} PROCESS_INFORMATION;

but problem is that this structure is available only after creating process with CreateProcess API function. Main goal is to prevent program users to use different tools available online like ProcessExplorer etc to terminate process. I acheived that with success hooking TerminateProcess API calls and preventing that way closing my app but Suspend option in those process exploring tools can Suspend my process. It is internet kiosk application and it is vital that users can't close that application. Applications is currently running in Windows XP and it has to be run on administrator account because other apps that users are using after logging in my application requires administrator account to operate, so I can't simply run my application under restricted user.

Is there any way that I can get my main application main thread handle in Delphi ?

Thanks in advance

Body:
If you have the thread ID, you can get a handle for it using OpenThread:

HANDLE WINAPI OpenThread(
  __in  DWORD dwDesiredAccess,
  __in  BOOL bInheritHandle,
  __in  DWORD dwThreadId
);


问:
placement of dynamically added buttons in javafx
I have dynamically created a bunch of buttons. I gave a fixed width to each of them. I want it to be added until space is available to its parents and when it overlaps with some other nodes, it will automatically go to the next line in order to avoid collision. I want it to be responsive at different screen sizes.

```<code>for(Data i:datas){
  Button btn=new Button(i.getName());
  anchorPane.getChildren().addAll(btn);
}
</code>```

I want to arrange the buttons in a new line only when the buttons in the first line have covered its total width. How can I accomplish it? Any help is appreciated.

答:
James_D provided a great resource—there's a built in layout for anything you need and FlowPane has what you want here.

Using your example, just swap out your AnchorPane for FlowPane:

```<code>FlowPane flowPane = new FlowPane();

for(Data i:datas){
  Button btn=new Button(i.getName());
  flowPane.getChildren().addAll(btn);
}
</code>```

To make it responsive (i.e. expand and contract with the parent container/stage), bind the FlowPane's width and height to those of its parent:

```<code>flowPane.prefWidthProperty().bind(stage.widthProperty());
flowPane.prefHeightProperty().bind(stage.heightProperty());
</code>```

Body:
I have dynamically created a bunch of buttons. I gave a fixed width to each of them. I want it to be added until space is available to its parents and when it overlaps with some other nodes, it will automatically go to the next line in order to avoid collision. I want it to be responsive at different screen sizes.

for(Data i:datas){
  Button btn=new Button(i.getName());
  anchorPane.getChildren().addAll(btn);
}

I want to arrange the buttons in a new line only when the buttons in the first line have covered its total width. How can I accomplish it? Any help is appreciated.

Body:
James_D provided a great resource—there's a built in layout for anything you need and FlowPane has what you want here.

Using your example, just swap out your AnchorPane for FlowPane:

FlowPane flowPane = new FlowPane();

for(Data i:datas){
  Button btn=new Button(i.getName());
  flowPane.getChildren().addAll(btn);
}

To make it responsive (i.e. expand and contract with the parent container/stage), bind the FlowPane's width and height to those of its parent:

flowPane.prefWidthProperty().bind(stage.widthProperty());
flowPane.prefHeightProperty().bind(stage.heightProperty());


问:
Data Class Equality in Kotlin
Hello everyone I am trying to use the == to check if two variables are structurally equal

```<code>// PersonImpl0 has the name variable in the primary constructor
data class PersonImpl0(val id: Long, var name: String="") {
}

// PersonImpl1 has the name variable in the body
data class PersonImpl1(val id: Long) {
     var name: String=""
}

fun main(args: Array<String>) {
    val person0 = PersonImpl0(0)
    person0.name = "Charles"

    val person1 = PersonImpl0(0)
    person1.name = "Eugene"

    val person2 = PersonImpl1(0)
    person0.name = "Charles"

    val person3 = PersonImpl1(0)
    person1.name = "Eugene"

    println(person0 == person1) // Are not equal ??
    println(person2 == person3) // Are equal ??

 }
</code>```

Here the output I got

```<code>false
true
</code>```

Why is it that the 2 variables are not equal in the first case and equal in the second case ?

THank you for clearing this up for me

答:
Kotlin compiler generates hashCode and equals methods for data classes, including properties in the constructor only. The property name in PersonImpl1 is not included in the hashCode/equals, hence the difference. See the de-compiled code:

```<code>  //hashcode implementation of PersonImpl1
  public int hashCode()
  {
    long tmp4_1 = this.id;
    return (int)(tmp4_1 ^ tmp4_1 >>> 32);
  }

  //equals implementation of PersonImpl1
  public boolean equals(Object paramObject)
  {
    if (this != paramObject)
    {
      if ((paramObject instanceof PersonImpl1))
      {
        PersonImpl1 localPersonImpl1 = (PersonImpl1)paramObject;
        if ((this.id == localPersonImpl1.id ? 1 : 0) == 0) {}
      }
    }
    else {
      return true;
    }
    return false;
  }
</code>```

Title: Data Class Equality in Kotlin

Body:
Hello everyone I am trying to use the == to check if two variables are structurally equal

// PersonImpl0 has the name variable in the primary constructor
data class PersonImpl0(val id: Long, var name: String="") {
}

// PersonImpl1 has the name variable in the body
data class PersonImpl1(val id: Long) {
     var name: String=""
}

fun main(args: Array<String>) {
    val person0 = PersonImpl0(0)
    person0.name = "Charles"

    val person1 = PersonImpl0(0)
    person1.name = "Eugene"

    val person2 = PersonImpl1(0)
    person0.name = "Charles"

    val person3 = PersonImpl1(0)
    person1.name = "Eugene"

    println(person0 == person1) // Are not equal ??
    println(person2 == person3) // Are equal ??

 }

Here the output I got

false
true

Why is it that the 2 variables are not equal in the first case and equal in the second case ?

THank you for clearing this up for me

Body:
Kotlin compiler generates hashCode and equals methods for data classes, including properties in the constructor only. The property name in PersonImpl1 is not included in the hashCode/equals, hence the difference. See the de-compiled code:

  //hashcode implementation of PersonImpl1
  public int hashCode()
  {
    long tmp4_1 = this.id;
    return (int)(tmp4_1 ^ tmp4_1 >>> 32);
  }

  //equals implementation of PersonImpl1
  public boolean equals(Object paramObject)
  {
    if (this != paramObject)
    {
      if ((paramObject instanceof PersonImpl1))
      {
        PersonImpl1 localPersonImpl1 = (PersonImpl1)paramObject;
        if ((this.id == localPersonImpl1.id ? 1 : 0) == 0) {}
      }
    }
    else {
      return true;
    }
    return false;
  }


问:
Syntax for an async arrow function
I can mark a JavaScript function as "async" (i.e., returning a promise) with the async keyword. Like this:

```<code>async function foo() {
  // Do something
}
</code>```

What is the equivalent syntax for arrow functions?

答:
This the simplest way to assign an async arrow function expression to a named variable:

```<code>const foo = async () => {
  // do something
}
</code>```

(Note that this is not strictly equivalent to async function foo() { }. Besides the differences between the function keyword and an arrow expression, the function in this answer is not "hoisted to the top".)

Title: Syntax for an async arrow function

Body:
I can mark a JavaScript function as "async" (i.e., returning a promise) with the async keyword. Like this:

async function foo() {
  // Do something
}

What is the equivalent syntax for arrow functions?

Body:
This the simplest way to assign an async arrow function expression to a named variable:

const foo = async () => {
  // do something
}

(Note that this is not strictly equivalent to async function foo() { }. Besides the differences between the function keyword and an arrow expression, the function in this answer is not "hoisted to the top".)


问:
Minify/compress CSS with regex?
In PHP can you compress/minify CSS with regex (PCRE)?

(As a theoretical in regex. I'm sure there are libraries out there that do this well.)

Background note: After spending hours writing an answer to a deleted (half crap) question, I thought I'd post a part of the underlying question and answer it my self. Hope it's ok.

答:
Here's a slightly modified version of @Qtax's answer which resolves the issues with calc() thanks to an alternative regex from @matthiasmullie's Minify library.

function minify_css( $string = '' ) {
    $comments = <<<'EOS'
(?sx)
    # don't change anything inside of quotes
    ( "(?:[^"\\]++|\\.)*+" | '(?:[^'\\]++|\\.)*+' )
|
    # comments
    /\* (?> .*? \*/ )
EOS;

    $everything_else = <<<'EOS'
(?six)
    # don't change anything inside of quotes
    ( "(?:[^"\\]++|\\.)*+" | '(?:[^'\\]++|\\.)*+' )
|
    # spaces before and after ; and }
    \s*+ ; \s*+ ( } ) \s*+
|
    # all spaces around meta chars/operators (excluding + and -)
    \s*+ ( [*$~^|]?+= | [{};,>~] | !important\b ) \s*+
|
    # all spaces around + and - (in selectors only!)
    \s*([+-])\s*(?=[^}]*{)
|
    # spaces right of ( [ :
    ( [[(:] ) \s++
|
    # spaces left of ) ]
    \s++ ( [])] )
|
    # spaces left (and right) of : (but not in selectors)!
    \s+(:)(?![^\}]*\{)
|
    # spaces at beginning/end of string
    ^ \s++ | \s++ \z
|
    # double spaces to single
    (\s)\s+
EOS;

    $search_patterns  = array( "%{$comments}%", "%{$everything_else}%" );
    $replace_patterns = array( '$1', '$1$2$3$4$5$6$7$8' );

    return preg_replace( $search_patterns, $replace_patterns, $string );
}
```

Title: Minify/compress CSS with regex?


问:
How to retrieve object from Go http.Request?
I have a working app that recieves HTTP GET parameters. They've been Strings and ints until now and it has worked fine getting each field using

```<code>http.Request.FormValue("field")
</code>```

But now I've added an array of simple objects in the parameters and I don't know how to transform it to a slice of Go structs.

The array in question is

```<code>mods:[{
    name : x,
    max : 1,
    min : 2
 },{
    name:y,...
 }]
</code>```

So I'm not sure how to proceed to map it to a Go struct. Should I create the struct first and map the result of r.FormValue using JSON?

答:
Check out the encoding/json package. In Go, you have to marshal and unmarshal your Go structures into and out of their encoding. It isn't quick an easy, but it's an good modern solution for a strictly typed language like Go.

In your case, you'll want to create a struct that matches the structure of the json you are trying to extract, and then unmarshal the json into a variable of the struct type you created.

Body:
I have a working app that recieves HTTP GET parameters. They've been Strings and ints until now and it has worked fine getting each field using

http.Request.FormValue("field")

But now I've added an array of simple objects in the parameters and I don't know how to transform it to a slice of Go structs.

The array in question is

mods:[{
    name : x,
    max : 1,
    min : 2
 },{
    name:y,...
 }]

So I'm not sure how to proceed to map it to a Go struct. Should I create the struct first and map the result of r.FormValue using JSON?


问:
Join to a table only when column value is true
I am using SQL Server 2005. I am trying to join 2 tables together, but only when a column value in the main table is true. Like this:

```<code>select * from T1
join T2 on T1.value = T2.value
where T2.value2 = 'variable2'
and T2.value3 = 'variable3'
</code>```

There is a column value in T1 which says if I have to use the values in T2. I could to a case around the where clause, but it will always join to the table, and if the value in T1 is false, there are no values in T2 to join to, so the select returns no rows.

You can't put a case around the join, so I am a little bit stuck with this ... can anyone help ?

答:
Similar to what Dave posted, but I also read that to mean you want to actually substitute values in the results.  In that case:

```<code>SELECT
    COALESCE(T2.Value, T1.Value) AS Value,
    COALESCE(T2.Value2, T1.Value2) AS Value2,
    COALESCE(T2.Value3, T1.Value3) AS Value3
FROM T1
LEFT JOIN T2 ON T2.value = T1.value
    AND T2.Value2= @Variable2 AND T2.Value3 = @Variable3
</code>```

Note that I'm treating your constants as real variables, too.

OwnerDisplayName: Arni Gunnar Ragnarsson

Body:
I am using SQL Server 2005. I am trying to join 2 tables together, but only when a column value in the main table is true. Like this:

select * from T1
join T2 on T1.value = T2.value
where T2.value2 = 'variable2'
and T2.value3 = 'variable3'

There is a column value in T1 which says if I have to use the values in T2. I could to a case around the where clause, but it will always join to the table, and if the value in T1 is false, there are no values in T2 to join to, so the select returns no rows.

You can't put a case around the join, so I am a little bit stuck with this ... can anyone help ?

Body:
Similar to what Dave posted, but I also read that to mean you want to actually substitute values in the results.  In that case:

SELECT
    COALESCE(T2.Value, T1.Value) AS Value,
    COALESCE(T2.Value2, T1.Value2) AS Value2,
    COALESCE(T2.Value3, T1.Value3) AS Value3
FROM T1
LEFT JOIN T2 ON T2.value = T1.value
    AND T2.Value2= @Variable2 AND T2.Value3 = @Variable3

Note that I'm treating your constants as real variables, too.

OwnerDisplayName: Joel Coehoorn


问:
How to use nuSOAP for messages with multiple namespaces
I'm trying to access a WebService using nuSOAP (because I'm bound to PHP4 here) that uses more than 1 namespace in a message. Is that possible?

An example request message would look like this:

```<code><soapenv:Envelope ...
  xmlns:ns1="http://domain.tld/namespace1"
  xmlns:ns2="http://domain.tld/namespace2">
  <soapenv:Header/>
  <soapenv:Body>
    <ns1:myOperation>
      <ns2:Person>
        <ns2:Firstname>..</ns2:Firstname>
        ..
      </ns2:Person>
      <ns1:Attribute>..</ns1:Attribute>
    </ns1:myOperation>
  </soapenv:Body>
</soapenv:Envelope>
</code>```

I tried to following:

```<code>$client = new nusoap_client("my.wsdl", true);
$params = array(
  'Person' => array(
    'FirstName'  => 'Thomas',
    ..
   ),
   'Attribute' => 'foo'
 );

 $result = $client->call('myOperation', $params, '', 'soapAction');
</code>```

in the hope that nuSOAP would try to match these names to the correct namespaces and nodes. Then I tried to use soapval() to generate the elements and their namespace - but if I call an operation, nuSOAP creates the following request:

```<code><SOAP-ENV:Envelope ...>
  <SOAP-ENV:Body>
    <queryCCApplicationDataRequest xmlns="http://domain.tld/namespace1"/>
  </SOAP-ENV:Body>
</SOAP-ENV:Envelope>
</code>```

So something goes wrong during the "matching" phase.

答:
Another bypass this issue would be a modification to nusoap_client::call() function. Next to the this line (7359 in version 1.123) in nusoap.php:

$nsPrefix = $this->wsdl->getPrefixFromNamespace($namespace);

I added this one:

```<code>$nsPrefix = $this->wsdl->getPrefixFromNamespace("other_ns_name");
</code>```

And it worked! Since I only needed this library for one project, it was OK for me to hardcode this hack. Otherwise, I would dig more and modify the function to accept array instead of string for a namespace parameter.

OwnerDisplayName: wilth

Body:
I'm trying to access a WebService using nuSOAP (because I'm bound to PHP4 here) that uses more than 1 namespace in a message. Is that possible?

An example request message would look like this:

<soapenv:Envelope ...
  xmlns:ns1="http://domain.tld/namespace1"
  xmlns:ns2="http://domain.tld/namespace2">
  <soapenv:Header/>
  <soapenv:Body>
    <ns1:myOperation>
      <ns2:Person>
        <ns2:Firstname>..</ns2:Firstname>
        ..
      </ns2:Person>
      <ns1:Attribute>..</ns1:Attribute>
    </ns1:myOperation>
  </soapenv:Body>
</soapenv:Envelope>

I tried to following:

$client = new nusoap_client("my.wsdl", true);
$params = array(
  'Person' => array(
    'FirstName'  => 'Thomas',
    ..
   ),
   'Attribute' => 'foo'
 );

 $result = $client->call('myOperation', $params, '', 'soapAction');

in the hope that nuSOAP would try to match these names to the correct namespaces and nodes. Then I tried to use soapval() to generate the elements and their namespace - but if I call an operation, nuSOAP creates the following request:

<SOAP-ENV:Envelope ...>
  <SOAP-ENV:Body>
    <queryCCApplicationDataRequest xmlns="http://domain.tld/namespace1"/>
  </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

So something goes wrong during the "matching" phase.

Body:
Another bypass this issue would be a modification to nusoap_client::call() function. Next to the this line (7359 in version 1.123) in nusoap.php:

$nsPrefix = $this->wsdl->getPrefixFromNamespace($namespace);

I added this one:

$nsPrefix = $this->wsdl->getPrefixFromNamespace("other_ns_name");

And it worked! Since I only needed this library for one project, it was OK for me to hardcode this hack. Otherwise, I would dig more and modify the function to accept array instead of string for a namespace parameter.