问:
Bayesian vs OLS
I found this question online. Can someone explain in details please, why using OLS is better? Is it only because the number of samples is not enough? Also, why not use all the 1000 samples to estimate the prior distribution?

We have 1000 randomly sampled data points. The goal is to try to build
  a regression model with one response variable from k regressor
  variables. Which is better? 1. (Bayesian Regression) Using the first
  500 samples to estimate the parameters of an assumed prior
  distribution and then use the last 500 samples to update the prior to
  a posterior distribution with posterior estimates to be used in the
  final regression model. 2. (OLS Regression) Use a simple ordinary
  least squares regression model with all 1000 regressor variables

答:
"Better" is always a matter of opinion, and it greatly depends on context.

Advantages to a frequentist OLS approach: Simpler, faster, more accessible to a wider audience (and therefore less to explain).  A wise professor of mine used to say "You don't need to build an atom smasher when a flyswatter will do the trick."

Advantages to an equivalent Bayesian approach: More flexible to further model development, can directly model posteriors of derived/calculated quantities (there are more, but these have been my motivations for going Bayesian with a given analysis).  Note the word "equivalent" - there are things you can do in a Bayesian framework that you can't do within a frequentist approach.

And hey, here's a exploration in R, first simulating data, then using a typical OLS approach.

```<code>N <- 1000
x <- 1:N
epsilon <- rnorm(N, 0, 1)
y <- x + epsilon

summary(lm(y ~ x))
##
## Call:
## lm(formula = y ~ x)
##
## Residuals:
##     Min      1Q  Median      3Q     Max
## -2.9053 -0.6723  0.0116  0.6937  3.7880
##
## Coefficients:
##              Estimate Std. Error  t value Pr(>|t|)
## (Intercept) 0.0573955  0.0641910    0.894    0.371
## x           0.9999997  0.0001111 9000.996   <2e-16 ***
## ---
## Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
##
## Residual standard error: 1.014 on 998 degrees of freedom
## Multiple R-squared:      1,  Adjusted R-squared:      1
## F-statistic: 8.102e+07 on 1 and 998 DF,  p-value: < 2.2e-16
</code>```

...and here's an equivalent Bayesian regression, using non-informative priors on the regression parameters and all 1000 data points.

```<code>library(R2jags)
cat('model {
  for (i in 1:N){
    y[i] ~ dnorm(y.hat[i], tau)
    y.hat[i] <- a + b * x[i]
  }
  a ~ dnorm(0, .0001)
  b ~ dnorm(0, .0001)
  tau <- pow(sigma, -2)
  sigma ~ dunif(0, 100)
}', file="test.jags")

test.data <- list(x=x,y=y,N=1000)
test.jags.out <- jags(model.file="test.jags", data=test.data,
                  parameters.to.save=c("a","b","tau","sigma"), n.chains=3, n.iter=10000)
test.jags.out$BUGSoutput$mean$a
## [1] 0.05842661
test.jags.out$BUGSoutput$sd$a
## [1] 0.06606705
test.jags.out$BUGSoutput$mean$b
## [1] 0.9999976
test.jags.out$BUGSoutput$sd$b
## [1] 0.0001122533
</code>```

Note that the parameter estimates and standard errors/standard deviations are essentially equivalent!

Now here's another Bayesian regression, using the first 500 data points to estimate the priors and then the last 500 to estimate posteriors.

```<code>test.data <- list(x=x[1:500],y=y[1:500],N=500)
test.jags.out <- jags(model.file="test.jags", data=test.data,
                  parameters.to.save=c("a","b","tau","sigma"), n.chains=3, n.iter=10000)

cat('model {
  for (i in 1:N){
    y[i] ~ dnorm(y.hat[i], tau)
    y.hat[i] <- a + b * x[i]
  }
  a ~ dnorm(a_mn, a_prec)
  b ~ dnorm(b_mn, b_prec)
  a_prec <- pow(a_sd, -2)
  b_prec <- pow(b_sd, -2)
  tau <- pow(sigma, -2)
  sigma ~ dunif(0, 100)
}', file="test.jags1")

test.data1 <- list(x=x[501:1000],y=y[501:1000],N=500,
                   a_mn=test.jags.out$BUGSoutput$mean$a,a_sd=test.jags.out$BUGSoutput$sd$a,
                   b_mn=test.jags.out$BUGSoutput$mean$b,b_sd=test.jags.out$BUGSoutput$sd$b)
test.jags.out1 <- jags(model.file="test.jags1", data=test.data1,
                  parameters.to.save=c("a","b","tau","sigma"), n.chains=3, n.iter=10000)

test.jags.out1$BUGSoutput$mean$a
## [1] 0.01491162
test.jags.out1$BUGSoutput$sd$a
## [1] 0.08513474
test.jags.out1$BUGSoutput$mean$b
## [1] 1.000054
test.jags.out1$BUGSoutput$sd$b
## [1] 0.0001201778
</code>```

Interestingly, the inferences are similar to the OLS results, but not nearly as much so.  This leads me to suspect that the 500 data points used to train the prior are not carrying as much weight in the analysis as the last 500, and the prior is effectively getting washed out, though I'm not sure on this point.

Regardless, I can't think of a reason not to use all 1000 data points (and non-informative priors) either, particularly since I suspect the 500+500 is using the first 500 and last 500 differently.

So perhaps, the answer to all of this is: I trust the OLS and 1000-point Bayesian results more than the 500+500, and OLS is simpler.

Title: Bayesian vs OLS

Body:
"Better" is always a matter of opinion, and it greatly depends on context.

Advantages to a frequentist OLS approach: Simpler, faster, more accessible to a wider audience (and therefore less to explain).  A wise professor of mine used to say "You don't need to build an atom smasher when a flyswatter will do the trick."

Advantages to an equivalent Bayesian approach: More flexible to further model development, can directly model posteriors of derived/calculated quantities (there are more, but these have been my motivations for going Bayesian with a given analysis).  Note the word "equivalent" - there are things you can do in a Bayesian framework that you can't do within a frequentist approach.

And hey, here's a exploration in R, first simulating data, then using a typical OLS approach.

N <- 1000
x <- 1:N
epsilon <- rnorm(N, 0, 1)
y <- x + epsilon

summary(lm(y ~ x))
##
## Call:
## lm(formula = y ~ x)
##
## Residuals:
##     Min      1Q  Median      3Q     Max
## -2.9053 -0.6723  0.0116  0.6937  3.7880
##
## Coefficients:
##              Estimate Std. Error  t value Pr(>|t|)
## (Intercept) 0.0573955  0.0641910    0.894    0.371
## x           0.9999997  0.0001111 9000.996   <2e-16 ***
## ---
## Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
##
## Residual standard error: 1.014 on 998 degrees of freedom
## Multiple R-squared:      1,  Adjusted R-squared:      1
## F-statistic: 8.102e+07 on 1 and 998 DF,  p-value: < 2.2e-16

...and here's an equivalent Bayesian regression, using non-informative priors on the regression parameters and all 1000 data points.

library(R2jags)
cat('model {
  for (i in 1:N){
    y[i] ~ dnorm(y.hat[i], tau)
    y.hat[i] <- a + b * x[i]
  }
  a ~ dnorm(0, .0001)
  b ~ dnorm(0, .0001)
  tau <- pow(sigma, -2)
  sigma ~ dunif(0, 100)
}', file="test.jags")

test.data <- list(x=x,y=y,N=1000)
test.jags.out <- jags(model.file="test.jags", data=test.data,
                  parameters.to.save=c("a","b","tau","sigma"), n.chains=3, n.iter=10000)
test.jags.out$BUGSoutput$mean$a
## [1] 0.05842661
test.jags.out$BUGSoutput$sd$a
## [1] 0.06606705
test.jags.out$BUGSoutput$mean$b
## [1] 0.9999976
test.jags.out$BUGSoutput$sd$b
## [1] 0.0001122533

Note that the parameter estimates and standard errors/standard deviations are essentially equivalent!

Now here's another Bayesian regression, using the first 500 data points to estimate the priors and then the last 500 to estimate posteriors.

test.data <- list(x=x[1:500],y=y[1:500],N=500)
test.jags.out <- jags(model.file="test.jags", data=test.data,
                  parameters.to.save=c("a","b","tau","sigma"), n.chains=3, n.iter=10000)

cat('model {
  for (i in 1:N){
    y[i] ~ dnorm(y.hat[i], tau)
    y.hat[i] <- a + b * x[i]
  }
  a ~ dnorm(a_mn, a_prec)
  b ~ dnorm(b_mn, b_prec)
  a_prec <- pow(a_sd, -2)
  b_prec <- pow(b_sd, -2)
  tau <- pow(sigma, -2)
  sigma ~ dunif(0, 100)
}', file="test.jags1")

test.data1 <- list(x=x[501:1000],y=y[501:1000],N=500,
                   a_mn=test.jags.out$BUGSoutput$mean$a,a_sd=test.jags.out$BUGSoutput$sd$a,
                   b_mn=test.jags.out$BUGSoutput$mean$b,b_sd=test.jags.out$BUGSoutput$sd$b)
test.jags.out1 <- jags(model.file="test.jags1", data=test.data1,
                  parameters.to.save=c("a","b","tau","sigma"), n.chains=3, n.iter=10000)

test.jags.out1$BUGSoutput$mean$a
## [1] 0.01491162
test.jags.out1$BUGSoutput$sd$a
## [1] 0.08513474
test.jags.out1$BUGSoutput$mean$b
## [1] 1.000054
test.jags.out1$BUGSoutput$sd$b
## [1] 0.0001201778

Interestingly, the inferences are similar to the OLS results, but not nearly as much so.  This leads me to suspect that the 500 data points used to train the prior are not carrying as much weight in the analysis as the last 500, and the prior is effectively getting washed out, though I'm not sure on this point.

Regardless, I can't think of a reason not to use all 1000 data points (and non-informative priors) either, particularly since I suspect the 500+500 is using the first 500 and last 500 differently.

So perhaps, the answer to all of this is: I trust the OLS and 1000-point Bayesian results more than the 500+500, and OLS is simpler.


来源: stackexchange

问:
How do I find the length of an array?
Is there a way to find how many values an array has?  Detecting whether or not I've reached the end of an array would also work.</p>

答:
For C++/CX (when writing e.g. UWP apps using C++ in Visual Studio) we can find the number  of values in an array by  simply using the size() function.

Source Code:

```<code>string myArray[] = { "Example1", "Example2", "Example3", "Example4" };
int size_of_array=size(myArray);
</code>```

If you cout the size_of_array the output will be:

```<code>>>> 4
</code>```

ContentLicense: CC BY-SA 3.0

Title: How do I find the length of an array?

Body:
For C++/CX (when writing e.g. UWP apps using C++ in Visual Studio) we can find the number  of values in an array by  simply using the size() function.

