问:
Insert a symbol ">" between the characters in a list of strings
I have a column in Excel like this:

```<code>ABC
BCD
BA
</code>```

How can I put the symbols ">" between every letters in the strings? The expected output should be like this:

```<code>A>B>C
B>C>D
B>A
</code>```

Or could we do this in Matlab ?

答:
Here is the working macro code</p>

```<code>Sub gt()

Dim a As Integer, b As String, U(100) As String, J

b = Selection
a = Len(Selection)
Selection.Offset(0, 1).Select

For i = 1 To a

If i <> a Then
J = J & Mid(b, i, 1) & ">"
Else
J = J & Mid(b, i, 1)
End If

Next i

ActiveCell = J

End Sub
</code>```

Body:
I have a column in Excel like this:

ABC
BCD
BA

How can I put the symbols ">" between every letters in the strings? The expected output should be like this:

A>B>C
B>C>D
B>A

Or could we do this in Matlab ?

Body:
Here is the working macro code

Sub gt()

Dim a As Integer, b As String, U(100) As String, J

b = Selection
a = Len(Selection)
Selection.Offset(0, 1).Select

For i = 1 To a

If i <> a Then
J = J & Mid(b, i, 1) & ">"
Else
J = J & Mid(b, i, 1)
End If

Next i

ActiveCell = J

End Sub


来源: stackexchange

问:
Wordpress Category ID vs Eval Issue
Ok this is a little complex. I am creating a plugin, and want to find the category ID from the Post page.

That's the easy part.

What makes it complex is I am doing it within an ob_start (started in a 'template_redirect' action) as I want to edit the full page before it is returned to the browser. Again that is easy enough from the ob_start function.

With the ID returned I want to evaluate some php stored in a sql field. I am trying to do this from within the ob_start function

```<code>$tui_cifp_insertvalue = tui_cifp_evaluate_html($tui_cifp_insertvalue);
</code>```

This calls this

```<code>function tui_cifp_evaluate_html($string) {
return preg_replace_callback("/(<\?php|<\?|< \?php)(.*?)\?>/si",'EvalBuffer', $string);
}
</code>```

Which in turn calls

```<code>function EvalBuffer($string) {
ob_start();
eval("$string[2];");
$ret = ob_get_contents();
ob_end_clean();
return $ret;
}
</code>```

And the php I am trying to evaluate is.

```<code><?php tui_findPostThumbIMG([categoryID],100,100,'categoryintro-thumbnail','','',''); ?>
</code>```

This all works outside the ob_start routine, but here even simple php doesn't work. From within the ob_start routine the plugin breaks and a blank page returns.

So I thought I could evaluate the php before the start of the ob_start and pass the result through a global variable. That works, but at the point this starts using the following, the category ID is not available.

```<code>if ( strpos($_SERVER['REQUEST_URI'], 'wp-admin') === false ) {

global $holdvalue;

$tui_cifp_insertvalue = get_option('tui_cifp_insertvalue');

$categories = get_the_category();
$categoryID = $categories[0]->cat_ID;

$tui_cifp_insertvalue = str_replace("[categoryID]", $categoryID, $tui_cifp_insertvalue);

$holdvalue = tui_cifp_evaluate_html($tui_cifp_insertvalue);

add_action('template_redirect','tui_cifp_ob_start'); //

}
</code>```

The ob_start function

```<code>function tui_cifp_ob_start()
{

ob_start('tui_cifp_templatefilter');

}
</code>```

Ok I am stumped ... any ideas?

I either need to find a hook that executes at the right time so that I have access to the category ID, or I need to work out how to evaluate the php during the ob_start.

Oh ... I guess I should say. What I want to do is replace a tag on a wordpress page with some other information saved in a string, but need to be able to do this once the full page if drawn.

Thanks
Stephen

PS I have asked this on the wordpress forums without a response. Sorry for the cross posting but I am a little desperate.

答:
Im not partial to eval, but this seems to work, with or without the output buffering at the end ...</p>

```<code>function tui_findPostThumbIMG()
{
 echo "hey hey\n";
}

ob_start();
$categoryID = 10;
$tui_cifp_insertvalue = "<?php tui_findPostThumbIMG([categoryID],100,100,'categoryintro-thumbnail','','',''); ?>";
$tui_cifp_insertvalue = str_replace("[categoryID]", $categoryID, $tui_cifp_insertvalue);
$tui_cifp_insertvalue = tui_cifp_evaluate_html($tui_cifp_insertvalue);
echo $tui_cifp_insertvalue;
ob_end_flush();
</code>```

OwnerDisplayName: Stephen Baugh

ContentLicense: CC BY-SA 2.5

Title: Wordpress Category ID vs Eval Issue

Body:
Ok this is a little complex. I am creating a plugin, and want to find the category ID from the Post page.

That's the easy part.

What makes it complex is I am doing it within an ob_start (started in a 'template_redirect' action) as I want to edit the full page before it is returned to the browser. Again that is easy enough from the ob_start function.

With the ID returned I want to evaluate some php stored in a sql field. I am trying to do this from within the ob_start function

$tui_cifp_insertvalue = tui_cifp_evaluate_html($tui_cifp_insertvalue);

This calls this

function tui_cifp_evaluate_html($string) {
return preg_replace_callback("/(<\?php|<\?|< \?php)(.*?)\?>/si",'EvalBuffer', $string);
}

Which in turn calls

function EvalBuffer($string) {
ob_start();
eval("$string[2];");
$ret = ob_get_contents();
ob_end_clean();
return $ret;
}

And the php I am trying to evaluate is.

<?php tui_findPostThumbIMG([categoryID],100,100,'categoryintro-thumbnail','','',''); ?>

This all works outside the ob_start routine, but here even simple php doesn't work. From within the ob_start routine the plugin breaks and a blank page returns.

So I thought I could evaluate the php before the start of the ob_start and pass the result through a global variable. That works, but at the point this starts using the following, the category ID is not available.

if ( strpos($_SERVER['REQUEST_URI'], 'wp-admin') === false ) {

global $holdvalue;

$tui_cifp_insertvalue = get_option('tui_cifp_insertvalue');

$categories = get_the_category();
$categoryID = $categories[0]->cat_ID;

$tui_cifp_insertvalue = str_replace("[categoryID]", $categoryID, $tui_cifp_insertvalue);

$holdvalue = tui_cifp_evaluate_html($tui_cifp_insertvalue);

add_action('template_redirect','tui_cifp_ob_start'); //

}

The ob_start function

function tui_cifp_ob_start()
{

ob_start('tui_cifp_templatefilter');

}

Ok I am stumped ... any ideas?

I either need to find a hook that executes at the right time so that I have access to the category ID, or I need to work out how to evaluate the php during the ob_start.

Oh ... I guess I should say. What I want to do is replace a tag on a wordpress page with some other information saved in a string, but need to be able to do this once the full page if drawn.

Thanks
Stephen

PS I have asked this on the wordpress forums without a response. Sorry for the cross posting but I am a little desperate.

LastEditorDisplayName: Stephen Baugh

Body:
Im not partial to eval, but this seems to work, with or without the output buffering at the end ...

function tui_findPostThumbIMG()
{
 echo "hey hey\n";
}

ob_start();
$categoryID = 10;
$tui_cifp_insertvalue = "<?php tui_findPostThumbIMG([categoryID],100,100,'categoryintro-thumbnail','','',''); ?>";
$tui_cifp_insertvalue = str_replace("[categoryID]", $categoryID, $tui_cifp_insertvalue);
$tui_cifp_insertvalue = tui_cifp_evaluate_html($tui_cifp_insertvalue);
echo $tui_cifp_insertvalue;
ob_end_flush();

OwnerDisplayName: OIS


问:
Having trouble with Bash / Shell While Loop String Comparison
I'm learning scripting to help with my work, and I'm just trying to wrap my head around using while loops.

I want to repeat a question if a user doesn't answer with Yes or No.
Currently I have that working with an if conditional statement, that was easy, but it simply exits the script if the user doesn't answer with y or n.

I've tried various iterations of the below, figured out that I can't use -ne unless it's an integer, but what I can't seem to get right is the string comparison.

I found much better ways to do this online, but it's pointless to copy-paste those if I'm missing something basic about a simple while loop.

```<code>#!/bin/sh

while [ $CONFIRM != "^y"|"^n"] # This is where I'm stuck
do
echo "Please say Yes or No."   # Probably not doing this right either
read CONFIRM                   # Or this
done

if  echo "$CONFIRM" | grep -iq "^n" ; then
echo "Okay, stopping script."
else

#do some cool stuff

fi
</code>```

Any and all advice appreciated.

And the correct answer is...

```<code>#!/bin/bash

shopt -s nocasematch

while ! [[ $CONFIRM =~ ^(y|n) ]]
do
echo "Please say Yes or No."
read CONFIRM
done

echo "Success!"
</code>```

答:
Try something like this:</p>

