问:
Getting different output with same simplexmlobject file...?
Sorry, i forgot to put a check for the $MeshHeading->QualifierName... now i did... but i still get the error...?

If got this simpleXMLobject:

```<code>[MeshHeading] => Array
                                        (
                                            [0] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Acoustic Stimulationment Object
                                                    [QualifierName] => methods
                                                )

                                            [1] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Adolescent
                                                )

                                            [2] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Age Factors
                                                )

                                            [3] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Child
                                                )

                                            [4] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Electromyography
                                                    [QualifierName] => methods
                                                )

                                            [5] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Female
                                                )

                                            [6] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Galvanic Skin Response
                                                    [QualifierName] => physiology
                                                )

                                            [7] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Humans
                                                )

                                            [8] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Male
                                                )

                                            [9] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Muscle, Skeletal
                                                    [QualifierName] => physiology
                                                )

                                            [10] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Probability
                                                )

                                            [11] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Reaction Time
                                                    [QualifierName] => physiology
                                                )

                                            [12] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Sex Factors
                                                )

                                            [13] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Startle Reaction
                                                    [QualifierName] => physiology
                                                )
</code>```

If i put in this code:

```<code>if ($Citation->MeshHeadingList)
  {
   foreach ($Citation->MeshHeadingList->MeshHeading as $MeshHeading)
   {

   echo "```";
   echo "[" .$MeshHeading->DescriptorName . "] ";
   echo "[" .$MeshHeading->DescriptorName->attributes() . "]";
   echo "
QualifierName);
      {
  echo "[" .$MeshHeading->QualifierName . "] ";
  echo "[" .$MeshHeading->QualifierName->attributes() . "]";
  }

   echo "```";
   }
  }
 else
  {
  echo "mesheading is missing in article " . $i . "<br />";
  $l++;
  }
</code>```

I get this...?

```<code>[Acoustic Stimulation] [N]

[Adolescent] [N]

Warning:  main() [function.main]: Node no longer exists in /home/thijs/project/phptest/pubmed_fetch.php on line 119

[]

[Age Factors] [N]

Warning:  main() [function.main]: Node no longer exists in /home/thijs/project/phptest/pubmed_fetch.php on line 119

[]

[Child] [N]

Warning:  main() [function.main]: Node no longer exists in /home/thijs/project/phptest/pubmed_fetch.php on line 119

[]

[Electromyography] [N]

[Female] [N]

Warning:  main() [function.main]: Node no longer exists in /home/thijs/project/phptest/pubmed_fetch.php on line 119

[]
</code>```

Best regards
Thijs

答:
I think this is the problem :</p>

```<code>if ($MeshHeading->QualifierName);
________________________________^ <-- remove semicolon

if ($MeshHeading->QualifierName)
{
  ...
}