Source Code:

string myArray[] = { "Example1", "Example2", "Example3", "Example4" };
int size_of_array=size(myArray);

If you cout the size_of_array the output will be:

>>> 4


问:
How to convert this query from MySQL to SQL Server?
Here is the source table:

```<code>+----+-------+
| Id | Score |
+----+-------+
| 1  | 3.50  |
| 2  | 3.65  |
| 3  | 4.00  |
| 4  | 3.85  |
| 5  | 4.00  |
| 6  | 3.65  |
+----+-------+
</code>```

Here is the result table:

```<code>+-------+------+
| Score | Rank |
+-------+------+
| 4.00  | 1    |
| 4.00  | 1    |
| 3.85  | 2    |
| 3.65  | 3    |
| 3.65  | 3    |
| 3.50  | 4    |
+-------+------+
</code>```

I have the MySQL version query, how to convert it to SQL server version? I tried to do the declare but I have no idea how to update the value of the variables.

```<code>SELECT Score, ranking AS Rank
FROM
(
SELECT
    Score,
    CASE
        WHEN @dummy = Score
        THEN @ranking := @ranking
        ELSE @ranking := @ranking + 1
    END as ranking,
    @dummy := Score
FROM Scores, (SELECT @ranking := 0, @dummy := -1) init
ORDER BY Score DESC
)AS Result
</code>```

答:
SQL Server doesn't support variables used in that manner, so the syntax doesn't translate.  Scalar variables are set once by a query, not set once for each row of the result set.  MySQL's syntax here is a hack to get analytic-function-like behavior without analytic function support.  You should just use:

```<code>SELECT Score,
    DENSE_RANK() OVER(ORDER BY Score DESC) AS Rank
FROM Scores
ORDER BY Score DESC;
</code>```

If you insist on not using DENSE_RANK(), you can use the SQL Server syntax from SQL Server 2000:

```<code>SELECT s1.Score,
    (SELECT COUNT(DISTINCT s2.Score) FROM Scores s2 WHERE s1.Score <= s2.Score) AS Ranking
FROM Scores s1
ORDER BY s1.Score DESC;
</code>```

Body:
Here is the source table:

+----+-------+
| Id | Score |
+----+-------+
| 1  | 3.50  |
| 2  | 3.65  |
| 3  | 4.00  |
| 4  | 3.85  |
| 5  | 4.00  |
| 6  | 3.65  |
+----+-------+

Here is the result table:

+-------+------+
| Score | Rank |
+-------+------+
| 4.00  | 1    |
| 4.00  | 1    |
| 3.85  | 2    |
| 3.65  | 3    |
| 3.65  | 3    |
| 3.50  | 4    |
+-------+------+

I have the MySQL version query, how to convert it to SQL server version? I tried to do the declare but I have no idea how to update the value of the variables.

SELECT Score, ranking AS Rank
FROM
(
SELECT
    Score,
    CASE
        WHEN @dummy = Score
        THEN @ranking := @ranking
        ELSE @ranking := @ranking + 1
    END as ranking,
    @dummy := Score
FROM Scores, (SELECT @ranking := 0, @dummy := -1) init
ORDER BY Score DESC
)AS Result

Body:
SQL Server doesn't support variables used in that manner, so the syntax doesn't translate.  Scalar variables are set once by a query, not set once for each row of the result set.  MySQL's syntax here is a hack to get analytic-function-like behavior without analytic function support.  You should just use:

SELECT Score,
    DENSE_RANK() OVER(ORDER BY Score DESC) AS Rank
FROM Scores
ORDER BY Score DESC;

If you insist on not using DENSE_RANK(), you can use the SQL Server syntax from SQL Server 2000:

SELECT s1.Score,
    (SELECT COUNT(DISTINCT s2.Score) FROM Scores s2 WHERE s1.Score <= s2.Score) AS Ranking
FROM Scores s1
ORDER BY s1.Score DESC;


问:
Is there a way to export SAS number using commas instead of dots?
The question is pretty straightforward.

When I do calculations on SAS and export them to an Excel spreadsheet, the numbers are exported using a dot as a decimal delimiter. Can I use a comma as a decimal delimiter when exporting on SAS software?

For example, I have this number: 32.53 but I want it exported to Excel as 32,53.

答:
When I tested this, the decimal separator (. in the US, , in some European countries) was controlled entirely by the NLS setting in Windows.

To test this, I exported a list of numbers, saw they looked like 0.1, went into Windows control panel, Region and Language, changed Decimal Symbol (on Additional Settings on the first tab) to ,, re-opened Excel and they now looked like 0,1 in the exported file.

Be careful using the NUMXw.d format as suggested elsewhere; it's very easy to get thousands and decimal switched in Excel.  See for example this:

```<code>data test;
  do x = 1 to 2 by 0.1;
    y=x;
    output;
  end;
  format y numx8.3;
run;

ods excel file="c:\temp\test_ods.xlsx";
  proc print data=test;
  run;
ods excel close;
</code>```

Excel prints the numbers as you'd want in the y column - but they're actually thousands.  Oops!

ODS Excel does not have an option to set the decimal separator.  ODS Tagsets.ExcelXP claims to, but it doesn't seem to do anything.

Body:
When I tested this, the decimal separator (. in the US, , in some European countries) was controlled entirely by the NLS setting in Windows.

To test this, I exported a list of numbers, saw they looked like 0.1, went into Windows control panel, Region and Language, changed Decimal Symbol (on Additional Settings on the first tab) to ,, re-opened Excel and they now looked like 0,1 in the exported file.

Be careful using the NUMXw.d format as suggested elsewhere; it's very easy to get thousands and decimal switched in Excel.  See for example this:

data test;
  do x = 1 to 2 by 0.1;
    y=x;
    output;
  end;
  format y numx8.3;
run;

ods excel file="c:\temp\test_ods.xlsx";
  proc print data=test;
  run;
ods excel close;

Excel prints the numbers as you'd want in the y column - but they're actually thousands.  Oops!

ODS Excel does not have an option to set the decimal separator.  ODS Tagsets.ExcelXP claims to, but it doesn't seem to do anything.


问:
Unable to cast object of type 'System.Web.UI.WebControls.LinkButton' to type 'System.Web.UI.WebControls.Button')
i have a linked button in my a datalist with value of datatype int onclick it is supposed to display all details in a datalist list on another page based on the id link button chosen.

But i am having  this error in my codes:

An exception of type 'System.InvalidCastException' occurred in App_Web_m5vpwb3j.dll but was not handled in user code

Additional information: Unable to cast object of type 'System.Web.UI.WebControls.LinkButton' to type 'System.Web.UI.WebControls.Button')

答:
Both a LinkButton and a Button are a subclass of WebControl. However, they are siblings in the type hierarchy, so you cannot cast one into the other. They are not compatible to each other.

So what you are doing simply doesn’t work, you will have to look for another way to achieve what you want to achieve.


问:
JMeter 3.0 Report Generation - Why is my report dashboard blank?
I am new to JMeter, and I'm trying to get JMeter to produce the html report dashboard for an existing test script. I do not get any exceptions in processing, and the log indicates no issues generating the reports:

```<code>2016/07/08 12:42:24 DEBUG - jmeter.report.dashboard.ReportGenerator: Start report generation
2016/07/08 12:42:25 INFO  - jmeter.report.processor.NormalizerSampleConsumer: Using format:ms to parse timeStamp field
2016/07/08 12:42:25 DEBUG - jmeter.report.dashboard.ReportGenerator: Start samples processing
2016/07/08 12:42:25 INFO  - org.apache.jmeter.report.processor.AbstractSampleConsumer: class org.apache.jmeter.report.processor.AggregateConsumer#stopProducing(): beginDate produced 0 samples
2016/07/08 12:42:25 INFO  - org.apache.jmeter.report.processor.AbstractSampleConsumer: class org.apache.jmeter.report.processor.AggregateConsumer#stopProducing(): endDate produced 0 samples
2016/07/08 12:42:25 INFO  - org.apache.jmeter.report.processor.AbstractSampleConsumer: class org.apache.jmeter.report.processor.ApdexSummaryConsumer#stopProducing(): apdexSummary produced 0 samples
2016/07/08 12:42:25 INFO  - org.apache.jmeter.report.processor.AbstractSampleConsumer: class org.apache.jmeter.report.processor.RequestsSummaryConsumer#stopProducing(): requestsSummary produced 0 samples
2016/07/08 12:42:25 INFO  - org.apache.jmeter.report.processor.AbstractSampleConsumer: class org.apache.jmeter.report.processor.StatisticsSummaryConsumer#stopProducing(): statisticsSummary produced 0 samples
2016/07/08 12:42:25 INFO  - org.apache.jmeter.report.processor.AbstractSampleConsumer: class org.apache.jmeter.report.processor.ErrorsSummaryConsumer#stopProducing(): errorsSummary produced 0 samples
2016/07/08 12:42:25 INFO  - org.apache.jmeter.report.processor.AbstractSampleConsumer: class org.apache.jmeter.report.processor.graph.impl.LatencyVSRequestGraphConsumer#stopProducing(): latencyVsRequest produced 0 samples
2016/07/08 12:42:25 INFO  - org.apache.jmeter.report.processor.AbstractSampleConsumer: class org.apache.jmeter.report.processor.graph.impl.HitsPerSecondGraphConsumer#stopProducing(): hitsPerSecond produced 0 samples
2016/07/08 12:42:25 INFO  - org.apache.jmeter.report.processor.AbstractSampleConsumer: class org.apache.jmeter.report.processor.graph.impl.CodesPerSecondGraphConsumer#stopProducing(): codesPerSecond produced 0 samples
2016/07/08 12:42:25 INFO  - org.apache.jmeter.report.processor.AbstractSampleConsumer: class org.apache.jmeter.report.processor.graph.impl.ResponseTimeVSRequestGraphConsumer#stopProducing(): responseTimeVsRequest produced 0 samples
2016/07/08 12:42:25 INFO  - org.apache.jmeter.report.processor.AbstractSampleConsumer: class org.apache.jmeter.report.processor.FilterConsumer#stopProducing(): startIntervalControlerFilter produced 4175 samples
2016/07/08 12:42:25 INFO  - org.apache.jmeter.report.processor.AbstractSampleConsumer: class org.apache.jmeter.report.processor.graph.impl.ResponseTimePercentilesGraphConsumer#stopProducing(): responseTimePercentiles produced 0 samples
2016/07/08 12:42:25 INFO  - org.apache.jmeter.report.processor.AbstractSampleConsumer: class org.apache.jmeter.report.processor.graph.impl.ResponseTimeOverTimeGraphConsumer#stopProducing(): responseTimesOverTime produced 0 samples
2016/07/08 12:42:25 INFO  - org.apache.jmeter.report.processor.AbstractSampleConsumer: class org.apache.jmeter.report.processor.graph.impl.BytesThroughputGraphConsumer#stopProducing(): bytesThroughputOverTime produced 0 samples
2016/07/08 12:42:25 INFO  - org.apache.jmeter.report.processor.AbstractSampleConsumer: class org.apache.jmeter.report.processor.graph.impl.ActiveThreadsGraphConsumer#stopProducing(): activeThreadsOverTime produced 0 samples
2016/07/08 12:42:25 INFO  - org.apache.jmeter.report.processor.AbstractSampleConsumer: class org.apache.jmeter.report.processor.graph.impl.TimeVSThreadGraphConsumer#stopProducing(): timeVsThreads produced 0 samples
2016/07/08 12:42:25 INFO  - org.apache.jmeter.report.processor.AbstractSampleConsumer: class org.apache.jmeter.report.processor.graph.impl.ResponseTimeDistributionGraphConsumer#stopProducing(): responseTimeDistribution produced 0 samples
2016/07/08 12:42:25 INFO  - org.apache.jmeter.report.processor.AbstractSampleConsumer: class org.apache.jmeter.report.processor.graph.impl.LatencyOverTimeGraphConsumer#stopProducing(): latenciesOverTime produced 0 samples
2016/07/08 12:42:25 INFO  - org.apache.jmeter.report.processor.AbstractSampleConsumer: class org.apache.jmeter.report.processor.graph.impl.TransactionsPerSecondGraphConsumer#stopProducing(): transactionsPerSecond produced 0 samples
2016/07/08 12:42:25 INFO  - org.apache.jmeter.report.processor.AbstractSampleConsumer: class org.apache.jmeter.report.processor.FilterConsumer#stopProducing(): nameFilter produced 10020 samples
2016/07/08 12:42:25 INFO  - org.apache.jmeter.report.processor.AbstractSampleConsumer: class org.apache.jmeter.report.processor.NormalizerSampleConsumer#stopProducing(): normalizer produced 2505 samples
2016/07/08 12:42:25 INFO  - org.apache.jmeter.report.processor.CsvFileSampleSource: produce(): 835 samples produced in 481ms on channel 0
2016/07/08 12:42:25 DEBUG - jmeter.report.dashboard.ReportGenerator: End of samples processing
2016/07/08 12:42:25 DEBUG - jmeter.report.dashboard.ReportGenerator: Start data exporting
2016/07/08 12:42:25 INFO  - jmeter.report.dashboard.ReportGenerator: Exporting data using exporter:'html' of className:'org.apache.jmeter.report.dashboard.HtmlTemplateExporter'
2016/07/08 12:42:25 DEBUG - jmeter.report.dashboard.HtmlTemplateExporter: Start template processing
2016/07/08 12:42:25 INFO  - jmeter.report.dashboard.HtmlTemplateExporter: Will generate dashboard in folder:/tmp/jmeter
2016/07/08 12:42:26 INFO  - jmeter.report.dashboard.HtmlTemplateExporter: Report will be generated in:/tmp/jmeter, creating folder structure
2016/07/08 12:42:26 DEBUG - jmeter.report.dashboard.HtmlTemplateExporter: End of template processing
2016/07/08 12:42:26 DEBUG - jmeter.report.dashboard.ReportGenerator: End of data exporting
2016/07/08 12:42:26 DEBUG - jmeter.report.dashboard.ReportGenerator: End of report generation
</code>```