```<code>while [[ -z $confirm || ( $confirm != y && $confirm != n ) ]]; do
 read confirm
done
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm learning scripting to help with my work, and I'm just trying to wrap my head around using while loops.

I want to repeat a question if a user doesn't answer with Yes or No.
Currently I have that working with an if conditional statement, that was easy, but it simply exits the script if the user doesn't answer with y or n.

I've tried various iterations of the below, figured out that I can't use -ne unless it's an integer, but what I can't seem to get right is the string comparison.

I found much better ways to do this online, but it's pointless to copy-paste those if I'm missing something basic about a simple while loop.

#!/bin/sh

while [ $CONFIRM != "^y"|"^n"] # This is where I'm stuck
do
echo "Please say Yes or No."   # Probably not doing this right either
read CONFIRM                   # Or this
done

if  echo "$CONFIRM" | grep -iq "^n" ; then
echo "Okay, stopping script."
else

#do some cool stuff

fi

Any and all advice appreciated.

And the correct answer is...

#!/bin/bash

shopt -s nocasematch

while ! [[ $CONFIRM =~ ^(y|n) ]]
do
echo "Please say Yes or No."
read CONFIRM
done

echo "Success!"

Body:
Try something like this:

while [[ -z $confirm || ( $confirm != y && $confirm != n ) ]]; do
 read confirm
done

ContentLicense: CC BY-SA 3.0


问:
BizTalk 2013 R2 Cumulative update 2 - not installing adapter pack update
I'm trying to install the BizTalk 2013 R2 Cumulative update 2.
The BizTalk server part is installing correct, but asking for install pack for BizTalk Adapter Pack x86 and x64. I have already installed the LOB.

Can anyone tell why the CU2 is asking to "insert the Microsoft BizTalk Adapter pack disk and click OK", for the Adapter Pack x86 and x64?

答: The reason it's asking your for a CD/DVD is because you don't have the installation package for BizTalk 2013 R2 still mounted on your server. I had the same issue, and it stopped asking for a CD when I mounted the BizTalk installation .iso disc image onto the server I was installing the CU pack on. If you connect the installation software to your current BizTalk server, it will show in the DVD drive under My Computer. Re-running the CU installation afterwards will correctly install the updates. This has worked for both CU2 and CU6. </p>


问:
selenium returning empty text
Following a tutorial to test search functionality on wikipedia using c#. My test keeps failing because the the text from the h1 element im trying to return keeps returning empty. There is definitely text inside the h1 header. Any idea why This element is returning empty when it has text?</p>

```<code>IWebDriver driver = new FirefoxDriver();
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(5));
driver.Navigate().GoToUrl("https://en.wikipedia.org/wiki/Main_Page");

IWebElement searchInput = driver.FindElement(By.Id("searchInput"));
searchInput.SendKeys("Christiaan Barnard");
searchInput.SendKeys(Keys.Enter);

IWebElement firstHeading = driver.FindElement(By.Id("firstHeading"));
Assert.AreEqual("Christiaan Barnard", firstHeading.Text);
driver.Quit();
</code>```

答:
It may be because the element is found, but does not yet have the expected value. The best approach is to wait until the text has the expected value, using WebDriverWait:</p>

```<code>var wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(5));
var result = wait.Until(ExpectedConditions.TextToBePresentInElementLocated(By.Id("firstHeading"), "Christiaan Barnard"));
Assert.IsTrue(result);
</code>```

Title: selenium returning empty text

Body:
Following a tutorial to test search functionality on wikipedia using c#. My test keeps failing because the the text from the h1 element im trying to return keeps returning empty. There is definitely text inside the h1 header. Any idea why This element is returning empty when it has text?

IWebDriver driver = new FirefoxDriver();
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(5));
driver.Navigate().GoToUrl("https://en.wikipedia.org/wiki/Main_Page");

IWebElement searchInput = driver.FindElement(By.Id("searchInput"));
searchInput.SendKeys("Christiaan Barnard");
searchInput.SendKeys(Keys.Enter);

IWebElement firstHeading = driver.FindElement(By.Id("firstHeading"));
Assert.AreEqual("Christiaan Barnard", firstHeading.Text);
driver.Quit();

Body:
It may be because the element is found, but does not yet have the expected value. The best approach is to wait until the text has the expected value, using WebDriverWait:

var wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(5));
var result = wait.Until(ExpectedConditions.TextToBePresentInElementLocated(By.Id("firstHeading"), "Christiaan Barnard"));
Assert.IsTrue(result);


问:
Suggestions for speeding up LEFT JOIN in MySQL
I have a tabled named usr_data with 40,000 or so records that I want to left join with the user's organization data (roughly 1000 records) via a select in a join, obviously this is really slow (up to 150 seconds).

I was wondering if there were any ways to speed this up? Unfortunately this is the speediest query for the sub-select in the join.

My Query

```<code>    SELECT  usr_data.usr_id,usr_data.login,orgus.title FROM usr_data
    LEFT JOIN (
        SELECT object_reference.ref_id,rbac_ua.usr_id,object_data.obj_id,object_data.title
        FROM rbac_ua
        JOIN rbac_fa ON rbac_fa.rol_id = rbac_ua.rol_id
        JOIN object_reference ON rbac_fa.parent = object_reference.ref_id
        JOIN object_data ON object_data.obj_id = object_reference.obj_id
        JOIN object_data role ON role.obj_id = rbac_ua.rol_id
        WHERE object_data.type = 'orgu') as orgus on orgus.usr_id = usr_data.usr_id
    WHERE usr_data.usr_id > 0 AND usr_data.login <> "anonymous"