/* even better */
if (isset($MeshHeading->QualifierName))
{
  ...
}
</code>```

Body:
Sorry, i forgot to put a check for the $MeshHeading->QualifierName... now i did... but i still get the error...?

If got this simpleXMLobject:

[MeshHeading] => Array
                                        (
                                            [0] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Acoustic Stimulationment Object
                                                    [QualifierName] => methods
                                                )

                                            [1] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Adolescent
                                                )

                                            [2] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Age Factors
                                                )

                                            [3] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Child
                                                )

                                            [4] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Electromyography
                                                    [QualifierName] => methods
                                                )

                                            [5] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Female
                                                )

                                            [6] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Galvanic Skin Response
                                                    [QualifierName] => physiology
                                                )

                                            [7] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Humans
                                                )

                                            [8] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Male
                                                )

                                            [9] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Muscle, Skeletal
                                                    [QualifierName] => physiology
                                                )

                                            [10] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Probability
                                                )

                                            [11] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Reaction Time
                                                    [QualifierName] => physiology
                                                )

                                            [12] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Sex Factors
                                                )

                                            [13] => SimpleXMLElement Object
                                                (
                                                    [DescriptorName] => Startle Reaction
                                                    [QualifierName] => physiology
                                                )

If i put in this code:

if ($Citation->MeshHeadingList)
  {
   foreach ($Citation->MeshHeadingList->MeshHeading as $MeshHeading)
   {

   echo "
";
   echo "[" .$MeshHeading->DescriptorName . "] ";
   echo "[" .$MeshHeading->DescriptorName->attributes() . "]";
   echo "
QualifierName);
      {
  echo "[" .$MeshHeading->QualifierName . "] ";
  echo "[" .$MeshHeading->QualifierName->attributes() . "]";
  }

   echo "
";
   }
  }
 else
  {
  echo "mesheading is missing in article " . $i . "
";
  $l++;
  }

I get this...?

[Acoustic Stimulation] [N]

[Adolescent] [N]

Warning:  main() [function.main]: Node no longer exists in /home/thijs/project/phptest/pubmed_fetch.php on line 119

[]

[Age Factors] [N]

Warning:  main() [function.main]: Node no longer exists in /home/thijs/project/phptest/pubmed_fetch.php on line 119

[]

[Child] [N]

Warning:  main() [function.main]: Node no longer exists in /home/thijs/project/phptest/pubmed_fetch.php on line 119

[]

[Electromyography] [N]

[Female] [N]

Warning:  main() [function.main]: Node no longer exists in /home/thijs/project/phptest/pubmed_fetch.php on line 119

[]

Best regards
Thijs

Body:
I think this is the problem :

if ($MeshHeading->QualifierName);
________________________________^ <-- remove semicolon

if ($MeshHeading->QualifierName)
{
  ...
}

/* even better */
if (isset($MeshHeading->QualifierName))
{
  ...
}


来源: stackexchange

问:
No code input window in Netbeans 8 for Java
I am trying to learn Java using the Netbeans 8.0 IDE.

On creating a new project and .java file, instead of getting a main code input window, the main window (where the start page tab is on 1st launching netbeans), shows a checked history button, and compare mode, but nowhere to input code.

I have looked at videos, and followed the exact same few simple steps that they did, but of the code template they get, instead I get this "history" tab, and nowhere to input code.

答:
Try removing the userdir.

From the wiki at netbeans.org:

The NetBeans userdir is a directory where NetBeans stores user configuration data such as window layouts, editor settings, menu and toolbar customizations and various module settings.

By default on Windows and Mac OS X the userdir is inside a directory NetBeans in application settings folder.

On Windows this can be found at C:\Users\<username>\AppData\Roaming\

On OS X this can be found at /Users/<username>/Library/Application Support/

See a related questions here and here.

ContentLicense: CC BY-SA 3.0


问:
Desktop shortcuts via a GPO
i'm trying to create a "restart" & "shutdown" shortcuts on the desktop on a test machine (Win 7) with a GPO. the "shutdown" icon appears on the test client desktop but not the restart icon.

'Restart' Shortcut item settings set as below:

```<code>Target type: File System Object
Shortcut Path: %DesktopDir%\Restart
Target path: %windir%\system32\shutdown.exe -r
Icon path: %SystemRoot%\system32\Shell32.dll
Icon index: 27
Shortcut key: None
Run: Normal Window
</code>```

the only difference between the two shortcuts is the "-r" for the restart target path.

a bit stumped here!

答:
Since the command has a "-r" parameter, it may be using the string as long as it does not encounter a space.....

Could we see the actual way the GPO is written ? We are also trying to use GPO to create shortcuts (or URLs) on end-user desktops. Could you put either single or double quotes around the entire command ? Would that make a difference ?

Title: Desktop shortcuts via a GPO

Body:
i'm trying to create a "restart" & "shutdown" shortcuts on the desktop on a test machine (Win 7) with a GPO. the "shutdown" icon appears on the test client desktop but not the restart icon.

'Restart' Shortcut item settings set as below:

Target type: File System Object
Shortcut Path: %DesktopDir%\Restart
Target path: %windir%\system32\shutdown.exe -r
Icon path: %SystemRoot%\system32\Shell32.dll
Icon index: 27
Shortcut key: None
Run: Normal Window

the only difference between the two shortcuts is the "-r" for the restart target path.

a bit stumped here!


问:
Can git tell me if a rebase will conflict without actually rebasing?
I would like to programmatically determine with of my feature branches would have rebase conflicts if I tried to rebase them.  Is there a way I can get git to tell me this information without actually performing the rebase?

Failing that, what is the simplest way to detect if a rebase failed before git rebase --aborting it?

My question is similar to these two, which are the same but for merge instead of rebase

Can git tell me if a merge will conflict without actually merging?

Is there a git-merge --dry-run option?

答:
Failing that, what is the simplest way to detect if a rebase failed before git rebase --aborting it?

git rebase returns a falsy status when it fails, so you could do something like

```<code>git rebase feature && echo "Success" || echo "fail" && git rebase --abort
</code>```

This will, however, perform the actual rebase when it is successful.
If you want to test if a rebase would be successful without actually performing it, I'm afraid my only idea is to checkout another branch, check if the rebase is successful and switch back, for example:

```<code>branch=$(git branch | grep '* .*' | sed s/..//); git checkout -b $branch-rebase > /dev/null ; git rebase test-2 > /dev/null && result="Success" || result="fail" ; git rebase --abort ; git checkout $branch ; git branch -D $branch-rebase ; echo $result
</code>```

I first remember the current branch in a variable (if anyone has a better solution for determining the current branch, let me know), switch to branchname-rebase, perform the rebase, checkout the original branch and delete the test branch before I echo the result. Hacky, but depending on your usecase, this might work.

Body:
Failing that, what is the simplest way to detect if a rebase failed before git rebase --aborting it?

git rebase returns a falsy status when it fails, so you could do something like

git rebase feature && echo "Success" || echo "fail" && git rebase --abort

This will, however, perform the actual rebase when it is successful.
If you want to test if a rebase would be successful without actually performing it, I'm afraid my only idea is to checkout another branch, check if the rebase is successful and switch back, for example:

branch=$(git branch | grep '* .*' | sed s/..//); git checkout -b $branch-rebase > /dev/null ; git rebase test-2 > /dev/null && result="Success" || result="fail" ; git rebase --abort ; git checkout $branch ; git branch -D $branch-rebase ; echo $result

I first remember the current branch in a variable (if anyone has a better solution for determining the current branch, let me know), switch to branchname-rebase, perform the rebase, checkout the original branch and delete the test branch before I echo the result. Hacky, but depending on your usecase, this might work.


问:
input time in web2py
I want to take input time to complete a task in format no. of days,hours in web2py. Is there any defined field,type for this in SQLField.
time module in python allows only max 24 hours time.</p>

答:
Sorry Field(...'time') only allows 24 hours and there is no specific type for timeinterval. Yet you can make define one using:

```<code> timeinterval = SQLCustomType(....)
</code>```

and use it as

```<code> Field('name',type=timeinterval, widget=....)
</code>```

You can also make your own widget to handle it.

Please ask on the web2py mailing list so we keep the info in one place. I will be happy to provide a complete example.

ContentLicense: CC BY-SA 2.5

Title: input time in web2py

Body:
Sorry Field(...'time') only allows 24 hours and there is no specific type for timeinterval. Yet you can make define one using:

 timeinterval = SQLCustomType(....)

and use it as

 Field('name',type=timeinterval, widget=....)

You can also make your own widget to handle it.

Please ask on the web2py mailing list so we keep the info in one place. I will be happy to provide a complete example.


问:
Select fields on Microsoft Graph list of Messages
I'm using Microsoft Graph to get a list of messages for a user.

I'm using the following URL
https://graph.microsoft.com/v1.0/me/mailFolders/inbox/messages

One important thing that is returned by this is the meetingMessageType when the message revolves around a meeting request.

I would also like to get the uniqueBody of the message.  However, that's not provided by default.  One needs to specifically ask for that field.  I can do that by adding ?$select=uniqueBody to the URL.

However, that now means that I need to add the rest of the fields I want to the $select query parameter.  That's not a big deal until I run into meetingMessageType.  Microsoft Graph returns:

Could not find a property named 'meetingMessageType' on type 'Microsoft.OutlookServices.Message'.

What can I do to ensure I get both uniqueBody and meetingMessageType?

答:
Try this:

$select=uniqueBody, microsoft.graph.eventMessage/meetingMessageType


问:
Can not handle properly a simple exception
I wrote a PHP class to manage some statistic functions but there are some functions that need a minimum of elements i.e. >0.
So I added a try catch and I still get the same error.

```<code>/**
 * Calculates the minimum for a given set of values.
 *
 * @param array $values The input values
 * @return float|int The minimum of values as an integer or float
 */
public static function min($values)
{
    try {
        min($values);
    } catch (Exception $e) {
        return 0;
    }
}
</code>```

And I get:

```<code>ErrorException in Statistics.php line 41: min(): Array must contain at least one element
</code>```

Thanks in advance.

答:
Since I am using Laravel as Alex noticed I was missing a use Exception to handle this Exception.
After that I was able to catch that error.
Thanks all of you guys</p>

Body:
I wrote a PHP class to manage some statistic functions but there are some functions that need a minimum of elements i.e. >0.
So I added a try catch and I still get the same error.

/**
 * Calculates the minimum for a given set of values.
 *
 * @param array $values The input values
 * @return float|int The minimum of values as an integer or float
 */
public static function min($values)
{
    try {
        min($values);
    } catch (Exception $e) {
        return 0;
    }
}

And I get:

ErrorException in Statistics.php line 41: min(): Array must contain at least one element

Thanks in advance.


问:
If I want something to consistently be happening while the rest of my program is still running in Python, what do I do?
If i want to make an interest class, where I use a time function to continuously add interest while the rest of the program runs, how would I carry that out?</p>

答:
Use threading:    </p>

```<code>import threading

def interest():
    while True:
        print('interest is running')

d = threading.Thread(target=interest)
d.setDaemon(True)
d.start()

print('Your main job is here')
</code>```

Body:
Use threading:

import threading

def interest():
    while True:
        print('interest is running')

d = threading.Thread(target=interest)
d.setDaemon(True)
d.start()

print('Your main job is here')


问:
Using MySQL's COUNT with two tables
I have the following MySQL table called tbl_pet_owners:

```<code>+--------+----------+--------+
| name   | pet      | city   |
+========+==========+========+
| jane   | cat      | Boston |
+--------+----------+--------+
| jane   | dog      | Boston |
+--------+----------+--------+
| jack   | cat      | Boston |
+--------+----------+--------+
| jim    | snake    | Boston |
+--------+----------+--------+
| jim    | goldfish | Boston |
+--------+----------+--------+
| joseph | cat      | NYC    |
+--------+----------+--------+
</code>```

I want to use COUNT to get the number of pets per city, BUT if an individual owns two or more pets of the same type, then those pets are counted as one. The pet types are listed in another MySQL table called tbl_pet_types:

```<code>+----------+---------+
| pet      | type    |
+==========+=========+
| cat      | mammal  |
+----------+---------+
| dog      | mammal  |
+----------+---------+
| snake    | reptile |
+----------+---------+
| goldfish | fish    |
+----------+---------+
</code>```

So since jane's cat and dog are of the same type, they're considered one pet.
In this example, the result would be:

```<code>Boston 4
NYC    1
</code>```

Any tips on how to achieve this?

答:
```<code>SELECT o.city, COUNT(DISTINCT o.name, t.type)
FROM tbl_pet_owners o, tbl_pet_types t
WHERE o.pet = t.pet
GROUP BY city
</code>```

Title: Using MySQL's COUNT with two tables

Body:
I have the following MySQL table called tbl_pet_owners:

+--------+----------+--------+
| name   | pet      | city   |
+========+==========+========+
| jane   | cat      | Boston |
+--------+----------+--------+
| jane   | dog      | Boston |
+--------+----------+--------+
| jack   | cat      | Boston |
+--------+----------+--------+
| jim    | snake    | Boston |
+--------+----------+--------+
| jim    | goldfish | Boston |
+--------+----------+--------+
| joseph | cat      | NYC    |
+--------+----------+--------+

I want to use COUNT to get the number of pets per city, BUT if an individual owns two or more pets of the same type, then those pets are counted as one. The pet types are listed in another MySQL table called tbl_pet_types:

+----------+---------+
| pet      | type    |
+==========+=========+
| cat      | mammal  |
+----------+---------+
| dog      | mammal  |
+----------+---------+
| snake    | reptile |
+----------+---------+
| goldfish | fish    |
+----------+---------+

So since jane's cat and dog are of the same type, they're considered one pet.
In this example, the result would be:

Boston 4
NYC    1

Any tips on how to achieve this?


问:
PHP5: Some Session files 0 length?
I'm seeing a strange situation, that I'm trying to figure out if it's a PHP issue, file issue, or normal operation.  I have some users complaining about very fast timeouts on our site (session expires?), and checking the php tmp directory, I see things like this:

```<code>-rw------- 1 www-data www-data  377 2009-01-15 22:46 sess_fc789ce04a3d54ce929a401cd33ea868
-rw------- 1 www-data www-data 1167 2009-01-15 23:21 sess_fcb67b1f44a3669d8ffee69d5fa9a2e8
-rw------- 1 www-data www-data    0 2009-01-15 23:22 sess_fe0ab79c78c612d71ecca575753afdc4
-rw------- 1 www-data www-data    0 2009-01-15 23:07 sess_fedd46db2b023215cb060d67a01d3382
-rw------- 1 www-data www-data    0 2009-01-15 23:21 sess_feec900e144c011303a9f06eb428574e
-rw------- 1 www-data www-data    0 2009-01-15 23:00 sess_ffb2ed75ca311d08e41ec69c7d708d08
-rw------- 1 www-data www-data 1142 2009-01-15 22:49 sess_ffc2c882af3b3ad39b844dc5a530dc44
-rw------- 1 www-data www-data    0 2009-01-15 22:51 sess_fffbd6f7734ce3b4ef9d8009a324a459
</code>```

Is this normal behavior?

TIA
Mike

答:
```<code><?php set_time_limit(100); ?>
</code>```

Title: PHP5: Some Session files 0 length?

Body:
I'm seeing a strange situation, that I'm trying to figure out if it's a PHP issue, file issue, or normal operation.  I have some users complaining about very fast timeouts on our site (session expires?), and checking the php tmp directory, I see things like this:

-rw------- 1 www-data www-data  377 2009-01-15 22:46 sess_fc789ce04a3d54ce929a401cd33ea868
-rw------- 1 www-data www-data 1167 2009-01-15 23:21 sess_fcb67b1f44a3669d8ffee69d5fa9a2e8
-rw------- 1 www-data www-data    0 2009-01-15 23:22 sess_fe0ab79c78c612d71ecca575753afdc4
-rw------- 1 www-data www-data    0 2009-01-15 23:07 sess_fedd46db2b023215cb060d67a01d3382
-rw------- 1 www-data www-data    0 2009-01-15 23:21 sess_feec900e144c011303a9f06eb428574e
-rw------- 1 www-data www-data    0 2009-01-15 23:00 sess_ffb2ed75ca311d08e41ec69c7d708d08
-rw------- 1 www-data www-data 1142 2009-01-15 22:49 sess_ffc2c882af3b3ad39b844dc5a530dc44
-rw------- 1 www-data www-data    0 2009-01-15 22:51 sess_fffbd6f7734ce3b4ef9d8009a324a459

Is this normal behavior?

TIA
Mike

Body: <?php set_time_limit(100); ?>

OwnerDisplayName: John


问:
Why a class's +load() was executed before main() in Objc?
why classes' +load() methods were invoked before project's main function? Is main function not the entrance of app? who invoked +load methods?</p>

答:
First of all: It is +load, not load() (+load() doesn't syntactically exist), because it is a method, not a function.

main() is the entry point of an app. load is sent from the runtime environment, what obviously starts before the app is "started" by calling main().

In reality all class objects of a bundle gets a load message after loading the bundle. Obviously this is easier than having a flag for each class, whether it has already gotten the message.

However, that should not be a problem for your code, because the implementation +load should not rely on anything outside the class.


问:
How to integrate ZXing in Android Studio project so that I can edit code in the Core directory
I've been able to add ZXing by simply adding the dependency in my gradle file, however this doesn't let me edit the code of ZXing.

I'm wanting to access the 2d boolean array that is passed to the Decoder class in ZXing core directory, however to do this I need to edit the code directly.

I tried adding ZXing Core as a module, but as it has no gradle files I could not.

How can I integrate ZXing in this way? (i.e. in such a way that I can edit the files of the library)

答:
In case anyone has the same problem as me, I had to download the source files for ZXing core, create a new android studio project using those downloaded source files, make sure that project compiled smoothly on its own, then in my actual project, I added to the dependencies section of my cradle file:

compile project(":ZXINGPROJECTNAME")

Don't leave out that colon. Worked fine after that


问:
How to kill Hibernates database connections in Spring boot 1.5.2?
The problem is simple when I use Spring boot 1.5.2 with Hibernate to connect to a datasource with configued like this:

```<code>@Bean
public DataSource dataSource() {
   DataSourceBuilder = datasourceBuilder = DataSourceBuilder.create();
   dataSourceBuilder.url(DATASOURCE_URL);
   dataSourceBuilder.username(DATASOURCE_USERNAME);
   dataSourceBuilder.password(DATASOURCE_PASSWORD);
   return dataSourceBuilder.build();
}
</code>```

and this is a Command line application, so when the application is almost done, I just want to close the Hibernate connections to the database and rename the database with JDBC. However, I don't know how to do this in Spring boot, any idea?

I tried to inject the DataSource object to a class to rename database but it cannot close the connections to database.

```<code>@Autowired
private DataSource dataSource;

public void closeConnection() {
    dataSource.close();
}
</code>```

with error

```<code>org.postgresql.util.PSQLException: ERROR: database "DATABASE" is being accessed by other users
Detail: There are 10 other sessions using the database.
</code>```

答:
You can use pg_terminate_backend() to kill a connection. You have to be superuser to use this function. This works on all operating systems the same.

refer this stackoverflow link :

https://stackoverflow.com/a/5109190/7801800

Body:
The problem is simple when I use Spring boot 1.5.2 with Hibernate to connect to a datasource with configued like this:

@Bean
public DataSource dataSource() {
   DataSourceBuilder = datasourceBuilder = DataSourceBuilder.create();
   dataSourceBuilder.url(DATASOURCE_URL);
   dataSourceBuilder.username(DATASOURCE_USERNAME);
   dataSourceBuilder.password(DATASOURCE_PASSWORD);
   return dataSourceBuilder.build();
}

and this is a Command line application, so when the application is almost done, I just want to close the Hibernate connections to the database and rename the database with JDBC. However, I don't know how to do this in Spring boot, any idea?

I tried to inject the DataSource object to a class to rename database but it cannot close the connections to database.

@Autowired
private DataSource dataSource;

public void closeConnection() {
    dataSource.close();
}

with error

org.postgresql.util.PSQLException: ERROR: database "DATABASE" is being accessed by other users
Detail: There are 10 other sessions using the database.


问:
Using levenshtein in MySQL search for one result
I am trying to do a search on my MySQL database to get the row that contains the most similar value to the one searched for.

Even if the closest result is very different, I'd still like to return it (Later on I do a string comparison and add the 'unknown' into the learning pool)

I would like to search my table 'responses' via the 'msg1' column and get one result, the one with the lowest levenshtein score, as in the one that is the most similar out of the whole column.

This sort of thing:

```<code>SELECT * FROM people WHERE levenshtein('$message', 'msg1') ORDER BY ??? LIMIT 1
</code>```

I don't quite grasp the concept of levenshtein here, as you can see I am searching the whole table, sorting it by ??? (the function's score?) and then limiting it to one result.

I'd then like to set $reply to the value in column "reply" from this singular row that I get.

Help would be greatly appreciated, I can't find many examples of what I'm looking for. I may be doing this completely wrong, I'm not sure.

Thank you!

答:
You would do:

```<code>SELECT p.*
FROM people p
ORDER BY levenshtein('$message', msg1) ASC
LIMIT 1;
</code>```

If you want a threshold (to limit the number of rows for sorting, then use a WHERE clause.  Otherwise, you just need ORDER BY.

Body:
I am trying to do a search on my MySQL database to get the row that contains the most similar value to the one searched for.

Even if the closest result is very different, I'd still like to return it (Later on I do a string comparison and add the 'unknown' into the learning pool)

I would like to search my table 'responses' via the 'msg1' column and get one result, the one with the lowest levenshtein score, as in the one that is the most similar out of the whole column.

This sort of thing:

SELECT * FROM people WHERE levenshtein('$message', 'msg1') ORDER BY ??? LIMIT 1

I don't quite grasp the concept of levenshtein here, as you can see I am searching the whole table, sorting it by ??? (the function's score?) and then limiting it to one result.

I'd then like to set $reply to the value in column "reply" from this singular row that I get.

Help would be greatly appreciated, I can't find many examples of what I'm looking for. I may be doing this completely wrong, I'm not sure.

Thank you!

Body:
You would do:

SELECT p.*
FROM people p
ORDER BY levenshtein('$message', msg1) ASC
LIMIT 1;

If you want a threshold (to limit the number of rows for sorting, then use a WHERE clause.  Otherwise, you just need ORDER BY.


问:
React add image field and save in pouchdb
I want to add a file/image field to my current field and save in pouchdb. Is there any cool way to handle this?

Here's what I have currently:

```<code>this.newInfo = {
      id: uuid(),
      createdAt: toDate(),
      Info: {
        name: '',
        dob: '',
        designation: ''
      }
  }

this.state = {
    doc: this.newInfo
  }
</code>```

In another file:

```<code>submitInfo (event) {
    event.preventDefault()

    let Info = Object.assign({}, this.props.doc)

    if (!Info._id) {
      Info._id = Info.id
    }

    console.log('About to post to pouch...', Info._id)

    // Save to pouchdb
    this.db.put(Info , (err, result) => {
      if (!err) {
        console.log('Successfully posted to pouchdb!')
        this.props.clearCurrentDoc()
      } else {
        console.log('Error saving to pouch...')
        console.log(err)
      }
    })
  }
</code>```

The form:

```<code><fieldset>
  <legend>Info</legend>

            <input name='name'
              value={props['name']}
              type='text'
              placeholder='Enter Name'
              onChange={handleChange}
            />
            <input name='dob'
              value={props['dob']}
              type='date'
              placeholder='Date of Birth'
              onChange={handleChange}
            />
            <input name='designation'
              value={props['designation']}
              type='text'
              placeholder='Designation'
              onChange={handleChange}
            />
          </fieldset>
</code>```

I want to add one more field for saving images. Maybe call it picture. Sorry, I can't put the entire code but everything else is working fine. I just need to add a field that will browse for image or file and save it with the existing ones.

答:
I've got a good sample on jsbin that should help you to sort through this. There is an input button that let's you select an image and then submit this to PouchDB. If you are using CouchDB the code is also there to replicate the data to CouchDb. The general idea is to use something like this:

```<code><input type="text" name="field1" />
<input type="text" name="field2" />
<input type="file" name="file" />
<script>
 var field1= window.document.reportform.field1.value;
 var field2= window.document.reportform.field2.value;
 var inputFile = document.querySelector("#file");
 getFile = inputFile.files[0];

 var myDoc = {
   _id: new Date().toISOString(),
   field1: field1,
   field2: field2,
   _attachments: {
     "file": {
       content_type: getFile.type,
       data: getFile
     }
   }
 }

 db.put(myDoc, function(err, response) {
   if (err) {
     return console.log(err);
   } else {
     console.log("Document created Successfully");
   }
});
  db.replicate.to(remote);
}
</script>
</code>```

JSbin: PouchDB image select and put()

I have not been able to get  to work. I have asked on stackoverflow and the PouchDB Slack channel. Some suggestions have been made but so far I haven't gotten it working.

The PouchDB documentation is very good. PouchDB Attachments Guide

Body:
I want to add a file/image field to my current field and save in pouchdb. Is there any cool way to handle this?

Here's what I have currently:

this.newInfo = {
      id: uuid(),
      createdAt: toDate(),
      Info: {
        name: '',
        dob: '',
        designation: ''
      }
  }

this.state = {
    doc: this.newInfo
  }

In another file:

submitInfo (event) {
    event.preventDefault()

    let Info = Object.assign({}, this.props.doc)

    if (!Info._id) {
      Info._id = Info.id
    }

    console.log('About to post to pouch...', Info._id)

    // Save to pouchdb
    this.db.put(Info , (err, result) => {
      if (!err) {
        console.log('Successfully posted to pouchdb!')
        this.props.clearCurrentDoc()
      } else {
        console.log('Error saving to pouch...')
        console.log(err)
      }
    })
  }

The form:

<fieldset>
  <legend>Info</legend>

            <input name='name'
              value={props['name']}
              type='text'
              placeholder='Enter Name'
              onChange={handleChange}
            />
            <input name='dob'
              value={props['dob']}
              type='date'
              placeholder='Date of Birth'
              onChange={handleChange}
            />
            <input name='designation'
              value={props['designation']}
              type='text'
              placeholder='Designation'
              onChange={handleChange}
            />
          </fieldset>

I want to add one more field for saving images. Maybe call it picture. Sorry, I can't put the entire code but everything else is working fine. I just need to add a field that will browse for image or file and save it with the existing ones.

Body:
I've got a good sample on jsbin that should help you to sort through this. There is an input button that let's you select an image and then submit this to PouchDB. If you are using CouchDB the code is also there to replicate the data to CouchDb. The general idea is to use something like this:

<input type="text" name="field1" />
<input type="text" name="field2" />
<input type="file" name="file" />
<script>
 var field1= window.document.reportform.field1.value;
 var field2= window.document.reportform.field2.value;
 var inputFile = document.querySelector("#file");
 getFile = inputFile.files[0];

 var myDoc = {
   _id: new Date().toISOString(),
   field1: field1,
   field2: field2,
   _attachments: {
     "file": {
       content_type: getFile.type,
       data: getFile
     }
   }
 }

 db.put(myDoc, function(err, response) {
   if (err) {
     return console.log(err);
   } else {
     console.log("Document created Successfully");
   }
});
  db.replicate.to(remote);
}
</script>

JSbin: PouchDB image select and put()

I have not been able to get  to work. I have asked on stackoverflow and the PouchDB Slack channel. Some suggestions have been made but so far I haven't gotten it working.

The PouchDB documentation is very good. PouchDB Attachments Guide


问:
numpy.array operation / method: subtract value of one element from the value of next element
I tried to build the differences from the values of one element [n] to the next element [n+1] in the same numpy.array.

This must be repeated for all n, I expect n-1 result values.

Furthermore I want to avoid using loops, because loops may be a source of errors numbering the elements.

Now I'm looking for an operation like:

```<code>result = array[n+1] - array[n]
</code>```

for all n.

I tried much similar implementations, but I always get some error messages.

How can I make it work?

Body:
I tried to build the differences from the values of one element [n] to the next element [n+1] in the same numpy.array.

This must be repeated for all n, I expect n-1 result values.

Furthermore I want to avoid using loops, because loops may be a source of errors numbering the elements.

Now I'm looking for an operation like:

result = array[n+1] - array[n]

for all n.

I tried much similar implementations, but I always get some error messages.

How can I make it work?

Body:
x = np.array([2,3,1,0])
result = x[:-1] - x[1:]

Output:

[-1,  2,  1]


问:
Volttron not compiling agents
I have a computer where I have recently re-installed Ubuntu and all of volttron. The code (GUI) has been tested on another machine running Volttron and it works fine.

Here's the mystery part: I start Volttron (cd Volttron, . env/bin/activate, volttron -vv -l volttron.log&) so that I am running in the environment. Then I use this line to compile my code so that I can run it:

```<code>./scripts/core/pack_install.sh examples/GUI examples/GUI/config agent.py
</code>```

Normally (on my other machine) this spits out 8-10 lines of response and an agent ID that I can use to run the agent (typically use: volttron-ctl start --name GUI-0.1).

On this new machine, I use that same exact compile line and instead, it spits out two lines following:

VOLTTRON_HOME UNSET setting to /home/sntvizlab/.volttron
  VOLTTRON_HOME=/home/sntvizlab/.volttron

  2017-07-06 09:24:28,841 () volttron.platform.packaging ERROR: no last exception doesn't exist

Anyone have any ideas?

Things I have tried:

1. I have used sudo apt-get update to make sure that all of the components are up to date.

2. I checked the log file using tail -f volttron.log to see if there was anything useful in there.  All there is are the start-up commands successfully completing.

3. I un-installed and re-installed Ubuntu 16.04.2 and subsequently re-installed Volttron and its components to see if it was a problem with my installation.  There is no change in my initial problem.

答:
The most common general error we see while installing agents stems from starting the platform without redirecting stderr and stdout to /dev/null and detaching the VOLTTRON process from the terminal.

One of the libraries we use for agent installation outputs to stdout. If the process is detached and the outputs are not redirected this will result in an error during agent installation.

When you start VOLTTRON use this command line to work around the problem:

```<code>volttron -vv -l volttron.log > /dev/null 2>&1&
</code>```

Let me know if this doesn't resolve the problem.

Title: Volttron not compiling agents

Body:
I have a computer where I have recently re-installed Ubuntu and all of volttron. The code (GUI) has been tested on another machine running Volttron and it works fine.

Here's the mystery part: I start Volttron (cd Volttron, . env/bin/activate, volttron -vv -l volttron.log&) so that I am running in the environment. Then I use this line to compile my code so that I can run it:

./scripts/core/pack_install.sh examples/GUI examples/GUI/config agent.py

Normally (on my other machine) this spits out 8-10 lines of response and an agent ID that I can use to run the agent (typically use: volttron-ctl start --name GUI-0.1).

On this new machine, I use that same exact compile line and instead, it spits out two lines following:

VOLTTRON_HOME UNSET setting to /home/sntvizlab/.volttron
  VOLTTRON_HOME=/home/sntvizlab/.volttron

  2017-07-06 09:24:28,841 () volttron.platform.packaging ERROR: no last exception doesn't exist

Anyone have any ideas?

Things I have tried:

1. I have used sudo apt-get update to make sure that all of the components are up to date.

2. I checked the log file using tail -f volttron.log to see if there was anything useful in there.  All there is are the start-up commands successfully completing.

3. I un-installed and re-installed Ubuntu 16.04.2 and subsequently re-installed Volttron and its components to see if it was a problem with my installation.  There is no change in my initial problem.

Body:
The most common general error we see while installing agents stems from starting the platform without redirecting stderr and stdout to /dev/null and detaching the VOLTTRON process from the terminal.

One of the libraries we use for agent installation outputs to stdout. If the process is detached and the outputs are not redirected this will result in an error during agent installation.

When you start VOLTTRON use this command line to work around the problem:

volttron -vv -l volttron.log > /dev/null 2>&1&

Let me know if this doesn't resolve the problem.


问:
print all possible permutations of r elements in a given integer array of size n in Java
Given an array of size n, generate and print all possible permutations of r elements in array.

For example, if n is 4, input array is [0, 1, 2, 3], and r is 3, then output should be

```<code>[0, 1, 2]
[0, 1, 3]
[0, 2, 1]
[0, 2, 3]
[0, 3, 1]
[0, 3, 2]
[1, 0, 2]
[1, 0, 3]
[1, 2, 0]
[1, 2, 3]
[1, 3, 0]
[1, 3, 2]
[2, 0, 1]
[2, 0, 3]
[2, 1, 0]
[2, 1, 3]
[2, 3, 0]
[2, 3, 1]
[3, 0, 1]
[3, 0, 2]
[3, 1, 0]
[3, 1, 2]
[3, 2, 0]
[3, 2, 1]
</code>```

All elements in the input array are integers, from 0 to n-1. How can I use Java to print all possible permutations?

Important: the number of all elements in a single permutation is not always the size of original array. It's less or equal to the size of original array. Additionally, the order of elements in each permutation does matter.

I have written some code when n=4 and r=3. If n = 100 and r = 50, my code will be really ugly. Is there any smart way to do this when parameters are only n and r?

```<code>public static void main(String[] args) {

    // original array
    ArrayList < Integer > items = new ArrayList < > ();

    // all permutations
    ArrayList < ArrayList < Integer >> allPermutations = new ArrayList < ArrayList < Integer >> ();

    // define the end item of the original array.
    // this is n, suppose it's 4 now.
    int endItem = 4;
    for (int i = 0; i < endItem; i++) {
        items.add(i);
    }

    // r means how many elements in each single permutation
    // suppose it's 3 now, i have to write for-loop three times
    // if r is 100, i have to write for-loop 100 times

    // first of the "r"
    for (int i = 0; i < items.size(); i++) {
        // second of the "r"
        for (int j = 0; j < items.size(); j++) {
            // can't be identical to i
            if (j == i)
                continue;

            // third of the "r"
            for (int k = 0; k < items.size(); k++) {
                // can't be identical to i or j
                if (k == i || k == j)
                    continue;

                // a single permutation
                ArrayList < Integer > singlePermutation = new ArrayList < > ();
                singlePermutation.add(items.get(i));
                singlePermutation.add(items.get(j));
                singlePermutation.add(items.get(k));

                // all permutations
                allPermutations.add(singlePermutation);

            }
        }
    }
    for (ArrayList < Integer > permutation: allPermutations) {
        System.out.println(permutation);
    }
    System.out.println(allPermutations.size());

}
</code>```

答:
Moved solution from question to answer:

Solution:

Thanks to older coder, I managed to find the solution.

```<code>public class PermutationTest10 {
    // a is the original array
    // k is the number of elements in each permutation
    public static ArrayList<ArrayList<Integer>> choose(ArrayList<Integer> a, int k) {
        ArrayList<ArrayList<Integer>> allPermutations = new ArrayList<ArrayList<Integer>>();
        enumerate(a, a.size(), k, allPermutations);
        return allPermutations;
    }

  // a is the original array
    // n is the array size
    // k is the number of elements in each permutation
    // allPermutations is all different permutations
    private static void enumerate(ArrayList<Integer> a, int n, int k, ArrayList<ArrayList<Integer>> allPermutations) {
        if (k == 0) {
            ArrayList<Integer> singlePermutation = new ArrayList<Integer>();
            for (int i = n; i < a.size(); i++){
                singlePermutation.add(a.get(i));
            }
            allPermutations.add(singlePermutation);
            return;
        }

      for (int i = 0; i < n; i++) {
            swap(a, i, n-1);
            enumerate(a, n-1, k-1, allPermutations);
            swap(a, i, n-1);
        }
    }

  // helper function that swaps a.get(i) and a.get(j)
    public static void swap(ArrayList<Integer> a, int i, int j) {
        Integer temp = a.get(i);
        a.set(i, a.get(j));
        a.set(j, temp);
    }

  // sample client
    public static void main(String[] args) {

      // n is the end item of the array.
        // if n = 5, the array is [0, 1, 2, 3, 4, 5]
        // k is the number of elements of each permutation.
        int n =5;
        int k =3;

      // create original array
        ArrayList<Integer> elements = new ArrayList<> ();
        for (int i =0; i < n; i ++){
            elements.add(i);
        }

      ArrayList<Integer> a = new ArrayList<> ();
        for (int i = 0; i < n; i ++){
            a.add(elements.get(i));
        }
        System.out.println(choose(a, k));
    }
}
</code>```

Body:
Given an array of size n, generate and print all possible permutations of r elements in array.

For example, if n is 4, input array is [0, 1, 2, 3], and r is 3, then output should be

[0, 1, 2]
[0, 1, 3]
[0, 2, 1]
[0, 2, 3]
[0, 3, 1]
[0, 3, 2]
[1, 0, 2]
[1, 0, 3]
[1, 2, 0]
[1, 2, 3]
[1, 3, 0]
[1, 3, 2]
[2, 0, 1]
[2, 0, 3]
[2, 1, 0]
[2, 1, 3]
[2, 3, 0]
[2, 3, 1]
[3, 0, 1]
[3, 0, 2]
[3, 1, 0]
[3, 1, 2]
[3, 2, 0]
[3, 2, 1]

All elements in the input array are integers, from 0 to n-1. How can I use Java to print all possible permutations?

Important: the number of all elements in a single permutation is not always the size of original array. It's less or equal to the size of original array. Additionally, the order of elements in each permutation does matter.

I have written some code when n=4 and r=3. If n = 100 and r = 50, my code will be really ugly. Is there any smart way to do this when parameters are only n and r?

public static void main(String[] args) {

    // original array
    ArrayList < Integer > items = new ArrayList < > ();

    // all permutations
    ArrayList < ArrayList < Integer >> allPermutations = new ArrayList < ArrayList < Integer >> ();

    // define the end item of the original array.
    // this is n, suppose it's 4 now.
    int endItem = 4;
    for (int i = 0; i < endItem; i++) {
        items.add(i);
    }

    // r means how many elements in each single permutation
    // suppose it's 3 now, i have to write for-loop three times
    // if r is 100, i have to write for-loop 100 times

    // first of the "r"
    for (int i = 0; i < items.size(); i++) {
        // second of the "r"
        for (int j = 0; j < items.size(); j++) {
            // can't be identical to i
            if (j == i)
                continue;

            // third of the "r"
            for (int k = 0; k < items.size(); k++) {
                // can't be identical to i or j
                if (k == i || k == j)
                    continue;

                // a single permutation
                ArrayList < Integer > singlePermutation = new ArrayList < > ();
                singlePermutation.add(items.get(i));
                singlePermutation.add(items.get(j));
                singlePermutation.add(items.get(k));

                // all permutations
                allPermutations.add(singlePermutation);

            }
        }
    }
    for (ArrayList < Integer > permutation: allPermutations) {
        System.out.println(permutation);
    }
    System.out.println(allPermutations.size());

}

Body:
Moved solution from question to answer:

Solution:

Thanks to older coder, I managed to find the solution.

public class PermutationTest10 {
    // a is the original array
    // k is the number of elements in each permutation
    public static ArrayList<ArrayList<Integer>> choose(ArrayList<Integer> a, int k) {
        ArrayList<ArrayList<Integer>> allPermutations = new ArrayList<ArrayList<Integer>>();
        enumerate(a, a.size(), k, allPermutations);
        return allPermutations;
    }

  // a is the original array
    // n is the array size
    // k is the number of elements in each permutation
    // allPermutations is all different permutations
    private static void enumerate(ArrayList<Integer> a, int n, int k, ArrayList<ArrayList<Integer>> allPermutations) {
        if (k == 0) {
            ArrayList<Integer> singlePermutation = new ArrayList<Integer>();
            for (int i = n; i < a.size(); i++){
                singlePermutation.add(a.get(i));
            }
            allPermutations.add(singlePermutation);
            return;
        }

      for (int i = 0; i < n; i++) {
            swap(a, i, n-1);
            enumerate(a, n-1, k-1, allPermutations);
            swap(a, i, n-1);
        }
    }

  // helper function that swaps a.get(i) and a.get(j)
    public static void swap(ArrayList<Integer> a, int i, int j) {
        Integer temp = a.get(i);
        a.set(i, a.get(j));
        a.set(j, temp);
    }

  // sample client
    public static void main(String[] args) {

      // n is the end item of the array.
        // if n = 5, the array is [0, 1, 2, 3, 4, 5]
        // k is the number of elements of each permutation.
        int n =5;
        int k =3;

      // create original array
        ArrayList<Integer> elements = new ArrayList<> ();
        for (int i =0; i < n; i ++){
            elements.add(i);
        }

      ArrayList<Integer> a = new ArrayList<> ();
        for (int i = 0; i < n; i ++){
            a.add(elements.get(i));
        }
        System.out.println(choose(a, k));
    }
}


问:
What is the C++ equivalent for the CRT?
I am new to C++, but I have worked with C before.

A program written in C must be linked with the CRT (in Windows, it is the file libcmt.lib) which contains the C functions (for example: printf()).

But I am wondering, is there such a thing as "C++RT" (as opposed to CRT), I mean where are the C++ functions and classes (for example: std::ofstream) stored.

And I have another question, if I used some C functions (for example: printf()), will my C++ program be linked with both the CRT and the "C++RT", or does the "C++RT" contains the CRT?

答:
This depends on an exact implementation of C++ standard library  you are using.

GCC ships with libstdc++ and your program is automatically linked against libstdc++*.so* or libstdc++*.dll* (filename may vary depending on distribution, build options and version used)

Clang/LLVM ships with libc++ and libc++*.so* on Linux and OS X, but uses Visual C++ library on Windows.

Microsoft Visual C++ links against one of the libcp*.lib or mscp*.lib (and associated .dll) depending on configuration (link).

Note that it is often possible to use non-default Standard library implementation. For example Clang can use either libstdc++ or libc++ on Linux. Intel compiler uses Microsoft library on Windows and libstdc++ on Linux. There are (were) also implementations that are not associated with a particular compiler, like STLport.

Title: What is the C++ equivalent for the CRT?


问:
Get the export value of a checkbox using iTextSharp
I'm working on dynamically filling in the fields on a pdf document using ITextSharp.  I'd like to be able to determine the "export value" of the checkbox is from the codebehind in order to determine what value to send to this checkbox if it should be checked.  Most of the documents I've worked with in the past had the same export value for every check box but the one I'm currently working with varies from checkbox to checkbox.  I could go through all of the text boxes and make them consistent but it would save a lot of time in the future if I could just determine what the export value of these checkboxes are at runtime and set them accordingly.

Thanks in advance!

I tried to implement the solution below in C# and ended up with the following code:

```<code> public string GetCheckBoxExportValue(AcroFields pdfDocument, string checkBoxFieldName)
    {
        AcroFields.Item item = pdfDocument.GetFieldItem(checkBoxFieldName);
        if (item.values.Count > 0)
        {
            PdfDictionary valueDict = item.GetValue(0);

            PdfDictionary appearanceDict = valueDict.GetAsDict(PdfName.AP);

            // if there's an appearance dict at all, one key will be "Off", and the other
            // will be the export value... there should only be two.
            if (appearanceDict != null)
            {

                foreach (PdfName curKey in appearanceDict.Keys)
                {
                    if (!PdfName.OFF.Equals(curKey))
                    {
                        return curKey.ToString(); // string will have a leading '/' character
                    }
                }
            }

            // if that doesn't work, there might be an /AS key, whose value is a name with
            // the export value, again with a leading '/'
            PdfName curVal = valueDict.GetAsName(PdfName.AS);
            if (curVal != null)
            {
                return curVal.ToString();
            }

        }
        //return null if you get this far
            return null;

    }