However, when I view the produced index.html file, there is no data:

The result.csv file is not empty though:

My reportgenerator and saveservice config is:

```<code>#---------------------------------------------------------------------------
# Reporting configuration
#---------------------------------------------------------------------------
# If you want to debug reporting, uncomment this line
log_level.jmeter.report=DEBUG
jmeter.reportgenerator.report_title=AMP JMeter-test Dashboard
jmeter.reportgenerator.overall_granularity=6000
jmeter.reportgenerator.temp_dir = /tmp
#---------------------------------------------------------------------------
# Results file configuration
#---------------------------------------------------------------------------
jmeter.save.saveservice.output_format=csv
# assertion_results_failure_message only affects CSV output
jmeter.save.saveservice.assertion_results_failure_message=true
jmeter.save.saveservice.assertion_results=all
#jmeter.save.saveservice.data_type=true
jmeter.save.saveservice.label=true
jmeter.save.saveservice.response_code=true

jmeter.save.saveservice.response_message=true
jmeter.save.saveservice.successful=true
jmeter.save.saveservice.thread_name=true
jmeter.save.saveservice.time=true
jmeter.save.saveservice.subresults=true
jmeter.save.saveservice.assertions=true
jmeter.save.saveservice.latency=true
jmeter.save.saveservice.bytes=true
jmeter.save.saveservice.thread_counts=true
jmeter.save.saveservice.timestamp_format=ms
jmeter.save.saveservice.default_delimiter=,
jmeter.save.saveservice.print_field_names=true

csvread.delimiter=,
</code>```

I have tried to search for similar problems (here and elsewhere), but I cannot find anything that addresses such a situation. The results are being written and populated in the CSV file in the format I expect, but something seems to go wrong in reading the data. If I can at least get the Errors and Result Summary parts populated I would be happy at this point.

I have noticed in the log (contained in the snippet), that there are a lot of 0 samples reported for different things...but I think I only care about the CsvFileSampleSource, which it correctly identifies as having 800-something samples...

Also, I run my test like:

```<code>jmeter -n -t /path/to/my/amp_automation.jmx -l /tmp/result.csv -e -o /tmp/jmeter
</code>```

Any insight would be appreciated, I may jut be missing something here. I ideally do not want to revert to the "older" ways of getting html reports generated for jmeter (with ant, or other listeners etc.)

Thank you!

答: I had similar issue. I realized that I used double quotes as one of the HTTP request name in the .jtl report. I removed double quotes from jtl, regenerated the dashboard. It worked like a charm!. </p>

Body:
I am new to JMeter, and I'm trying to get JMeter to produce the html report dashboard for an existing test script. I do not get any exceptions in processing, and the log indicates no issues generating the reports:

2016/07/08 12:42:24 DEBUG - jmeter.report.dashboard.ReportGenerator: Start report generation
2016/07/08 12:42:25 INFO  - jmeter.report.processor.NormalizerSampleConsumer: Using format:ms to parse timeStamp field
2016/07/08 12:42:25 DEBUG - jmeter.report.dashboard.ReportGenerator: Start samples processing
2016/07/08 12:42:25 INFO  - org.apache.jmeter.report.processor.AbstractSampleConsumer: class org.apache.jmeter.report.processor.AggregateConsumer#stopProducing(): beginDate produced 0 samples
2016/07/08 12:42:25 INFO  - org.apache.jmeter.report.processor.AbstractSampleConsumer: class org.apache.jmeter.report.processor.AggregateConsumer#stopProducing(): endDate produced 0 samples
2016/07/08 12:42:25 INFO  - org.apache.jmeter.report.processor.AbstractSampleConsumer: class org.apache.jmeter.report.processor.ApdexSummaryConsumer#stopProducing(): apdexSummary produced 0 samples
2016/07/08 12:42:25 INFO  - org.apache.jmeter.report.processor.AbstractSampleConsumer: class org.apache.jmeter.report.processor.RequestsSummaryConsumer#stopProducing(): requestsSummary produced 0 samples
2016/07/08 12:42:25 INFO  - org.apache.jmeter.report.processor.AbstractSampleConsumer: class org.apache.jmeter.report.processor.StatisticsSummaryConsumer#stopProducing(): statisticsSummary produced 0 samples
2016/07/08 12:42:25 INFO  - org.apache.jmeter.report.processor.AbstractSampleConsumer: class org.apache.jmeter.report.processor.ErrorsSummaryConsumer#stopProducing(): errorsSummary produced 0 samples
2016/07/08 12:42:25 INFO  - org.apache.jmeter.report.processor.AbstractSampleConsumer: class org.apache.jmeter.report.processor.graph.impl.LatencyVSRequestGraphConsumer#stopProducing(): latencyVsRequest produced 0 samples
2016/07/08 12:42:25 INFO  - org.apache.jmeter.report.processor.AbstractSampleConsumer: class org.apache.jmeter.report.processor.graph.impl.HitsPerSecondGraphConsumer#stopProducing(): hitsPerSecond produced 0 samples
2016/07/08 12:42:25 INFO  - org.apache.jmeter.report.processor.AbstractSampleConsumer: class org.apache.jmeter.report.processor.graph.impl.CodesPerSecondGraphConsumer#stopProducing(): codesPerSecond produced 0 samples
2016/07/08 12:42:25 INFO  - org.apache.jmeter.report.processor.AbstractSampleConsumer: class org.apache.jmeter.report.processor.graph.impl.ResponseTimeVSRequestGraphConsumer#stopProducing(): responseTimeVsRequest produced 0 samples
2016/07/08 12:42:25 INFO  - org.apache.jmeter.report.processor.AbstractSampleConsumer: class org.apache.jmeter.report.processor.FilterConsumer#stopProducing(): startIntervalControlerFilter produced 4175 samples
2016/07/08 12:42:25 INFO  - org.apache.jmeter.report.processor.AbstractSampleConsumer: class org.apache.jmeter.report.processor.graph.impl.ResponseTimePercentilesGraphConsumer#stopProducing(): responseTimePercentiles produced 0 samples
2016/07/08 12:42:25 INFO  - org.apache.jmeter.report.processor.AbstractSampleConsumer: class org.apache.jmeter.report.processor.graph.impl.ResponseTimeOverTimeGraphConsumer#stopProducing(): responseTimesOverTime produced 0 samples
2016/07/08 12:42:25 INFO  - org.apache.jmeter.report.processor.AbstractSampleConsumer: class org.apache.jmeter.report.processor.graph.impl.BytesThroughputGraphConsumer#stopProducing(): bytesThroughputOverTime produced 0 samples
2016/07/08 12:42:25 INFO  - org.apache.jmeter.report.processor.AbstractSampleConsumer: class org.apache.jmeter.report.processor.graph.impl.ActiveThreadsGraphConsumer#stopProducing(): activeThreadsOverTime produced 0 samples
2016/07/08 12:42:25 INFO  - org.apache.jmeter.report.processor.AbstractSampleConsumer: class org.apache.jmeter.report.processor.graph.impl.TimeVSThreadGraphConsumer#stopProducing(): timeVsThreads produced 0 samples
2016/07/08 12:42:25 INFO  - org.apache.jmeter.report.processor.AbstractSampleConsumer: class org.apache.jmeter.report.processor.graph.impl.ResponseTimeDistributionGraphConsumer#stopProducing(): responseTimeDistribution produced 0 samples
2016/07/08 12:42:25 INFO  - org.apache.jmeter.report.processor.AbstractSampleConsumer: class org.apache.jmeter.report.processor.graph.impl.LatencyOverTimeGraphConsumer#stopProducing(): latenciesOverTime produced 0 samples
2016/07/08 12:42:25 INFO  - org.apache.jmeter.report.processor.AbstractSampleConsumer: class org.apache.jmeter.report.processor.graph.impl.TransactionsPerSecondGraphConsumer#stopProducing(): transactionsPerSecond produced 0 samples
2016/07/08 12:42:25 INFO  - org.apache.jmeter.report.processor.AbstractSampleConsumer: class org.apache.jmeter.report.processor.FilterConsumer#stopProducing(): nameFilter produced 10020 samples
2016/07/08 12:42:25 INFO  - org.apache.jmeter.report.processor.AbstractSampleConsumer: class org.apache.jmeter.report.processor.NormalizerSampleConsumer#stopProducing(): normalizer produced 2505 samples
2016/07/08 12:42:25 INFO  - org.apache.jmeter.report.processor.CsvFileSampleSource: produce(): 835 samples produced in 481ms on channel 0
2016/07/08 12:42:25 DEBUG - jmeter.report.dashboard.ReportGenerator: End of samples processing
2016/07/08 12:42:25 DEBUG - jmeter.report.dashboard.ReportGenerator: Start data exporting
2016/07/08 12:42:25 INFO  - jmeter.report.dashboard.ReportGenerator: Exporting data using exporter:'html' of className:'org.apache.jmeter.report.dashboard.HtmlTemplateExporter'
2016/07/08 12:42:25 DEBUG - jmeter.report.dashboard.HtmlTemplateExporter: Start template processing
2016/07/08 12:42:25 INFO  - jmeter.report.dashboard.HtmlTemplateExporter: Will generate dashboard in folder:/tmp/jmeter
2016/07/08 12:42:26 INFO  - jmeter.report.dashboard.HtmlTemplateExporter: Report will be generated in:/tmp/jmeter, creating folder structure
2016/07/08 12:42:26 DEBUG - jmeter.report.dashboard.HtmlTemplateExporter: End of template processing
2016/07/08 12:42:26 DEBUG - jmeter.report.dashboard.ReportGenerator: End of data exporting
2016/07/08 12:42:26 DEBUG - jmeter.report.dashboard.ReportGenerator: End of report generation