</code>```

Describe of Query

```<code>+------+-------------+------------------+--------+-----------------------+---------+---------+--------------------------------+------+--------------------------+
| id   | select_type | table            | type   | possible_keys         | key     | key_len | ref                            | rows | Extra                    |
+------+-------------+------------------+--------+-----------------------+---------+---------+--------------------------------+------+--------------------------+
|    1 | SIMPLE      | usr_data         | range  | PRIMARY,i1_idx        | PRIMARY | 4       | NULL                           | 8148 | Using where              |
|    1 | SIMPLE      | rbac_ua          | ref    | PRIMARY,i1_idx,i2_idx | PRIMARY | 4       | ildCPC.usr_data.usr_id         |    2 | Using where; Using index |
|    1 | SIMPLE      | rbac_fa          | ref    | PRIMARY,i1_idx        | PRIMARY | 4       | ildCPC.rbac_ua.rol_id          |    1 | Using where; Using index |
|    1 | SIMPLE      | role             | eq_ref | PRIMARY               | PRIMARY | 4       | ildCPC.rbac_ua.rol_id          |    1 | Using index              |
|    1 | SIMPLE      | object_reference | eq_ref | PRIMARY,i1_idx        | PRIMARY | 4       | ildCPC.rbac_fa.parent          |    1 | Using where              |
|    1 | SIMPLE      | object_data      | eq_ref | PRIMARY,i1_idx        | PRIMARY | 4       | ildCPC.object_reference.obj_id |    1 | Using where              |
+------+-------------+------------------+--------+-----------------------+---------+---------+--------------------------------+------+--------------------------+
</code>```

usr_data table

```<code>+----------------------+---------------+------+-----+---------+-------+
| Field                | Type          | Null | Key | Default | Extra |
+----------------------+---------------+------+-----+---------+-------+
| usr_id               | int(11)       | NO   | PRI | 0       |       |
| login                | varchar(80)   | YES  | MUL | NULL    |       |
| passwd               | varchar(80)   | YES  |     | NULL    |       |
| firstname            | varchar(32)   | YES  |     | NULL    |       |
| lastname             | varchar(32)   | YES  |     | NULL    |       |
| title                | varchar(32)   | YES  |     | NULL    |       |
| gender               | char(1)       | YES  |     | m       |       |
| email                | varchar(80)   | YES  |     | NULL    |       |
</code>```

usr_data indexes

```<code>+----------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table    | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+----------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| usr_data |          0 | PRIMARY  |            1 | usr_id      | A         |       29354 |     NULL | NULL   |      | BTREE      |         |               |
| usr_data |          1 | i1_idx   |            1 | login       | A         |       29354 |     NULL | NULL   | YES  | BTREE      |         |               |
| usr_data |          1 | i1_idx   |            2 | passwd      | A         |       29354 |     NULL | NULL   | YES  | BTREE      |         |               |
| usr_data |          1 | i2_idx   |            1 | ext_account | A         |           2 |     NULL | NULL   | YES  | BTREE      |         |               |
| usr_data |          1 | i2_idx   |            2 | auth_mode   | A         |           4 |     NULL | NULL   | YES  | BTREE      |         |               |
+----------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
</code>```

I've tried to make a temp-table for that SELECT in the LEFT JOIN but it didn't really speed it up any, the query takes up to 150 seconds currently, with a right join it brings it down to about 1 second. (It's the smaller table).

```<code>select * from object_data where type = 'orgu' returns 1058 rows.
</code>```

SHOW CREATE TABLE rbac_ua

```<code>+---------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table   | Create Table                                                                                |
+---------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| rbac_ua | CREATE TABLE `rbac_ua` (
  `usr_id` int(11) NOT NULL DEFAULT '0',
  `rol_id` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`usr_id`,`rol_id`),
  KEY `i1_idx` (`usr_id`),
  KEY `i2_idx` (`rol_id`),
  KEY `rol_id` (`rol_id`,`usr_id`),
  KEY `rol_usr` (`rol_id`,`usr_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ROW_FORMAT=DYNAMIC |
+---------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
</code>```

SHOW CREATE TABLE rbac_fa

```<code>+---------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table   | Create Table                                                                                |
+---------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| rbac_fa | CREATE TABLE `rbac_fa` (
  `rol_id` int(11) NOT NULL DEFAULT '0',
  `parent` int(11) NOT NULL DEFAULT '0',
  `assign` char(1) COLLATE utf8_unicode_ci DEFAULT NULL,
  `protected` char(1) COLLATE utf8_unicode_ci DEFAULT 'n',
  PRIMARY KEY (`rol_id`,`parent`),
  KEY `i1_idx` (`parent`),
  KEY `parent` (`parent`,`rol_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ROW_FORMAT=DYNAMIC |
+---------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
</code>```

SHOW CREATE TABLE object_data

```<code>+-------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table       | Create Table                                                                                |
+-------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| object_data | CREATE TABLE `object_data` (
  `obj_id` int(11) NOT NULL DEFAULT '0',
  `type` char(4) COLLATE utf8_unicode_ci DEFAULT 'none',
  `title` char(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `description` char(128) COLLATE utf8_unicode_ci DEFAULT NULL,
  `owner` int(11) NOT NULL DEFAULT '0',
  `create_date` datetime DEFAULT NULL,
  `last_update` datetime DEFAULT NULL,
  `import_id` char(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`obj_id`),
  KEY `i1_idx` (`type`),
  KEY `i2_idx` (`title`),
  KEY `i4_idx` (`import_id`),
  FULLTEXT KEY `i3_idx` (`title`,`description`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ROW_FORMAT=DYNAMIC |
+-------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
</code>```

SHOW CREATE TABLE object_reference

```<code>+------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table            | Create Table                                                                                |
+------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| object_reference | CREATE TABLE `object_reference` (
  `ref_id` int(11) NOT NULL DEFAULT '0',
  `obj_id` int(11) NOT NULL DEFAULT '0',
  `deleted` datetime DEFAULT NULL,
  PRIMARY KEY (`ref_id`),
  KEY `i1_idx` (`obj_id`),
  KEY `i2_idx` (`deleted`),
  KEY `obj_id` (`obj_id`,`ref_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ROW_FORMAT=DYNAMIC |
+------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
</code>```

If i'm missing any useful information, please let me know.

Thanks in Advance.

答:
By using LEFT JOIN you are demanding a large result set, containing a row for every item that matches your WHERE usr_data whatever clauses. That will take time to push to your client software even if the query planner does a great job.

usr_data.usr_id > 0 seems redundant because your usr_id column seems to be an autoincrement column. Are all the values above zero?

The subselect is definitely a performance hog.

Mr. Thrasher is close, I think.  The problem is mentioning a LEFT JOINed table's colum in a WHERE clause: that converts the LEFT JOIN to a straight JOIN.

Try this to see if you get appropriate results. I don't understand your schema so there's a little guesswork here.

```<code>     SELECT usr_data.usr_id, usr_data.login, object_data.title
       FROM usr_data
  LEFT JOIN rbac_ua ON rbac_ua.usr_id = usr_data.usr_id
  LEFT JOIN rbac_fa ON rbac_fa.rol_id = rbac_ua.rol_id
  LEFT JOIN object_reference ON rbac_fa.parent = object_reference.ref_id
  LEFT JOIN object_data   ON object_data.obj_id = object_reference.obj_id
                         AND object_data.type = 'orgu'
  LEFT JOIN object_data role ON role.obj_id = rbac_ua.rol_id
      WHERE usr_data.login <> 'anonymous'
</code>```

Notice how object_data.type = 'orgu' ended up in the ON clause. (Yes, ON clauses can contain the same sort of stuff as WHERE clauses!) That keeps it from making  LEFT JOIN into a straight JOIN.

I'm not sure the point of this line.

```<code>  LEFT JOIN object_data role ON role.obj_id = rbac_ua.rol_id
</code>```

That table doesn't seem to contribute to your result set.

Body:
I have a tabled named usr_data with 40,000 or so records that I want to left join with the user's organization data (roughly 1000 records) via a select in a join, obviously this is really slow (up to 150 seconds).

I was wondering if there were any ways to speed this up? Unfortunately this is the speediest query for the sub-select in the join.

My Query

    SELECT  usr_data.usr_id,usr_data.login,orgus.title FROM usr_data
    LEFT JOIN (
        SELECT object_reference.ref_id,rbac_ua.usr_id,object_data.obj_id,object_data.title
        FROM rbac_ua
        JOIN rbac_fa ON rbac_fa.rol_id = rbac_ua.rol_id
        JOIN object_reference ON rbac_fa.parent = object_reference.ref_id
        JOIN object_data ON object_data.obj_id = object_reference.obj_id
        JOIN object_data role ON role.obj_id = rbac_ua.rol_id
        WHERE object_data.type = 'orgu') as orgus on orgus.usr_id = usr_data.usr_id
    WHERE usr_data.usr_id > 0 AND usr_data.login <> "anonymous"

Describe of Query

+------+-------------+------------------+--------+-----------------------+---------+---------+--------------------------------+------+--------------------------+
| id   | select_type | table            | type   | possible_keys         | key     | key_len | ref                            | rows | Extra                    |
+------+-------------+------------------+--------+-----------------------+---------+---------+--------------------------------+------+--------------------------+
|    1 | SIMPLE      | usr_data         | range  | PRIMARY,i1_idx        | PRIMARY | 4       | NULL                           | 8148 | Using where              |
|    1 | SIMPLE      | rbac_ua          | ref    | PRIMARY,i1_idx,i2_idx | PRIMARY | 4       | ildCPC.usr_data.usr_id         |    2 | Using where; Using index |
|    1 | SIMPLE      | rbac_fa          | ref    | PRIMARY,i1_idx        | PRIMARY | 4       | ildCPC.rbac_ua.rol_id          |    1 | Using where; Using index |
|    1 | SIMPLE      | role             | eq_ref | PRIMARY               | PRIMARY | 4       | ildCPC.rbac_ua.rol_id          |    1 | Using index              |
|    1 | SIMPLE      | object_reference | eq_ref | PRIMARY,i1_idx        | PRIMARY | 4       | ildCPC.rbac_fa.parent          |    1 | Using where              |
|    1 | SIMPLE      | object_data      | eq_ref | PRIMARY,i1_idx        | PRIMARY | 4       | ildCPC.object_reference.obj_id |    1 | Using where              |
+------+-------------+------------------+--------+-----------------------+---------+---------+--------------------------------+------+--------------------------+

usr_data table

+----------------------+---------------+------+-----+---------+-------+
| Field                | Type          | Null | Key | Default | Extra |
+----------------------+---------------+------+-----+---------+-------+
| usr_id               | int(11)       | NO   | PRI | 0       |       |
| login                | varchar(80)   | YES  | MUL | NULL    |       |
| passwd               | varchar(80)   | YES  |     | NULL    |       |
| firstname            | varchar(32)   | YES  |     | NULL    |       |
| lastname             | varchar(32)   | YES  |     | NULL    |       |
| title                | varchar(32)   | YES  |     | NULL    |       |
| gender               | char(1)       | YES  |     | m       |       |
| email                | varchar(80)   | YES  |     | NULL    |       |

usr_data indexes

+----------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table    | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+----------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| usr_data |          0 | PRIMARY  |            1 | usr_id      | A         |       29354 |     NULL | NULL   |      | BTREE      |         |               |
| usr_data |          1 | i1_idx   |            1 | login       | A         |       29354 |     NULL | NULL   | YES  | BTREE      |         |               |
| usr_data |          1 | i1_idx   |            2 | passwd      | A         |       29354 |     NULL | NULL   | YES  | BTREE      |         |               |
| usr_data |          1 | i2_idx   |            1 | ext_account | A         |           2 |     NULL | NULL   | YES  | BTREE      |         |               |
| usr_data |          1 | i2_idx   |            2 | auth_mode   | A         |           4 |     NULL | NULL   | YES  | BTREE      |         |               |
+----------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+

I've tried to make a temp-table for that SELECT in the LEFT JOIN but it didn't really speed it up any, the query takes up to 150 seconds currently, with a right join it brings it down to about 1 second. (It's the smaller table).

select * from object_data where type = 'orgu' returns 1058 rows.

SHOW CREATE TABLE rbac_ua

+---------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table   | Create Table                                                                                |
+---------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| rbac_ua | CREATE TABLE `rbac_ua` (
  `usr_id` int(11) NOT NULL DEFAULT '0',
  `rol_id` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`usr_id`,`rol_id`),
  KEY `i1_idx` (`usr_id`),
  KEY `i2_idx` (`rol_id`),
  KEY `rol_id` (`rol_id`,`usr_id`),
  KEY `rol_usr` (`rol_id`,`usr_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ROW_FORMAT=DYNAMIC |
+---------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+

SHOW CREATE TABLE rbac_fa

+---------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table   | Create Table                                                                                |
+---------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| rbac_fa | CREATE TABLE `rbac_fa` (
  `rol_id` int(11) NOT NULL DEFAULT '0',
  `parent` int(11) NOT NULL DEFAULT '0',
  `assign` char(1) COLLATE utf8_unicode_ci DEFAULT NULL,
  `protected` char(1) COLLATE utf8_unicode_ci DEFAULT 'n',
  PRIMARY KEY (`rol_id`,`parent`),
  KEY `i1_idx` (`parent`),
  KEY `parent` (`parent`,`rol_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ROW_FORMAT=DYNAMIC |
+---------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+

SHOW CREATE TABLE object_data

+-------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table       | Create Table                                                                                |
+-------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| object_data | CREATE TABLE `object_data` (
  `obj_id` int(11) NOT NULL DEFAULT '0',
  `type` char(4) COLLATE utf8_unicode_ci DEFAULT 'none',
  `title` char(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `description` char(128) COLLATE utf8_unicode_ci DEFAULT NULL,
  `owner` int(11) NOT NULL DEFAULT '0',
  `create_date` datetime DEFAULT NULL,
  `last_update` datetime DEFAULT NULL,
  `import_id` char(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`obj_id`),
  KEY `i1_idx` (`type`),
  KEY `i2_idx` (`title`),
  KEY `i4_idx` (`import_id`),
  FULLTEXT KEY `i3_idx` (`title`,`description`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ROW_FORMAT=DYNAMIC |
+-------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

SHOW CREATE TABLE object_reference

+------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table            | Create Table                                                                                |
+------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| object_reference | CREATE TABLE `object_reference` (
  `ref_id` int(11) NOT NULL DEFAULT '0',
  `obj_id` int(11) NOT NULL DEFAULT '0',
  `deleted` datetime DEFAULT NULL,
  PRIMARY KEY (`ref_id`),
  KEY `i1_idx` (`obj_id`),
  KEY `i2_idx` (`deleted`),
  KEY `obj_id` (`obj_id`,`ref_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ROW_FORMAT=DYNAMIC |
+------------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+

If i'm missing any useful information, please let me know.

Thanks in Advance.

Body:
By using LEFT JOIN you are demanding a large result set, containing a row for every item that matches your WHERE usr_data whatever clauses. That will take time to push to your client software even if the query planner does a great job.

usr_data.usr_id > 0 seems redundant because your usr_id column seems to be an autoincrement column. Are all the values above zero?

The subselect is definitely a performance hog.

Mr. Thrasher is close, I think.  The problem is mentioning a LEFT JOINed table's colum in a WHERE clause: that converts the LEFT JOIN to a straight JOIN.

Try this to see if you get appropriate results. I don't understand your schema so there's a little guesswork here.

     SELECT usr_data.usr_id, usr_data.login, object_data.title
       FROM usr_data
  LEFT JOIN rbac_ua ON rbac_ua.usr_id = usr_data.usr_id
  LEFT JOIN rbac_fa ON rbac_fa.rol_id = rbac_ua.rol_id
  LEFT JOIN object_reference ON rbac_fa.parent = object_reference.ref_id
  LEFT JOIN object_data   ON object_data.obj_id = object_reference.obj_id
                         AND object_data.type = 'orgu'
  LEFT JOIN object_data role ON role.obj_id = rbac_ua.rol_id
      WHERE usr_data.login <> 'anonymous'

Notice how object_data.type = 'orgu' ended up in the ON clause. (Yes, ON clauses can contain the same sort of stuff as WHERE clauses!) That keeps it from making  LEFT JOIN into a straight JOIN.

I'm not sure the point of this line.

  LEFT JOIN object_data role ON role.obj_id = rbac_ua.rol_id

That table doesn't seem to contribute to your result set.


问:
How can I std::sqrt(boost::lambda::placeholder1_type)?
How do I std::sqrt() on a boost::lambda::placeholder1_type?

The following program compiles and executes fine. Somehow, it manages to convert boost::lambda::_1 to a double and multiply it with 5.0.

```<code>#include <boost/lambda/lambda.hpp>
#include <iostream>
#include <cmath>

int main() {

  std::array<double, 6> a = {1, 4, 9, 16, 25, 36};

  std::for_each(a.begin(), a.end(),
      std::cout << boost::lambda::_1 * 5.0 << " "
  );
}
</code>```

However, if I replace the std::cout line with

```<code>std::cout << std::sqrt(boost::lambda::_1) << " "
</code>```

the compiler (g++) says

no known conversion for argument 1 from
  ‘boost::lambda::placeholder1_type {aka const
  boost::lambda::lambda_functor >}’ to
  ‘double’

So, how can I take the square root from boost::lambda::_1 in this std::for_each loop?

答:
You need to delay the call of sqrt. To achieve this, you should use a
bind expression.

NB: You need to use a cast to select the correct sqrt overload.

```<code>#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>
#include <iostream>
#include <cmath>

int main()
{
    std::array<double, 6> a = {1, 4, 9, 16, 25, 36};

    std::for_each(a.begin(), a.end(),
        std::cout << boost::lambda::bind(static_cast<double(*)(double)>(std::sqrt), boost::lambda::_1) << " "
    );
}
</code>```

Output:

```<code>1 2 3 4 5 6
</code>```

Live Sample

Body:
How do I std::sqrt() on a boost::lambda::placeholder1_type?

The following program compiles and executes fine. Somehow, it manages to convert boost::lambda::_1 to a double and multiply it with 5.0.

#include <boost/lambda/lambda.hpp>
#include <iostream>
#include <cmath>

int main() {

  std::array<double, 6> a = {1, 4, 9, 16, 25, 36};

  std::for_each(a.begin(), a.end(),
      std::cout << boost::lambda::_1 * 5.0 << " "
  );
}

However, if I replace the std::cout line with

std::cout << std::sqrt(boost::lambda::_1) << " "

the compiler (g++) says

no known conversion for argument 1 from
  ‘boost::lambda::placeholder1_type {aka const
  boost::lambda::lambda_functor >}’ to
  ‘double’

So, how can I take the square root from boost::lambda::_1 in this std::for_each loop?

Body:
You need to delay the call of sqrt. To achieve this, you should use a
bind expression.

NB: You need to use a cast to select the correct sqrt overload.

#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>
#include <iostream>
#include <cmath>

int main()
{
    std::array<double, 6> a = {1, 4, 9, 16, 25, 36};

    std::for_each(a.begin(), a.end(),
        std::cout << boost::lambda::bind(static_cast<double(*)(double)>(std::sqrt), boost::lambda::_1) << " "
    );
}

Output:

1 2 3 4 5 6

Live Sample


问:
C++ -- Difference between "throw new BadConversion("xxx")" and "throw BadConversion("xxx")"
```<code>// http://www.parashift.com/c++-faq-lite/misc-technical-issues.html
class BadConversion : public std::runtime_error {
 public:
   BadConversion(std::string const& s)
     : std::runtime_error(s)
     { }
 };

 inline std::string stringify(double x)
 {
   std::ostringstream o;
   if (!(o << x))
     throw BadConversion("stringify(double)");
     // throw new BadConversion("stringify(double)");
   return o.str();
 }
</code>```

[Q1] When we throw an exception in the function, what is the difference between throw new ClassName() and throw ClassName()?

[Q2] Which one is better?

Thank you

答:
throw new ClassName() throws pointer to ClassName. You need to catch (ClassName * pc). It's not good idea. If new returns null or throws then you have null pointer when you catch or you have double exception.

throw ClassName() is usual way to throw an exception.  You need to catch (const ClassName & pc).

Body:
// http://www.parashift.com/c++-faq-lite/misc-technical-issues.html
class BadConversion : public std::runtime_error {
 public:
   BadConversion(std::string const& s)
     : std::runtime_error(s)
     { }
 };

 inline std::string stringify(double x)
 {
   std::ostringstream o;
   if (!(o << x))
     throw BadConversion("stringify(double)");
     // throw new BadConversion("stringify(double)");
   return o.str();
 }

[Q1] When we throw an exception in the function, what is the difference between throw new ClassName() and throw ClassName()?

[Q2] Which one is better?

Thank you


问:
List of strings from split() cant convert to int()
I'm unable to get list values to have int() called upon them. The list is build from user input(), a split() and append(). Code looks like:

```<code>coords = []

fcoords = input("Enter first coordinate pair:\n")

urlat, urlon = fcoords.split()
coords.append(urlat)
coords.append(urlon)

scoords = input("Enter second coordinate pair:\n")
lllat, lllon = scoords.split()
coords.append(lllat)
coords.append(lllon)

for coord in coords:
    print (int(coord))
</code>```

Gives me a ValueError: invalid literal for int() with base 10: '-122.4444'.

I can switch the int(coord) with float(coord) but that's just extra work since I am converting decimal degree to dms. Using int() gets the base without remainder which is what I want!

Is the split() method not correct here, or are extra characters being hidden?

答:
You can't change float string to int.

change your split() to:

```<code>urlat, urlon = fcoords.split('.')
</code>```

and:

```<code>lllat, lllon = scoords.split('.')
</code>```

Your code will work.

Body:
I'm unable to get list values to have int() called upon them. The list is build from user input(), a split() and append(). Code looks like:

coords = []

fcoords = input("Enter first coordinate pair:\n")

urlat, urlon = fcoords.split()
coords.append(urlat)
coords.append(urlon)

scoords = input("Enter second coordinate pair:\n")
lllat, lllon = scoords.split()
coords.append(lllat)
coords.append(lllon)

for coord in coords:
    print (int(coord))

Gives me a ValueError: invalid literal for int() with base 10: '-122.4444'.

I can switch the int(coord) with float(coord) but that's just extra work since I am converting decimal degree to dms. Using int() gets the base without remainder which is what I want!

Is the split() method not correct here, or are extra characters being hidden?

Body:
You can't change float string to int.

change your split() to:

urlat, urlon = fcoords.split('.')

and:

lllat, lllon = scoords.split('.')

Your code will work.


问:
XSLT Select all 3rd level children of current node by name
I am trying to use apply-templates to iterate over a particular child node from multiple similar parent nodes. Example below:

```<code><test_report
xmlns:gml="http://www.opengis.net/gml"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<countries>
    <country name='sample1'>
        <education>
            <men>
                <literacyRates>25,36,43</literacyRates>
            </men>
        </education>
    </country>
    <country name='sample2'>
        <education>
            <men>
                <literacyRates>45,46,55,56</literacyRates>
            </men>
        </education>
    </country>
</countries>
</code>```

Now, I want to apply a template on all the literacyRates element that falls under the countries element. I tried the below XSL:

```<code><xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="countries">
            <xsl:call-template name="countries" />
</xsl:template>

<xsl:template name="countries" match="literacyRate">
        <xsl:call-template name="testoutput"><xsl:with-param name="list" select="." /> </xsl:call-template>
    ]
</xsl:template>

<xsl:template name="testoutput">
        <xsl:param name="list" select="."/>
    list=<xsl:value-of select="$list" />
</xsl:template>
</code>```

I would have expected the output line starting with list= to have appeared twice since we have two matches for literacyRate element, but that is not the case. Need some help here.

答:
The existing XSL code

Your XSL has a number of problems.

You use call-template in ways that don't make much sense.  Using apply-templates would be more idiomatic.

You have three templates, but you only actually do anything in the last one -- and that one only outputs the string value of the <countries> element.  May as well have just one template:

```<code><xsl:template match="countries">
    list=<xsl:value-of select="."/>
</xsl:template>
</code>```

(I assume here that the newline and ] closing bracket in your second template is a typo.)

Your second template has both a name attribute and a match attribute.

```<code><xsl:template name="countries" match="literacyRate">
      <xsl:call-template name="testoutput"><xsl:with-param name="list" select="." /> </xsl:call-template>
    ]
</xsl:template>
</code>```

The match attribute only does anything if you are using apply-templates earlier in the processing flow.  Since you only ever use call-template instead, the match attribute does nothing.

Moreover, since the match attribute specifies literacyRate, but your input XML only has literacyRates elements, this still wouldn't do anything, even if you used apply-templates earlier.

A working approach: text output

It looks like you want to have one list= line for each individual <country> element.  To generate this output as straight text, the following works:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:output method="text"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="countries">
        <xsl:apply-templates select="country//literacyRates"/>
    </xsl:template>

    <xsl:template match="literacyRates">
        <xsl:text>list=</xsl:text>
        <xsl:value-of select="."/>
        <xsl:text>
</xsl:text>
    </xsl:template>

</xsl:stylesheet>
</code>```

Breaking this down, we have:

<xsl:output method="text"/> to specify that we are outputting text, not XML.  This may affect the output formatting, depending on your XSL processor.

<xsl:strip-space elements="*"/> to prevent whitespace (i.e. indentation) in the source XML and XSL from affecting whitespace in the output.

<xsl:apply-templates select="country//literacyRates"/> to apply-templates, and to specifically select only those literacyRates elements that are descendants of a country element.

Assumptions

This assumes that each <country> element has only one <literacyRates> descendant element.  If there are multiple such elements, the output will get messy -- each list of values will be appended to the output string, potentially resulting in output lines like list=25,36,4345,46,55,56 (where two lists are munged together, with nothing in between).

A working approach: XML output

The text output above is somewhat lossy and confusing -- we have no idea which list belongs to which country, and multiple <literacyRates> in one <country> will produce broken output.

Here's an alternative output that generates XML, with more information included.

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:output method="xml" indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="countries">
        <SampleOutput>
            <xsl:apply-templates select="country//literacyRates"/>
        </SampleOutput>
    </xsl:template>

    <xsl:template match="literacyRates">
        <literacyRates>
            <xsl:attribute name="country" select="ancestor::country/@name"/>
            <xsl:attribute name="type" select="name(..)"/>
            <xsl:value-of select="."/>
        </literacyRates>
    </xsl:template>

</xsl:stylesheet>
</code>```

Body:
I am trying to use apply-templates to iterate over a particular child node from multiple similar parent nodes. Example below:

<test_report
xmlns:gml="http://www.opengis.net/gml"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<countries>
    <country name='sample1'>
        <education>
            <men>
                <literacyRates>25,36,43</literacyRates>
            </men>
        </education>
    </country>
    <country name='sample2'>
        <education>
            <men>
                <literacyRates>45,46,55,56</literacyRates>
            </men>
        </education>
    </country>
</countries>

Now, I want to apply a template on all the literacyRates element that falls under the countries element. I tried the below XSL:

<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="countries">
            <xsl:call-template name="countries" />
</xsl:template>

<xsl:template name="countries" match="literacyRate">
        <xsl:call-template name="testoutput"><xsl:with-param name="list" select="." /> </xsl:call-template>
    ]
</xsl:template>

<xsl:template name="testoutput">
        <xsl:param name="list" select="."/>
    list=<xsl:value-of select="$list" />
</xsl:template>

I would have expected the output line starting with list= to have appeared twice since we have two matches for literacyRate element, but that is not the case. Need some help here.

Body:
The existing XSL code

Your XSL has a number of problems.

You use call-template in ways that don't make much sense.  Using apply-templates would be more idiomatic.

You have three templates, but you only actually do anything in the last one -- and that one only outputs the string value of the <countries> element.  May as well have just one template:

<xsl:template match="countries">
    list=<xsl:value-of select="."/>
</xsl:template>

(I assume here that the newline and ] closing bracket in your second template is a typo.)

Your second template has both a name attribute and a match attribute.

<xsl:template name="countries" match="literacyRate">
      <xsl:call-template name="testoutput"><xsl:with-param name="list" select="." /> </xsl:call-template>
    ]
</xsl:template>

The match attribute only does anything if you are using apply-templates earlier in the processing flow.  Since you only ever use call-template instead, the match attribute does nothing.

Moreover, since the match attribute specifies literacyRate, but your input XML only has literacyRates elements, this still wouldn't do anything, even if you used apply-templates earlier.

A working approach: text output

It looks like you want to have one list= line for each individual <country> element.  To generate this output as straight text, the following works:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:output method="text"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="countries">
        <xsl:apply-templates select="country//literacyRates"/>
    </xsl:template>

    <xsl:template match="literacyRates">
        <xsl:text>list=</xsl:text>
        <xsl:value-of select="."/>
        <xsl:text>&#10;</xsl:text>
    </xsl:template>

</xsl:stylesheet>

Breaking this down, we have:

<xsl:output method="text"/> to specify that we are outputting text, not XML.  This may affect the output formatting, depending on your XSL processor.

<xsl:strip-space elements="*"/> to prevent whitespace (i.e. indentation) in the source XML and XSL from affecting whitespace in the output.

<xsl:apply-templates select="country//literacyRates"/> to apply-templates, and to specifically select only those literacyRates elements that are descendants of a country element.

Assumptions

This assumes that each <country> element has only one <literacyRates> descendant element.  If there are multiple such elements, the output will get messy -- each list of values will be appended to the output string, potentially resulting in output lines like list=25,36,4345,46,55,56 (where two lists are munged together, with nothing in between).

A working approach: XML output

The text output above is somewhat lossy and confusing -- we have no idea which list belongs to which country, and multiple <literacyRates> in one <country> will produce broken output.

Here's an alternative output that generates XML, with more information included.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:output method="xml" indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="countries">
        <SampleOutput>
            <xsl:apply-templates select="country//literacyRates"/>
        </SampleOutput>
    </xsl:template>

    <xsl:template match="literacyRates">
        <literacyRates>
            <xsl:attribute name="country" select="ancestor::country/@name"/>
            <xsl:attribute name="type" select="name(..)"/>
            <xsl:value-of select="."/>
        </literacyRates>
    </xsl:template>

</xsl:stylesheet>


问:
Dynamic functions from class name
I want to under stead something about how Laravel does create the magic functions based on the Facade classes. Now what I want is a central class within the magic functions is created based on class names. For example:

```<code>// Example main class
class Facade
{
    public function __construct(array $aliases = [])
    {
        $this->aliases = $aliases;
    }

    public function load()
    {
        // Do some magic...
    }
}

// Example Facade subclass
class Navigation
{
    public function items(string $name)
    {
        return $name;
    }
}

// Array with aliases
$aliases = [
    'navigation' => 'App\Facades\Navigation',
];
new Facade($aliases);

// Then I want to call everywhere:
echo navigation()->items('name'); == 'name'
</code>```

How can I do this, I can't find anything about how Laravel this does.

答:
Define PHP autoloader instead of the Facade class:

```<code>spl_autoload_register(function ($class_name) {
    $aliases = [
        'navigation' => 'App\Facades\Navigation',
    ];

    if (array_key_exists($class_name, $aliases) {
        include $aliases[$class_name] . '.php';
    }
});
</code>```

And then call your class by (pay attention to the missing brackets):

```<code>echo navigation->items('name');
</code>```

For more info - PHP autoload doc

Title: Dynamic functions from class name

Body:
I want to under stead something about how Laravel does create the magic functions based on the Facade classes. Now what I want is a central class within the magic functions is created based on class names. For example:

// Example main class
class Facade
{
    public function __construct(array $aliases = [])
    {
        $this->aliases = $aliases;
    }

    public function load()
    {
        // Do some magic...
    }
}

// Example Facade subclass
class Navigation
{
    public function items(string $name)
    {
        return $name;
    }
}

// Array with aliases
$aliases = [
    'navigation' => 'App\Facades\Navigation',
];
new Facade($aliases);

// Then I want to call everywhere:
echo navigation()->items('name'); == 'name'

How can I do this, I can't find anything about how Laravel this does.

Body:
Define PHP autoloader instead of the Facade class:

spl_autoload_register(function ($class_name) {
    $aliases = [
        'navigation' => 'App\Facades\Navigation',
    ];

    if (array_key_exists($class_name, $aliases) {
        include $aliases[$class_name] . '.php';
    }
});

And then call your class by (pay attention to the missing brackets):

echo navigation->items('name');

For more info - PHP autoload doc


问:
Simulate a button on the keyboard being pressed, add the value of that keypress to text input
My objective is to be able to run a function that simulates a key being pressed on the keyboard, and then the value of that key being inserted into an input field. My reasoning for this is that I am using a js framework that automatically filters data based off of the input but it only filters the data when the input is typed in. Using document.getElementById('search_box').value will obviously populate the input with text. But doing this doesn't trigger the data to be filtered because the input text technically isn't typed in. So I was wondering if it was possible to run a function that would basically simulate keys being pressed and then inserting the value of those keys into an input field.

```<code>function populateField() {
    document.getElementById('search_box').value = "mr"; //this needs to be changed to insert the value via keyboard
    document.getElementById('search_box').focus();
}
</code>```

答:
According to filter.js's main repo's Issues #154: Can I trigger a filter programatically with jquery like $("#filterid").val("bla").change() ?

$("#filterid").trigger('change') will work. It also depend upon events: change, click etc

i.e
$('#searchbox').val("father").trigger('keyup')

In the example page , I used $('#searchbox').val("father").trigger('keyup') to add "father" to search and trigger a filter effect.

Body:
My objective is to be able to run a function that simulates a key being pressed on the keyboard, and then the value of that key being inserted into an input field. My reasoning for this is that I am using a js framework that automatically filters data based off of the input but it only filters the data when the input is typed in. Using document.getElementById('search_box').value will obviously populate the input with text. But doing this doesn't trigger the data to be filtered because the input text technically isn't typed in. So I was wondering if it was possible to run a function that would basically simulate keys being pressed and then inserting the value of those keys into an input field.

function populateField() {
    document.getElementById('search_box').value = "mr"; //this needs to be changed to insert the value via keyboard
    document.getElementById('search_box').focus();
}


问:
Conditional statement- compare to values store in array
Need help figuring out working perl code to put in place of "any of the elements in @array" </p>

```<code>%hash = (key1 => 'value1',key2 => 'value2',key3 => 'value3',);

@array= ('value3','value4','value6');

if ($hash{ 'key1' } ne <<any of the elements in @array>>) {print "YAY!";}
</code>```

答:
CPAN solution: use List::MoreUtils

```<code>use List::MoreUtils qw{any};
print "YAY!" if any { $hash{'key1'} eq $_ } @array;
</code>```

Why use this solution over the alternatives?

Can't use smart match in Perl before 5.10

grep solution loops through the entire list even if the first element of 1,000,000 long list matches. any will short-circuit and quit the moment the first match is found, thus it is more efficient.

Body:
Need help figuring out working perl code to put in place of "any of the elements in @array"

%hash = (key1 => 'value1',key2 => 'value2',key3 => 'value3',);

@array= ('value3','value4','value6');

if ($hash{ 'key1' } ne <<any of the elements in @array>>) {print "YAY!";}

Body:
CPAN solution: use List::MoreUtils

use List::MoreUtils qw{any};
print "YAY!" if any { $hash{'key1'} eq $_ } @array;

Why use this solution over the alternatives?

Can't use smart match in Perl before 5.10

grep solution loops through the entire list even if the first element of 1,000,000 long list matches. any will short-circuit and quit the moment the first match is found, thus it is more efficient.


问:
Building GHC: configure fails on happy despite successful cabal install
I am attempting to build GHC from source following this page. When installing dependencies, I had to install happy and alex:

```<code>$ cabal install alex happy
Resolving dependencies...
Configuring alex-3.2.1...
Configuring happy-1.19.5...
Building happy-1.19.5...
Building alex-3.2.1...
Installed alex-3.2.1
Installed happy-1.19.5
</code>```

yet when running configure I get an error message:

```<code>$ ./configure
...
checking for happy... no
checking for version of happy...
configure: error: Happy version 1.19.4 or later is required to compile GHC.
</code>```

I am running on Debian stretch:

```<code>$ uname -a
Linux <host> 4.8.0-1-amd64 #1 SMP Debian 4.8.5-1 (2016-10-28) x86_64 GNU/Linux
</code>```

Can anyone suggest an obvious step I could try to resolve this?

答:
You should install alex and happy as Debian packages as well. On a Debian machine, you can use apt-get for that:

```<code>sudo apt-get install alex happy
</code>```

Body:
I am attempting to build GHC from source following this page. When installing dependencies, I had to install happy and alex:

$ cabal install alex happy
Resolving dependencies...
Configuring alex-3.2.1...
Configuring happy-1.19.5...
Building happy-1.19.5...
Building alex-3.2.1...
Installed alex-3.2.1
Installed happy-1.19.5

yet when running configure I get an error message:

$ ./configure
...
checking for happy... no
checking for version of happy...
configure: error: Happy version 1.19.4 or later is required to compile GHC.

I am running on Debian stretch:

$ uname -a
Linux <host> 4.8.0-1-amd64 #1 SMP Debian 4.8.5-1 (2016-10-28) x86_64 GNU/Linux

Can anyone suggest an obvious step I could try to resolve this?

Body:
You should install alex and happy as Debian packages as well. On a Debian machine, you can use apt-get for that:

sudo apt-get install alex happy


问:
Understanding macros in C
Why is the output from the following code the value 5?</p>

```<code>#include<stdio.h>

#define A -B
#define B -C
#define C 5

int main()
{
  printf("The value of A is %d\n", A);
  return 0;
}
</code>```

答:
This is a tricky question because it is a stress test for the compiler preprocessor.

Depending if the preprocessor is an integrated phase of the compiler or a separate program passing its output to the compiler via a file or a pipe and in this case whether it is careful enough to not perform erroneous token pasting, you may get the expected output: 5 or you may get a compilation error.

After the preprocessed contents of stdio.h, the source code expands to:

```<code>int main()
{
  printf("The value of A is %d\n", --5);
  return 0;
}
</code>```

But the two - are separate tokens, so depending if the preprocessor separates them in its output or not, you may get a program that outputs 5 or one that does not compile because -- cannot be applied to a literal 5.

Both the gcc and the clang preprocessors behave correctly and separate the - with an extra space to prevent token pasting when they produce the preprocessor output with the -E command line option. They output this as preprocessed source code after the expansion of <stdio.h>:

```<code>int main()
{
  printf("The value of A is %d\n", - -5);
  return 0;
}
</code>```

Try your own compiler to check how it expands the source code. It seems Visual Studio 2013 and 2015 fail the test and reject the program with an error.

To makes things clear, I do not say the behavior of the program should depend on the compiler architecture.  I was hoping at least one common C compiler would mishandle this conformance test.  I am not surprised MS Visual Studio 2013 and 2015 fail this test.

The extra space in only needed in the textual output of the preprocessor. It does not matter if Visual Studio uses multiple separate phases or not, the source program is perfectly valid and their failure to compile it is a BUG.

Title: Understanding macros in C

Body:
Why is the output from the following code the value 5?

#include<stdio.h>

#define A -B
#define B -C
#define C 5

int main()
{
  printf("The value of A is %d\n", A);
  return 0;
}

Body:
This is a tricky question because it is a stress test for the compiler preprocessor.

Depending if the preprocessor is an integrated phase of the compiler or a separate program passing its output to the compiler via a file or a pipe and in this case whether it is careful enough to not perform erroneous token pasting, you may get the expected output: 5 or you may get a compilation error.

After the preprocessed contents of stdio.h, the source code expands to:

int main()
{
  printf("The value of A is %d\n", --5);
  return 0;
}

But the two - are separate tokens, so depending if the preprocessor separates them in its output or not, you may get a program that outputs 5 or one that does not compile because -- cannot be applied to a literal 5.

Both the gcc and the clang preprocessors behave correctly and separate the - with an extra space to prevent token pasting when they produce the preprocessor output with the -E command line option. They output this as preprocessed source code after the expansion of <stdio.h>:

int main()
{
  printf("The value of A is %d\n", - -5);
  return 0;
}

Try your own compiler to check how it expands the source code. It seems Visual Studio 2013 and 2015 fail the test and reject the program with an error.

To makes things clear, I do not say the behavior of the program should depend on the compiler architecture.  I was hoping at least one common C compiler would mishandle this conformance test.  I am not surprised MS Visual Studio 2013 and 2015 fail this test.

The extra space in only needed in the textual output of the preprocessor. It does not matter if Visual Studio uses multiple separate phases or not, the source program is perfectly valid and their failure to compile it is a BUG.


问:
iOS: FMDB questions adding a lot of data to an array
I am getting a lot of data from the database. This is an example on what I am doing.

```<code>NSMutableArray *array = [[NSMutableArray alloc] init];

FMResultSet *s = [db executeQuery:@"SELECT * FROM myTable"];
while ([s next]) {
     NSString *idNumber = [result stringForColumn:@"id"];
     [array addObject:idNumber];
}
</code>```

However, there is one issue that is making me nervous. What if I need to grab a lot of data from the database? Will this cause any memory issue or major slow downs? If so, what will be the best way to make sure this issue doesn't occur.

答:
Try to use query with filters WHERE

Use background thread

You're using only id field, so there's no need to grab all other fields: use SELECT id FROM myTable instead

Body:
I am getting a lot of data from the database. This is an example on what I am doing.

NSMutableArray *array = [[NSMutableArray alloc] init];

FMResultSet *s = [db executeQuery:@"SELECT * FROM myTable"];
while ([s next]) {
     NSString *idNumber = [result stringForColumn:@"id"];
     [array addObject:idNumber];
}

However, there is one issue that is making me nervous. What if I need to grab a lot of data from the database? Will this cause any memory issue or major slow downs? If so, what will be the best way to make sure this issue doesn't occur.


问:
How to access a protected method of superclass in a subclass?
I have parent-child classes in two different packages. I am overriding a method of protected type. I want to access super class protected method in subclass.

Consider below code:

```<code>package package1;

public class Super
{
    protected void demoMethod()
    {
        System.out.println("In super method");
    }
}

package package2;

import package1.Super;

public class Sub extends Super
{
    @Override
    protected void demoMethod()
    {
        System.out.println("In sub method");
    }

    public static void main(String[] args)
    {
        //code for accessing superclass demoMethod to print "In super method"
    }
}
</code>```

In the main method of sub class, I want to access super class demoMethod which prints "In super method". I know demoMethod won't be visible from sub class using super class object reference to call demoMethod.

Is it possible or not? If yes, how?

Consider me new to Java and provide answers replacing comment in main method.

答:
Your main() method cannot access the superclass implementation of demoMethod() -- because it's overridden in the child class.

Your main() method can access demoMethod(), through a reference of the subclass type, even though it's protected, because it's in the same package as your subclass. But it will call the subclass implementation.

But if you're "using superclass object reference to call demoMethod", the method will not be accessible, and your code will not compile. Your superclass is in a different package. Methods marked protected can only be accessed by subclasses and by code in the same package.

If you made the method public in both subclass and superclass, calling demoMethod() would call the subclass implementation, regardless whether the reference was of the super or subclass type.

An instance of the subclass can call super.demoMethod() as part of the implementation of its methods. But the main() method cannot.

Body:
I have parent-child classes in two different packages. I am overriding a method of protected type. I want to access super class protected method in subclass.

Consider below code:

package package1;

public class Super
{
    protected void demoMethod()
    {
        System.out.println("In super method");
    }
}

package package2;

import package1.Super;

public class Sub extends Super
{
    @Override
    protected void demoMethod()
    {
        System.out.println("In sub method");
    }

    public static void main(String[] args)
    {
        //code for accessing superclass demoMethod to print "In super method"
    }
}

In the main method of sub class, I want to access super class demoMethod which prints "In super method". I know demoMethod won't be visible from sub class using super class object reference to call demoMethod.

Is it possible or not? If yes, how?

Consider me new to Java and provide answers replacing comment in main method.


答:
[A1] With throw new, you'll have to catch a pointer. The language doesn't specify in this case who is responsible for deallocation, so you'll have to establish your own convention (typically you'd make the catcher responsible). Without new, you'll want to catch by reference.

[A2] If you're in a framework that commonly throws pointers, you may want to follow suit. Else, throw without new. See also the C++ FAQ, item 17.14.

Title: C++ -- Difference between "throw new BadConversion("xxx")" and "throw BadConversion("xxx")"


问:
Can IntentService and Service run on the same time?
I am developing an Android application where my SQLite database is inserted multiple times by Service and IntentService.

I start my Service right after application is started in MainActivity. My MainActivity has few tabs with fragments. One of the Fragments activates IntentService on its Resume. It means that my Service and IntentService may potentially run synchronously.

The data inserted by Service and IntentService could be the same. This situation may lead to duplication or Exception.

Can we assume that Service and IntentService can run on the same time and generate inconsistency in DataBase?

答:
If you have a Service, then when startService() is called this results in a call to onStartCommand() which runs on the main (UI) Thread in the process.

In an IntentService, when startService() is called this results in a call to onHandleIntent() which is called on a worker thread.

Obviously there is a potential that both of these calls will happen in parallel.

There are many ways to deal with potential parallel execution. Here are a few examples:

You can synchronize the database loading on a common object so that both threads cannot load the database at the same time. Each thread should check if the data has already been loaded before it loads to prevent duplicates.

To load your database, you can submit a job to a queue (or submit a Runnable to a Handler, or something similar). You then have a separate thread that dequeues entries from the queue and runs them serially (one after another). In this case, if both your services submit jobs to the queue, one will run before the other one and they will not run in parallel. Also here you should make sure that you prevent duplicates by either checking if the data has already been loaded before loading it again, or by making sure that you only run one job in the queue.

Create a table in your database that is used as a locking mechanism and has a column that indicates whether a load is in progress (this should be a primary key column that allows no duplicates). Before you start to the load the data, insert a row into the locking table. If there is a load in progress, this should fail with "duplicate key". If it is successful, load your data. When you are done, delete the row from the locking table.


问:
Getting parameters from query string
I am creating a web page using ASP.Net WebAPi, MVC and Knockout.

I have a normal MVC controller that loads the pages when I need them:

```<code> [Authorize]
    public class AdminController : Controller
    {
        public ActionResult Clients()
        {
            return View();
        }

        public ActionResult ClientEdit(int? Id)
        {
            return View();
        }
    }
</code>```

And once the page is loaded, my Knockout model takes care of the loading of the data. So, the 'Clients' controller simply loads a list of all clients. When on that screen, a user can click 'Edit' next to a client, and the page is navigated to the 'ClientEdit' controller, which takes an id.

So, my knockout click event looks like this in my knockout view model:

```<code>self.EditClick = function () {
        if (this.ClientId && typeof this.ClientId !== 'undefined') {
            window.location.href = "/Admin/ClientEdit/" + this.ClientId;
        }
        else
            window.location.href = "/Admin/ClientEdit/";
    }
</code>```

(It handles the 'Create New' button and the edit button, hence the 'if')

Once I redirect, the MVC controller loads the page, and the URL is:

http://localhost:49389/Admin/ClientEdit/1

I then load the knockout model, and would like to make an API call to get the data...

After my page loads, I want to bind the view model to the page. Here's my view model at the moment:

```<code>function AdminClientEditor() {
    var self = this;

    self.Name = ko.observable("");
    self.ContactName = ko.observable("");

ko.applyBindings(new AdminClientEditor(), $("#clienteditor")[0]);
</code>```

So, I will create a $.get method that calls a webAPI method that will return me data based on the id. I just need to get the ID somehow.

But, how do I get the Id (In this case, '1', from the URL?
And, is this the right way to achieve what I am trying to do?

答:
You can pass the id value to view via viewbag.

```<code>public ActionResult ClientEdit(int? Id)
{
     ViewBag.ClientId=id;
     return View();
}
</code>```

and in the view's script section

```<code>var clientId="@ViewBag.ClientId";
alert(clientId);
// use this
</code>```

If your javascript code which accesses this id value is inside a separate external js file, you may set this value to a js variable in your view and access it in your js file. Make sure to use namespacing to avoid global variable overwriting value issues.

So in your view

```<code><script>
    var myApp = myApp || {};
    myApp.ClientId= "@ViewBag.ClientId";
</script>
<script src="~/Scripts/PageSpecificExternalJsFile.js"></script>
</code>```

And in the PageSpecificExternalJsFile.js file,

```<code>var clientId=myApp.ClientId;
//use this as needed
</code>```

Title: Getting parameters from query string

Body:
I am creating a web page using ASP.Net WebAPi, MVC and Knockout.

I have a normal MVC controller that loads the pages when I need them:

 [Authorize]
    public class AdminController : Controller
    {
        public ActionResult Clients()
        {
            return View();
        }

        public ActionResult ClientEdit(int? Id)
        {
            return View();
        }
    }

And once the page is loaded, my Knockout model takes care of the loading of the data. So, the 'Clients' controller simply loads a list of all clients. When on that screen, a user can click 'Edit' next to a client, and the page is navigated to the 'ClientEdit' controller, which takes an id.

So, my knockout click event looks like this in my knockout view model:

self.EditClick = function () {
        if (this.ClientId && typeof this.ClientId !== 'undefined') {
            window.location.href = "/Admin/ClientEdit/" + this.ClientId;
        }
        else
            window.location.href = "/Admin/ClientEdit/";
    }

(It handles the 'Create New' button and the edit button, hence the 'if')

Once I redirect, the MVC controller loads the page, and the URL is:

http://localhost:49389/Admin/ClientEdit/1

I then load the knockout model, and would like to make an API call to get the data...

After my page loads, I want to bind the view model to the page. Here's my view model at the moment:

function AdminClientEditor() {
    var self = this;

    self.Name = ko.observable("");
    self.ContactName = ko.observable("");

ko.applyBindings(new AdminClientEditor(), $("#clienteditor")[0]);

So, I will create a $.get method that calls a webAPI method that will return me data based on the id. I just need to get the ID somehow.

But, how do I get the Id (In this case, '1', from the URL?
And, is this the right way to achieve what I am trying to do?

Body:
You can pass the id value to view via viewbag.

public ActionResult ClientEdit(int? Id)
{
     ViewBag.ClientId=id;
     return View();
}

and in the view's script section

var clientId="@ViewBag.ClientId";
alert(clientId);
// use this

If your javascript code which accesses this id value is inside a separate external js file, you may set this value to a js variable in your view and access it in your js file. Make sure to use namespacing to avoid global variable overwriting value issues.

So in your view

<script>
    var myApp = myApp || {};
    myApp.ClientId= "@ViewBag.ClientId";
</script>
<script src="~/Scripts/PageSpecificExternalJsFile.js"></script>

And in the PageSpecificExternalJsFile.js file,

var clientId=myApp.ClientId;
//use this as needed


问:
C# convert datetime to WCF datetime format
I parse c# object that has DateTime property with JsonNet and then I post it to the server. But it returns that the date format is wrong. It request to be with format like this:

```<code>"/Date(1327572000000-1000)/"
</code>```

How can I convert c# DateTime to this format?

答:
Since you asked how to serialize with this format using JSON.NET:

```<code>// Set the DateFormatHandling wherever you are configuring JSON.Net.
// This is usually globally configured per application.
var settings = new JsonSerializerSettings
{
    DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
};

// When you serialize, DateTime and DateTimeOffset values will be in this format.
string json = JsonConvert.SerializeObject(yourDateTimeValue, settings);
</code>```

However, I highly recommend you do NOT use this format unless you absolutely have to, usually for purposes of compatibility with old code.  The ISO-8601 format is preferred (de facto) format for dates and times in JSON.

See also:  On the nightmare that is JSON Dates.

Body:
I parse c# object that has DateTime property with JsonNet and then I post it to the server. But it returns that the date format is wrong. It request to be with format like this:

"/Date(1327572000000-1000)/"

How can I convert c# DateTime to this format?

Body:
Since you asked how to serialize with this format using JSON.NET:

// Set the DateFormatHandling wherever you are configuring JSON.Net.
// This is usually globally configured per application.
var settings = new JsonSerializerSettings
{
    DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
};

// When you serialize, DateTime and DateTimeOffset values will be in this format.
string json = JsonConvert.SerializeObject(yourDateTimeValue, settings);

However, I highly recommend you do NOT use this format unless you absolutely have to, usually for purposes of compatibility with old code.  The ISO-8601 format is preferred (de facto) format for dates and times in JSON.

See also:  On the nightmare that is JSON Dates.


问:
Sklearn Datasets
I am trying the code from sklearn.datasets import load_iris. For this I have installed sklearn module in my python 2.7.6 but it is showing me long error

```<code>Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    from sklearn.datasets import load_iris
  File "C:\Python27\lib\site-packages\sklearn\datasets\__init__.py", line 23, in <module>
    from .twenty_newsgroups import fetch_20newsgroups
  File "C:\Python27\lib\site-packages\sklearn\datasets\twenty_newsgroups.py", line 53, in <module>
    from ..feature_extraction.text import CountVectorizer
  File "C:\Python27\lib\site-packages\sklearn\feature_extraction\__init__.py", line 10, in <module>
    from . import text
  File "C:\Python27\lib\site-packages\sklearn\feature_extraction\text.py", line 24, in <module>
    from ..preprocessing import normalize
  File "C:\Python27\lib\site-packages\sklearn\preprocessing\__init__.py", line 6, in <module>
    from ._function_transformer import FunctionTransformer
  File "C:\Python27\lib\site-packages\sklearn\preprocessing\_function_transformer.py", line 2, in <module>
    from ..utils import check_array
ImportError: cannot import name check_array
</code>```

I want to know if installing sklearn module is enough or am I missing something? Please Help. Also I am working on Win 8.1

答:
Typically the error

```<code>from ..utils import check_array
ImportError: cannot import name check_array
</code>```

appears when there is a dependency version mismatch is there. To resolve the issue either
a) update to the latest version of sklearn via pip or easy_install . Or manually install
b) Create a Python virtual environment and try this. It will help you to manage the version specific depend libraries.

My two cents : Go for Anaconda or Enthought Python distributions if latest version of sklearn is okay. Else better to use virtualenv package in python to isolate the environments and avoid conflicts.

Happy Hacking

Title: Sklearn Datasets

Body:
I am trying the code from sklearn.datasets import load_iris. For this I have installed sklearn module in my python 2.7.6 but it is showing me long error

Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    from sklearn.datasets import load_iris
  File "C:\Python27\lib\site-packages\sklearn\datasets\__init__.py", line 23, in <module>
    from .twenty_newsgroups import fetch_20newsgroups
  File "C:\Python27\lib\site-packages\sklearn\datasets\twenty_newsgroups.py", line 53, in <module>
    from ..feature_extraction.text import CountVectorizer
  File "C:\Python27\lib\site-packages\sklearn\feature_extraction\__init__.py", line 10, in <module>
    from . import text
  File "C:\Python27\lib\site-packages\sklearn\feature_extraction\text.py", line 24, in <module>
    from ..preprocessing import normalize
  File "C:\Python27\lib\site-packages\sklearn\preprocessing\__init__.py", line 6, in <module>
    from ._function_transformer import FunctionTransformer
  File "C:\Python27\lib\site-packages\sklearn\preprocessing\_function_transformer.py", line 2, in <module>
    from ..utils import check_array
ImportError: cannot import name check_array

I want to know if installing sklearn module is enough or am I missing something? Please Help. Also I am working on Win 8.1

Body:
Typically the error

from ..utils import check_array
ImportError: cannot import name check_array

appears when there is a dependency version mismatch is there. To resolve the issue either
a) update to the latest version of sklearn via pip or easy_install . Or manually install
b) Create a Python virtual environment and try this. It will help you to manage the version specific depend libraries.

My two cents : Go for Anaconda or Enthought Python distributions if latest version of sklearn is okay. Else better to use virtualenv package in python to isolate the environments and avoid conflicts.

Happy Hacking


问:
jQuery UI dialog form, not sending correct variable
I'm loading a customer info page using jQuery. There's a list of customers with a link next to it:

```<code><a href="#" onclick="load_customer(<?php echo $c->id; ?>);return false;">View</a>
</code>```

That triggers this function:

```<code>function load_customer(id) {
  $("#dashboard").load('get_info/' + id);
}
</code>```

That works perfectly. On the page I'm loading, I have a jQuery UI modal dialog form for adding new information.

```<code><div id="addinfo">
  <form><input type="hidden" name="customer_id" value="<?php echo $c->id; ?>" /></form>
</div>
</code>```

My javascript:

```<code>  $("#addinfobutton").click(function(){
            $("#addinfo").dialog("open");
            return false;
   });
   $("#addinfo").dialog({
            autoOpen:false,
            width:400,
            height:550,
            modal: true
   });
</code>```

When you select a customer the first time, it populates the hidden field correctly, but then it stays the same even after selecting other customers.

I thought that by loading a new customer page, the form would reset as well... but apparently it's being stored/cached somewhere. If I echo the ID anywhere else in the page, it shows correctly... just not in the "addinfo" div.

Any help/suggestions would be appreciated! Thanks!

答:
I guess if the #addinfo div is updated it should capture the new content...anyway this would destroy the dialog after closing it to insure a new instance will be created:

```<code>$("#addinfobutton").click(function(){
    openDialog('#addinfo');
    return false;
});
function openDialog(elm) {
    $(elm).dialog({
        autoOpen:true,
        width:400,
        height:550,
        modal: true,
        close: function() {
            $(this).dialog('destroy');
        }
    });
}
</code>```

Body:
I'm loading a customer info page using jQuery. There's a list of customers with a link next to it:

<a href="#" onclick="load_customer(<?php echo $c->id; ?>);return false;">View

That triggers this function:

function load_customer(id) {
  $("#dashboard").load('get_info/' + id);
}

That works perfectly. On the page I'm loading, I have a jQuery UI modal dialog form for adding new information.

  <form><input type="hidden" name="customer_id" value="<?php echo $c->id; ?>" /></form>

My javascript:

  $("#addinfobutton").click(function(){
            $("#addinfo").dialog("open");
            return false;
   });
   $("#addinfo").dialog({
            autoOpen:false,
            width:400,
            height:550,
            modal: true
   });

When you select a customer the first time, it populates the hidden field correctly, but then it stays the same even after selecting other customers.

I thought that by loading a new customer page, the form would reset as well... but apparently it's being stored/cached somewhere. If I echo the ID anywhere else in the page, it shows correctly... just not in the "addinfo" div.

Any help/suggestions would be appreciated! Thanks!

Body:
I guess if the #addinfo div is updated it should capture the new content...anyway this would destroy the dialog after closing it to insure a new instance will be created:

$("#addinfobutton").click(function(){
    openDialog('#addinfo');
    return false;
});
function openDialog(elm) {
    $(elm).dialog({
        autoOpen:true,
        width:400,
        height:550,
        modal: true,
        close: function() {
            $(this).dialog('destroy');
        }
    });
}


问:
Convert Json to XML properly
I have following dictionary structure

```<code>[{
    "Body" : [{
        "Universal Lift Support" : ["1\"-9\" Extended Length",
                                    "10\"-14.5\" Extended Length",
                                    "15\"-19\" Extended Length",
                                    "20\" + Extended Length"]
    }]
</code>```

I wanted to use the dicttoxml library to get desired xml-output like:

<root>

        <Universal Lift Support>
            1"-9" Extended Length
            10"-14.5" Extended Length
            15"-19" Extended Length
            20" + Extended Length
        </Universal Lift Support>
```

<p>However, after applying the next code:</p>

```dicttoxml.dicttoxml(result, attr_type=False, root=True)
```

I got xml-structure like:

<?xml version="1.0" encoding="UTF-8" ?><root><item><item><Universal_Lift_Support><item>1"-9" Extended Length</item><item>10"-14.5" Extended Length</item><item>15"-19" Extended Length</item><item>

What options can help to format and get the output as descibed above?

答: If the software is called dicttoxml, then I think it would be reasonable to expect it to generate XML. The output that you say you want is not XML, so it's not surprising that this tool doesn't generate it. You seem to be complaining that the product does what it says on the tin.</p>

Title: Convert Json to XML properly

Body:
I have following dictionary structure

[{
    "Body" : [{
        "Universal Lift Support" : ["1\"-9\" Extended Length",
                                    "10\"-14.5\" Extended Length",
                                    "15\"-19\" Extended Length",
                                    "20\" + Extended Length"]
    }]

I wanted to use the dicttoxml library to get desired xml-output like:

<root>

        <Universal Lift Support>
            1"-9" Extended Length
            10"-14.5" Extended Length
            15"-19" Extended Length
            20" + Extended Length
        </Universal Lift Support>

However, after applying the next code:

dicttoxml.dicttoxml(result, attr_type=False, root=True)

I got xml-structure like:

<?xml version="1.0" encoding="UTF-8" ?><root><item><item><Universal_Lift_Support><item>1"-9" Extended Length</item><item>10"-14.5" Extended Length</item><item>15"-19" Extended Length</item><item>

What options can help to format and get the output as descibed above?