</code>```

This just returns "/D" every single time.  I'm not sure if the approach needs to be different in C# or if I'm just missing something.

答:
Okay, you need to check the low-level PDF objects for the appropriate values.  You can look up said values in the PDF Reference (chapter 12: Interactive Features, section 7: Interactive Forms).

In particular (and in Java):

```<code>AcroFields.Item item = acroFields.getFieldItem(fldName);
PdfDictionary valueDict = item.getValue(0);

PdfDictionary appearanceDict = valueDict .getAsDict(PdfName.AP);

if (appearanceDict != null) {
  PdfDictionary normalAppearances = appearanceDict.getAsDict(PdfName.N);
  // /D is for the "down" appearances.

  // if there are normal appearances, one key will be "Off", and the other
  // will be the export value... there should only be two.
  if (normalAppearances != null) {
    Set<PdfName> keys = normalAppearances .getKeys();
    for (PdfName curKey : keys) {
      if (!PdfName.OFF.equals(curKey)) {
        return curKey.toString(); // string will have a leading '/' character
      }
    }
  }

}
// if that doesn't work, there might be an /AS key, whose value is a name with
// the export value, again with a leading '/'
PdfName curVal = valueDict.getAsName(PdfName.AS);
if (curVal != null) {
  return curVal.toString();
}
</code>```

Something like that.  The usual "I just wrote this in the edit box here" provisions apply, but that should be good to go.  I write a distressingly large amount of low level iText code.

Body:
I'm working on dynamically filling in the fields on a pdf document using ITextSharp.  I'd like to be able to determine the "export value" of the checkbox is from the codebehind in order to determine what value to send to this checkbox if it should be checked.  Most of the documents I've worked with in the past had the same export value for every check box but the one I'm currently working with varies from checkbox to checkbox.  I could go through all of the text boxes and make them consistent but it would save a lot of time in the future if I could just determine what the export value of these checkboxes are at runtime and set them accordingly.

Thanks in advance!

I tried to implement the solution below in C# and ended up with the following code:

 public string GetCheckBoxExportValue(AcroFields pdfDocument, string checkBoxFieldName)
    {
        AcroFields.Item item = pdfDocument.GetFieldItem(checkBoxFieldName);
        if (item.values.Count > 0)
        {
            PdfDictionary valueDict = item.GetValue(0);

            PdfDictionary appearanceDict = valueDict.GetAsDict(PdfName.AP);

            // if there's an appearance dict at all, one key will be "Off", and the other
            // will be the export value... there should only be two.
            if (appearanceDict != null)
            {

                foreach (PdfName curKey in appearanceDict.Keys)
                {
                    if (!PdfName.OFF.Equals(curKey))
                    {
                        return curKey.ToString(); // string will have a leading '/' character
                    }
                }
            }

            // if that doesn't work, there might be an /AS key, whose value is a name with
            // the export value, again with a leading '/'
            PdfName curVal = valueDict.GetAsName(PdfName.AS);
            if (curVal != null)
            {
                return curVal.ToString();
            }

        }
        //return null if you get this far
            return null;

    }

This just returns "/D" every single time.  I'm not sure if the approach needs to be different in C# or if I'm just missing something.

Body:
Okay, you need to check the low-level PDF objects for the appropriate values.  You can look up said values in the PDF Reference (chapter 12: Interactive Features, section 7: Interactive Forms).

In particular (and in Java):

AcroFields.Item item = acroFields.getFieldItem(fldName);
PdfDictionary valueDict = item.getValue(0);

PdfDictionary appearanceDict = valueDict .getAsDict(PdfName.AP);

if (appearanceDict != null) {
  PdfDictionary normalAppearances = appearanceDict.getAsDict(PdfName.N);
  // /D is for the "down" appearances.

  // if there are normal appearances, one key will be "Off", and the other
  // will be the export value... there should only be two.
  if (normalAppearances != null) {
    Set<PdfName> keys = normalAppearances .getKeys();
    for (PdfName curKey : keys) {
      if (!PdfName.OFF.equals(curKey)) {
        return curKey.toString(); // string will have a leading '/' character
      }
    }
  }

}
// if that doesn't work, there might be an /AS key, whose value is a name with
// the export value, again with a leading '/'
PdfName curVal = valueDict.getAsName(PdfName.AS);
if (curVal != null) {
  return curVal.toString();
}

Something like that.  The usual "I just wrote this in the edit box here" provisions apply, but that should be good to go.  I write a distressingly large amount of low level iText code.


问:
UILabel with two different color text
How can i have a UILabel with two different colors for the font? I will have text in two different strings and i want to make text with first string as red and second as green. The length of both the string is variable.

答:
Swift 4

(Note: notation for attributed string key is changed in swift 4)

Here is an extension for NSMutableAttributedString, that add/set color on string/text.

```<code>extension NSMutableAttributedString {

    func setColor(color: UIColor, forText stringValue: String) {
        let range: NSRange = self.mutableString.range(of: stringValue, options: .caseInsensitive)
        self.addAttribute(NSAttributedStringKey.foregroundColor, value: color, range: range)
    }

}
</code>```

Now, try above extension with UILabel and see result

```<code>let label = UILabel()
label.frame = CGRect(x: 40, y: 100, width: 280, height: 200)
let red = "red"
let blue = "blue"
let green = "green"
let stringValue = "\(red)\n\(blue)\n&\n\(green)"
label.textColor = UIColor.lightGray
label.numberOfLines = 0
let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: stringValue)
attributedString.setColor(color: UIColor.red, forText: red)   // or use direct value for text "red"
attributedString.setColor(color: UIColor.blue, forText: blue)   // or use direct value for text "blue"
attributedString.setColor(color: UIColor.green, forText: green)   // or use direct value for text "green"
label.font = UIFont.systemFont(ofSize: 26)
label.attributedText = attributedString
self.view.addSubview(label)
</code>```

Here is solution in Swift 3:

```<code>extension NSMutableAttributedString {
        func setColorForText(textToFind: String, withColor color: UIColor) {
         let range: NSRange = self.mutableString.range(of: textToFind, options: .caseInsensitive)
          if range != nil {
            self.addAttribute(NSForegroundColorAttributeName, value: color, range: range)
          }
        }

}