However, when I view the produced index.html file, there is no data:

The result.csv file is not empty though:

My reportgenerator and saveservice config is:

#---------------------------------------------------------------------------
# Reporting configuration
#---------------------------------------------------------------------------
# If you want to debug reporting, uncomment this line
log_level.jmeter.report=DEBUG
jmeter.reportgenerator.report_title=AMP JMeter-test Dashboard
jmeter.reportgenerator.overall_granularity=6000
jmeter.reportgenerator.temp_dir = /tmp
#---------------------------------------------------------------------------
# Results file configuration
#---------------------------------------------------------------------------
jmeter.save.saveservice.output_format=csv
# assertion_results_failure_message only affects CSV output
jmeter.save.saveservice.assertion_results_failure_message=true
jmeter.save.saveservice.assertion_results=all
#jmeter.save.saveservice.data_type=true
jmeter.save.saveservice.label=true
jmeter.save.saveservice.response_code=true

jmeter.save.saveservice.response_message=true
jmeter.save.saveservice.successful=true
jmeter.save.saveservice.thread_name=true
jmeter.save.saveservice.time=true
jmeter.save.saveservice.subresults=true
jmeter.save.saveservice.assertions=true
jmeter.save.saveservice.latency=true
jmeter.save.saveservice.bytes=true
jmeter.save.saveservice.thread_counts=true
jmeter.save.saveservice.timestamp_format=ms
jmeter.save.saveservice.default_delimiter=,
jmeter.save.saveservice.print_field_names=true

csvread.delimiter=,

I have tried to search for similar problems (here and elsewhere), but I cannot find anything that addresses such a situation. The results are being written and populated in the CSV file in the format I expect, but something seems to go wrong in reading the data. If I can at least get the Errors and Result Summary parts populated I would be happy at this point.

I have noticed in the log (contained in the snippet), that there are a lot of 0 samples reported for different things...but I think I only care about the CsvFileSampleSource, which it correctly identifies as having 800-something samples...

Also, I run my test like:

jmeter -n -t /path/to/my/amp_automation.jmx -l /tmp/result.csv -e -o /tmp/jmeter

Any insight would be appreciated, I may jut be missing something here. I ideally do not want to revert to the "older" ways of getting html reports generated for jmeter (with ant, or other listeners etc.)

Thank you!


问:
Datatable: date / time sorting plug-in not ordering
I have a basic SpringBoot app., embedded Tomcat, Thymeleaf template engine
I want to order 1 date column of a datatable.

in my POJO:

```<code>public String getTimeFormatted() {
DateTimeFormatter formatter =
            DateTimeFormatter.ofPattern("EEEE, MMMM d,yyyy h:mm,a", Locale.ENGLISH);
        LocalDateTime dateTime = LocalDateTime.ofEpochSecond(time, 0, ZoneOffset.UTC);
        return dateTime.format(formatter);
    }
</code>```

in the template:

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.4/moment.min.js"></script>
<script src="https://cdn.datatables.net/plug-ins/1.10.15/sorting/datetime-moment.js"></script>

<script th:inline="javascript">
$(document).ready(function() {

    $.fn.dataTable.moment( 'EEEE, MMMM d,yyyy h:mm,a' );

    $('#table').dataTable( {
        "bLengthChange": false,
        "pageLength": 25,
    });
} );
</script>
</code>```

but it does not order properly

答:
Personally, I prefer to use a data-order attribute.  Then I just pass it the timestamp in either epoch or YYYYmmddHHiiss.

You can see an example here: https://datatables.net/examples/advanced_init/html5-data-attributes.html

Body:
I have a basic SpringBoot app., embedded Tomcat, Thymeleaf template engine
I want to order 1 date column of a datatable.

in my POJO:

public String getTimeFormatted() {
DateTimeFormatter formatter =
            DateTimeFormatter.ofPattern("EEEE, MMMM d,yyyy h:mm,a", Locale.ENGLISH);
        LocalDateTime dateTime = LocalDateTime.ofEpochSecond(time, 0, ZoneOffset.UTC);
        return dateTime.format(formatter);
    }

in the template:

but it does not order properly


问:
Django Query that gets objects based latest foreign key timestamp and orders them
I am looking to order a queryset based on a set of objects timestamp.

Here's a simplified example:

```<code>Class Device(models.Model:
    status = models.CharField(max_length=50)

class Event(models.Model):
    timestamp = models.DateTimeField(auto_now_add=True)
    device = models.ForeignKey(Device)
</code>```

I want to get the latest Event of the device so I can order a Device queryset based on that.

答:
You can use an annotation to get the most recent timestamp of an event for the device and then order by that annotated field, in descending order</p>

```<code>from django.db.models import Max

Device.objects.annotate(
    most_recent=Max('event_set__timestamp')
).order_by('-most_recent')
</code>```

Body:
I am looking to order a queryset based on a set of objects timestamp.

Here's a simplified example:

Class Device(models.Model:
    status = models.CharField(max_length=50)

class Event(models.Model):
    timestamp = models.DateTimeField(auto_now_add=True)
    device = models.ForeignKey(Device)

I want to get the latest Event of the device so I can order a Device queryset based on that.

Body:
You can use an annotation to get the most recent timestamp of an event for the device and then order by that annotated field, in descending order

from django.db.models import Max

Device.objects.annotate(
    most_recent=Max('event_set__timestamp')
).order_by('-most_recent')


问:
Validate if one of two form fields is filled?
At least one of the two fields is required, if field 1 is filled or field 2 is filled the form is sent, the required is just one of them filled. I'm trying to do this with the code below, but isn't working fine, this is working only validating like required the field 1 (text1). Thank you!

var field1 = text1;
var field2 = text2;

if (text2.length) {
    if (!field1.length || !field2.length) {
        return false;
    }
} else if (!field1.length) {
    return false;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" placeholder="text 1*" name="text1" class="text1" data-target="previewText1" maxlength="11">
<input type="text" placeholder="text 2" value="" name="text2" class="text2" data-target="previewText2" maxlength="11"></code>```

答:
It's a simple case of an AND condition on each length with the not operator.

```<code>if (!field1.length && !field2.length) {
    return false;
}
</code>```

So it's saying if field1 is empty AND field2 is empty then the form is invalid.

This assumes field1 and field2 are the string value and not the DOM elements. If they're DOM elements then you need to use field1.value.length and field2.value.length.

Body:
At least one of the two fields is required, if field 1 is filled or field 2 is filled the form is sent, the required is just one of them filled. I'm trying to do this with the code below, but isn't working fine, this is working only validating like required the field 1 (text1). Thank you!

var field1 = text1;
var field2 = text2;

if (text2.length) {
    if (!field1.length || !field2.length) {
        return false;
    }
} else if (!field1.length) {
    return false;
}

<input type="text" placeholder="text 1*" name="text1" class="text1" data-target="previewText1" maxlength="11">
<input type="text" placeholder="text 2" value="" name="text2" class="text2" data-target="previewText2" maxlength="11">

Body:
It's a simple case of an AND condition on each length with the not operator.

if (!field1.length && !field2.length) {
    return false;
}

So it's saying if field1 is empty AND field2 is empty then the form is invalid.

This assumes field1 and field2 are the string value and not the DOM elements. If they're DOM elements then you need to use field1.value.length and field2.value.length.


问:
updating form with date field generate error (symfony, php)
I would like to update a form containing a date field. I can create the form with no problem but I could not edit it because I got an error. So here is my first class Contract:

```<code><?php

 namespace AppBundle\Form;

use AppBundle\Entity\Contract;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\TextType;

class ContractType extends AbstractType {
  public function buildForm(FormBuilderInterface $builder, array $options)
 {
    $builder
        ->add('firstDay', DateType::class, array(
        'format' => 'yyyy-MM-dd',
      ))
        ->add('lastDay', DateType::class, array(
        'format' => 'yyyy-MM-dd',
      ))
        ;
}

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => Contract::class,
    ));
}
</code>```

And here is my update code (Controller part):

```<code>public function updateAction($id, Request $request) {

$encoder = new JsonEncoder ();
$normalizer = new GetSetMethodNormalizer();
$callback = function ($dateTime) {
  return $dateTime instanceof \DateTime ? $dateTime->format ( 'Y-m-d' ) : '';
};

$normalizer->setCallbacks ( array (
      'firstDay' => $callback
      ) );

$normalizer->setCallbacks ( array (
            'lastDay' => $callback
            ) );

$serializer = new Serializer ( array (
  new \AppBundle\DateTimeNormalizer(), $normalizer
                ), array (
                  $encoder
                  ) );
$headers = array('Accept' => 'application/json');
$response = Unirest\Request::get('link/contracts/'.$id
,$headers);
 $contract =
 $serializer->deserialize($response->raw_body,Contract::class, 'json');   // Here when I dump my variable it appears good
$form = $this->createForm(ContractType::class,$contract); // In this line I got my error
$form->handleRequest($request);
if ($form->isSubmitted()) {
   $headers = array('Content-Type' => 'application/json');
   $data = $serializer->serialize($contract, 'json');
  $response = Unirest\Request::put('link/contracts'.$id,
    $headers,$data);
   return $this->redirect ( $this->generateUrl ('contracts_list'));
 }
 return $this->render('AppBundle:Contract:ContractCreate.html.twig', array(
   'form' => $form->createView(),
 ));
</code>```

}

