问:
Does af:select one choice supports range size concept?
I have select one choice component dragged on to the page as filter. I have around 20 columns and each column is having select one choice as filter. and each filter having more than 1000 records. So, as the record count is much it is taking much time to load the page so, through view Accessor I have tried to display the data on to my component.

Still it is fetching all records in case soc. Is there any way to restrict the selectonechoice component to fetch all the data?

答:
Yes. Use iterator's property rangeSize to limit selectOneChoice record count in case that you using separate ViewObject for this LOV.

If you use embeded LOV for ViewObject attribute, then you need to edit corresponding accessor's property, tuning section. Retrieve row from database, only up to row number. Set required value there.


来源: stackexchange

问:
How to standardize the bag of words for train and test?
I am trying to classify based on the bag-of-words model from NLP.

Did pre-processing of the train data using NLTK (punctuation, stop words removal, lower case, stemming etc.)

Created tf-idf matrix for train.

Did pre-processing of test.

Created tf-idf matrix for test data.

Train and Test data have different bag of words so the no of features are different, so we cannot use a classification algo like knn.

I merged the train and test data together and created the tf-idf matrix. This solved the above problem of different bag of words. But the resultant matrix was too huge to process.

Here are my questions:

Is there a way to create the exact bag of words for train and test?

If there is not and my approach of adding train and test is correct, should I go for a dimensionality reduction algo like LDA?

答:
You may use the scikit learn's count vectorizer to first create vectors for given words in the document, use it to train a classifier of your choice and then use the classifer to test your data.

For the training set, you can use the vectorizer to train the data as follows:

```<code> LabeledWords=pd.DataFrame(columns=['word','label'])

 LabeledWords.append({'word':'Church','label':'Religion'} )

 vectorizer = CountVectorizer()

 Xtrain,yTrain=vectorizer.fit_transform(LabeledWords['word']).toarray(),vectorizer.fit_transform(LabeledWords['label']).toarray()
</code>```

You can then train the classifier of your choice with the above vectorizer like:

```<code>forest = RandomForestClassifier(n_estimators = 100)
clf=forest.fit(Xtrain,yTrain)
</code>```

In order to test your data:

```<code>for each_word,label in Preprocessed_list:
    test_featuresX.append(vectorizer.transform(each_word),toarray())
    test_featuresY.append(label.toarray())
clf.score(test_featuresX,test_featuresY)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You may use the scikit learn's count vectorizer to first create vectors for given words in the document, use it to train a classifier of your choice and then use the classifer to test your data.

For the training set, you can use the vectorizer to train the data as follows:

 LabeledWords=pd.DataFrame(columns=['word','label'])

 LabeledWords.append({'word':'Church','label':'Religion'} )

 vectorizer = CountVectorizer()

 Xtrain,yTrain=vectorizer.fit_transform(LabeledWords['word']).toarray(),vectorizer.fit_transform(LabeledWords['label']).toarray()

You can then train the classifier of your choice with the above vectorizer like:

forest = RandomForestClassifier(n_estimators = 100)
clf=forest.fit(Xtrain,yTrain)

In order to test your data:

for each_word,label in Preprocessed_list:
    test_featuresX.append(vectorizer.transform(each_word),toarray())
    test_featuresY.append(label.toarray())
clf.score(test_featuresX,test_featuresY)


问:
Vue+Webpack app deploy on heroku not working when page is refreshed
I generated a vue app using vue-cli with webpack template and deployed it to heroku using this guide. I was able to run it without problem but when I refresh the page, or I accessed a sub route directly it fails.

server.js

```<code>var express = require('express')
var path = require('path')
var serveStatic = require('serve-static')
app = express()
app.use(serveStatic(__dirname))
var port = process.env.PORT || 5000
app.listen(port)
console.log('server started '+ port)
</code>```

router.js

My vue router config

export default new Router({ mode: 'history', routes })

答:
Spa's generally have on one index.html and the navigation to other routes in the app is handled by javascript itself. This is causing failure when you refresh or directly access a sub-route.

Since you have history mode configured in your vuejs router configuration using mode: 'history' you can consider using connect-history-api-fallback as described here: Example server configurations.

npm install --save connect-history-api-fallback

Add this middleware to your express

```<code>var history = require('connect-history-api-fallback');