func multicolorTextLabel() {
        var string: NSMutableAttributedString = NSMutableAttributedString(string: "red\nblue\n&\ngreen")
        string.setColorForText(textToFind: "red", withColor: UIColor.red)
        string.setColorForText(textToFind: "blue", withColor: UIColor.blue)
        string.setColorForText(textToFind: "green", withColor: UIColor.green)
        labelObject.attributedText = string
    }
</code>```

Result:

Title: UILabel with two different color text

Body:
Swift 4

(Note: notation for attributed string key is changed in swift 4)

Here is an extension for NSMutableAttributedString, that add/set color on string/text.

extension NSMutableAttributedString {

    func setColor(color: UIColor, forText stringValue: String) {
        let range: NSRange = self.mutableString.range(of: stringValue, options: .caseInsensitive)
        self.addAttribute(NSAttributedStringKey.foregroundColor, value: color, range: range)
    }

}

Now, try above extension with UILabel and see result

let label = UILabel()
label.frame = CGRect(x: 40, y: 100, width: 280, height: 200)
let red = "red"
let blue = "blue"
let green = "green"
let stringValue = "\(red)\n\(blue)\n&\n\(green)"
label.textColor = UIColor.lightGray
label.numberOfLines = 0
let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: stringValue)
attributedString.setColor(color: UIColor.red, forText: red)   // or use direct value for text "red"
attributedString.setColor(color: UIColor.blue, forText: blue)   // or use direct value for text "blue"
attributedString.setColor(color: UIColor.green, forText: green)   // or use direct value for text "green"
label.font = UIFont.systemFont(ofSize: 26)
label.attributedText = attributedString
self.view.addSubview(label)

Here is solution in Swift 3:

extension NSMutableAttributedString {
        func setColorForText(textToFind: String, withColor color: UIColor) {
         let range: NSRange = self.mutableString.range(of: textToFind, options: .caseInsensitive)
          if range != nil {
            self.addAttribute(NSForegroundColorAttributeName, value: color, range: range)
          }
        }

}

func multicolorTextLabel() {
        var string: NSMutableAttributedString = NSMutableAttributedString(string: "red\nblue\n&\ngreen")
        string.setColorForText(textToFind: "red", withColor: UIColor.red)
        string.setColorForText(textToFind: "blue", withColor: UIColor.blue)
        string.setColorForText(textToFind: "green", withColor: UIColor.green)
        labelObject.attributedText = string
    }

Result:


问:
parent_id a foreign key(self reference) and null?
Going through Bill Karwin book “SQL Antipatterns”, chapter 3, Naive Trees (adjacency table, parent-child relationship) there is an example for a comment table.

```<code>CREATE TABLE Comments (
comment_id SERIAL PRIMARY KEY,
parent_id BIGINT UNSIGNED,
comment TEXT NOT NULL,
FOREIGN KEY (parent_id) REFERENCES Comments(comment_id)
);
</code>```

Sample data

```<code>| comment_id | parent_id | comments
|------------| ----------|-------------------------------------
|1           | NULL      |What’s the cause of this bug?
|2           | 1         |I think it's a null pointer
|3           | 2         |No, I checked for that
|4           | 1         |We need to check for invalid input
|5           | 4         |Yes,that's a bug
|6           | 4         |Yes, please add a check
|7           | 6         |That fixed it
</code>```

The table has a comment_id, parent_id and a comment column. The parent_id is a foreign key referring to the comment_id.

The comment_id auto increment starting from 1.

Question.

If parent_id is supposed to be a foreign key which refers to the comment_id then how come the row with the comment_id = 1 have parent_id null/0 when the purpose of having a foreign key is to ensure referential integrity.

Note: I created the table as it is and tried entering the data and got this error

#1452 - Cannot add or update a child row: a foreign key constraint fails (`category`.`comments`, CONSTRAINT `comments_ibfk_1` FOREIGN KEY (`parent_id`) REFERENCES `comments` (`comment_id`))

答:
Collecting some conclusions from the comments above in this CW answer.

The parent_id is NULL in this table for a "root" node, which is at the top of the tree and therefore has no parent.

Read https://dev.mysql.com/doc/refman/5.7/en/null-values.html: Be aware that the NULL value is different from values such as 0 for numeric types or the empty string for string types. For more information, see Section “Problems with NULL Values”.

Also be aware that the keyword NULL is not the same thing as the literal string with the word 'NULL'.

Read https://dev.mysql.com/doc/refman/5.7/en/numeric-type-overview.html: In MySQL SERIAL is an alias for BIGINT UNSIGNED NOT NULL AUTO_INCREMENT UNIQUE.

Body:
Going through Bill Karwin book “SQL Antipatterns”, chapter 3, Naive Trees (adjacency table, parent-child relationship) there is an example for a comment table.

CREATE TABLE Comments (
comment_id SERIAL PRIMARY KEY,
parent_id BIGINT UNSIGNED,
comment TEXT NOT NULL,
FOREIGN KEY (parent_id) REFERENCES Comments(comment_id)
);

Sample data

| comment_id | parent_id | comments
|------------| ----------|-------------------------------------
|1           | NULL      |What’s the cause of this bug?
|2           | 1         |I think it's a null pointer
|3           | 2         |No, I checked for that
|4           | 1         |We need to check for invalid input
|5           | 4         |Yes,that's a bug
|6           | 4         |Yes, please add a check
|7           | 6         |That fixed it

The table has a comment_id, parent_id and a comment column. The parent_id is a foreign key referring to the comment_id.

The comment_id auto increment starting from 1.

Question.

If parent_id is supposed to be a foreign key which refers to the comment_id then how come the row with the comment_id = 1 have parent_id null/0 when the purpose of having a foreign key is to ensure referential integrity.

Note: I created the table as it is and tried entering the data and got this error

#1452 - Cannot add or update a child row: a foreign key constraint fails (`category`.`comments`, CONSTRAINT `comments_ibfk_1` FOREIGN KEY (`parent_id`) REFERENCES `comments` (`comment_id`))


问:
Why is it bad to do things in if conditions
Today I discovered a code block in a code review that seamed weird to me but I could't find an objective reason why this code looks weird to me.

The code looks like this (it's PHP)

```<code>    // inside a for loop
    if( $thing->isGood() === true && saveThing($thing) ) {
      $successfulSavedCount++;
    }
    // for end

    function saveThing($thing) {
      // this method persists $thing to the database
    }