The error I got:

```<code>Unable to transform value for property path "firstDay": Expected a \DateTimeInterface.
</code>```

When I change line $serialize->deserialize ... with new Contract() it works, but I need to use serialize in order to use the same form.

答:
Try to use DateTimeType class instead of DateType in

```<code>$builder
    ->add('firstDay', DateType::class, array(
    'format' => 'yyyy-MM-dd',
  ))
</code>```

Body:
I would like to update a form containing a date field. I can create the form with no problem but I could not edit it because I got an error. So here is my first class Contract:

<?php

 namespace AppBundle\Form;

use AppBundle\Entity\Contract;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\TextType;

class ContractType extends AbstractType {
  public function buildForm(FormBuilderInterface $builder, array $options)
 {
    $builder
        ->add('firstDay', DateType::class, array(
        'format' => 'yyyy-MM-dd',
      ))
        ->add('lastDay', DateType::class, array(
        'format' => 'yyyy-MM-dd',
      ))
        ;
}

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => Contract::class,
    ));
}

And here is my update code (Controller part):

public function updateAction($id, Request $request) {

$encoder = new JsonEncoder ();
$normalizer = new GetSetMethodNormalizer();
$callback = function ($dateTime) {
  return $dateTime instanceof \DateTime ? $dateTime->format ( 'Y-m-d' ) : '';
};

$normalizer->setCallbacks ( array (
      'firstDay' => $callback
      ) );

$normalizer->setCallbacks ( array (
            'lastDay' => $callback
            ) );

$serializer = new Serializer ( array (
  new \AppBundle\DateTimeNormalizer(), $normalizer
                ), array (
                  $encoder
                  ) );
$headers = array('Accept' => 'application/json');
$response = Unirest\Request::get('link/contracts/'.$id
,$headers);
 $contract =
 $serializer->deserialize($response->raw_body,Contract::class, 'json');   // Here when I dump my variable it appears good
$form = $this->createForm(ContractType::class,$contract); // In this line I got my error
$form->handleRequest($request);
if ($form->isSubmitted()) {
   $headers = array('Content-Type' => 'application/json');
   $data = $serializer->serialize($contract, 'json');
  $response = Unirest\Request::put('link/contracts'.$id,
    $headers,$data);
   return $this->redirect ( $this->generateUrl ('contracts_list'));
 }
 return $this->render('AppBundle:Contract:ContractCreate.html.twig', array(
   'form' => $form->createView(),
 ));

}

The error I got:

Unable to transform value for property path "firstDay": Expected a \DateTimeInterface.

When I change line $serialize->deserialize ... with new Contract() it works, but I need to use serialize in order to use the same form.

Body:
Try to use DateTimeType class instead of DateType in

$builder
    ->add('firstDay', DateType::class, array(
    'format' => 'yyyy-MM-dd',
  ))


问:
ASP.NET Excluded View Being Hit
I have a scenario where I combined two Views into one shared View.

Excluded From Project but always gets hit

Views/Foo/Do.aspx

Views/Bar/Do.aspx

Exists in Project but never gets hit

Views/Shared/Do.aspx

The files still exist in source control but they are no longer a part of the project.

Why would a View that is no longer a part of the project have precedence over a View that is a part of the project? Maybe I'm thinking MVC is doing more that it does...

Does MVC just look for any file that it can find that matches regardless of it being a part of the Project?

Is this a potential security flaw if you could drop a file in there with the proper name even though it's not a part of the Project?

答:
Answer 2 is correct. MVC will search the view folders for a matching named view. Precedence is on a case of more-specific overrides more general (ie the "Do" view called from controller "Foo" will first look for Views/Foo/Do.aspx then look for Views/Shared/Do.aspx). The same is true for partials except the heirarchy prioritises first by extension (ascx) then by the specificity of the folder.

Being part of a project only affects Visual Studio (the tooling such as "go to view", publishing properties etc). Although if you choose to have compiled views then it may make a difference.

It is only a security flaw if you allow people to just drop files into your View folders, in which case they could just overwrite any of the views you had included in your project anyway.

ContentLicense: CC BY-SA 2.5

Title: ASP.NET Excluded View Being Hit


问:
How to delete document types in elasticsearch?
I create an index "myindex" with a specified document type "mytype". I am able to delete the index, but it appears that "mytype" still exists without being tied to the index.

How do I get rid of "mytype"?

答:
In the latest version of elastic search, they no longer support deleting document types. It's mentioned in the documentation

It is no longer possible to delete the mapping for a type. Instead you
  should delete the index and recreate it with the new mappings.


问:
How to save as ArrayList<String>, all possible combinations of a set of characters in string?
How can I save as an ArrayList all possible combinations of a set of characters in string?

You can see my code below. It only print the combinations, but doesn't save all combinations. Any idea?

```<code>public class All_Possible_Combinatons
{

static String combinations(char[] sequence, char[] data, int start, int end,
        int index, int r)
{

    if (index == r)
    {
        for (int j = 0; j < r; j++)
            // = data[j];
            System.out.print(data[j] + " ");
        System.out.println();
    }

    for (int i = start; i <= end && ((end - i + 1) >= (r - index)); i++)
    {
        data[index] = sequence[i];
        combinations(sequence, data, i + 1, end, index + 1, r);
    }
    return null;

}

public static void main(String args[])
{
    char[] sequence = { '0','1','2'/*,'3','4','5','6','7','8','9',':',';','<','=','>','?','@','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','[',']','^','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z' */};
    System.out.print("The combinations are: ");

  // printCombinations(sequence, sequence.length);

    int N=sequence.length;
    char[] data = new char[N];
    for (int r = 0; r < sequence.length; r++)
        combinations(sequence, data, 0, N - 1, 0, r);
}
</code>```

答:
With your current method.  You need to switch up your method to get this done properly.

My attempt using your current method.

```<code>import java.util.ArrayList;
import java.util.List;

public class JavaApplication47
{
    public static void main(String[] args)
    {
        char[] sequence = { '0','1','2'/*,'3','4','5','6','7','8','9',':',';','<','=','>','?','@','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','[',']','^','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z' */};

        System.out.print("The combinations are: ");

        // printCombinations(sequence, sequence.length);
        List<String> list = new ArrayList();

        int N=sequence.length;
        char[] data = new char[N];
        for (int r = 0; r <= sequence.length; r++)
        {
            list.add(combinations(sequence, data, 0, N - 1, 0, r));
        }

        System.out.println(list.size());
        for (String combo : list)
        {
            System.out.println(combo);
        }
    }

    static String combinations(char[] sequence, char[] data, int start, int end, int index, int r)
    {
        StringBuilder stringbuilder = new StringBuilder();
        if (index == r)
        {
            StringBuilder stringbuilder2 = new StringBuilder();

            for (int j = 0; j < r; j++)
            {
                //System.out.print(data[j] + " ");
                stringbuilder2.append(data[j]).append(" ");
            }
            //System.out.println();
            return stringbuilder2.append(" - ").toString();
        }

        for (int i = start; i <= end && ((end - i + 1) >= (r - index)); i++)
        {
            data[index] = sequence[i];
            stringbuilder.append(combinations(sequence, data, i + 1, end, index + 1, r));
        }
        return stringbuilder.toString();

    }

}
</code>```

Here is my version with your combinations method altered

```<code>import java.util.ArrayList;
import java.util.List;

public class JavaApplication47
{
    public static void main(String[] args)
    {
        char[] sequence = { '0','1','2'/*,'3','4','5','6','7','8','9',':',';','<','=','>','?','@','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','[',']','^','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z' */};

        System.out.print("The combinations are: ");

        // printCombinations(sequence, sequence.length);
        List<String> list = new ArrayList();

        int N=sequence.length;
        char[] data = new char[N];
        for (int r = 0; r <= sequence.length; r++)
        {
            list.addAll(combinations(sequence, data, 0, N - 1, 0, r));
        }

        for (String combo : list)
        {
            System.out.println(combo);
        }
        System.out.println("list size: " + list.size());
    }

    static List<String> combinations(char[] sequence, char[] data, int start, int end, int index, int r)
    {
        List<String> list = new ArrayList();
        if (index == r)
        {
            List<String> tempList = new ArrayList();
            StringBuilder stringbuilder2 = new StringBuilder();

            for (int j = 0; j < r; j++)
            {
                stringbuilder2.append(data[j]).append(" ");
            }

            tempList.add(stringbuilder2.toString());
            return tempList;
        }

        for (int i = start; i <= end && ((end - i + 1) >= (r - index)); i++)
        {
            data[index] = sequence[i];
            list.addAll(combinations(sequence, data, i + 1, end, index + 1, r));
        }
        return list;

    }

}
</code>```

Body:
How can I save as an ArrayList all possible combinations of a set of characters in string?

You can see my code below. It only print the combinations, but doesn't save all combinations. Any idea?

public class All_Possible_Combinatons
{

static String combinations(char[] sequence, char[] data, int start, int end,
        int index, int r)
{

    if (index == r)
    {
        for (int j = 0; j < r; j++)
            // = data[j];
            System.out.print(data[j] + " ");
        System.out.println();
    }

    for (int i = start; i <= end && ((end - i + 1) >= (r - index)); i++)
    {
        data[index] = sequence[i];
        combinations(sequence, data, i + 1, end, index + 1, r);
    }
    return null;

}

public static void main(String args[])
{
    char[] sequence = { '0','1','2'/*,'3','4','5','6','7','8','9',':',';','<','=','>','?','@','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','[',']','^','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z' */};
    System.out.print("The combinations are: ");

  // printCombinations(sequence, sequence.length);

    int N=sequence.length;
    char[] data = new char[N];
    for (int r = 0; r < sequence.length; r++)
        combinations(sequence, data, 0, N - 1, 0, r);
}

Body:
With your current method.  You need to switch up your method to get this done properly.

My attempt using your current method.

import java.util.ArrayList;
import java.util.List;

public class JavaApplication47
{
    public static void main(String[] args)
    {
        char[] sequence = { '0','1','2'/*,'3','4','5','6','7','8','9',':',';','<','=','>','?','@','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','[',']','^','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z' */};

        System.out.print("The combinations are: ");

        // printCombinations(sequence, sequence.length);
        List<String> list = new ArrayList();

        int N=sequence.length;
        char[] data = new char[N];
        for (int r = 0; r <= sequence.length; r++)
        {
            list.add(combinations(sequence, data, 0, N - 1, 0, r));
        }

        System.out.println(list.size());
        for (String combo : list)
        {
            System.out.println(combo);
        }
    }