var express = require('express')
var path = require('path')
var serveStatic = require('serve-static')
app = express()
//add this middleware
app.use(history());
app.use(serveStatic(__dirname))
var port = process.env.PORT || 5000
app.listen(port)
console.log('server started '+ port)
</code>```

Body:
I generated a vue app using vue-cli with webpack template and deployed it to heroku using this guide. I was able to run it without problem but when I refresh the page, or I accessed a sub route directly it fails.

server.js

var express = require('express')
var path = require('path')
var serveStatic = require('serve-static')
app = express()
app.use(serveStatic(__dirname))
var port = process.env.PORT || 5000
app.listen(port)
console.log('server started '+ port)

router.js

My vue router config

export default new Router({ mode: 'history', routes })

Body:
Spa's generally have on one index.html and the navigation to other routes in the app is handled by javascript itself. This is causing failure when you refresh or directly access a sub-route.

Since you have history mode configured in your vuejs router configuration using mode: 'history' you can consider using connect-history-api-fallback as described here: Example server configurations.

npm install --save connect-history-api-fallback

Add this middleware to your express

var history = require('connect-history-api-fallback');

var express = require('express')
var path = require('path')
var serveStatic = require('serve-static')
app = express()
//add this middleware
app.use(history());
app.use(serveStatic(__dirname))
var port = process.env.PORT || 5000
app.listen(port)
console.log('server started '+ port)


问:
Java: problems using stream to read a file
using what has been previously suggested to me here, I'm trying to read a file using Path and streams in the following way:

```<code>Path p= Paths.get(file);
        try (Stream<String> lines = Files.lines(p, StandardCharsets.UTF_8)) { // 1
            lines.map(line -> line.split(";"))                          // 2
                 .forEach(lineAsArray -> {
                     if (lineAsArray[0].equals("E")) {
                         creaEditore(lineAsArray[2], Integer.parseInt(lineAsArray[3]), lineAsArray[4]);
                     }
                     else if (lineAsArray[0].equals("L")) {
                        Libro tmp = null;
                        try {
                            tmp = creaLibro(lineAsArray[1], lineAsArray[2], Integer.parseInt(lineAsArray[3]), Double.parseDouble(lineAsArray[4]), lineAsArray[5]);
                        } catch (NumberFormatException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (EditoreInesistente e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        tmp.setQuantita(Integer.parseInt(lineAsArray[6]));
                     }
                 });
        }
        catch (IOException io)
        {
            System.out.println("Wrong reading");
        }
</code>```

Each line contains at the beginning a letter that corresponds to the object I want to create (either an "Editore" or a "Libro") and the following fields contains the value of its attributes (all fields are separated by a semi-column). However, when executing, I get the following exceptions and errors:

```<code>Exception in thread "main" java.lang.NumberFormatException: For input string: "cheih@gja.it"
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at libreria.Libreria.lambda$4(Libreria.java:122)
    at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(Unknown Source)
    at java.util.stream.ReferencePipeline$3$1.accept(Unknown Source)
    at java.util.Iterator.forEachRemaining(Unknown Source)
    at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Unknown Source)
    at java.util.stream.AbstractPipeline.copyInto(Unknown Source)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(Unknown Source)
    at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(Unknown Source)
    at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(Unknown Source)
    at java.util.stream.AbstractPipeline.evaluate(Unknown Source)
    at java.util.stream.ReferencePipeline.forEach(Unknown Source)
    at libreria.Libreria.leggi(Libreria.java:120)
    at Esempio.main(Esempio.java:20)
</code>```

Debugging I discovered that everything is perfectly working when reading the first line, but then the program is not able to parse it and get each field using lineAsArray[]. Can someone help me? The requirements of the program also asked for not considering lines with incorrect sintax, would my code do something like that automatically?

Here the sintax of my file:

Thanks in advance for your help,
Gianluca.

答:
I think you made a little misstake in the first part. E.g.

```<code>if (lineAsArray[0].equals("E")) {
creaEditore(lineAsArray[2], Integer.parseInt(lineAsArray[3]), lineAsArray[4]);
}
</code>```

Notice how you jumped from index '0' (in the if statement) to index '2' (in the first argument of "creaEditore"). If it wouldnt complain about the wrong argument in the "parseInt" method, this would throw an IndexOutOfBoundException because array indexing starts at 0 instead of 1.

Body:
using what has been previously suggested to me here, I'm trying to read a file using Path and streams in the following way:

Path p= Paths.get(file);
        try (Stream<String> lines = Files.lines(p, StandardCharsets.UTF_8)) { // 1
            lines.map(line -> line.split(";"))                          // 2
                 .forEach(lineAsArray -> {
                     if (lineAsArray[0].equals("E")) {
                         creaEditore(lineAsArray[2], Integer.parseInt(lineAsArray[3]), lineAsArray[4]);
                     }
                     else if (lineAsArray[0].equals("L")) {
                        Libro tmp = null;
                        try {
                            tmp = creaLibro(lineAsArray[1], lineAsArray[2], Integer.parseInt(lineAsArray[3]), Double.parseDouble(lineAsArray[4]), lineAsArray[5]);
                        } catch (NumberFormatException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (EditoreInesistente e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        tmp.setQuantita(Integer.parseInt(lineAsArray[6]));
                     }
                 });
        }
        catch (IOException io)
        {
            System.out.println("Wrong reading");
        }

Each line contains at the beginning a letter that corresponds to the object I want to create (either an "Editore" or a "Libro") and the following fields contains the value of its attributes (all fields are separated by a semi-column). However, when executing, I get the following exceptions and errors:

Exception in thread "main" java.lang.NumberFormatException: For input string: "cheih@gja.it"
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at libreria.Libreria.lambda$4(Libreria.java:122)
    at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(Unknown Source)
    at java.util.stream.ReferencePipeline$3$1.accept(Unknown Source)
    at java.util.Iterator.forEachRemaining(Unknown Source)
    at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Unknown Source)
    at java.util.stream.AbstractPipeline.copyInto(Unknown Source)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(Unknown Source)
    at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(Unknown Source)
    at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(Unknown Source)
    at java.util.stream.AbstractPipeline.evaluate(Unknown Source)
    at java.util.stream.ReferencePipeline.forEach(Unknown Source)
    at libreria.Libreria.leggi(Libreria.java:120)
    at Esempio.main(Esempio.java:20)

Debugging I discovered that everything is perfectly working when reading the first line, but then the program is not able to parse it and get each field using lineAsArray[]. Can someone help me? The requirements of the program also asked for not considering lines with incorrect sintax, would my code do something like that automatically?

Here the sintax of my file:

Thanks in advance for your help,
Gianluca.

Body:
I think you made a little misstake in the first part. E.g.

if (lineAsArray[0].equals("E")) {
creaEditore(lineAsArray[2], Integer.parseInt(lineAsArray[3]), lineAsArray[4]);
}

Notice how you jumped from index '0' (in the if statement) to index '2' (in the first argument of "creaEditore"). If it wouldnt complain about the wrong argument in the "parseInt" method, this would throw an IndexOutOfBoundException because array indexing starts at 0 instead of 1.


问:
How to scale symbols (circles) on plot of point realization
I am learning to make some plots in spatstat. I created a poisson point process of just one kind and attached some marks to it - a numerical value. Now when I plot, the plot has by default - circles. These circles are of relative proportion , But these circles are too big on my network. I want to ask if there is some scaling factor to control size of these circles drawn at point realizations.

So, I extracted points from point pattern process and using their x,y I was able to control this with the cex argument in plot function. But this does not control the size in the legend. So I tried to define a basic r legend() function to draw it on the plot. This is lot of additional work and is specific to each case.

So I am wondering if there is some scaling argument for plotting these realizations and their legends from within the spatstat functions.

Could someone guide me please.

答:
You use the argument markscale to set the scaling of the marks (incl.
in the legend). The built-in dataset spruces has both coordinates and
marks in meters, so to represent the tree sizes on a true scale you set
markscale = 1. This means that the diameter (and not the radius as
previously) of the circle representing the tree is equal to the mark
value measured in the coordinate units of the window. So this would be a
"true" map of the forrest:

library(spatstat)
plot(spruces, markscale = 1)
#> Warning: Interpretation of arguments maxsize and markscale has changed (in
#> spatstat version 1.37-0 and later). Size of a circle is now measured by its
#> diameter.
```

<p><img src="https://i.imgur.com/qA38eui.png" alt=""></p>

<p>If the mark values had been in decimetre you would have to do</p>

<pre class="lang-r prettyprint-override"><code>plot(spruces, markscale = 10)
</code>```

Body:
You use the argument markscale to set the scaling of the marks (incl.
in the legend). The built-in dataset spruces has both coordinates and
marks in meters, so to represent the tree sizes on a true scale you set
markscale = 1. This means that the diameter (and not the radius as
previously) of the circle representing the tree is equal to the mark
value measured in the coordinate units of the window. So this would be a
"true" map of the forrest:

library(spatstat)
plot(spruces, markscale = 1)
#> Warning: Interpretation of arguments maxsize and markscale has changed (in
#> spatstat version 1.37-0 and later). Size of a circle is now measured by its
#> diameter.

If the mark values had been in decimetre you would have to do

plot(spruces, markscale = 10)


问:
Adding UITableView on top of UIView
I want to add UITableView on top of UIView. Here's an image  of what exactly i want to do.
Sample code link/tutorial is appreciated.
Thanks

答: UIPopoverController + UITableViewController is all what you need. ;)</p>

ContentLicense: CC BY-SA 2.5

Title: Adding UITableView on top of UIView


问:
BigDump can't import because of constraint of foreign key phpMyAdmin
We are trying to get our database imported in our new DataBase environment.
At first we tried using the phpMyAdmin import function but the database is too big to do that.
Next, we used BigDump but it also gave us an error of a constraint of the foreign key.

I already took a look what this meant and I saw that the table is unable to drop, replace or update because it can't break the foreign key.

Is there any way to avoid this error?

I have tried this query (I don't have experience using queries):

```<code>SET FOREIGN_KEY_CHECKS=0;
</code>```

But unfortunately this didn't work.

Any more information needed? Feel free to ask!

Thanks in advance!

答:
When you use my BigDump script uncomment this line in bigdump.php config section in order to disable foreign key checks for each import session:</p>

```<code>$pre_query[]='SET foreign_key_checks = 0';
</code>```

Body:
We are trying to get our database imported in our new DataBase environment.
At first we tried using the phpMyAdmin import function but the database is too big to do that.
Next, we used BigDump but it also gave us an error of a constraint of the foreign key.

I already took a look what this meant and I saw that the table is unable to drop, replace or update because it can't break the foreign key.

Is there any way to avoid this error?

I have tried this query (I don't have experience using queries):

SET FOREIGN_KEY_CHECKS=0;

But unfortunately this didn't work.

Any more information needed? Feel free to ask!

Thanks in advance!

Body:
When you use my BigDump script uncomment this line in bigdump.php config section in order to disable foreign key checks for each import session:

$pre_query[]='SET foreign_key_checks = 0';


问:
incorrect syntax near where but all the brackets are in the right places
```<code>SELECT
    [GMI Division#], [GMI Division],
    [Type_Mapping],
    SUM(Delv_EQC_Fctr) AS Delv_EQC_Fctr,
    SUM(Cuts_EQC_Fctr) AS Cuts_EQC_Fctr
FROM
    (SELECT
         [GMI Division#], [GMI Division],
         [Type_Mapping], [Base Product#],
         SUM([BUoM_Delivery Quantity]) * ([dbo].[CF_VEDW_PRD_MATL_DIM_N].[EQC_FCTR]) AS Delv_EQC_Fctr,
         (SUM([BUoM_GMI Order Cut Total]) + SUM([BUoM_GMI Delivery Cut Total])) * ([dbo].[CF_VEDW_PRD_MATL_DIM_N].[EQC_FCTR]) AS Cuts_EQC_Fctr
     FROM
         [dbo].[CF_Weekly_Casefill_Final_TY]
     LEFT JOIN
         [dbo].[CF_VEDW_PRD_MATL_DIM_N] ON [dbo].[CF_Weekly_Casefill_Final_TY].[Base Product#] = CAST([dbo].[CF_VEDW_PRD_MATL_DIM_N].[BASPRD_NBR] AS BIGINT)
     GROUP BY
         [GMI Division#], [GMI Division], [Type_Mapping], [Base Product#],
         [EQC_FCTR], [BUoM_Delivery Quantity], [BUoM_GMI Order Cut Total], [BUoM_GMI Delivery Cut Total])
WHERE
    (([GMI Division#] IN (01, 03, 12, 16, 50)
      AND [Distribution channel] IN ('RT', 'ML')) OR
     ([GMI Division#] IN (08) AND [Distribution channel] IN ('FS')))
    AND RIGHT([Fiscal Year/Period], 4) IN (2018)
GROUP BY
    [GMI Division#], [GMI Division], [Type_Mapping], [EQC_FCTR]
</code>```

This throws an error "incorrect syntax near where"

答:
You have to give it a temp name as following notice MyTable:

```<code>Select [GMI Division#],[GMI Division],[Type_Mapping],Sum(Delv_EQC_Fctr) as Delv_EQC_Fctr,Sum(Cuts_EQC_Fctr) as Cuts_EQC_Fctr
from (
select[GMI Division#],[GMI Division],[Type_Mapping],[Base Product#],Sum([BUoM_Delivery Quantity])*([dbo].[CF_VEDW_PRD_MATL_DIM_N].[EQC_FCTR]) as Delv_EQC_Fctr,
    (Sum([BUoM_GMI Order Cut Total])+Sum([BUoM_GMI Delivery Cut Total]))*([dbo].[CF_VEDW_PRD_MATL_DIM_N].[EQC_FCTR]) as Cuts_EQC_Fctr
    from[dbo].[CF_Weekly_Casefill_Final_TY]left join [dbo].[CF_VEDW_PRD_MATL_DIM_N] on
    [dbo].[CF_Weekly_Casefill_Final_TY].[Base Product#]=cast([dbo].[CF_VEDW_PRD_MATL_DIM_N].[BASPRD_NBR] as bigint)
    group by[GMI Division#],[GMI Division],[Type_Mapping],[Base Product#],[EQC_FCTR],[BUoM_Delivery Quantity],[BUoM_GMI Order Cut Total],[BUoM_GMI Delivery Cut Total]) MyTable
    where (([GMI Division#] in (01,03,12,16,50) and [Distribution channel]in ('RT','ML')) or([GMI Division#] in (08)and [Distribution channel]in ('FS')))
    and  right([Fiscal Year/Period],4) in (2018)
    group by [GMI Division#],[GMI Division],[Type_Mapping],[EQC_FCTR]
</code>```

Body:
SELECT
    [GMI Division#], [GMI Division],
    [Type_Mapping],
    SUM(Delv_EQC_Fctr) AS Delv_EQC_Fctr,
    SUM(Cuts_EQC_Fctr) AS Cuts_EQC_Fctr
FROM
    (SELECT
         [GMI Division#], [GMI Division],
         [Type_Mapping], [Base Product#],
         SUM([BUoM_Delivery Quantity]) * ([dbo].[CF_VEDW_PRD_MATL_DIM_N].[EQC_FCTR]) AS Delv_EQC_Fctr,
         (SUM([BUoM_GMI Order Cut Total]) + SUM([BUoM_GMI Delivery Cut Total])) * ([dbo].[CF_VEDW_PRD_MATL_DIM_N].[EQC_FCTR]) AS Cuts_EQC_Fctr
     FROM
         [dbo].[CF_Weekly_Casefill_Final_TY]
     LEFT JOIN
         [dbo].[CF_VEDW_PRD_MATL_DIM_N] ON [dbo].[CF_Weekly_Casefill_Final_TY].[Base Product#] = CAST([dbo].[CF_VEDW_PRD_MATL_DIM_N].[BASPRD_NBR] AS BIGINT)
     GROUP BY
         [GMI Division#], [GMI Division], [Type_Mapping], [Base Product#],
         [EQC_FCTR], [BUoM_Delivery Quantity], [BUoM_GMI Order Cut Total], [BUoM_GMI Delivery Cut Total])
WHERE
    (([GMI Division#] IN (01, 03, 12, 16, 50)
      AND [Distribution channel] IN ('RT', 'ML')) OR
     ([GMI Division#] IN (08) AND [Distribution channel] IN ('FS')))
    AND RIGHT([Fiscal Year/Period], 4) IN (2018)
GROUP BY
    [GMI Division#], [GMI Division], [Type_Mapping], [EQC_FCTR]

This throws an error "incorrect syntax near where"

Body:
You have to give it a temp name as following notice MyTable:

Select [GMI Division#],[GMI Division],[Type_Mapping],Sum(Delv_EQC_Fctr) as Delv_EQC_Fctr,Sum(Cuts_EQC_Fctr) as Cuts_EQC_Fctr
from (
select[GMI Division#],[GMI Division],[Type_Mapping],[Base Product#],Sum([BUoM_Delivery Quantity])*([dbo].[CF_VEDW_PRD_MATL_DIM_N].[EQC_FCTR]) as Delv_EQC_Fctr,
    (Sum([BUoM_GMI Order Cut Total])+Sum([BUoM_GMI Delivery Cut Total]))*([dbo].[CF_VEDW_PRD_MATL_DIM_N].[EQC_FCTR]) as Cuts_EQC_Fctr
    from[dbo].[CF_Weekly_Casefill_Final_TY]left join [dbo].[CF_VEDW_PRD_MATL_DIM_N] on
    [dbo].[CF_Weekly_Casefill_Final_TY].[Base Product#]=cast([dbo].[CF_VEDW_PRD_MATL_DIM_N].[BASPRD_NBR] as bigint)
    group by[GMI Division#],[GMI Division],[Type_Mapping],[Base Product#],[EQC_FCTR],[BUoM_Delivery Quantity],[BUoM_GMI Order Cut Total],[BUoM_GMI Delivery Cut Total]) MyTable
    where (([GMI Division#] in (01,03,12,16,50) and [Distribution channel]in ('RT','ML')) or([GMI Division#] in (08)and [Distribution channel]in ('FS')))
    and  right([Fiscal Year/Period],4) in (2018)
    group by [GMI Division#],[GMI Division],[Type_Mapping],[EQC_FCTR]


问:
Update attched sqlite database
I need to update a sqlite db table from another database.
I used the below code to copy it but I can't make it update whenever the single.sqlite db has new rows.

Here is what I have:

```<code>$db = new SQLite3("db/multi_db.db");
// copy/clone single.sqlite to multi_db.db
$db->exec("ATTACH DATABASE 'db/single.sqlite' AS single");
$db->exec('CREATE TABLE "vars" AS SELECT * FROM single."vars"');
// update multi_db with new rows from single.sqlite
$db->exec('UPDATE TABLE "vars" SELECT * FROM single."vars"');
</code>```

I tried different ways to update, but it doesn't do anything.

答:
It looks like you've spelled your table incorrectly. I'm assuming that it should be single."vars", not single."vras".

```<code>$db = new SQLite3("db/multi_db.db");
// copy/clone single.sqlite to multi_db.db
$db->exec("ATTACH DATABASE 'db/single.sqlite' AS single");
$db->exec('CREATE TABLE "vars" AS SELECT * FROM single."vars"');
// update multi_db with new rows from single.sqlite
$db->exec('UPDATE TABLE "vars" SELECT * FROM single."vars"');
</code>```

Title: Update attched sqlite database

Body:
I need to update a sqlite db table from another database.
I used the below code to copy it but I can't make it update whenever the single.sqlite db has new rows.

Here is what I have:

$db = new SQLite3("db/multi_db.db");
// copy/clone single.sqlite to multi_db.db
$db->exec("ATTACH DATABASE 'db/single.sqlite' AS single");
$db->exec('CREATE TABLE "vars" AS SELECT * FROM single."vars"');
// update multi_db with new rows from single.sqlite
$db->exec('UPDATE TABLE "vars" SELECT * FROM single."vars"');

I tried different ways to update, but it doesn't do anything.

Body:
It looks like you've spelled your table incorrectly. I'm assuming that it should be single."vars", not single."vras".

$db = new SQLite3("db/multi_db.db");
// copy/clone single.sqlite to multi_db.db
$db->exec("ATTACH DATABASE 'db/single.sqlite' AS single");
$db->exec('CREATE TABLE "vars" AS SELECT * FROM single."vars"');
// update multi_db with new rows from single.sqlite
$db->exec('UPDATE TABLE "vars" SELECT * FROM single."vars"');


问:
How to calculate form fields values to update hidden field value?
I want to know how to calculate the input values of the following fields

```<code><input type="text" name="score1" class="auto-sum">
<input type="text" name="score2" class="auto-sum">
<input type="text" name="score3" class="auto-sum">
</code>```

And update the span text and the hidden field value

```<code>TOTAL <span id="amountTotal">0 </span>
<input id="total" type="hidden" name="total" value="">
</code>```

Thanks in advance

答:
Try with query each() function .Use with parseFloat convert the string to number .for real time update do with keyup event

$('.auto-sum').keyup(function(){
var a=0;
$('.auto-sum').each(function(){
a+=parseFloat($(this).val())
})
$('#amountTotal').text(a|0)
$('#total').val(a|0)
console.log($('#total')[0].outerHTML)//its show the hidden field value
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="score1" class="auto-sum" value="2" >
<input type="text" name="score2" class="auto-sum" value="5">
<input type="text" name="score3" class="auto-sum" value="5">

TOTAL  <span id="amountTotal" >0 </span>
<input id="total" type="hidden" name="total" value=""></code>```

Body:
I want to know how to calculate the input values of the following fields

<input type="text" name="score1" class="auto-sum">
<input type="text" name="score2" class="auto-sum">
<input type="text" name="score3" class="auto-sum">

And update the span text and the hidden field value

TOTAL 0
<input id="total" type="hidden" name="total" value="">

Thanks in advance

Body:
Try with query each() function .Use with parseFloat convert the string to number .for real time update do with keyup event

$('.auto-sum').keyup(function(){
var a=0;
$('.auto-sum').each(function(){
a+=parseFloat($(this).val())
})
$('#amountTotal').text(a|0)
$('#total').val(a|0)
console.log($('#total')[0].outerHTML)//its show the hidden field value
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="score1" class="auto-sum" value="2" >
<input type="text" name="score2" class="auto-sum" value="5">
<input type="text" name="score3" class="auto-sum" value="5">

TOTAL  <span id="amountTotal" >0 </span>
<input id="total" type="hidden" name="total" value="">


问:
How to edit Sublime Text 3 Soda Theme
I installed the Soda Theme on Sublime Text 3 on OSX and I was wondering where are the actual files and folder to the theme that way I could look at the theme file and make my own edits to it, along with I would like to adjust a few of the images used in the theme. </p>

<p>On the Git documents it says if you are to manually install Soda on Sublime you place the soda folder in the package directory, although when I install Soda via Control Package I don't see the Soda theme in package directory. </p>

答:
This answer is similar to the accepted solution, but with little more steps if it is not working out of the box. This might help someone if they are stuck with an issue which I have described in one of the below steps.

install PackageResourceViewer using Package Control

Go to Preferences->Package Settings->PackageResourceViewer->Setting-User. copy paste the following 3 lines,save and close it.

```<code>{
"single_command": false
}
</code>```

press Ctrl+shift+p to open Package Control and select PackageResourceViewer: Edit Package Resource from the list. Find the package you want to edit and click on it. In my case, I want to edit a theme which is installed via ColorSublime Package, So I selected that theme.

Now you will see that the selected package file opened in the sublime editor itself. Edit it as you want and save it and close it. The changes should reflect in sublime editor. In my case, since I changed the theme I need reload it. So I continued with the following steps too.

go to view menu select 'Show Console' and run following command to reset the theme.

```<code>view.settings().erase("color_scheme")
</code>```

open Preferences->Settings and delete the "color_scheme" attribute and its value from the settings file and close it. Again select the color theme from Preferences->Color scheme. Now you should able to see the changes reflected which you made in the theme package.

Hope this helps!

Title: How to edit Sublime Text 3 Soda Theme

Body:
I installed the Soda Theme on Sublime Text 3 on OSX and I was wondering where are the actual files and folder to the theme that way I could look at the theme file and make my own edits to it, along with I would like to adjust a few of the images used in the theme.

On the Git documents it says if you are to manually install Soda on Sublime you place the soda folder in the package directory, although when I install Soda via Control Package I don't see the Soda theme in package directory.

Body:
This answer is similar to the accepted solution, but with little more steps if it is not working out of the box. This might help someone if they are stuck with an issue which I have described in one of the below steps.

install PackageResourceViewer using Package Control

Go to Preferences->Package Settings->PackageResourceViewer->Setting-User. copy paste the following 3 lines,save and close it.

{
"single_command": false
}

press Ctrl+shift+p to open Package Control and select PackageResourceViewer: Edit Package Resource from the list. Find the package you want to edit and click on it. In my case, I want to edit a theme which is installed via ColorSublime Package, So I selected that theme.

Now you will see that the selected package file opened in the sublime editor itself. Edit it as you want and save it and close it. The changes should reflect in sublime editor. In my case, since I changed the theme I need reload it. So I continued with the following steps too.

go to view menu select 'Show Console' and run following command to reset the theme.

view.settings().erase("color_scheme")

open Preferences->Settings and delete the "color_scheme" attribute and its value from the settings file and close it. Again select the color theme from Preferences->Color scheme. Now you should able to see the changes reflected which you made in the theme package.

Hope this helps!


问:
sqlserver sum with minus
I use sqlserver 2012.
I have a query like this

```<code>SELECT SUM(TH.CLEAVE_EARN_DAY), SUM(TH.CLEAVE_DAY),
       SUM(TH.CLEAVE_EARN_DAY) - SUM(TH.CLEAVE_DAY)
FROM TH_LEAVE_CARD TH
</code>```

The result is 0, 14.5, -15
so -15 is wrong. Must be -14.5

any suggestion ?

答:
To perform mathematical operations on columns:

Used columns should be converted into same numeric/decimal data type.

To handle null values you may use ISNULL function.
Ex:

```<code>SELECT SUM(TH.CLEAVE_EARN_DAY), SUM(TH.CLEAVE_DAY),
   SUM(cast  (TH.CLEAVE_EARN_DAY) as decimal(5,1)) - SUM(cast ( (TH.CLEAVE_DAY) as decimal(5,1))
FROM TH_LEAVE_CARD
</code>```

Title: sqlserver sum with minus

Body:
I use sqlserver 2012.
I have a query like this

SELECT SUM(TH.CLEAVE_EARN_DAY), SUM(TH.CLEAVE_DAY),
       SUM(TH.CLEAVE_EARN_DAY) - SUM(TH.CLEAVE_DAY)
FROM TH_LEAVE_CARD TH

The result is 0, 14.5, -15
so -15 is wrong. Must be -14.5

any suggestion ?

Body:
To perform mathematical operations on columns:

Used columns should be converted into same numeric/decimal data type.

To handle null values you may use ISNULL function.
Ex:

SELECT SUM(TH.CLEAVE_EARN_DAY), SUM(TH.CLEAVE_DAY),
   SUM(cast  (TH.CLEAVE_EARN_DAY) as decimal(5,1)) - SUM(cast ( (TH.CLEAVE_DAY) as decimal(5,1))
FROM TH_LEAVE_CARD


问:
How to add implicit imports to ipython?
I am using a the PYTHONSTARTUP=~/pythonstartup.py approach in order to make ipython the default python shell but I want to extend it do have some additional imports by default (like importing few common packages).

How can I do that?

```<code>#!/usr/bin/env python
import os
import sys
import re
import time
import platform
import IPython

os.environ['PYTHONSTARTUP'] = ''  # Prevent running this again
IPython.start_ipython()
raise SystemExit
</code>```

答:
Problem solved by adding</p>

```<code>IPython.start_ipython(user_ns=locals())
</code>```

Title: How to add implicit imports to ipython?

Body:
I am using a the PYTHONSTARTUP=~/pythonstartup.py approach in order to make ipython the default python shell but I want to extend it do have some additional imports by default (like importing few common packages).

How can I do that?

#!/usr/bin/env python
import os
import sys
import re
import time
import platform
import IPython

os.environ['PYTHONSTARTUP'] = ''  # Prevent running this again
IPython.start_ipython()
raise SystemExit

Body:
Problem solved by adding

IPython.start_ipython(user_ns=locals())


问:
Can't programmatically hide UIButton created with IB
My iOS UIButton is correctly linked from IB to an IBOutlet in my view controller, as I can change its title from my code. Ie:

```<code>[self.myButton setTitle:@"new title" forState:UIControlStateNormal]; //works
</code>```

However,

```<code>[self.myButton setHidden:YES]; //doesn't work
//or
self.myButton.hidden = YES; //doesn't work
</code>```

What's going on? How can I make myButton disappear?

Update: some additional info

Here's the code related in to my UIButton:

in my .h file

```<code>IBOutlet UIButton *myButton;
-(IBAction)pushedMyButton:(id)sender;
@property (nonatomic,retain) UIButton *myButton;
</code>```

in my .m file

```<code>@synthesize myButton;
- (void)pushedMyButton:(id)sender{
    self.myButton.hidden = YES;
}
- (void)dealloc{
    [self.myButton release];
}
</code>```

答: That should work, try rename it and hide it just to check that there aren't two buttons on top of each other.</p>

Body:
My iOS UIButton is correctly linked from IB to an IBOutlet in my view controller, as I can change its title from my code. Ie:

[self.myButton setTitle:@"new title" forState:UIControlStateNormal]; //works

However,

[self.myButton setHidden:YES]; //doesn't work
//or
self.myButton.hidden = YES; //doesn't work

What's going on? How can I make myButton disappear?

Update: some additional info

Here's the code related in to my UIButton:

in my .h file

IBOutlet UIButton *myButton;
-(IBAction)pushedMyButton:(id)sender;
@property (nonatomic,retain) UIButton *myButton;

in my .m file

@synthesize myButton;
- (void)pushedMyButton:(id)sender{
    self.myButton.hidden = YES;
}
- (void)dealloc{
    [self.myButton release];
}


问:
How to add a Reason for Deletion to all DRF Delete APIs
In a Django Rest Framework app using Django Simple History to track model changes, how would one force a user to pass a Reason for Deletion for all Destroy End Points and then pass that reason to Django Simple History's Change Reason?

Also, for related models with a Delete Cascade, would that reason be passed on to the related deleted entries?

Update:

Tried overriding the destroy method as below following another question here on SO. Issue is, where is the changeReason i.e. history_change_reason located after the delete? I thought it would be a column in the historical table? However, its not there so even if the code below is working, I can't find where the reason has been saved.

```<code>class DeleteViewSet(mixins.DestroyModelMixin):
    def destroy(self, request, *args, **kwargs):
        try:
            if 'delete_reason' not in request.data.keys():
                return Response(status=status.HTTP_400_BAD_REQUEST,data='{delete_reason: Invalid Delete Reason}')
            else:
                instance = self.get_object()
                instance.changeReason = request.data['delete_reason']
                instance.save()
                self.perform_destroy(instance)
        except Http404:
            pass
        return Response(status=status.HTTP_204_NO_CONTENT)
</code>```

Missing History Change Reason Column:

The only history_* I see in all history tables are:

```<code>1. history_id
2. history_date
3. history_type
4. history_user_id
</code>```

I can't find history_change_reason in any of the history tables

答:
Ok. Found the answer to two of my problems.

Missing History Change Reason Column:

This was a version issue. pip3.6 install --upgrade django-simple-history and then migrate solved this.

Deletion Reason as a Mixin:

This works by checking if deletion_reason is provided.

```<code>class DeleteViewSet(mixins.DestroyModelMixin):
    def destroy(self, request, *args, **kwargs):
        try:
            if 'delete_reason' not in request.data.keys():
                return Response(status=status.HTTP_400_BAD_REQUEST,data='{delete_reason: Invalid Delete Reason}')
            else:
                instance = self.get_object()
                instance.changeReason = request.data['delete_reason']
                # instance.save()  ==>Don't do this because it will cause a second instance to be saved in the history tables
                self.perform_destroy(instance)
        except Http404:
            pass
        return Response(status=status.HTTP_204_NO_CONTENT)
</code>```

Not solved:

Passing the deletion_reason to all tables that are subsequently deleted when you have a delete_cascade in the relation between models.

Body:
In a Django Rest Framework app using Django Simple History to track model changes, how would one force a user to pass a Reason for Deletion for all Destroy End Points and then pass that reason to Django Simple History's Change Reason?

Also, for related models with a Delete Cascade, would that reason be passed on to the related deleted entries?

Update:

Tried overriding the destroy method as below following another question here on SO. Issue is, where is the changeReason i.e. history_change_reason located after the delete? I thought it would be a column in the historical table? However, its not there so even if the code below is working, I can't find where the reason has been saved.

class DeleteViewSet(mixins.DestroyModelMixin):
    def destroy(self, request, *args, **kwargs):
        try:
            if 'delete_reason' not in request.data.keys():
                return Response(status=status.HTTP_400_BAD_REQUEST,data='{delete_reason: Invalid Delete Reason}')
            else:
                instance = self.get_object()
                instance.changeReason = request.data['delete_reason']
                instance.save()
                self.perform_destroy(instance)
        except Http404:
            pass
        return Response(status=status.HTTP_204_NO_CONTENT)

Missing History Change Reason Column:

The only history_* I see in all history tables are:

1. history_id
2. history_date
3. history_type
4. history_user_id

I can't find history_change_reason in any of the history tables

Body:
Ok. Found the answer to two of my problems.

Missing History Change Reason Column:

This was a version issue. pip3.6 install --upgrade django-simple-history and then migrate solved this.

Deletion Reason as a Mixin:

This works by checking if deletion_reason is provided.

class DeleteViewSet(mixins.DestroyModelMixin):
    def destroy(self, request, *args, **kwargs):
        try:
            if 'delete_reason' not in request.data.keys():
                return Response(status=status.HTTP_400_BAD_REQUEST,data='{delete_reason: Invalid Delete Reason}')
            else:
                instance = self.get_object()
                instance.changeReason = request.data['delete_reason']
                # instance.save()  ==>Don't do this because it will cause a second instance to be saved in the history tables
                self.perform_destroy(instance)
        except Http404:
            pass
        return Response(status=status.HTTP_204_NO_CONTENT)

Not solved:

Passing the deletion_reason to all tables that are subsequently deleted when you have a delete_cascade in the relation between models.


问:
Neo4J - Return Node Name instead of ID
I would like to know how I can return the node names instead of the node IDs in the Java console.

The following output is shown in the console:

The desired output should look like:

Just without all the information but only with the Node names (which equal Airportnames).

My Java code looks like the following:

```<code>    package com.routesNeo4j;

import org.neo4j.driver.v1.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by e on 11.06.17.
 */
public class Neo4JRouting implements AutoCloseable, Neo4J_Connector {

    static Driver driver;

    public Neo4JRouting(String startAirport, String destinationAirport, StatementResult shortestPath) {

        driver = GraphDatabase.driver("bolt://ec2-13-58-101-13.us-east-2.compute.amazonaws.com:7687",
                AuthTokens.basic("neo4j", "Einloggen_123"));

        try(Session session = driver.session()) {

            shortestPath = session.run("MATCH (a:" + startAirport.toLowerCase() + "), (b:" + destinationAirport.toLowerCase()
            + "), p = allShortestPaths((a)-[r*1..4]-(b)) UNWIND rels(p) AS rel RETURN nodes(p), sum(rel.weight) " +
                    "AS weight ORDER BY sum(rel.weight)");

            List<Record> storeList = storeList(shortestPath);
            while (shortestPath.hasNext()) {
                System.out.println(shortestPath.next().toString());
            }
            System.out.println(storeList);

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

    public List<Record> storeList(StatementResult statementResult) {

        List<Record> list = new ArrayList<>();
        while (statementResult.hasNext()) {

            list.add(statementResult.next());

        }

        return list;

    }

    @Override
    public Driver runDriver(String user, AuthToken basicAuthToken) throws Exception {
        return null;
    }

    @Override
    public void close() throws Exception {

    }

}
</code>```

I am looking forward to your answers. Many thanks!

答:
Every row you are returning contains a list of nodes and a weight. That's what you ask in your query and that's what you get. So you have to "unpack" that result into the format that you desire.

Couple of code-snippets to show what I mean :

```<code>        StatementResult vResult = vSession.run(aCypher);

        while (vResult.hasNext()) {
            Record vRecord = vResult.next();

            vMutator.pushNode("row");

            for (Pair <String, Value> vListEntry : vRecord.fields()) {
                process_listentry(vSession, vMutator, vListEntry.key(), vListEntry.value());
            }

            vMutator.popNode(); // row
        }
</code>```

and then in process_listentry :

```<code>private void process_listentry(Session vSession, IHDSMutator vMutator, String vKey, Value vValue) {
...
    else if (vValue.type().equals(vSession.typeSystem().NODE())){
        vMutator.pushNode(vKey);
        vMutator.addNode("_id", Long.toString(vValue.asNode().id()));
        for (String lLabel : vValue.asNode().labels()) {
            vMutator.addNode("_label", lLabel);
        }
        for (String lKey : vValue.asNode().keys()) {
            Value lValue = vValue.asNode().get(lKey);
            process_listentry(vSession, vMutator, lKey, lValue);
        }
        vMutator.popNode();
    }
</code>```

...
but it does depend on what you ask in the query and thus have to unpack ...

Hope this helps,
Tom

Title: Neo4J - Return Node Name instead of ID

Body:
I would like to know how I can return the node names instead of the node IDs in the Java console.

The following output is shown in the console:

The desired output should look like:

Just without all the information but only with the Node names (which equal Airportnames).

My Java code looks like the following:

    package com.routesNeo4j;

import org.neo4j.driver.v1.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by e on 11.06.17.
 */
public class Neo4JRouting implements AutoCloseable, Neo4J_Connector {

    static Driver driver;

    public Neo4JRouting(String startAirport, String destinationAirport, StatementResult shortestPath) {

        driver = GraphDatabase.driver("bolt://ec2-13-58-101-13.us-east-2.compute.amazonaws.com:7687",
                AuthTokens.basic("neo4j", "Einloggen_123"));

        try(Session session = driver.session()) {

            shortestPath = session.run("MATCH (a:" + startAirport.toLowerCase() + "), (b:" + destinationAirport.toLowerCase()
            + "), p = allShortestPaths((a)-[r*1..4]-(b)) UNWIND rels(p) AS rel RETURN nodes(p), sum(rel.weight) " +
                    "AS weight ORDER BY sum(rel.weight)");

            List<Record> storeList = storeList(shortestPath);
            while (shortestPath.hasNext()) {
                System.out.println(shortestPath.next().toString());
            }
            System.out.println(storeList);

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

    public List<Record> storeList(StatementResult statementResult) {

        List<Record> list = new ArrayList<>();
        while (statementResult.hasNext()) {

            list.add(statementResult.next());

        }

        return list;

    }

    @Override
    public Driver runDriver(String user, AuthToken basicAuthToken) throws Exception {
        return null;
    }

    @Override
    public void close() throws Exception {

    }

}

I am looking forward to your answers. Many thanks!

Body:
Every row you are returning contains a list of nodes and a weight. That's what you ask in your query and that's what you get. So you have to "unpack" that result into the format that you desire.

Couple of code-snippets to show what I mean :

        StatementResult vResult = vSession.run(aCypher);

        while (vResult.hasNext()) {
            Record vRecord = vResult.next();

            vMutator.pushNode("row");

            for (Pair <String, Value> vListEntry : vRecord.fields()) {
                process_listentry(vSession, vMutator, vListEntry.key(), vListEntry.value());
            }

            vMutator.popNode(); // row
        }

and then in process_listentry :

private void process_listentry(Session vSession, IHDSMutator vMutator, String vKey, Value vValue) {
...
    else if (vValue.type().equals(vSession.typeSystem().NODE())){
        vMutator.pushNode(vKey);
        vMutator.addNode("_id", Long.toString(vValue.asNode().id()));
        for (String lLabel : vValue.asNode().labels()) {
            vMutator.addNode("_label", lLabel);
        }
        for (String lKey : vValue.asNode().keys()) {
            Value lValue = vValue.asNode().get(lKey);
            process_listentry(vSession, vMutator, lKey, lValue);
        }
        vMutator.popNode();
    }

...
but it does depend on what you ask in the query and thus have to unpack ...

Hope this helps,
Tom


问:
Custom EditText freezes on clearing text using backspace
I have implemented a Custom EditText which can take Bold, Italics, Underline text.
Everything works fine except when I try to delete text by long pressing the backspace button. On long pressing backspace there is a delay in clearing the text.

Here is the overriden onTextChanged() method

```<code>protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {

    Log.d(VIEW_LOG_TAG,"Start: "+start+" Length before: "+lengthBefore+" Length After: "+lengthAfter+" TextLength: "+text.length());
    Spannable str = this.getText();
    CharacterStyle ss;
    UnderlineSpan ss1=null;
    int endLength = text.toString().length();

    switch (currentTypeface) {
        case TYPEFACE_NORMAL:
            ss = new StyleSpan(Typeface.NORMAL);
            break;
        case TYPEFACE_BOLD:
            ss = new StyleSpan(Typeface.BOLD);
            break;
        case TYPEFACE_ITALICS:
            ss = new StyleSpan(Typeface.ITALIC);
            break;
        case TYPEFACE_BOLD_ITALICS:
            ss = new StyleSpan(Typeface.BOLD_ITALIC);
            break;
        case TYPEFACE_UNDERLINE:
            ss= new UnderlineSpan();
            break;
        case TYPEFACE_BOLD_UNDERLINE:
            ss = new StyleSpan(Typeface.BOLD);
            ss1=new UnderlineSpan();
            break;
        case TYPEFACE_ITALICS_UNDERLINE:
            ss = new StyleSpan(Typeface.ITALIC);
            ss1=new UnderlineSpan();
            break;
        case TYPEFACE_BOLD_ITALICS_UNDERLINE:
            ss = new StyleSpan(Typeface.BOLD_ITALIC);
            ss1=new UnderlineSpan();
            break;
        default:
            ss = new StyleSpan(Typeface.NORMAL);
    }
        if(lastCursorPosition>endLength)
            return;
        Log.d(TextArea.class.getSimpleName(), new Integer(lastCursorPosition).toString() + new Integer(endLength).toString());
    if(ss1!=null)
        str.setSpan(ss1, lastCursorPosition, endLength, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        str.setSpan(ss, lastCursorPosition, endLength, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
</code>```

答:
That isn't a function of EditText, its a function of TextWatcher.  You aren't making a custom EditText, you're trying to do a quick hack to avoid making a custom EditText.  The difference is important because your technique lacks a lot of the power that creating a real custom edit text would have.

Secondly-  are you sure the delay isn't in the keyboard?  A typical technique for keys who's longpress is different than short press is to delay the action.  Many keyboards even allow you to customize the delay (see Swype for example).  So it may not be your code delaying it, its the keyboard's built in functionality.  (I think this is the most likely answer).

Third- you're doing things really, really inefficiently.  You should not be creating new Spans every time this is called.  You should be creating 1 set of spans at creation time, and reusing them each time this is called.  That alone would give you a good speedup if it is your performance that's the problem.

Body:
I have implemented a Custom EditText which can take Bold, Italics, Underline text.
Everything works fine except when I try to delete text by long pressing the backspace button. On long pressing backspace there is a delay in clearing the text.

Here is the overriden onTextChanged() method

protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {

    Log.d(VIEW_LOG_TAG,"Start: "+start+" Length before: "+lengthBefore+" Length After: "+lengthAfter+" TextLength: "+text.length());
    Spannable str = this.getText();
    CharacterStyle ss;
    UnderlineSpan ss1=null;
    int endLength = text.toString().length();

    switch (currentTypeface) {
        case TYPEFACE_NORMAL:
            ss = new StyleSpan(Typeface.NORMAL);
            break;
        case TYPEFACE_BOLD:
            ss = new StyleSpan(Typeface.BOLD);
            break;
        case TYPEFACE_ITALICS:
            ss = new StyleSpan(Typeface.ITALIC);
            break;
        case TYPEFACE_BOLD_ITALICS:
            ss = new StyleSpan(Typeface.BOLD_ITALIC);
            break;
        case TYPEFACE_UNDERLINE:
            ss= new UnderlineSpan();
            break;
        case TYPEFACE_BOLD_UNDERLINE:
            ss = new StyleSpan(Typeface.BOLD);
            ss1=new UnderlineSpan();
            break;
        case TYPEFACE_ITALICS_UNDERLINE:
            ss = new StyleSpan(Typeface.ITALIC);
            ss1=new UnderlineSpan();
            break;
        case TYPEFACE_BOLD_ITALICS_UNDERLINE:
            ss = new StyleSpan(Typeface.BOLD_ITALIC);
            ss1=new UnderlineSpan();
            break;
        default:
            ss = new StyleSpan(Typeface.NORMAL);
    }
        if(lastCursorPosition>endLength)
            return;
        Log.d(TextArea.class.getSimpleName(), new Integer(lastCursorPosition).toString() + new Integer(endLength).toString());
    if(ss1!=null)
        str.setSpan(ss1, lastCursorPosition, endLength, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        str.setSpan(ss, lastCursorPosition, endLength, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}


答:
I tried with blur method for after mouseleave from input and check all input values and added ! Then update to wanted element !!

```<code>$("input").on("blur",function(){
    var total = 0;
    $("[type='text']").each(function(){
        if($(this).val() != "") {
            total += parseInt($(this).val());
        }
    });
    $("#amountTotal").text(total);
    $("#total").val(total);
});
</code>```

Title: How to calculate form fields values to update hidden field value?

Body:
I tried with blur method for after mouseleave from input and check all input values and added ! Then update to wanted element !!

$("input").on("blur",function(){
    var total = 0;
    $("[type='text']").each(function(){
        if($(this).val() != "") {
            total += parseInt($(this).val());
        }
    });
    $("#amountTotal").text(total);
    $("#total").val(total);
});


答:
You can use <input type="number" /> inputs to force values entered to be a number.

From there you can call jQuery with the query selector input.auto-sum to get all of the input elements with the class auto-sum

Using the each function you can add the numeric to an accumulator to get the total.

You can then use jQuery with the query selectors needed to set any other elements on the page with the Total value.

function getTotal() {
   var total=0;
   $('input.auto-sum').each(function(i,e)
   {
      total += Number($(e).val());

   });
   $('#amountTotal').text(total);
   $('#total').val(total);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Score 1: <input type="number" name="score1" class="auto-sum"><br />
Score 2: <input type="number" name="score2" class="auto-sum"><br />
Score 3: <input type="number" name="score3" class="auto-sum"><br />
TOTAL:  <span id="amountTotal">0 </span><br />
<input id="total" type="hidden" name="total" value="">
<input type="button" id="btnTotal" onclick="getTotal()" value="Get Total" /></code>```

Body:
You can use <input type="number" /> inputs to force values entered to be a number.

From there you can call jQuery with the query selector input.auto-sum to get all of the input elements with the class auto-sum

Using the each function you can add the numeric to an accumulator to get the total.

You can then use jQuery with the query selectors needed to set any other elements on the page with the Total value.

function getTotal() {
   var total=0;
   $('input.auto-sum').each(function(i,e)
   {
      total += Number($(e).val());

   });
   $('#amountTotal').text(total);
   $('#total').val(total);
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Score 1: <input type="number" name="score1" class="auto-sum"><br />
Score 2: <input type="number" name="score2" class="auto-sum"><br />
Score 3: <input type="number" name="score3" class="auto-sum"><br />
TOTAL:  <span id="amountTotal">0 </span><br />
<input id="total" type="hidden" name="total" value="">
<input type="button" id="btnTotal" onclick="getTotal()" value="Get Total" />


问:
How to generate UUID in Mapreduce?
I want to write a MapReduce java Program where I need to create UUID for a set of data in csv/txt file. The data will be a customer data with set of rows and column. The input csv is located in the HDFS directory.

Just need to generate UUID using Mapreduce.
I have an input file which has colums a, b and c and has 5 rows.
I need a column d with UUID with 5 rows i.e. 5 different UUIDs

How can i go about it?

Here is the code for Mapper class:

public class MapRed_Mapper extends Mapper{

```<code>public void map(Text key, Text value, Context context) throws IOException, InterruptedException
{
     Text uuid = new Text(UUID.randomUUID().toString());
    context.write(key, uuid);
}
</code>```

}

答:
Mapreduce java approach

1) Read your rows in mapper  class map method from text file

2) add UUID as shown below in reduce method as extra column (use single reducer to reduce your csv as extracolumn)

3) emit it through context.write

java.util.UUID, available since JDK 5.

Creating a random UUID (Universally unique identifier).

To obtain the value of the random string generated we need to call the UUID.toString() method.

```<code>    UUID uuid = UUID.randomUUID();
    String randomUUIDString = uuid.toString();

    System.out.println("Random UUID String = " + randomUUIDString);
   // System.out.println("UUID version       = " + uuid.version());
   // System.out.println("UUID variant       = " + uuid.variant());
</code>```

For CSV genearation :

Use TextOutputFormat. The default key/ value separator is a tab character.Change the separator by setting the property mapred.textoutputformat.separatorText in your driver.

```<code>conf.set("mapred.textoutputformat.separatorText", ",");
</code>```

Spark Approach (since you added spark tag I thought of giving below pointer) :

There is already existing answer in SO, pls see.

add-a-new-column-to-a-dataframe-new-column-i-want-it-to-be-a-uuid-generator

Then you can do below to convert to csv format.

```<code>df.write.format("com.databricks.spark.csv").save(filepath)
</code>```

Title: How to generate UUID in Mapreduce?

Body:
I want to write a MapReduce java Program where I need to create UUID for a set of data in csv/txt file. The data will be a customer data with set of rows and column. The input csv is located in the HDFS directory.

Just need to generate UUID using Mapreduce.
I have an input file which has colums a, b and c and has 5 rows.
I need a column d with UUID with 5 rows i.e. 5 different UUIDs

How can i go about it?

Here is the code for Mapper class:

public class MapRed_Mapper extends Mapper{

public void map(Text key, Text value, Context context) throws IOException, InterruptedException
{
     Text uuid = new Text(UUID.randomUUID().toString());
    context.write(key, uuid);
}

}

Body:
Mapreduce java approach

1) Read your rows in mapper  class map method from text file

2) add UUID as shown below in reduce method as extra column (use single reducer to reduce your csv as extracolumn)

3) emit it through context.write

java.util.UUID, available since JDK 5.

Creating a random UUID (Universally unique identifier).

To obtain the value of the random string generated we need to call the UUID.toString() method.

    UUID uuid = UUID.randomUUID();
    String randomUUIDString = uuid.toString();

    System.out.println("Random UUID String = " + randomUUIDString);
   // System.out.println("UUID version       = " + uuid.version());
   // System.out.println("UUID variant       = " + uuid.variant());

For CSV genearation :

Use TextOutputFormat. The default key/ value separator is a tab character.Change the separator by setting the property mapred.textoutputformat.separatorText in your driver.

conf.set("mapred.textoutputformat.separatorText", ",");

Spark Approach (since you added spark tag I thought of giving below pointer) :

There is already existing answer in SO, pls see.

add-a-new-column-to-a-dataframe-new-column-i-want-it-to-be-a-uuid-generator

Then you can do below to convert to csv format.

df.write.format("com.databricks.spark.csv").save(filepath)


问:
Cloning a repo without tags?
I want to create bare git project without tags using clone.But through Google came to know that there is no option like "--no-tags".

Is there any way to clone without tags like below?

```<code>$ git clone {path}/test.git --no-tags --mirror
</code>```

Any help will be appreciated!! :)

答:
According to the Release notes of git/2.14.0, now there would be a support to exclude tags while cloning a repository.

```<code>"git clone" learned the "--no-tags" option not to fetch all tags
initially, and also set up the tagopt not to follow any tags in
subsequent fetches.
</code>```

Use the following command in future :-

```<code>git clone <repositoryUrl> --no-tags
</code>```

Title: Cloning a repo without tags?

Body:
I want to create bare git project without tags using clone.But through Google came to know that there is no option like "--no-tags".

Is there any way to clone without tags like below?

$ git clone {path}/test.git --no-tags --mirror

Any help will be appreciated!! :)

Body:
According to the Release notes of git/2.14.0, now there would be a support to exclude tags while cloning a repository.

"git clone" learned the "--no-tags" option not to fetch all tags
initially, and also set up the tagopt not to follow any tags in
subsequent fetches.

Use the following command in future :-

git clone <repositoryUrl> --no-tags


问:
Python date string to date object
How do I convert a string to a date object in python?

The string would be: "24052010" (corresponding to the format: "%d%m%Y")

I don't want a datetime.datetime object, but rather a datetime.date.

答:
you have a date string like this, "24052010" and you want date object for this,

```<code>from datetime import datetime
cus_date = datetime.strptime("24052010", "%d%m%Y").date()
</code>```

this cus_date will give you date object.

you can retrieve date string from your date object using this,

```<code>cus_date.strftime("%d%m%Y")
</code>```

ContentLicense: CC BY-SA 4.0

Title: Python date string to date object

Body:
you have a date string like this, "24052010" and you want date object for this,

from datetime import datetime
cus_date = datetime.strptime("24052010", "%d%m%Y").date()

this cus_date will give you date object.

you can retrieve date string from your date object using this,

cus_date.strftime("%d%m%Y")


答:
This should do what you want to achieve:

function displaySum () {
  var sum = 0;
  // iterate over the input fields
  $('.auto-sum').each(function () {
    var value = $(this).val() || 0;
    var number = parseInt(value, 10); // parse the input value to an integer
    if (isNaN(number)) {
      number = 0;
    }
    sum += number; // add the value to the sum
  });
  // set the value of the two elements
  $('#amountTotal').text(sum);
  $('#total').val(sum);
}

// whenever the value of one of the input fields changes, call the displaySum function
$('.auto-sum').on('change, keyup', displaySum);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="score1" class="auto-sum">
<input type="text" name="score2" class="auto-sum">
<input type="text" name="score3" class="auto-sum">

TOTAL  <span id="amountTotal">0 </span>
<input id="total" type="hidden" name="total" value=""></code>```

Body:
I want to know how to calculate the input values of the following fields

<input type="text" name="score1" class="auto-sum">
<input type="text" name="score2" class="auto-sum">
<input type="text" name="score3" class="auto-sum">

And update the span text and the hidden field value

TOTAL 0
<input id="total" type="hidden" name="total" value="">

Thanks in advance

Body:
This should do what you want to achieve:

function displaySum () {
  var sum = 0;
  // iterate over the input fields
  $('.auto-sum').each(function () {
    var value = $(this).val() || 0;
    var number = parseInt(value, 10); // parse the input value to an integer
    if (isNaN(number)) {
      number = 0;
    }
    sum += number; // add the value to the sum
  });
  // set the value of the two elements
  $('#amountTotal').text(sum);
  $('#total').val(sum);
}

// whenever the value of one of the input fields changes, call the displaySum function
$('.auto-sum').on('change, keyup', displaySum);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="score1" class="auto-sum">
<input type="text" name="score2" class="auto-sum">
<input type="text" name="score3" class="auto-sum">

TOTAL  <span id="amountTotal">0 </span>
<input id="total" type="hidden" name="total" value="">


问:
How to retrieve one table row and list of rows that are connected to the first row in Linq .NET
I have specific problem. I'm not too experienced with SQL so this may be a silly question. I have the following class

```<code>class StructuredResult
{
    public Pay Pay{ get; set; }
    public Processing Processing{ get; set; }
    public Member Member { get; set; }

    public StructuredResult()
    {
    }
}
</code>```

And this is the code I'm getting this with

```<code>var allPaying = (from pay in Entities.Pays
                join prc in Entities.Processingss on pay.IDCalculation equals cal.IDCalculation
                join mbr in Entities.Members on pay.IDMember equals mbr.IDMember

                where pay.IDMember == IDMember
                orderby prc.DateFrom descending
                select new StructuredResult()
                {
                    Pay = pay,
                    Processing = prc,
                    Member = mbr
                }).ToList();
</code>```

The code is working fine I changed things for posting here, maybe some name changes are not ok. What I need to get is this:

```<code>class StructuredResult
{
    public Pay Pay{ get; set; }
    public Processing Processing{ get; set; }
    public Member Member { get; set; }
    public List<PayDetail> PayDetails { get; set; }

    public StructuredResult()
    {
    }
}
</code>```

Does anyone know if this is even possible? Pay detail is connected with Pay.ID = PayDetail.ID
Thanks in advance

答:
In order to also populate StructuredResult with a collection of PayDetails you need to use Group Join. See:

MSDN on GroupJoin

And last Linq to Entities join vs groupjoin.

So:

```<code>var allPaying = from pay in Entities.Pays
                join prc in Entities.Processingss on pay.IDCalculation equals cal.IDCalculation
                join mbr in Entities.Members on pay.IDMember equals mbr.IDMember
                join d in Entities.PayDetails on pay.IDMember equals d.ID into details

                where pay.IDMember == IDMember
                orderby prc.DateFrom descending

                select new StructuredResult()
                {
                    Pay = pay,
                    Processing = prc,
                    Member = mbr,
                    PayDetails = details
                };
</code>```

I'd also recommend that since you are using EF look into Navigation Properties. By defining your classes a bit differently you will get much more capabilities with much less (no need for writing the joins for example)

MSDN - Entity Framework Relationships and Navigation Properties

MSDN - How to: Navigate Relationships Using Navigation Properties

And just a small tip - you are defining a default constructor with no logic in id. If this is true also in the real code then there is no need for it. It is defined automatically.

Body:
I have specific problem. I'm not too experienced with SQL so this may be a silly question. I have the following class

class StructuredResult
{
    public Pay Pay{ get; set; }
    public Processing Processing{ get; set; }
    public Member Member { get; set; }

    public StructuredResult()
    {
    }
}

And this is the code I'm getting this with

var allPaying = (from pay in Entities.Pays
                join prc in Entities.Processingss on pay.IDCalculation equals cal.IDCalculation
                join mbr in Entities.Members on pay.IDMember equals mbr.IDMember

                where pay.IDMember == IDMember
                orderby prc.DateFrom descending
                select new StructuredResult()
                {
                    Pay = pay,
                    Processing = prc,
                    Member = mbr
                }).ToList();

The code is working fine I changed things for posting here, maybe some name changes are not ok. What I need to get is this:

class StructuredResult
{
    public Pay Pay{ get; set; }
    public Processing Processing{ get; set; }
    public Member Member { get; set; }
    public List<PayDetail> PayDetails { get; set; }

    public StructuredResult()
    {
    }
}

Does anyone know if this is even possible? Pay detail is connected with Pay.ID = PayDetail.ID
Thanks in advance

Body:
In order to also populate StructuredResult with a collection of PayDetails you need to use Group Join. See:

MSDN on GroupJoin

And last Linq to Entities join vs groupjoin.

So:

var allPaying = from pay in Entities.Pays
                join prc in Entities.Processingss on pay.IDCalculation equals cal.IDCalculation
                join mbr in Entities.Members on pay.IDMember equals mbr.IDMember
                join d in Entities.PayDetails on pay.IDMember equals d.ID into details

                where pay.IDMember == IDMember
                orderby prc.DateFrom descending

                select new StructuredResult()
                {
                    Pay = pay,
                    Processing = prc,
                    Member = mbr,
                    PayDetails = details
                };

I'd also recommend that since you are using EF look into Navigation Properties. By defining your classes a bit differently you will get much more capabilities with much less (no need for writing the joins for example)

MSDN - Entity Framework Relationships and Navigation Properties

MSDN - How to: Navigate Relationships Using Navigation Properties

And just a small tip - you are defining a default constructor with no logic in id. If this is true also in the real code then there is no need for it. It is defined automatically.


问:
C# Elegant way to handle checking for an item in a collection
I've posted a code sample below. Firstly let me explain

termStore.Groups in the code below is a collection of Group Objects (The exact class is irrelevant).

Checking for null : if (termStore.Groups[groupName] == null) seems like a logical (clean) approach, but if the Groups collection is empty then an exception is produced.

using the termStore.Groups.Contains is not an option either because this expects a strong type i.e: .Contains(Group)... not .Contains(GroupName as string)

Can someone recommend a clean / generic way I can check for if an item exists in collection .

Thank you....

```<code>TermStore termStore = session.TermStores.Where(ts => ts.Name == termStoreName).FirstOrDefault();
                if (termStore.Groups[groupName] == null)
                {
                    termStore.CreateGroup(groupName);
                    termStore.CommitAll();
                }
</code>```

Update: The exact class Sharepoint Taxonomy Classes. http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.taxonomy.group.aspx

Update 2, the exact collection : http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.taxonomy.groupcollection.aspx

答:
I think this is what you are looking for:

```<code>termStore.Groups.ContainsKey(groupName)
</code>```

Checks that the key exists, doesn't throw an exception if it doesn't.  This is assuming that Groups is a collection that implements IDictionary.

Body:
I've posted a code sample below. Firstly let me explain

termStore.Groups in the code below is a collection of Group Objects (The exact class is irrelevant).

Checking for null : if (termStore.Groups[groupName] == null) seems like a logical (clean) approach, but if the Groups collection is empty then an exception is produced.

using the termStore.Groups.Contains is not an option either because this expects a strong type i.e: .Contains(Group)... not .Contains(GroupName as string)

Can someone recommend a clean / generic way I can check for if an item exists in collection .

Thank you....

TermStore termStore = session.TermStores.Where(ts => ts.Name == termStoreName).FirstOrDefault();
                if (termStore.Groups[groupName] == null)
                {
                    termStore.CreateGroup(groupName);
                    termStore.CommitAll();
                }

Update: The exact class Sharepoint Taxonomy Classes. http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.taxonomy.group.aspx

Update 2, the exact collection : http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.taxonomy.groupcollection.aspx

Body:
I think this is what you are looking for:

termStore.Groups.ContainsKey(groupName)

Checks that the key exists, doesn't throw an exception if it doesn't.  This is assuming that Groups is a collection that implements IDictionary.


问:
Create row as a column in stored procedure
I have the following three tables and I want to so as last table using a stored procedure. Can anyone tell me how I can join them?

Disc:

```<code>DiscId  DiscName
1         a
2         b
3         c
</code>```

DiscDetail:

```<code>DiscDetailId  DiscId  DiscDetailName  Percentage
1             1       p               5
2             1       q               10
3             2       r               12
4             2       s               11
5             2       t               13
6             3       u               19
7             3       v               20
</code>```

Pur:

```<code>PurId  DiscId
1      1
2      2
3      1
4      1
</code>```

I want to show data as follows:

```<code>PurId  p  q   r   s   t
1      5  10
2             12  11  13
3      5  10
4      5  10
</code>```

答:
```<code>SELECT PurId ,
CASE WHEN DD.DiscDetailName ='P' THEN DD.Percentage END 'P',
CASE WHEN DD.DiscDetailName ='q' THEN DD.Percentage END 'q',
CASE WHEN DD.DiscDetailName ='r' THEN DD.Percentage END 'r',
CASE WHEN DD.DiscDetailName ='s' THEN DD.Percentage END 's',
CASE WHEN DD.DiscDetailName ='t' THEN DD.Percentage END 't'
FROM
(
SELECT * FROM DISC_DETAIL D
INNER JOIN  CHILD_TABLE CT ON DD.DiscId =CT.DiscId
)DD
</code>```

Try above query.

Body:
I have the following three tables and I want to so as last table using a stored procedure. Can anyone tell me how I can join them?

Disc:

DiscId  DiscName
1         a
2         b
3         c

DiscDetail:

DiscDetailId  DiscId  DiscDetailName  Percentage
1             1       p               5
2             1       q               10
3             2       r               12
4             2       s               11
5             2       t               13
6             3       u               19
7             3       v               20

Pur:

PurId  DiscId
1      1
2      2
3      1
4      1

I want to show data as follows:

PurId  p  q   r   s   t
1      5  10
2             12  11  13
3      5  10
4      5  10

Body:
SELECT PurId ,
CASE WHEN DD.DiscDetailName ='P' THEN DD.Percentage END 'P',
CASE WHEN DD.DiscDetailName ='q' THEN DD.Percentage END 'q',
CASE WHEN DD.DiscDetailName ='r' THEN DD.Percentage END 'r',
CASE WHEN DD.DiscDetailName ='s' THEN DD.Percentage END 's',
CASE WHEN DD.DiscDetailName ='t' THEN DD.Percentage END 't'
FROM
(
SELECT * FROM DISC_DETAIL D
INNER JOIN  CHILD_TABLE CT ON DD.DiscId =CT.DiscId
)DD

Try above query.


问:
create a foreach table in html email template php
I have an email template am trying to send to users after they have ordered for some items. to send the email am using inline css with html as the email teplate where it is saved as .html. the problem is how do i load all the items the user bought into a for each table and pass it to the email html template file before sending it

```<code><tbody style="-webkit-box-sizing: border-box;-moz-box-sizing: border-box;box-sizing: border-box;margin: 0;font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;font-size: 14px;">
    {{ item }}
</tbody>
</code>```

this is my php for sending the mail

```<code>$mail = new PHPMailer;

$mail->From = "email@email.com";
$mail->FromName = "test";
$mail->addAddress($email); //Recipient name is optional
$mail->addReplyTo("email@email.com", "Reply");
$mail->isHTML(true);
$variables = array();
$variables['name'] = 'john';
$template = file_get_contents("eorder.html");
foreach($data as $row){
$eprodname = $this->get_name_from_id('product_name','product','product_id',$row['id']);
$variables['item'] ='<tr style="-webkit-box-sizing: border-box;-moz-box-sizing: border-box;box-sizing: border-box;margin: 0;font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;font-size: 14px;page-break-inside: avoid;">
<td style="-webkit-box-sizing: border-box;-moz-box-sizing: border-box;box-sizing: border-box;margin: 0;font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;font-size: 14px;vertical-align: top;padding: 8px;line-height: 1.428571429;border-top: 1px solid #ddd;background-color: #fff!important;">1</td>
<td style="-webkit-box-sizing: border-box;-moz-box-sizing: border-box;box-sizing: border-box;margin: 0;font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;font-size: 14px;vertical-align: top;padding: 8px;line-height: 1.428571429;border-top: 1px solid #ddd;background-color: #fff!important;">'. $eprodname .'</td>
 <td style="-webkit-box-sizing: border-box;-moz-box-sizing: border-box;box-sizing: border-box;margin: 0;font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;font-size: 14px;vertical-align: top;padding: 8px;line-height: 1.428571429;border-top: 1px solid #ddd;background-color: #fff!important;">'. $row['quantity'] .'</td>
 <td style="-webkit-box-sizing: border-box;-moz-box-sizing: border-box;box-sizing: border-box;margin: 0;font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;font-size: 14px;vertical-align: top;padding: 8px;line-height: 1.428571429;border-top: 1px solid #ddd;background-color: #fff!important;">'. $row['price'] .'</td>
</tr>';

}
foreach($variables as $key => $value)
{
  $template = str_replace('{{ '.$key.' }}', $value, $template);
}
$mail->Subject = "Order Details";
$mail->Body = $template;
$mail->Send();
</code>```

My problem: I have with this code is that if a user orders more than one product, this code will only load the last product on the table

答:
You are replacing {{ item }} with $value! That it is one "key" and you want replace it by your array!!
You should combine your items and then replace with 'item' one time!

Body:
I have an email template am trying to send to users after they have ordered for some items. to send the email am using inline css with html as the email teplate where it is saved as .html. the problem is how do i load all the items the user bought into a for each table and pass it to the email html template file before sending it

    {{ item }}

this is my php for sending the mail

$mail = new PHPMailer;

$mail->From = "email@email.com";
$mail->FromName = "test";
$mail->addAddress($email); //Recipient name is optional
$mail->addReplyTo("email@email.com", "Reply");
$mail->isHTML(true);
$variables = array();
$variables['name'] = 'john';
$template = file_get_contents("eorder.html");
foreach($data as $row){
$eprodname = $this->get_name_from_id('product_name','product','product_id',$row['id']);
$variables['item'] ='

1
'. $eprodname .'
 '. $row['quantity'] .'
 '. $row['price'] .'

';

}
foreach($variables as $key => $value)
{
  $template = str_replace('{{ '.$key.' }}', $value, $template);
}
$mail->Subject = "Order Details";
$mail->Body = $template;
$mail->Send();

My problem: I have with this code is that if a user orders more than one product, this code will only load the last product on the table


问:
Reference one RoslynPad script from another
What I'd like to do is reference one script from another.

One way to make this happen might be using assemblies.  RoslynPad allows compiling a script into an assembly.  Here is what I have tried so far.

Script A, which is compiled to SOME_PATH\thing.dll

```<code>    class Thing
    {
        public string Name { get; set; }
    }
</code>```

Script B

```<code>    #r "SOME_PATH\thing.dll"

    using static Program;

    var t = new Thing();
    t.Name = "TEST";
    t.Name.Dump();
</code>```

This gives the error "The type or namespace 'Thing' could not be found..." so I tried the following.

```<code>    #r "SOME_PATH\thing.dll"

    var t = new Program.Thing();
    t.Name = "TEST";
    t.Name.Dump();
</code>```

This gave the following error "The type name 'Thing' does not exist in the type 'Program'".

Is there a way to "Compile and Save assembly" and then reference it from another script?  Or, is there a more direct way to cross reference between scripts?

答:
What you're looking for is the #load directive:

```<code>#load "Path\To\ScriptA.csx"

var t = new Thing();
</code>```

You can read more about the C# script variant in the Roslyn wiki. Note that not everything there is relevant to RoslynPad, which unlike the C# Interactive window, is not a REPL.

Body:
What I'd like to do is reference one script from another.

One way to make this happen might be using assemblies.  RoslynPad allows compiling a script into an assembly.  Here is what I have tried so far.

Script A, which is compiled to SOME_PATH\thing.dll

    class Thing
    {
        public string Name { get; set; }
    }

Script B

    #r "SOME_PATH\thing.dll"

    using static Program;

    var t = new Thing();
    t.Name = "TEST";
    t.Name.Dump();

This gives the error "The type or namespace 'Thing' could not be found..." so I tried the following.

    #r "SOME_PATH\thing.dll"

    var t = new Program.Thing();
    t.Name = "TEST";
    t.Name.Dump();

This gave the following error "The type name 'Thing' does not exist in the type 'Program'".

Is there a way to "Compile and Save assembly" and then reference it from another script?  Or, is there a more direct way to cross reference between scripts?

Body:
What you're looking for is the #load directive:

#load "Path\To\ScriptA.csx"

var t = new Thing();

You can read more about the C# script variant in the Roslyn wiki. Note that not everything there is relevant to RoslynPad, which unlike the C# Interactive window, is not a REPL.


问:
Exception in property when setting a binary value
I have the following method which gives me a stackoverflow exception on setting a value. I can't step into it and debug it application just crashes few seconds later. Here is the code

```<code>public byte[] ImageTIFF
{
    get
    {
        try
        {
            string filePath = ImageTIFFDir + ImageId + ".TIFF";

            if (File.Exists(filePath))
            {
                return File.ReadAllBytes(ImageTIFFDir + ImageCollectionId + ".TIFF");
            }
            else
            {
                return null;
            }
        }
        catch (Exception e)
        {
            Logger.log("Can't read TIFF image from file.", e);
            throw;
        }
    }
    set
    {
        try
        {
            ImageTIFF = value;
        }
        catch (Exception e)
        {
            Logger.log("Can't set image TIFF.", e);
            throw;
        }

    }
}
</code>```

This gets called during an export and it fails on a first call:

```<code>someImage.ImageTIFF = File.ReadAllBytes(imageName);
</code>```

答:
This is because , you are setting property itself in the set block

```<code>ImageTIFF = value;
</code>```

make a byte[] array variable and set in the set block and in the get block return this variable.

Body:
I have the following method which gives me a stackoverflow exception on setting a value. I can't step into it and debug it application just crashes few seconds later. Here is the code

public byte[] ImageTIFF
{
    get
    {
        try
        {
            string filePath = ImageTIFFDir + ImageId + ".TIFF";

            if (File.Exists(filePath))
            {
                return File.ReadAllBytes(ImageTIFFDir + ImageCollectionId + ".TIFF");
            }
            else
            {
                return null;
            }
        }
        catch (Exception e)
        {
            Logger.log("Can't read TIFF image from file.", e);
            throw;
        }
    }
    set
    {
        try
        {
            ImageTIFF = value;
        }
        catch (Exception e)
        {
            Logger.log("Can't set image TIFF.", e);
            throw;
        }

    }
}

This gets called during an export and it fails on a first call:

someImage.ImageTIFF = File.ReadAllBytes(imageName);

Body:
This is because , you are setting property itself in the set block

ImageTIFF = value;

make a byte[] array variable and set in the set block and in the get block return this variable.


问:
MySQL database and ASP.NET global connection
I have developed a website in which I have used ASP.NET with VB.NET as the backend programming language and a MySQL database. I have used ASP.NET and the MySQL database connector to run the website on my local computer, and it is working fine. The code of web.config file is given below:

```<code><?xml version="1.0"?>
<!--
    For more information on how to configure your ASP.NET application, please
    visit
    http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
    <system.web>
        <trust level="Medium"/>
        <customErrors mode="Off" defaultRedirect="Home.aspx"/>
        <compilation debug="true" strict="false" explicit="true"
                     targetFramework="4.0">
            <assemblies>
                <add assembly="MySql.Data, Version=6.9.9.0, Culture=neutral,
                     PublicKeyToken=C5687FC88969C44D"/>
            </assemblies>
        </compilation>
    </system.web>
</configuration>
</code>```

But now I have uploaded this website and database on the global server and have put the global database connection in my code. now the code of web.config file is

```<code><?xml version="1.0"?>
<!--
    For more information on how to configure your ASP.NET application, please
    visit
    http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
    <connectionStrings>
        <add name="myConnectionString" connectionString= "Server=globalservername;
             Database=databasename; Uid=userid; Pwd=passwd;"
             providerName="MySql.Data.MySqlClient" />
    </connectionStrings>
    <system.web>
        <trust level="Medium"/>
        <customErrors mode="Off" defaultRedirect="Home.aspx"/>
        <compilation debug="true" strict="false" explicit="true"
                     targetFramework="4.0">
        </compilation>
    </system.web>
</configuration>
</code>```

And when I open any page then it is showing the following error

Compiler Error Message: BC30002: Type 'MySqlConnection' is not defined.

in this line which is in every Visual Basic file of my project (connection string):

```<code>Dim SQLConnection As New MySqlConnection("Server=globalservername;
Database=databasename; Uid=userid; Pwd=passwd;")
</code>```

What should I add or remove in the web.config file to remove this error?

答:
You might be missing the required DLL file, MySQL.Data in a production environment. You can use the NuGet package* MySQL.Data* then build and deploy.

Alternatively, you can place the MySQL.Data DLL file in your bin folder and deploy.

Body:
I have developed a website in which I have used ASP.NET with VB.NET as the backend programming language and a MySQL database. I have used ASP.NET and the MySQL database connector to run the website on my local computer, and it is working fine. The code of web.config file is given below:

<?xml version="1.0"?>

<configuration>
    <system.web>
        <trust level="Medium"/>
        <customErrors mode="Off" defaultRedirect="Home.aspx"/>
        <compilation debug="true" strict="false" explicit="true"
                     targetFramework="4.0">
            <assemblies>
                <add assembly="MySql.Data, Version=6.9.9.0, Culture=neutral,
                     PublicKeyToken=C5687FC88969C44D"/>
            </assemblies>
        </compilation>
    </system.web>
</configuration>

But now I have uploaded this website and database on the global server and have put the global database connection in my code. now the code of web.config file is

<?xml version="1.0"?>

<configuration>
    <connectionStrings>
        <add name="myConnectionString" connectionString= "Server=globalservername;
             Database=databasename; Uid=userid; Pwd=passwd;"
             providerName="MySql.Data.MySqlClient" />
    </connectionStrings>
    <system.web>
        <trust level="Medium"/>
        <customErrors mode="Off" defaultRedirect="Home.aspx"/>
        <compilation debug="true" strict="false" explicit="true"
                     targetFramework="4.0">
        </compilation>
    </system.web>
</configuration>

And when I open any page then it is showing the following error

Compiler Error Message: BC30002: Type 'MySqlConnection' is not defined.

in this line which is in every Visual Basic file of my project (connection string):

Dim SQLConnection As New MySqlConnection("Server=globalservername;
Database=databasename; Uid=userid; Pwd=passwd;")

What should I add or remove in the web.config file to remove this error?


问:
std::lock_guard<std::mutex> segfaults on construction?
I'm attempting to access a shared std::queue using a std::mutex and a std::lock_guard. The mutex (pending_md_mtx_) is a member variable of another object (whose address is valid). My code seems to be segfault'ing on the construction of the lock_guard.

Any ideas? Should I be using a std::unique_lock (or some other object) instead? Running GCC 4.6 (--std=c++0x) under Ubuntu Linux. I can't post the entire class, but the only accesses to the mutex and queue listed below.

```<code>template <typename ListenerT>
class Driver
{
public:
    template <typename... Args>
    Driver(Args&&... args) :
        listener_(std::forward<Args>(args)...) {}

    void enqueue_md(netw::Packet* packet)
    {
        std::lock_guard<std::mutex> lock(pending_md_mtx_);
        pending_md_.push(packet);
    }

    void process_md()
    {
        std::lock_guard<std::mutex> lock(pending_md_mtx_);
        while (pending_md_.size())
        {
            netw::Packet* pkt=pending_md_.front();
            pending_md_.pop();
            process_md(*pkt);
        }
    }
    //... Other code which I can't post...

private:
    ListenerT listener_;
    std::mutex pending_md_mtx_;
    std::queue<netw::Packet*> pending_md_;
};
</code>```

GDB Stacktrace:

```<code>(gdb) bt
#0  __pthread_mutex_lock (mutex=0x2f20aa75e6f4000) at pthread_mutex_lock.c:50
#1  0x000000000041a2dc in __gthread_mutex_lock (__mutex=0xff282ceacb40) at /usr/include/c++/4.6/x86_64-linux-gnu/./bits/gthr-default.h:742
#2  lock (this=0xff282ceacb40) at /usr/include/c++/4.6/mutex:90
#3  lock_guard (__m=..., this=0x7f2874fc4db0) at /usr/include/c++/4.6/mutex:445
#4  driver::Driver<Listener, false>::enqueue_md (this=0xff282ceac8a0, packet=...) at exec/../../driver/Driver.hpp:95
</code>```

答: I recently encountered this problem. It was caused by line of code causing a buffer overrun after acquiring the lock. It would seem odd for a line of code below the lock to be causing a problem a few lines earlier, but I suppose the buffer overrun would cause some corruption that causes a problem on a second call to the function. </p>

Body:
I'm attempting to access a shared std::queue using a std::mutex and a std::lock_guard. The mutex (pending_md_mtx_) is a member variable of another object (whose address is valid). My code seems to be segfault'ing on the construction of the lock_guard.

Any ideas? Should I be using a std::unique_lock (or some other object) instead? Running GCC 4.6 (--std=c++0x) under Ubuntu Linux. I can't post the entire class, but the only accesses to the mutex and queue listed below.

template <typename ListenerT>
class Driver
{
public:
    template <typename... Args>
    Driver(Args&&... args) :
        listener_(std::forward<Args>(args)...) {}

    void enqueue_md(netw::Packet* packet)
    {
        std::lock_guard<std::mutex> lock(pending_md_mtx_);
        pending_md_.push(packet);
    }

    void process_md()
    {
        std::lock_guard<std::mutex> lock(pending_md_mtx_);
        while (pending_md_.size())
        {
            netw::Packet* pkt=pending_md_.front();
            pending_md_.pop();
            process_md(*pkt);
        }
    }
    //... Other code which I can't post...

private:
    ListenerT listener_;
    std::mutex pending_md_mtx_;
    std::queue<netw::Packet*> pending_md_;
};

GDB Stacktrace:

(gdb) bt
#0  __pthread_mutex_lock (mutex=0x2f20aa75e6f4000) at pthread_mutex_lock.c:50
#1  0x000000000041a2dc in __gthread_mutex_lock (__mutex=0xff282ceacb40) at /usr/include/c++/4.6/x86_64-linux-gnu/./bits/gthr-default.h:742
#2  lock (this=0xff282ceacb40) at /usr/include/c++/4.6/mutex:90
#3  lock_guard (__m=..., this=0x7f2874fc4db0) at /usr/include/c++/4.6/mutex:445
#4  driver::Driver<Listener, false>::enqueue_md (this=0xff282ceac8a0, packet=...) at exec/../../driver/Driver.hpp:95