</code>```

Checking if $this->isGood() === true is fine for me but calling a method that does something feels wrong to me.

A long time ago I read somewhere that doing things in conditions is bad style but I can't remember why it is bad style.

Maybe someone of you can explain why it is bad (or fine)?

答:
In most instances, doing things within a condition is just bad style, for it can be hard to read and maintain later on. There is nothing wrong with this though, as it is permitted by the language. The most convincing reason to avoid overly complicated condition statements are side effects. Consider the code below.

```<code>$globalVariable = true;
....
if(checkVariable() && changeVariable()){
    do stuff....
}
function checkVariable(){
    return $globalVariable;
}
function changeVariable(){
    $globalVariable = false;
    return true; //Marking success
}
</code>```

This if-statement would execute as the conditions, in order, are all true. But adding && checkVariable() to the conditions would make it false, because of the side effect of changeVariable() modifying the behavior of checkVariable(). This then means checkVariable() holds two values, which is unintuitive and bad coding practice, but valid here. The rule of thumb is to have functions/methods execute before the condition and store the results in variable to use in the condition, to avoid the ambiguity.

Body:
Today I discovered a code block in a code review that seamed weird to me but I could't find an objective reason why this code looks weird to me.

The code looks like this (it's PHP)

    // inside a for loop
    if( $thing->isGood() === true && saveThing($thing) ) {
      $successfulSavedCount++;
    }
    // for end

    function saveThing($thing) {
      // this method persists $thing to the database
    }

Checking if $this->isGood() === true is fine for me but calling a method that does something feels wrong to me.

A long time ago I read somewhere that doing things in conditions is bad style but I can't remember why it is bad style.

Maybe someone of you can explain why it is bad (or fine)?

Body:
In most instances, doing things within a condition is just bad style, for it can be hard to read and maintain later on. There is nothing wrong with this though, as it is permitted by the language. The most convincing reason to avoid overly complicated condition statements are side effects. Consider the code below.

$globalVariable = true;
....
if(checkVariable() && changeVariable()){
    do stuff....
}
function checkVariable(){
    return $globalVariable;
}
function changeVariable(){
    $globalVariable = false;
    return true; //Marking success
}

This if-statement would execute as the conditions, in order, are all true. But adding && checkVariable() to the conditions would make it false, because of the side effect of changeVariable() modifying the behavior of checkVariable(). This then means checkVariable() holds two values, which is unintuitive and bad coding practice, but valid here. The rule of thumb is to have functions/methods execute before the condition and store the results in variable to use in the condition, to avoid the ambiguity.


问:
WPF MainWindow to display other pages
I am trying to create a Main Window that will have a Header for navigation/buttons, and a footer for displaying information.
(similar to the top and bottom bars on StackOverflow.com)

What is the best way to make the Main Window function as a container that could display any page in between the header/footer?

答:
I would create a 3 row Grid, with the center item being a ContentControl.  Bind it to a CurrentPage property on your view model.

Create a Base Page class, and subclass it for each page of data you want to display.  This subclass is also the viewmodel for each individual page.

Add a DataTemplate for each subclass of Page for the ContentControl to use, making sure to specify the Type attribute (This is what physically attaches the page type to the UI based on the CurrentPage property).  The content of the DataTemplate should be a UserControl that contains the UI for each page type.

Now when you want to change pages, just set CurrentPage to an instance of the page you want, and it will automatically change.

This pattern will keep each page's UI separate from all the other, and gives them a strong view model (the Page subclass).  It allows for super easy changing of pages. and follows the MVVM pattern nicely.  You can even load all your pages in to a list that you present to the user. With a little more binding the user selecting a page can flow right in to the page change behavior with very little work.

Title: WPF MainWindow to display other pages


问:
How to get specific batch of rows of table using eloquent laravel 5.3?
I'm making a chat app using laravel. There is a button in top of the chat box which if it is pressed the 30 last messages before the last previous messages in the box are loaded to the box. I know how to get 30 last messages (take methode) from table but don't know how do it for next 30 last messages.
Can anyone help me please?

This is Message table columns:

```<code>content | from_id | to_id | created_at | users_id
 ------- --------- ------- ------------ ---------
  hello |   39    |   12  |  7/6/2017  |  39:12