    static String combinations(char[] sequence, char[] data, int start, int end, int index, int r)
    {
        StringBuilder stringbuilder = new StringBuilder();
        if (index == r)
        {
            StringBuilder stringbuilder2 = new StringBuilder();

            for (int j = 0; j < r; j++)
            {
                //System.out.print(data[j] + " ");
                stringbuilder2.append(data[j]).append(" ");
            }
            //System.out.println();
            return stringbuilder2.append(" - ").toString();
        }

        for (int i = start; i <= end && ((end - i + 1) >= (r - index)); i++)
        {
            data[index] = sequence[i];
            stringbuilder.append(combinations(sequence, data, i + 1, end, index + 1, r));
        }
        return stringbuilder.toString();

    }

}

Here is my version with your combinations method altered

import java.util.ArrayList;
import java.util.List;

public class JavaApplication47
{
    public static void main(String[] args)
    {
        char[] sequence = { '0','1','2'/*,'3','4','5','6','7','8','9',':',';','<','=','>','?','@','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','[',']','^','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z' */};

        System.out.print("The combinations are: ");

        // printCombinations(sequence, sequence.length);
        List<String> list = new ArrayList();

        int N=sequence.length;
        char[] data = new char[N];
        for (int r = 0; r <= sequence.length; r++)
        {
            list.addAll(combinations(sequence, data, 0, N - 1, 0, r));
        }

        for (String combo : list)
        {
            System.out.println(combo);
        }
        System.out.println("list size: " + list.size());
    }