</code>```

答:
Hi i believe you can do this in laravel very easily

```<code>YourModel::paginate(30);
</code>```

with this you can get data in paginated form and you dont have to use take method

Body:
I'm making a chat app using laravel. There is a button in top of the chat box which if it is pressed the 30 last messages before the last previous messages in the box are loaded to the box. I know how to get 30 last messages (take methode) from table but don't know how do it for next 30 last messages.
Can anyone help me please?

This is Message table columns:

content | from_id | to_id | created_at | users_id
 ------- --------- ------- ------------ ---------
  hello |   39    |   12  |  7/6/2017  |  39:12

Body:
Hi i believe you can do this in laravel very easily

YourModel::paginate(30);

with this you can get data in paginated form and you dont have to use take method


问:
Links are firing after jQuery sortables is stopped
My sortable list is a connected list with a bunch of links. The links should not fire when the user is sorting the list or after they let go of the mouse to stop sorting. With the following code, the links are not fired when sorted within the same list.  However, when you transfer the item over to the connected list then the link is clicked.  How can I prevent this?</p>

```<code>    a("app_link:not(.ui-sortable-helper)").live("click", function () {

    });
</code>```

答: Updating from jQuery UI 1.7.2 to 1.8+ fixed this issue.</p>

Body:
My sortable list is a connected list with a bunch of links. The links should not fire when the user is sorting the list or after they let go of the mouse to stop sorting. With the following code, the links are not fired when sorted within the same list.  However, when you transfer the item over to the connected list then the link is clicked.  How can I prevent this?

    a("app_link:not(.ui-sortable-helper)").live("click", function () {

    });


问:
Update textbox with AJAX
When a dropdown's value changes, I need the values of two textboxes to change, based on the new value of the dropdown, without refreshing the page.

This should be dead easy, but I'm having trouble figuring out what makes AJAX tick. I seem to be able to get the value, but I can't set the textbox.

This similar question didn't help me. Neither did this.

JavaScript:

```<code>// Dropdown ID = PatientID, textbox ID = DoB
var patient = $("#PatientID");
patient.change(function () {
    var newDob;
    $.ajax({
        url: '@(Url.Action("PatientDob"))?patientId=' + patient.val(),
        type: "GET",
        success: function (result) {
            // Displays correct result
            alert(result);
            newDob = result;
        },
        error: function (xhr, status, err) {
            alert(err);
        }
    });
    // Causes the box to become blank, HTML value attribute doesn't change
    $("#DoB").val(newDob);
});
</code>```

Controller:

```<code>[HttpGet]
public string PatientDob(int patientId)
{
    return db.Patients.Find(patientId).DateOfBirth.ToString("MM/dd/yyyy");
}
</code>```

答:
try doing this. and please check if the textbox is pure html input or any plugin generated textbox. if second one, you have to check with the plugin to refresh with new content.</p>

```<code>// Dropdown ID = PatientID, textbox ID = DoB
var patient = $("#PatientID");
patient.change(function () {
    var newDob;
    $.ajax({
        url: '@(Url.Action("PatientDob"))?patientId=' + patient.val(),
        type: "GET",
        success: function (result) {
            // Displays correct result
            $("#DoB").val(result);
        },
        error: function (xhr, status, err) {
            alert(err);
        }
    });
    // Causes the box to become blank, HTML value attribute doesn't change

});
</code>```

ContentLicense: CC BY-SA 4.0

Title: Update textbox with AJAX

Body:
When a dropdown's value changes, I need the values of two textboxes to change, based on the new value of the dropdown, without refreshing the page.

This should be dead easy, but I'm having trouble figuring out what makes AJAX tick. I seem to be able to get the value, but I can't set the textbox.

This similar question didn't help me. Neither did this.

JavaScript:

// Dropdown ID = PatientID, textbox ID = DoB
var patient = $("#PatientID");
patient.change(function () {
    var newDob;
    $.ajax({
        url: '@(Url.Action("PatientDob"))?patientId=' + patient.val(),
        type: "GET",
        success: function (result) {
            // Displays correct result
            alert(result);
            newDob = result;
        },
        error: function (xhr, status, err) {
            alert(err);
        }
    });
    // Causes the box to become blank, HTML value attribute doesn't change
    $("#DoB").val(newDob);
});

Controller:

[HttpGet]
public string PatientDob(int patientId)
{
    return db.Patients.Find(patientId).DateOfBirth.ToString("MM/dd/yyyy");
}

Body:
try doing this. and please check if the textbox is pure html input or any plugin generated textbox. if second one, you have to check with the plugin to refresh with new content.

// Dropdown ID = PatientID, textbox ID = DoB
var patient = $("#PatientID");
patient.change(function () {
    var newDob;
    $.ajax({
        url: '@(Url.Action("PatientDob"))?patientId=' + patient.val(),
        type: "GET",
        success: function (result) {
            // Displays correct result
            $("#DoB").val(result);
        },
        error: function (xhr, status, err) {
            alert(err);
        }
    });
    // Causes the box to become blank, HTML value attribute doesn't change

});


问:
Microsoft Access Query
I have one settings table that is storing different setting keys for a app built using Microsoft Access
One of the settings key drives how many records should be seen in a dropdown list
The query behind the list is similar to the one below:

```<code>Select Top 3 id, name FROM tblRegular
</code>```

Now, I want to achieve something like this:

```<code>Select Top (Select keyValue FROM tblSettings WHERE key="rowNumber") id, name FROM tblRegular
</code>```

But, using it like this does not work as it fires errors
Could someone tell me if it can be done?

EDIT: The table structure looks similar to the one below:
tblRegular:

```<code>id  | name
1     'A'
2     'B'
3     'C'
</code>```

tblSettings:

```<code>id  | key          | keyValue
1     'rowNumber'    2
</code>```

Thank you!

答:
Consider the pure SQL solution using a correlated subquery to calculate a rowCount that is then used in outer query to filter by number of rows:

```<code>SELECT main.id, main.[name]
FROM
   (SELECT t.id, t.[name],
          (SELECT Count(*) FROM tblRegular sub
           WHERE sub.[name] <= t.[name]) AS rowCount
    FROM tblRegular t) AS main
WHERE main.rowCount <= (SELECT Max(s.keyValue) FROM tblSettings s
                        WHERE s.key = 'rowNumber')
</code>```

Alternatively with the domain aggregate, DMax():

```<code>SELECT main.id, main.[name]
FROM
   (SELECT t.id, t.[name],
          (SELECT Count(*) FROM tblRegular sub
           WHERE sub.[name] <= t.[name]) AS rowCount
    FROM tblRegular t) AS main
WHERE main.rowCount <= DMax("keyValue", "tblSettings", "key = 'rowNumber'")
</code>```

Title: Microsoft Access Query

Body:
I have one settings table that is storing different setting keys for a app built using Microsoft Access
One of the settings key drives how many records should be seen in a dropdown list
The query behind the list is similar to the one below:

Select Top 3 id, name FROM tblRegular

Now, I want to achieve something like this:

Select Top (Select keyValue FROM tblSettings WHERE key="rowNumber") id, name FROM tblRegular

But, using it like this does not work as it fires errors
Could someone tell me if it can be done?

EDIT: The table structure looks similar to the one below:
tblRegular:

id  | name
1     'A'
2     'B'
3     'C'

tblSettings:

id  | key          | keyValue
1     'rowNumber'    2

Thank you!

Body:
Consider the pure SQL solution using a correlated subquery to calculate a rowCount that is then used in outer query to filter by number of rows:

SELECT main.id, main.[name]
FROM
   (SELECT t.id, t.[name],
          (SELECT Count(*) FROM tblRegular sub
           WHERE sub.[name] <= t.[name]) AS rowCount
    FROM tblRegular t) AS main
WHERE main.rowCount <= (SELECT Max(s.keyValue) FROM tblSettings s
                        WHERE s.key = 'rowNumber')

Alternatively with the domain aggregate, DMax():

SELECT main.id, main.[name]
FROM
   (SELECT t.id, t.[name],
          (SELECT Count(*) FROM tblRegular sub
           WHERE sub.[name] <= t.[name]) AS rowCount
    FROM tblRegular t) AS main
WHERE main.rowCount <= DMax("keyValue", "tblSettings", "key = 'rowNumber'")


问:
Google Play console reporting crashes from unreleased applications
I would like to share a situation I am facing analysing the new features at Google Play console and try to find a solution for it.

As many of you may already know, Google has released updates at Google Play console and introduced Android vitals. One of the good particularities is that now the session ANRs & Crashes shows all ANRs & crashes collected from Android devices whose users have opted in to automatically share usage and diagnostics data (during phone first setup).

However, I am seeing crash reports from unreleased applications. I mean, from a developer version that hasn't been published yet. Moreover, this crash report came from an application signed with an android-debug key, not my production key. I have looked into the available documentation but I couldn't found details on the filtering for these reports.

It seems harmful and wrong to me using any income data without validating signing as anyone can simply write a short peace of code and start flooding a specific application package name with tons of dummy stacktraces.

Do you know if this is the normal behavior for this new tool ?

答:
As we are interested in publishing only release applications, we may adopt following strategy to get rid of messing up crash reports :

./build.gradle :

```<code>android {
    ...
    defaultConfig {
        applicationId "my.app.package"
        ...
    }
    ...
    buildTypes {
        release {
            ...
        }
        debug {
            ...
            applicationIdSuffix ".dev"
        }
    }
...
}
</code>```

Body:
As we are interested in publishing only release applications, we may adopt following strategy to get rid of messing up crash reports :

./build.gradle :

android {
    ...
    defaultConfig {
        applicationId "my.app.package"
        ...
    }
    ...
    buildTypes {
        release {
            ...
        }
        debug {
            ...
            applicationIdSuffix ".dev"
        }
    }
...
}


问:
Python: ImportError: lxml not found, please install it
I have the following code (in PyCharm (MacOS)):

```<code>import pandas as pd