    static List<String> combinations(char[] sequence, char[] data, int start, int end, int index, int r)
    {
        List<String> list = new ArrayList();
        if (index == r)
        {
            List<String> tempList = new ArrayList();
            StringBuilder stringbuilder2 = new StringBuilder();

            for (int j = 0; j < r; j++)
            {
                stringbuilder2.append(data[j]).append(" ");
            }

            tempList.add(stringbuilder2.toString());
            return tempList;
        }

        for (int i = start; i <= end && ((end - i + 1) >= (r - index)); i++)
        {
            data[index] = sequence[i];
            list.addAll(combinations(sequence, data, i + 1, end, index + 1, r));
        }
        return list;

    }

}


问:
Does array assignment create a new reference
I am running into the following situation. I am initializing an array, and assigning it to an object's property.

```<code>var arr = [1,2,3,4,5];
var obj = { 'numbers': arr };
</code>```

I understand that I passed a reference to my array arr to my object obj. So I can do the following:

```<code>arr.push(6);
console.log(obj);
</code>```

will display the following, as expected:

```<code>{ numbers: [ 1, 2, 3, 4, 5, 6] }
</code>```

Now for the unexpected part. The value of arr changes, through an external event, and I want the value of obj.numbers to change at the same time. But it does not:

```<code>arr = [0,0,0,0,0];
console.log(arr);
console.log(obj);
arr --> [0,0,0,0,0]
obj --> { numbers: [ 1, 2, 3, 4, 5, 6] }
</code>```

So the value of my arr variable changed, but not the numbers property in my obj variable.

So, my only explanation is, that as soon as you perform an assignment to an array, you break the old reference and create a new reference. Is that so?

And how would I assign my new values [0,0,0,0,0] to my arr variable and the obj.numbers (at the same time)?

答:
You could use Array#splice as well for a new array.

var array = [1,2,3,4,5],
    object = { numbers: array },
    newArray = [41, 42, 43];

[].splice.apply(array, [0, array.length].concat(newArray));

console.log(object);```

Body:
I am running into the following situation. I am initializing an array, and assigning it to an object's property.

var arr = [1,2,3,4,5];
var obj = { 'numbers': arr };

I understand that I passed a reference to my array arr to my object obj. So I can do the following:

arr.push(6);
console.log(obj);

will display the following, as expected:

{ numbers: [ 1, 2, 3, 4, 5, 6] }

Now for the unexpected part. The value of arr changes, through an external event, and I want the value of obj.numbers to change at the same time. But it does not:

arr = [0,0,0,0,0];
console.log(arr);
console.log(obj);
arr --> [0,0,0,0,0]
obj --> { numbers: [ 1, 2, 3, 4, 5, 6] }

So the value of my arr variable changed, but not the numbers property in my obj variable.

So, my only explanation is, that as soon as you perform an assignment to an array, you break the old reference and create a new reference. Is that so?

And how would I assign my new values [0,0,0,0,0] to my arr variable and the obj.numbers (at the same time)?


问:
ruby 1.9 how to convert array to string without brackets
My question is about how to convert array elements to string in ruby 1.9 without getting the brackets and quotation marks. I've got an array (DB extract), from which I want to use to create a periodic report.

```<code>myArray = ["Apple", "Pear", "Banana", "2", "15", "12"]
</code>```

In ruby 1.8 I had the following line

```<code>reportStr = "In the first quarter we sold " + myArray[3].to_s + " " + myArray[0].to_s + "(s)."
puts reportStr
</code>```

Which produced the (wanted) output

In the first quarter we sold 2 Apple(s).

The same two lines in ruby 1.9 produce (not wanted)

In the first quarter we sold ["2"] ["Apple"] (s).

After reading in the documentation
Ruby 1.9.3 doc#Array#slice
I thought I could produce code like

```<code>reportStr = "In the first quarter we sold " + myArray[3] + " " + myArray[0] + "(s)."
puts reportStr
</code>```

which returns a runtime error

/home/test/example.rb:450:in `+': can't convert Array into String (TypeError)

My current solution is to remove brackets and quotation marks with a temporary string, like

```<code>tempStr0 = myArray[0].to_s
myLength = tempStr0.length
tempStr0 = tempStr0[2..myLength-3]
tempStr3 = myArray[3].to_s
myLength = tempStr3.length
tempStr3 = tempStr3[2..myLength-3]
reportStr = "In the first quarter we sold " + tempStr3 + " " + tempStr0 + "(s)."
puts reportStr
</code>```

which in general works.

However, what would be a more elegant "ruby" way how to do that?

答:
You can think of this as arrayToString()

array = array * " "

E.g.,

myArray = ["One.","_1_?! Really?!","Yes!"]

=> "One.","_1_?! Really?!","Yes!"

myArray = myArray * " "

=> "One. _1_?! Really?! Yes."

Body:
My question is about how to convert array elements to string in ruby 1.9 without getting the brackets and quotation marks. I've got an array (DB extract), from which I want to use to create a periodic report.

myArray = ["Apple", "Pear", "Banana", "2", "15", "12"]

In ruby 1.8 I had the following line

reportStr = "In the first quarter we sold " + myArray[3].to_s + " " + myArray[0].to_s + "(s)."
puts reportStr

Which produced the (wanted) output

In the first quarter we sold 2 Apple(s).

The same two lines in ruby 1.9 produce (not wanted)

In the first quarter we sold ["2"] ["Apple"] (s).

After reading in the documentation
Ruby 1.9.3 doc#Array#slice
I thought I could produce code like

reportStr = "In the first quarter we sold " + myArray[3] + " " + myArray[0] + "(s)."
puts reportStr

which returns a runtime error

/home/test/example.rb:450:in `+': can't convert Array into String (TypeError)

My current solution is to remove brackets and quotation marks with a temporary string, like

tempStr0 = myArray[0].to_s
myLength = tempStr0.length
tempStr0 = tempStr0[2..myLength-3]
tempStr3 = myArray[3].to_s
myLength = tempStr3.length
tempStr3 = tempStr3[2..myLength-3]
reportStr = "In the first quarter we sold " + tempStr3 + " " + tempStr0 + "(s)."
puts reportStr

which in general works.

However, what would be a more elegant "ruby" way how to do that?


问:
to open new page for successful registration in nodejs
I have code something like this

```<code> router.post('/register', function(req, res) {
</code>```

//saving to db if successful
       res.sendStatus(200);
});

on successful registration i want to open a new page!!!

答:
If you want redirect page in your project, try this:</p>

```<code>router.post('/register', function(req, res) {
    ...
    do something
    ...
    res.redirect('/foo/bar');
}
</code>```

Body:
I have code something like this

 router.post('/register', function(req, res) {

//saving to db if successful
       res.sendStatus(200);
});

on successful registration i want to open a new page!!!

Body:
If you want redirect page in your project, try this:

router.post('/register', function(req, res) {
    ...
    do something
    ...
    res.redirect('/foo/bar');
}


问:
Check if all other checkboxes are checked; working but I want something more
```<code><script>$(function(){
  $('#admin_permission_check').on('change',function(){
     $('.admin_permission_check').prop('checked',$(this).prop('checked'));
  });
  $('.admin_permission_check').on('change',function(){
     $('#admin_permission_check').prop('checked',$('.admin_permission_check:checked').length ? true: false);
  });

});</script>
<input type=checkbox id='admin_permission_check' value="1" /> Select All
<input type=checkbox class='admin_permission_check' value="2" />
<input type=checkbox class='admin_permission_check' value="2" />
</code>```

This is working fine and i am able to check all check boxes with class admin_permission_check when checkbox with id admin_permission_check is being checked.

But when i have unchecked any checkbox with class admin_permission_check then the checkbox with id admin_permission_check is not being unchecked automatically and what should i do to if all the checkboxes with class admin_permission_check are checked already on pageload then the checkbox with id admin_permission_check automatically gets checked.

I don't know about Javascript but searching helped me to achieve the code above which is working but not as expected.

答:
You can use :not() selector to see if one of the checkboxes is not checked and after this you can adjust the checked property of the first one with id. The same function can be called on document ready to set the checked attribute of "Select All" checkbox if other checkboxes are checked. See the snippet below (I've put the initialization into setCheckBoxUpHandlers method to allow passing the id/class name for some different test cases).

$(document).ready(function(){
  setCheckBoxUpHandlers('admin_permission_check');
  setCheckBoxUpHandlers('admin_permission_check1');
  setCheckBoxUpHandlers('admin_permission_check2');
});

function setCheckBoxUpHandlers(name){
  $('#' + name).on('change',function(){
    $('.' + name).prop('checked', $(this).prop('checked'));
  });

  function checkIfAllAreChecked(){
    $('#'+ name).prop('checked', $('.' + name + ':not(:checked)').length ? false: true);
  }

  checkIfAllAreChecked();

  $('.' + name).on('change',function(){
    checkIfAllAreChecked();
  });
}```
<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=checkbox id='admin_permission_check' value="1" /> Select All
<input type=checkbox class='admin_permission_check' value="2" />
<input type=checkbox class='admin_permission_check' value="2" />

<br/>
<span>-------------------------------------------------------------------</span>
<br/>

<input type=checkbox id='admin_permission_check1' value="3" /> Select All
<input type=checkbox class='admin_permission_check1' value="4" />
<input type=checkbox class='admin_permission_check1' value="4" checked/>
<input type=checkbox class='admin_permission_check1' value="4" />

<br/>
<span>-------------------------------------------------------------------</span>
<br/>

<input type=checkbox id='admin_permission_check2' value="5" /> Select All
<input type=checkbox class='admin_permission_check2' value="6" checked/>
<input type=checkbox class='admin_permission_check2' value="6" checked/></code>```

Body:
<input type=checkbox id='admin_permission_check' value="1" /> Select All
<input type=checkbox class='admin_permission_check' value="2" />
<input type=checkbox class='admin_permission_check' value="2" />

This is working fine and i am able to check all check boxes with class admin_permission_check when checkbox with id admin_permission_check is being checked.

But when i have unchecked any checkbox with class admin_permission_check then the checkbox with id admin_permission_check is not being unchecked automatically and what should i do to if all the checkboxes with class admin_permission_check are checked already on pageload then the checkbox with id admin_permission_check automatically gets checked.

I don't know about Javascript but searching helped me to achieve the code above which is working but not as expected.

Body:
You can use :not() selector to see if one of the checkboxes is not checked and after this you can adjust the checked property of the first one with id. The same function can be called on document ready to set the checked attribute of "Select All" checkbox if other checkboxes are checked. See the snippet below (I've put the initialization into setCheckBoxUpHandlers method to allow passing the id/class name for some different test cases).

$(document).ready(function(){
  setCheckBoxUpHandlers('admin_permission_check');
  setCheckBoxUpHandlers('admin_permission_check1');
  setCheckBoxUpHandlers('admin_permission_check2');
});

function setCheckBoxUpHandlers(name){
  $('#' + name).on('change',function(){
    $('.' + name).prop('checked', $(this).prop('checked'));
  });

  function checkIfAllAreChecked(){
    $('#'+ name).prop('checked', $('.' + name + ':not(:checked)').length ? false: true);
  }

  checkIfAllAreChecked();

  $('.' + name).on('change',function(){
    checkIfAllAreChecked();
  });
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type=checkbox id='admin_permission_check' value="1" /> Select All
<input type=checkbox class='admin_permission_check' value="2" />
<input type=checkbox class='admin_permission_check' value="2" />

<br/>
<span>-------------------------------------------------------------------</span>
<br/>

<input type=checkbox id='admin_permission_check1' value="3" /> Select All
<input type=checkbox class='admin_permission_check1' value="4" />
<input type=checkbox class='admin_permission_check1' value="4" checked/>
<input type=checkbox class='admin_permission_check1' value="4" />

<br/>
<span>-------------------------------------------------------------------</span>
<br/>

<input type=checkbox id='admin_permission_check2' value="5" /> Select All
<input type=checkbox class='admin_permission_check2' value="6" checked/>
<input type=checkbox class='admin_permission_check2' value="6" checked/>


问:
Access - Do not select a text box by default on a form
I have an access program with a splash screen at the start.
On the splash screen, two text boxes are shown: "Component" and "Version", which are linked to a table with those values in. My problem is this:
Even though the text box properties are set to Tab Stop = No and Back Style = Transparent, the first text box still selects itself and the text is selected and does not look good.
The actual form's "Allow additions, edits, etc" are all set to No and Data Entry is off. Here is what happens when the form is opened:
Highlighted Text Screenshot

I have tried to stop it by turning tab stop = no and turning off all the options that allow data to be entered or edited. I want it to not be highlighted. How can I achieve this?
Thank you.

答:
In Design view, set both text boxes to

```<code>Enabled = No
Locked = Yes
</code>```

This way they can't get the focus.

Body:
In Design view, set both text boxes to

Enabled = No
Locked = Yes

This way they can't get the focus.


问:
Create ZIP Files and Deploy as GitHub-Release on AppVeyor
I wan't to create ZIP Files on AppVeyor to publish it on GitHub as an Release.

Currently, the Build-Process make following Steps:

Install Node.js v7

Start the .\Build-All.bat

The Bild.bat has following Steps:

Create Temp and Build Directory

Move Source to Temp

Install depencies with npm install

Start electron-packager to create binary files (See directory structure of /Build/ directory)

Directory Structure:

```<code>/Source/
/Build/
  L /DSTEd-darwin-x64/
  L /DSTEd-linux-armv7l/
  L /DSTEd-linux-ia32/
  L /DSTEd-linux-x64/
  L /DSTEd-mas-x64/
  L /DSTEd-win32-ia32/
  L /DSTEd-win32-x64/
/Temp/
/Build.bat
</code>```

Here is that, what i want:

Package each Build-Directory (for sample /Build/DSTEd-win32-x64/) to an ZIP-Archive like /Build/DSTEd-win32-x64.zip

Add all ZIP-Archives (/Build/DSTEd-*-*.zip) to the release

I had created manually a Release on GitHub for sample; That is, what i want:
 https://github.com/DST-Tools/DSTEd/releases/tag/1.0.0

Here is my appveyor.yml:

```<code>version: 1.0.0-{build}

# Set the Node Version
environment:
  matrix:
    - nodejs_version: "7"

# Install scripts. (runs after repo cloning)
install:
  - ps: Install-Product node $env:nodejs_version
  - npm -g install electron-packager
  - .\Build-All.bat

# Caching
cache:
  - node_modules

# Deployment Options
deploy:
  tag: $(appveyor_build_version)
  release: 'DSTEd v${appveyor_build_version} - Pre-Release (Preview)'
  description: ' ![Preview](https://github.com/DST-Tools/DSTEd/raw/master/Screenshots/preview.png)  ## Pre-Release v1.0.0 (Preview) Builded binarys for `Windows` (`32bit` & `64bit`), `Linux` (`32bit`, `64bit` & `armv7`) and `Mac OS X` (`darwin` & `mas`, only `64bit`).'
  provider: GitHub
  auth_token:
    secure: b202f536350628ff69af69d08daee9f76a9cff20
  artifact: '**\*.zip'
  draft: false
  prerelease: true
  on:
    branch: master
    appveyor_repo_tag: true

matrix:
  fast_finish: true

build: OFF
test: OFF
</code>```

答:
Missed part is artifact packaging. You can list all those folders are artifacts and Appveyor will zip them for you. After that deployment will "see" them.

Side note: you might want to remove on/branch:master part because in most cases tag name replaces branch name in incoming webhook. More details are here. In general I would recommend to start with simplest possible deployment configuration and add settings one by one after basic one works.

Body:
I wan't to create ZIP Files on AppVeyor to publish it on GitHub as an Release.

Currently, the Build-Process make following Steps:

Install Node.js v7

Start the .\Build-All.bat

The Bild.bat has following Steps:

Create Temp and Build Directory

Move Source to Temp

Install depencies with npm install

Start electron-packager to create binary files (See directory structure of /Build/ directory)

Directory Structure:

/Source/
/Build/
  L /DSTEd-darwin-x64/
  L /DSTEd-linux-armv7l/
  L /DSTEd-linux-ia32/
  L /DSTEd-linux-x64/
  L /DSTEd-mas-x64/
  L /DSTEd-win32-ia32/
  L /DSTEd-win32-x64/
/Temp/
/Build.bat

Here is that, what i want:

Package each Build-Directory (for sample /Build/DSTEd-win32-x64/) to an ZIP-Archive like /Build/DSTEd-win32-x64.zip

Add all ZIP-Archives (/Build/DSTEd-*-*.zip) to the release

I had created manually a Release on GitHub for sample; That is, what i want:
 https://github.com/DST-Tools/DSTEd/releases/tag/1.0.0

Here is my appveyor.yml:

version: 1.0.0-{build}

# Set the Node Version
environment:
  matrix:
    - nodejs_version: "7"

# Install scripts. (runs after repo cloning)
install:
  - ps: Install-Product node $env:nodejs_version
  - npm -g install electron-packager
  - .\Build-All.bat

# Caching
cache:
  - node_modules

# Deployment Options
deploy:
  tag: $(appveyor_build_version)
  release: 'DSTEd v${appveyor_build_version} - Pre-Release (Preview)'
  description: ' ![Preview](https://github.com/DST-Tools/DSTEd/raw/master/Screenshots/preview.png)  ## Pre-Release v1.0.0 (Preview) Builded binarys for `Windows` (`32bit` & `64bit`), `Linux` (`32bit`, `64bit` & `armv7`) and `Mac OS X` (`darwin` & `mas`, only `64bit`).'
  provider: GitHub
  auth_token:
    secure: b202f536350628ff69af69d08daee9f76a9cff20
  artifact: '**\*.zip'
  draft: false
  prerelease: true
  on:
    branch: master
    appveyor_repo_tag: true

matrix:
  fast_finish: true

build: OFF
test: OFF


问:
(unix) How to write script to count the number of files in a directory using loop
How can I create a bash script to count the number of files in a directory using a loop.

The script should take a target directory and output: Number of files in ::

答:
You don't really need a loop. The following will count the files in a directory:</p>

```<code>files=($(ls $1))
echo ${#files[@]}
</code>```

Body:
You don't really need a loop. The following will count the files in a directory:

files=($(ls $1))
echo ${#files[@]}


问:
ViewComponent in external assembly cannot be found
I am using the latest VS.2017 updates and templates for an MVC .NET Core web application. I decided I wanted ViewComponents in an external assembly since I read several posts that indicated it was not possible without odd tricks.

I have my main web application and then I created a .NET Framework class library named MySite.Components which is the "external assembly". In it I installed the ViewFeatures NuGet. I created my View component CSHTML in its /Views/Shared/Components/GoogleAdsense/Default.cshtml.

I noticed that my CSPROJ already has the GoogleAdSense as an embedded resource:

```<code> <ItemGroup>
  <None Include="app.config" />
  <None Include="packages.config" />
  <EmbeddedResource Include="Views\Shared\Components\GoogleAdsense\Default.cshtml" />
 </ItemGroup>
</code>```

The view component is actually quite simple:

```<code>namespace MySite.Components.ViewComponents {
     [ViewComponent(Name = "GoogleAdsense")]
     public class GoogleAdsense : ViewComponent {
        public async Task<IViewComponentResult> InvokeAsync(string adSlot, string clientId, string adStyle = "")
        {
          var model = await GetConfigAsync(adSlot, clientId, adStyle);
          return View(model);
        }

        private Task<GoogleAdUnitCompModel> GetConfigAsync(string adSlot, string clientId, string adStyle)
        {
             GoogleAdUnitCompModel model = new GoogleAdUnitCompModel
           {
            ClientId = clientId,    // apparently we can't access App_Data because there is no AppDomain in .NET core
            SlotNr = adSlot,
            Style = adStyle
           };
           return Task.FromResult(model);
        }
     }
}
</code>```

Then in the main project (the ASP.NET Core web application) I installed the File Provider NuGet and modified my Startup:

```<code>services.Configure<RazorViewEngineOptions>(options =>
        {
            options.FileProviders.Add(new EmbeddedFileProvider(
                 typeof(MySite.Components.ViewComponents.GoogleAdsense).GetTypeInfo().Assembly,
                 "MySite.Components.ViewComponents"
            ));
        });
</code>```

Then I try to use the view component in a view like this:

```<code>@using MySite.Components.ViewComponents
            :
@Component.InvokeAsync(nameof(GoogleAdsense), new { adSlot = "2700000000", clientId = "ca-pub-0000000000000000", adStyle="" })
</code>```

And I get an error saying

```<code>*InvalidOperationException: A view component named 'GoogleAdsense' could not be found.*
</code>```

Also tried using the notation without nameof() that uses a generic parameter for InvokeAsync but that fails too but with

```<code> *"Argument 1: cannot convert from 'method group' to 'object'"*
</code>```

And using the TagHelper form simply renders it as an unrecognized HTML:

```<code><vc:GoogleAdsense adSlot = "2700000000" clientId = "ca-pub-0000000000000000"></vc:GoogleAdsense>
</code>```

Finally, on the Main Assembly (the actual web application) I used the GetManifestResourceNames() on the external assembly type to verify it was embedded and the returned list had it listed as:

```<code>[0] = "MySite.Components.Views.Shared.Components.GoogleAdsense.Default.cshtml"
</code>```

答:
I was able to get a ViewComponent working from an external solution by generating and installing a NuGet package from the "external" assembly into the consuming solution with no problem. I had originally tried to add a reference to the dll without creating my own NuGet package and it did not work.

I'd recommend trying the NuGet package first. If it still doesn't work, can you post both projects so I can help debug?

Body:
I am using the latest VS.2017 updates and templates for an MVC .NET Core web application. I decided I wanted ViewComponents in an external assembly since I read several posts that indicated it was not possible without odd tricks.

I have my main web application and then I created a .NET Framework class library named MySite.Components which is the "external assembly". In it I installed the ViewFeatures NuGet. I created my View component CSHTML in its /Views/Shared/Components/GoogleAdsense/Default.cshtml.

I noticed that my CSPROJ already has the GoogleAdSense as an embedded resource:

 <ItemGroup>
  <None Include="app.config" />
  <None Include="packages.config" />
  <EmbeddedResource Include="Views\Shared\Components\GoogleAdsense\Default.cshtml" />
 </ItemGroup>

The view component is actually quite simple:

namespace MySite.Components.ViewComponents {
     [ViewComponent(Name = "GoogleAdsense")]
     public class GoogleAdsense : ViewComponent {
        public async Task<IViewComponentResult> InvokeAsync(string adSlot, string clientId, string adStyle = "")
        {
          var model = await GetConfigAsync(adSlot, clientId, adStyle);
          return View(model);
        }

        private Task<GoogleAdUnitCompModel> GetConfigAsync(string adSlot, string clientId, string adStyle)
        {
             GoogleAdUnitCompModel model = new GoogleAdUnitCompModel
           {
            ClientId = clientId,    // apparently we can't access App_Data because there is no AppDomain in .NET core
            SlotNr = adSlot,
            Style = adStyle
           };
           return Task.FromResult(model);
        }
     }
}

Then in the main project (the ASP.NET Core web application) I installed the File Provider NuGet and modified my Startup:

services.Configure<RazorViewEngineOptions>(options =>
        {
            options.FileProviders.Add(new EmbeddedFileProvider(
                 typeof(MySite.Components.ViewComponents.GoogleAdsense).GetTypeInfo().Assembly,
                 "MySite.Components.ViewComponents"
            ));
        });

Then I try to use the view component in a view like this:

@using MySite.Components.ViewComponents
            :
@Component.InvokeAsync(nameof(GoogleAdsense), new { adSlot = "2700000000", clientId = "ca-pub-0000000000000000", adStyle="" })

And I get an error saying

*InvalidOperationException: A view component named 'GoogleAdsense' could not be found.*

Also tried using the notation without nameof() that uses a generic parameter for InvokeAsync but that fails too but with

 *"Argument 1: cannot convert from 'method group' to 'object'"*

And using the TagHelper form simply renders it as an unrecognized HTML:

<vc:GoogleAdsense adSlot = "2700000000" clientId = "ca-pub-0000000000000000"></vc:GoogleAdsense>

Finally, on the Main Assembly (the actual web application) I used the GetManifestResourceNames() on the external assembly type to verify it was embedded and the returned list had it listed as:

[0] = "MySite.Components.Views.Shared.Components.GoogleAdsense.Default.cshtml"


问:
How does one resolve link error with Qt?
I'm new to Qt, and trying to compile and link a simple "Hello, World" program using Microsoft's "CL.exe".  Any advice on how to do this?

The program is:

```<code>#include <QtGui>

int main ( int argc, char * argv [] )
    {
    QApplication app ( argc, argv ) ;
    QLabel label ( "Hello, world!" ) ;
    label.show() ;
    return app.exec() ;
    }
</code>```

I compile and link with:

```<code>C:\PROGRA~1\MICROS~1.0\VC\bin\cl.EXE -nologo -Zm200 -Zc:wchar_t- -O2 -MD ^
-W3 -w34100 -w34189 -DUNICODE ^
-DWIN32 -DQT_LARGEFILE_SUPPORT -DQT_NO_DEBUG -DQT_GUI_LIB -DQT_CORE_LIB ^
-DQT_THREAD_SUPPORT -DQT_NO_DYNAMIC_CAST ^
-I"C:\Qt\2010.05\qt\include\QtCore" ^
-I"C:\Qt\2010.05\qt\include\QtGui" ^
-I"C:\Qt\2010.05\qt\include" ^
-I"." ^
-I"C:\Qt\2010.05\qt\include\ActiveQt" ^
-I"release" ^
-I"C:\Qt\2010.05\qt\mkspecs\win32-msvc2008" ^
-I"C:\Progra~1\MICROS~1.0\VC\include" ^
Hello.cpp ^
/link /LIBPATH:"C:\Qt\2010.05\qt\lib" ^
/LIBPATH:"C:\Progra~1\MICROS~1.0\VC\lib" ^
/LIBPATH:"C:\Progra~1\MID05A~1\VC\PLATFO~1\Lib"
</code>```

My linker errors include:

```<code>Hello.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) pub
lic: virtual __thiscall QApplication::~QApplication(void)" (__imp_??1QApplicatio
n@@UAE@XZ) referenced in function _main
Hello.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) pub
lic: virtual __thiscall QLabel::~QLabel(void)" (__imp_??1QLabel@@UAE@XZ) referen
ced in function _main
Hello.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) pub
lic: static int __cdecl QApplication::exec(void)" (__imp_?exec@QApplication@@SAH
XZ) referenced in function _main
Hello.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) pub
lic: void __thiscall QWidget::show(void)" (__imp_?show@QWidget@@QAEXXZ) referenc
ed in function _main
.
.
.
</code>```

My Hello.pro file contains:

```<code>######################################################################
# Automatically generated by qmake (2.01a) Mon Dec 13 15:58:13 2010
######################################################################

TEMPLATE = app
TARGET =
DEPENDPATH += .
INCLUDEPATH += .

# Input
SOURCES += Hello.cpp
</code>```

答:
You should be linking against QtCore and QtGui libraries but you don't. What does your .pro file look like?

Edited to add after the .pro file was posted: Your .pro file looks all right. You're not overwriting the QT variable which by default includes core gui, which should result in QtCode and QtGui being linked to. It's also evident by the fact that both QtCore and QtGui are present in your include paths.

I haven't used cl.exe with Qt but you could try adding LIBS += -lQtCore -lQtGui to force linking to QtCore and QtGui. (There's probably a more elegant fix though.)

Body:
I'm new to Qt, and trying to compile and link a simple "Hello, World" program using Microsoft's "CL.exe".  Any advice on how to do this?

The program is:

#include <QtGui>

int main ( int argc, char * argv [] )
    {
    QApplication app ( argc, argv ) ;
    QLabel label ( "Hello, world!" ) ;
    label.show() ;
    return app.exec() ;
    }

I compile and link with:

C:\PROGRA~1\MICROS~1.0\VC\bin\cl.EXE -nologo -Zm200 -Zc:wchar_t- -O2 -MD ^
-W3 -w34100 -w34189 -DUNICODE ^
-DWIN32 -DQT_LARGEFILE_SUPPORT -DQT_NO_DEBUG -DQT_GUI_LIB -DQT_CORE_LIB ^
-DQT_THREAD_SUPPORT -DQT_NO_DYNAMIC_CAST ^
-I"C:\Qt\2010.05\qt\include\QtCore" ^
-I"C:\Qt\2010.05\qt\include\QtGui" ^
-I"C:\Qt\2010.05\qt\include" ^
-I"." ^
-I"C:\Qt\2010.05\qt\include\ActiveQt" ^
-I"release" ^
-I"C:\Qt\2010.05\qt\mkspecs\win32-msvc2008" ^
-I"C:\Progra~1\MICROS~1.0\VC\include" ^
Hello.cpp ^
/link /LIBPATH:"C:\Qt\2010.05\qt\lib" ^
/LIBPATH:"C:\Progra~1\MICROS~1.0\VC\lib" ^
/LIBPATH:"C:\Progra~1\MID05A~1\VC\PLATFO~1\Lib"

My linker errors include:

Hello.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) pub
lic: virtual __thiscall QApplication::~QApplication(void)" (__imp_??1QApplicatio
n@@UAE@XZ) referenced in function _main
Hello.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) pub
lic: virtual __thiscall QLabel::~QLabel(void)" (__imp_??1QLabel@@UAE@XZ) referen
ced in function _main
Hello.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) pub
lic: static int __cdecl QApplication::exec(void)" (__imp_?exec@QApplication@@SAH
XZ) referenced in function _main
Hello.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) pub
lic: void __thiscall QWidget::show(void)" (__imp_?show@QWidget@@QAEXXZ) referenc
ed in function _main
.
.
.

My Hello.pro file contains:

######################################################################
# Automatically generated by qmake (2.01a) Mon Dec 13 15:58:13 2010
######################################################################

TEMPLATE = app
TARGET =
DEPENDPATH += .
INCLUDEPATH += .

# Input
SOURCES += Hello.cpp