fiddy_states = pd.read_html('https://simple.wikipedia.org/wiki/List_of_U.S._states')

print(fiddy_states)
</code>```

And I get the following error:

```<code>/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6 /Users/user_name/PycharmProjects/PandasTest/Doc3.py
Traceback (most recent call last):
  File "/Users/user_name/PycharmProjects/PandasTest/Doc3.py", line 9, in <module>
    fiddy_states = pd.read_html('https://simple.wikipedia.org/wiki/List_of_U.S._states')
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/io/html.py", line 906, in read_html
    keep_default_na=keep_default_na)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/io/html.py", line 733, in _parse
    parser = _parser_dispatch(flav)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/io/html.py", line 693, in _parser_dispatch
    raise ImportError("lxml not found, please install it")
ImportError: lxml not found, please install it
</code>```

In Anaconda does appear installed the last version of lxml (3.8.0). Despite of that, I have tried to reinstall it by: 1) writing pip install lxml and 2) downloading the lxml wheel corresponding to my python version (lxml-3.8.0-cp36-cp36m-win_amd64.whl), but in any case all remains the same (in the second case I get that it is not a supported wheel on this platform, even though the version of python is correct (3.6, 64 bits)).

I've read similar questions here (even with the same code above, since it's from a tutorial), but the problem still persists.

答:
Based on the fact that the error is:

```<code>/Library/Frameworks/Python.framework/Versions/<b>3.6</b>/bin/python3.6</code>```

This means that you are working with python-3.6. Now usually the package manager for python-3.x is pip3. So you probably should install it with:

```<code>pip<b>3</b> install lxml</code>```

Body:
I have the following code (in PyCharm (MacOS)):

import pandas as pd

fiddy_states = pd.read_html('https://simple.wikipedia.org/wiki/List_of_U.S._states')

print(fiddy_states)

And I get the following error:

/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6 /Users/user_name/PycharmProjects/PandasTest/Doc3.py
Traceback (most recent call last):
  File "/Users/user_name/PycharmProjects/PandasTest/Doc3.py", line 9, in <module>
    fiddy_states = pd.read_html('https://simple.wikipedia.org/wiki/List_of_U.S._states')
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/io/html.py", line 906, in read_html
    keep_default_na=keep_default_na)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/io/html.py", line 733, in _parse
    parser = _parser_dispatch(flav)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/io/html.py", line 693, in _parser_dispatch
    raise ImportError("lxml not found, please install it")
ImportError: lxml not found, please install it

In Anaconda does appear installed the last version of lxml (3.8.0). Despite of that, I have tried to reinstall it by: 1) writing pip install lxml and 2) downloading the lxml wheel corresponding to my python version (lxml-3.8.0-cp36-cp36m-win_amd64.whl), but in any case all remains the same (in the second case I get that it is not a supported wheel on this platform, even though the version of python is correct (3.6, 64 bits)).

I've read similar questions here (even with the same code above, since it's from a tutorial), but the problem still persists.

Body:
Based on the fact that the error is:

/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6

This means that you are working with python-3.6. Now usually the package manager for python-3.x is pip3. So you probably should install it with:

pip3 install lxml


问:
Install python module psutil in Heroku
I am unable to install psutil by requeriments.txt neither by logging in with heroku run bash command and using the pip install psutil command.

The log is very large, so, I will put the "most important" part of it:

```<code>unable to execute 'gcc': No such file or directory
error: command 'gcc' failed with exit status 1

Command "/app/.heroku/python/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-759b4csi/psutil/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-addox7ji-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-759b4csi/psutil/
</code>```

Can someone help me with this?
I am using python 3.6.0 and pip 9.0.1

答: I used pip freeze > requirements.txt to generate a new requirements and this new file was processed by the deploy tool correctly.

Title: Install python module psutil in Heroku

Body:
I am unable to install psutil by requeriments.txt neither by logging in with heroku run bash command and using the pip install psutil command.

The log is very large, so, I will put the "most important" part of it:

unable to execute 'gcc': No such file or directory
error: command 'gcc' failed with exit status 1

Command "/app/.heroku/python/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-759b4csi/psutil/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-addox7ji-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-759b4csi/psutil/

Can someone help me with this?
I am using python 3.6.0 and pip 9.0.1


问:
How to set canvas origin to center in fabricjs?
When I draw a circle on fabricjs canvas it always appears on bottom right corner even though I set the coordinates to center. How can I make the circle draw  center of the canvas?</p>

```<code>var circle = new fabric.Circle({
         top: 300,
         left: 300,
         radius: 100
});
</code>```

答:
You have centerObject().

```<code>     canvas.add(oImg)
     canvas.centerObject(circle);
     canvas.renderAll();
</code>```

That sets your circle in the center of the canvas.

Body:
When I draw a circle on fabricjs canvas it always appears on bottom right corner even though I set the coordinates to center. How can I make the circle draw  center of the canvas?

var circle = new fabric.Circle({
         top: 300,
         left: 300,
         radius: 100
});

Body:
You have centerObject().

     canvas.add(oImg)
     canvas.centerObject(circle);
     canvas.renderAll();

That sets your circle in the center of the canvas.


答:
You can set drawing origin of the circle object to center, using originX and originY property.

var canvas = new fabric.Canvas('c');

var circle = new fabric.Circle({
   top: 100,
   left: 100,
   radius: 50,
   originX: 'center',
   originY: 'center'
});

canvas.add(circle);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>canvas{border:1px solid #ccc}</code>```

<canvas id="c" width="200" height="200"></canvas>```

Title: How to set canvas origin to center in fabricjs?

Body:
You can set drawing origin of the circle object to center, using originX and originY property.

var canvas = new fabric.Canvas('c');

var circle = new fabric.Circle({
   top: 100,
   left: 100,
   radius: 50,
   originX: 'center',
   originY: 'center'
});

canvas.add(circle);

canvas{border:1px solid #ccc}

<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.14/fabric.min.js"></script>
<canvas id="c" width="200" height="200"></canvas>