问:
Apache is not running from XAMPP Control Panel ( Error: Apache shutdown unexpectedly. This may be due to a blocked port)
I have installed XAMPP (xampp-win32-1.8.2-0-VC9-installer.exe) on Windows 7 successfully. But unfortunately, the following error was found during running Apache from XAMPP Control Panel:

```<code>5:38:38 PM  [Apache]    Error: Apache shutdown unexpectedly.
5:38:38 PM  [Apache]    This may be due to a blocked port, missing dependencies,
5:38:38 PM  [Apache]    improper privileges, a crash, or a shutdown by another method.
5:38:38 PM  [Apache]    Press the Logs button to view error logs and check
5:38:38 PM  [Apache]    the Windows Event Viewer for more clues
5:38:38 PM  [Apache]    If you need more help, copy and post this
5:38:38 PM  [Apache]    entire log window on the forums
</code>```

答:
Probably you change configuration file in "httpd-ssl.conf"

```<code><VirtualHost _default_:443>
DocumentRoot "D:/Server/xServer"
ServerName xyz.abc.com
SSLCertificateFile "conf/ssl.crt/xyz.crt"
SSLCertificateKeyFile "conf/ssl.key/sftaps.in.key"
</VirtualHost>
</code>```

May be you change certificate name or something in Apache folder.

Body:
I have installed XAMPP (xampp-win32-1.8.2-0-VC9-installer.exe) on Windows 7 successfully. But unfortunately, the following error was found during running Apache from XAMPP Control Panel:

5:38:38 PM  [Apache]    Error: Apache shutdown unexpectedly.
5:38:38 PM  [Apache]    This may be due to a blocked port, missing dependencies,
5:38:38 PM  [Apache]    improper privileges, a crash, or a shutdown by another method.
5:38:38 PM  [Apache]    Press the Logs button to view error logs and check
5:38:38 PM  [Apache]    the Windows Event Viewer for more clues
5:38:38 PM  [Apache]    If you need more help, copy and post this
5:38:38 PM  [Apache]    entire log window on the forums

Body:
Probably you change configuration file in "httpd-ssl.conf"

<VirtualHost _default_:443>
DocumentRoot "D:/Server/xServer"
ServerName xyz.abc.com
SSLCertificateFile "conf/ssl.crt/xyz.crt"
SSLCertificateKeyFile "conf/ssl.key/sftaps.in.key"
</VirtualHost>

May be you change certificate name or something in Apache folder.


来源: stackexchange

问:
On your very first program, which construct hooked you on programming?
To me it was the If statement, I'm psyched up, since then I believed that computers are very intelligent, or I can at least make it appear intelligent because of it.</p>

答:
IF-GOTO.

No joke. I was hooked long before I got such a language as had pointers.

I had already written pointer-like algorithms using array indexes by that point.

OwnerDisplayName: Michael Buen

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Triptych

OwnerDisplayName: Joshua


问:
Cumulatively count how many times a condition has ocurred in a row
In a data.table (or a data.frame), how can I count "cumulatively" how many times such condition has occurred in a row?

To illustrate,

```<code>DT <- data.table(A=c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),
                 B=c(1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1))
</code>```

If I would like to add a column C that indicates

if (A==B), add 1 to the value above current row.

if (A!=B), start again with 0

So the answer would be

```<code>DT <- data.table(A=c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),
                 B=c(1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1),
                 C=c(1, 0, 1, 2, 0, 1, 2, 3, 0, 1, 2, 3, 4, 0, 1)]
</code>```

It seems simple but I can't seem to do it. I'm guessing that it could build on something like this?

```<code>DT[,C:=ifelse(A==B, ??, 0)]
</code>```

Also, I'm afraid it may be a duplicate question but can't seen to find it.

ContentLicense: CC BY-SA 3.0

Body:
In a data.table (or a data.frame), how can I count "cumulatively" how many times such condition has occurred in a row?

To illustrate,

DT <- data.table(A=c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),
                 B=c(1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1))

If I would like to add a column C that indicates

if (A==B), add 1 to the value above current row.

if (A!=B), start again with 0

So the answer would be

DT <- data.table(A=c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),
                 B=c(1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1),
                 C=c(1, 0, 1, 2, 0, 1, 2, 3, 0, 1, 2, 3, 4, 0, 1)]

It seems simple but I can't seem to do it. I'm guessing that it could build on something like this?

DT[,C:=ifelse(A==B, ??, 0)]

Also, I'm afraid it may be a duplicate question but can't seen to find it.

Body:
Using ave in base R:

x <- with(dt, A==B)
cbind(dt, C = ave(x, cumsum(x == 0), FUN = cumsum))

   # A B C
 # 1: 1 1 1
 # 2: 1 0 0
 # 3: 1 1 1
 # 4: 1 1 2
 # 5: 1 0 0
 # 6: 1 1 1
 # 7: 1 1 2
 # 8: 1 1 3
 # 9: 1 0 0
# 10: 1 1 1
# 11: 1 1 2
# 12: 1 1 3
# 13: 1 1 4
# 14: 1 0 0
# 15: 1 1 1


问:
why is my express API not responding?

Background

I am testing a simple Hello World app using NodeJs v7 and express in cloud9.
I am trying to make my example work but I am failing.

Problem

All my cloud9 configurations are fine so that is not the problem. The problem is my app. When i debug, the route "api/v1/HolaBananas" never gets called and I don't know why!

Even worst, when i make the request, the browser just hangs, like it is waiting for an answer from the server that will never come!

Code

The index.js has the initialization and launch code. It is important for me that I keep this separate from api.js for modular reasons.

index.js

```<code>"use strict";

const express = require("express");

const app = express();
app.use("/api/v1", require("./api.js"));

app.listen(process.env.PORT);
console.log(`Server listening on port ${process.env.PORT}!`);
</code>```

The api.js simply contains the routes and what they are supposed to do.

api.js

```<code>"use strict";

const express = require("express");

module.exports = function() {

    const api = express.Router();

    api.get("/HolaBananas", function(req, res){
        res.send("hello bananas!");
    });

    return api;
};
</code>```

Question

I am sure I am not using api.get in the right way, but I truly want to separate my initialization and launch code from the api.

How can I fix my code so it works?

Note

I am following the course

https://www.edx.org/course/introduction-mongodb-using-mean-stack-mongodbx-m101x-0

答:
There is one subtle thing about it: You have to invoke the function that you export in your api.js and use the router object that is returned from that function, so here is what you should do:

You have to replace this line:

```<code>app.use("/api/v1", require("./api.js"));
</code>```

with this:

```<code>app.use("/api/v1", require("./api.js")());
</code>```

Title: why is my express API not responding?

Body:
Background

I am testing a simple Hello World app using NodeJs v7 and express in cloud9.
I am trying to make my example work but I am failing.

Problem

All my cloud9 configurations are fine so that is not the problem. The problem is my app. When i debug, the route "api/v1/HolaBananas" never gets called and I don't know why!

Even worst, when i make the request, the browser just hangs, like it is waiting for an answer from the server that will never come!

Code

The index.js has the initialization and launch code. It is important for me that I keep this separate from api.js for modular reasons.

index.js

"use strict";

const express = require("express");

const app = express();
app.use("/api/v1", require("./api.js"));

app.listen(process.env.PORT);
console.log(`Server listening on port ${process.env.PORT}!`);

The api.js simply contains the routes and what they are supposed to do.

api.js

"use strict";

const express = require("express");

module.exports = function() {

    const api = express.Router();

    api.get("/HolaBananas", function(req, res){
        res.send("hello bananas!");
    });

    return api;
};

Question

I am sure I am not using api.get in the right way, but I truly want to separate my initialization and launch code from the api.

How can I fix my code so it works?

Note

I am following the course

https://www.edx.org/course/introduction-mongodb-using-mean-stack-mongodbx-m101x-0

Body:
There is one subtle thing about it: You have to invoke the function that you export in your api.js and use the router object that is returned from that function, so here is what you should do:

You have to replace this line:

app.use("/api/v1", require("./api.js"));

with this:

app.use("/api/v1", require("./api.js")());


问:
how to summarize characters in r
I have a data frame:

```<code>df <- data.frame(id = c("a","a","a","b","b","b"), survey = rep("1a",6), q1 = c(NA,NA,"y","n",NA,NA),q2 = c("y",NA,NA,NA,"y",NA), q3 = c(NA,"n",NA,NA,NA,"y"))
</code>```

These are survey data which I need to collapse to one for each id and survey. I can get close by:

```<code>df %>% group_by(id, survey) %>% summarize_all(toString)
Source: local data frame [2 x 5]
Groups: id [?]

      id survey        q1        q2        q3
    <fctr> <fctr>     <chr>     <chr>     <chr>
1      a     1a NA, NA, y y, NA, NA NA, n, NA
2      b     1a n, NA, NA NA, y, NA NA, NA, y
</code>```

What I really need is:

```<code>  id survey q1 q2 q3
1  a     1a  y  y  n
2  b     1a  n  y  y
</code>```

The real data frame is fairly large (1.2 million records).

Fundamentally different from suppress NAs in paste(). Answer to my question not found there.

答:
The simpliest solution is:</p>

```<code>df %>% group_by(id, survey) %>% summarise_all(na.omit)
</code>```

Title: how to summarize characters in r

Body:
I have a data frame:

df <- data.frame(id = c("a","a","a","b","b","b"), survey = rep("1a",6), q1 = c(NA,NA,"y","n",NA,NA),q2 = c("y",NA,NA,NA,"y",NA), q3 = c(NA,"n",NA,NA,NA,"y"))

These are survey data which I need to collapse to one for each id and survey. I can get close by:

df %>% group_by(id, survey) %>% summarize_all(toString)
Source: local data frame [2 x 5]
Groups: id [?]

      id survey        q1        q2        q3
    <fctr> <fctr>     <chr>     <chr>     <chr>
1      a     1a NA, NA, y y, NA, NA NA, n, NA
2      b     1a n, NA, NA NA, y, NA NA, NA, y

What I really need is:

  id survey q1 q2 q3
1  a     1a  y  y  n
2  b     1a  n  y  y

The real data frame is fairly large (1.2 million records).

Fundamentally different from suppress NAs in paste(). Answer to my question not found there.

Body:
The simpliest solution is:

df %>% group_by(id, survey) %>% summarise_all(na.omit)


问:
Select row where specific column has the highest value
As you can see in the title, I need SQL query(MySql) to get row where specific column has the greatest value.

So I need to select row where fav has the highest value. That means its bigger than def,rop,tip and uio. In my case it should be row number 3. Bellow you can see one part of my sql table

I tried with this query but it seems to me very slow(0,009s) on 20 records, any other query takes max. 0,003s.

```<code>SELECT id FROM table WHERE fav>def AND fav>rop AND fav>tip AND fav>uio
</code>```

Is there any better way for this? Thank you

table

table td {padding:4px 8px}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table border="1">
<tr>
<td>id</td><td>fav</td><td>def</td><td>rop</td><td>tip</td><td>uio</td>
</tr>
<tr>
<td>1</td><td>293</td><td>331</td><td>773</td><td>225</td><td>982</td>
</tr>
<tr>
<td>2</td><td>123</td><td>533</td><td>224</td><td>111</td><td>632</td>
</tr>
<tr style="background-color:lightblue">
<td>3</td><td>982</td><td>398</td><td>182</td><td>321</td><td>222</td>
</tr>
<tr>
<td>4</td><td>343</td><td>765</td><td>700</td><td>901</td><td>300</td>
</tr>
</table></code>```

答:
You are going to have to do a full table scan for this type of query.  However, performance on 20 rows should not be taken as a guid for overall performance.  Databases are designed to handle much larger queries and 0.009 seconds is pretty small on human timeframes.

I don't think there is a way around it.

You can simplify the query using greatest():

```<code>SELECT id
FROM table
WHERE fav > GREATEST(def, rop, tip, uio);
</code>```

If I had to guess, this would slightly slow down the query.

Body:
As you can see in the title, I need SQL query(MySql) to get row where specific column has the greatest value.

So I need to select row where fav has the highest value. That means its bigger than def,rop,tip and uio. In my case it should be row number 3. Bellow you can see one part of my sql table

I tried with this query but it seems to me very slow(0,009s) on 20 records, any other query takes max. 0,003s.

SELECT id FROM table WHERE fav>def AND fav>rop AND fav>tip AND fav>uio

Is there any better way for this? Thank you

table

table td {padding:4px 8px}

id	fav	def	rop	tip	uio

1	293	331	773	225	982

2	123	533	224	111	632

3	982	398	182	321	222

4	343	765	700	901	300

Body:
You are going to have to do a full table scan for this type of query.  However, performance on 20 rows should not be taken as a guid for overall performance.  Databases are designed to handle much larger queries and 0.009 seconds is pretty small on human timeframes.

I don't think there is a way around it.

You can simplify the query using greatest():

SELECT id
FROM table
WHERE fav > GREATEST(def, rop, tip, uio);

If I had to guess, this would slightly slow down the query.


问:
SQL UPDATE SET interchanges values
I update a View to get in two columns the same value, but it interchanges the two values instead of just setting it. My (reduced for so) view UpdateADAuftrag2 is this.

```<code>SELECT     dbo.CSDokument.AD1, dbo.UpdateAS400zuSellingBenutzer2.BenutzerNr
FROM       dbo.AS400Auftrag
           INNER JOIN
           dbo.CSDokument ON dbo.AS400Auftrag.Angebotsnummer = dbo.CSDokument.Angebotsnummer
           INNER JOIN
           dbo.UpdateAS400zuSellingBenutzer2 ON dbo.AS400Auftrag.AD = dbo.UpdateAS400zuSellingBenutzer2.SchluesselWert
           AND
           dbo.CSDokument.AD1 <> dbo.UpdateAS400zuSellingBenutzer2.BenutzerNr
           WHERE     (dbo.AS400Auftrag.AD IS NOT NULL)
</code>```

The important part is dbo.CSDokument.AD1 <> dbo.UpdateAS400zuSellingBenutzer2.BenutzerNr

AD1 is user number for external workers and BenutzerNr means user number. So e.g. the person Charlie Brown is an external worker and has the user number 31. When in AD1 is 31 - Charlie Brown is the external worker for this document (order in this case).

The Update statement loos like this

```<code> UPDATE [dbo].[UpdateADAuftrag2]
 SET [AD1] = [BenutzerNr]
</code>```

I have for example these values

```<code>AD1 | BenutzerNr
31  | 54
99  | 384
112 | 93
</code>```

after the update the result is this

```<code>AD1 | BenutzerNr
54  | 31
384 | 99
93  | 112
</code>```

Why not this?

```<code>AD1 | BenutzerNr
54  | 54
384 | 384
93  | 93
</code>```

edit: UpdateAS400zuSellingBenutzer is also a View, but as far as I can see it includes only BenutzerNr and not AD1.

答: There were 2 bugs - Bug 1 View UpdateAS400zuSellingBenutzer2 had 2 results sometimes for one entry in CSDokument and Bug 2 There were 2 entries in Table AS400Auftrag and then it switched between these two entries. So it just looked like the SET switched the two entries but it was just by chance. Thanks for reading. </p>

Title: SQL UPDATE SET interchanges values

Body:
I update a View to get in two columns the same value, but it interchanges the two values instead of just setting it. My (reduced for so) view UpdateADAuftrag2 is this.

SELECT     dbo.CSDokument.AD1, dbo.UpdateAS400zuSellingBenutzer2.BenutzerNr
FROM       dbo.AS400Auftrag
           INNER JOIN
           dbo.CSDokument ON dbo.AS400Auftrag.Angebotsnummer = dbo.CSDokument.Angebotsnummer
           INNER JOIN
           dbo.UpdateAS400zuSellingBenutzer2 ON dbo.AS400Auftrag.AD = dbo.UpdateAS400zuSellingBenutzer2.SchluesselWert
           AND
           dbo.CSDokument.AD1 <> dbo.UpdateAS400zuSellingBenutzer2.BenutzerNr
           WHERE     (dbo.AS400Auftrag.AD IS NOT NULL)

The important part is dbo.CSDokument.AD1 <> dbo.UpdateAS400zuSellingBenutzer2.BenutzerNr

AD1 is user number for external workers and BenutzerNr means user number. So e.g. the person Charlie Brown is an external worker and has the user number 31. When in AD1 is 31 - Charlie Brown is the external worker for this document (order in this case).

The Update statement loos like this

 UPDATE [dbo].[UpdateADAuftrag2]
 SET [AD1] = [BenutzerNr]

I have for example these values

AD1 | BenutzerNr
31  | 54
99  | 384
112 | 93

after the update the result is this

AD1 | BenutzerNr
54  | 31
384 | 99
93  | 112

Why not this?

AD1 | BenutzerNr
54  | 54
384 | 384
93  | 93

edit: UpdateAS400zuSellingBenutzer is also a View, but as far as I can see it includes only BenutzerNr and not AD1.


问:
fastest (low latency) method for Inter Process Communication between Java and C/C++
I have a Java app, connecting through TCP socket to a "server" developed in C/C++.

both app & server are running on the same machine, a Solaris box (but we're considering migrating to Linux eventually).
type of data exchanged is simple messages (login, login ACK, then client asks for something, server replies). each message is around 300 bytes long.

Currently we're using Sockets, and all is OK, however I'm looking for a faster way to exchange data (lower latency), using IPC methods.

I've been researching the net and came up with references to the following technologies:

shared memory

pipes

queues

as well as what's referred as DMA (Direct Memory Access)

but I couldn't find proper analysis of their respective performances, neither how to implement them in both JAVA and C/C++ (so that they can talk to each other), except maybe pipes that I could imagine how to do.

can anyone comment about performances & feasibility of each method in this context ?
any pointer / link to useful implementation information ?

EDIT / UPDATE

following the comment & answers I got here, I found info about Unix Domain Sockets, which seem to be built just over pipes, and would save me the whole TCP stack.
it's platform specific, so I plan on testing it with JNI or either juds or junixsocket.

next possible steps would be direct implementation of pipes, then shared memory, although I've been warned of the extra level of complexity...

thanks for your help

答:
Oracle bug report on JNI performance:  http://bugs.java.com/bugdatabase/view_bug.do?bug_id=4096069

JNI is a slow interface and so Java TCP sockets are the fastest method for notification between applications, however that doesn't mean you have to send the payload over a socket.  Use LDMA to transfer the payload, but as previous questions have pointed out, Java support for memory mapping is not ideal and you so will want to implement a JNI library to run mmap.


问:
How to set default colour for bars in Chart.js
This seems stupidly trivial but try as I might I cannot seem to find how to set a default colour for bars in chart.js.

My charts is taking its data from an ajax request and the chart is rendering just fine. However neither updating Chart.defaults.global.defaultColor nor adding defaultColor to the dataset as an option has any effect.

I would very much appreciate anyone pointing me in the right direction here.

```<code>$.ajax({
type: 'GET',
async: true,
url: "{{route('stats.monthlyData')}}",
dataType: 'json',
success: function (response) {
    var labels = [];
    var data = [];
    $.each(response, function () {
        labels.push(this.month_name);
        data.push(this.record_count);
    });
    drawChart('# of Records', labels, data);
}
});

function drawChart(label, labels, data){
    var ctx = document.getElementById("chart");
    //Chart.defaults.global.defaultColor = "#3498db"; Tried this but does not work
    var myChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: labels,
            datasets: [{
                label: label,
                data: data,
                //defaultColor: ['#3498db'], Tried this but does not work
                backgroundColor: ['#3498db'], //Only the first bar gets set
                borderColor: [],
                borderWidth: 1
            }]
        },
        options: {
            scales: {
                yAxes: [{
                    ticks: {
                        beginAtZero:true
                    }
                }]
            }
        }
    });

}
</code>```

Thanks.

UPDATE

In case it helps anyone, the issue was that I was setting the backgroundColor property to an array with only a single entry. If you want to default it for all columns then it should only be set to a string.
Credit to @mp77 for leading me to notice this issue.

答:
You need to use fillColor property in your datasets array like this -
(and instead of borderColor, try strokeColor like below)

datasets: [{
    label: label,
    data: data,
    fillColor: "rgba(14,72,100,1)", //version >2 useus background color
    strokeColor: "brown",
    borderWidth: 1
}]
```

A full working example can be seen from one of the demos of chartjs here

Body:
This seems stupidly trivial but try as I might I cannot seem to find how to set a default colour for bars in chart.js.

My charts is taking its data from an ajax request and the chart is rendering just fine. However neither updating Chart.defaults.global.defaultColor nor adding defaultColor to the dataset as an option has any effect.

I would very much appreciate anyone pointing me in the right direction here.

$.ajax({
type: 'GET',
async: true,
url: "{{route('stats.monthlyData')}}",
dataType: 'json',
success: function (response) {
    var labels = [];
    var data = [];
    $.each(response, function () {
        labels.push(this.month_name);
        data.push(this.record_count);
    });
    drawChart('# of Records', labels, data);
}
});

function drawChart(label, labels, data){
    var ctx = document.getElementById("chart");
    //Chart.defaults.global.defaultColor = "#3498db"; Tried this but does not work
    var myChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: labels,
            datasets: [{
                label: label,
                data: data,
                //defaultColor: ['#3498db'], Tried this but does not work
                backgroundColor: ['#3498db'], //Only the first bar gets set
                borderColor: [],
                borderWidth: 1
            }]
        },
        options: {
            scales: {
                yAxes: [{
                    ticks: {
                        beginAtZero:true
                    }
                }]
            }
        }
    });

}

Thanks.

UPDATE

In case it helps anyone, the issue was that I was setting the backgroundColor property to an array with only a single entry. If you want to default it for all columns then it should only be set to a string.
Credit to @mp77 for leading me to notice this issue.

Body:
You need to use fillColor property in your datasets array like this -
(and instead of borderColor, try strokeColor like below)

datasets: [{
    label: label,
    data: data,
    fillColor: "rgba(14,72,100,1)", //version >2 useus background color
    strokeColor: "brown",
    borderWidth: 1
}]

A full working example can be seen from one of the demos of chartjs here

ContentLicense: CC BY-SA 4.0


问:
Rails database configuration does not specify adapter. What do I do?
The following is the error message:

```<code>/Users/davidzabner/.rvm/gems/ruby-1.9.3-p448/gems/activerecord-3.2.13/lib/active_record/connection_adapters/abstract/connection_specification.rb:47:in `resolve_hash_connection'
    /Users/davidzabner/.rvm/gems/ruby-1.9.3-p448/gems/activerecord-3.2.13/lib/active_record/connection_adapters/abstract/connection_specification.rb:41:in `resolve_string_connection'
    ...
    /Users/davidzabner/.rvm/gems/ruby-1.9.3-p448/gems/railties-3.2.13/lib/rails/application.rb:103:in `require_environment!'
    /Users/davidzabner/.rvm/gems/ruby-1.9.3-p448/gems/railties-3.2.13/lib/rails/application.rb:297:in `block (2 levels) in initialize_tasks'
    /Users/davidzabner/.rvm/gems/ruby-1.9.3-p448/bin/ruby_noexec_wrapper:14:in `eval'
    /Users/davidzabner/.rvm/gems/ruby-1.9.3-p448/bin/ruby_noexec_wrapper:14:in `<main>'
</code>```

My database.yml file:

```<code>development:
  adapter: sqlite3
  database: db/development.sqlite3
  pool: 5
  timeout: 5000

test:
  adapter: sqlite3
  database: db/test.sqlite3
  pool: 5
  timeout: 5000

production:
  adapter: sqlite3
  database: db/production.sqlite3
  pool: 5
  timeout: 5000
</code>```

My Gemfile:

```<code>source 'https://rubygems.org'

gem "therubyracer"
gem "less-rails" #Sprockets (what Rails 3.1 uses for its asset pipeline) supports LESS
gem "twitter-bootstrap-rails"
gem 'jquery-rails'
gem 'devise'

gem 'rails', '3.2.13'

# Bundle edge Rails instead:
# gem 'rails', :git => 'git://github.com/rails/rails.git'

group :development, :test do
    gem 'sqlite3'
end

group :production do
    gem 'pg'
end

gem 'mini_magick'
gem "rmagick"
gem "carrierwave"

# Gems used only for assets and not required
# in production environments by default.
group :assets do
  gem 'sass-rails',   '~> 3.2.3'
  gem 'coffee-rails', '~> 3.2.1'

  # See https://github.com/sstephenson/execjs#readme for more supported runtimes
  # gem 'therubyracer', :platforms => :ruby

  gem 'uglifier', '>= 1.0.3'
end

gem 'jquery-rails'

# To use ActiveModel has_secure_password
# gem 'bcrypt-ruby', '~> 3.0.0'

# To use Jbuilder templates for JSON
# gem 'jbuilder'

# Use unicorn as the app server
# gem 'unicorn'

# Deploy with Capistrano
# gem 'capistrano'

# To use debugger
# gem 'debugger'
</code>```

答: Realise this is a little old, but have just come across whilst looking for an answer on a similar issue.  Just wanted to point out that you still have sqlite3 as your adaptor in your .yml.  As you have probably found out since, Heroku does not allow sqlite3 as a production db. SQLite on Heroku</p>

Body:
The following is the error message:

/Users/davidzabner/.rvm/gems/ruby-1.9.3-p448/gems/activerecord-3.2.13/lib/active_record/connection_adapters/abstract/connection_specification.rb:47:in `resolve_hash_connection'
    /Users/davidzabner/.rvm/gems/ruby-1.9.3-p448/gems/activerecord-3.2.13/lib/active_record/connection_adapters/abstract/connection_specification.rb:41:in `resolve_string_connection'
    ...
    /Users/davidzabner/.rvm/gems/ruby-1.9.3-p448/gems/railties-3.2.13/lib/rails/application.rb:103:in `require_environment!'
    /Users/davidzabner/.rvm/gems/ruby-1.9.3-p448/gems/railties-3.2.13/lib/rails/application.rb:297:in `block (2 levels) in initialize_tasks'
    /Users/davidzabner/.rvm/gems/ruby-1.9.3-p448/bin/ruby_noexec_wrapper:14:in `eval'
    /Users/davidzabner/.rvm/gems/ruby-1.9.3-p448/bin/ruby_noexec_wrapper:14:in `'

My database.yml file:

development:
  adapter: sqlite3
  database: db/development.sqlite3
  pool: 5
  timeout: 5000

test:
  adapter: sqlite3
  database: db/test.sqlite3
  pool: 5
  timeout: 5000

production:
  adapter: sqlite3
  database: db/production.sqlite3
  pool: 5
  timeout: 5000

My Gemfile:

source 'https://rubygems.org'

gem "therubyracer"
gem "less-rails" #Sprockets (what Rails 3.1 uses for its asset pipeline) supports LESS
gem "twitter-bootstrap-rails"
gem 'jquery-rails'
gem 'devise'

gem 'rails', '3.2.13'

# Bundle edge Rails instead:
# gem 'rails', :git => 'git://github.com/rails/rails.git'

group :development, :test do
    gem 'sqlite3'
end

group :production do
    gem 'pg'
end

gem 'mini_magick'
gem "rmagick"
gem "carrierwave"

# Gems used only for assets and not required
# in production environments by default.
group :assets do
  gem 'sass-rails',   '~> 3.2.3'
  gem 'coffee-rails', '~> 3.2.1'

  # See https://github.com/sstephenson/execjs#readme for more supported runtimes
  # gem 'therubyracer', :platforms => :ruby

  gem 'uglifier', '>= 1.0.3'
end

gem 'jquery-rails'

# To use ActiveModel has_secure_password
# gem 'bcrypt-ruby', '~> 3.0.0'

# To use Jbuilder templates for JSON
# gem 'jbuilder'

# Use unicorn as the app server
# gem 'unicorn'

# Deploy with Capistrano
# gem 'capistrano'

# To use debugger
# gem 'debugger'


问:
Call property from parent class like dictionary in c#
May I dont know how too look for it, but fact is I cant find anything that helps me.

Is there a way to call property from a parent class like an assoc array (dictionary) ?

Sample:

```<code>using System;

class Foobar
{
    public string bla;
    public Foobar()
    {
        this.bla = "hello world";
    }
}

public class Test
{
    public static void Main()
    {
        Foobar x = new Foobar();
        Console.WriteLine(x.bla); //this works (prints hello world)
        Console.WriteLine(x["bla"]); //this wont work but is my achivment
    }
}
</code>```

To clarify what I want is...

I want to create a class that has some propertys e.g

```<code>class SomeClass
{
    private string aaa {get;set;};
    private string bbb {get;set;};
    private string ccc {get;set;};
    private string ddd {get;set;};
    ....
}
</code>```

and than loop this in a other class by a dictionary

```<code>SomeClass x = new SomeClass();
IDictionary<string, string> dict = new Dictionary<string, string>();
dict["a"] = "aaa";
dict["b"] = "bbb";
dict["d"] = "ddd";

foreach( d in dict )
{
    someMethode(x[d]);
}
</code>```

答:
You should do it in this way to extend it ^^</p>

```<code>using System;

    class Program
    {
        static void Main(string[] args)
        {
            Foobar x = new Foobar();
            Console.WriteLine(x.bla); //this works (prints hello world)
            Console.WriteLine(x["bla"]); //this wont work but is my achivment
        }
    }

    class Foobar : Class
    {
        public Foobar()
        {
            this.bla = "hello world";
        }

        public string bla { get; set; }
    }

    class Class
    {
        public string this[string name]
        {
            get
            {
                return this.GetType().GetProperty(name).GetValue(this).ToString();
            }
        }
    }
</code>```

Body:
May I dont know how too look for it, but fact is I cant find anything that helps me.

Is there a way to call property from a parent class like an assoc array (dictionary) ?

Sample:

using System;

class Foobar
{
    public string bla;
    public Foobar()
    {
        this.bla = "hello world";
    }
}

public class Test
{
    public static void Main()
    {
        Foobar x = new Foobar();
        Console.WriteLine(x.bla); //this works (prints hello world)
        Console.WriteLine(x["bla"]); //this wont work but is my achivment
    }
}

To clarify what I want is...

I want to create a class that has some propertys e.g

class SomeClass
{
    private string aaa {get;set;};
    private string bbb {get;set;};
    private string ccc {get;set;};
    private string ddd {get;set;};
    ....
}

and than loop this in a other class by a dictionary

SomeClass x = new SomeClass();
IDictionary<string, string> dict = new Dictionary<string, string>();
dict["a"] = "aaa";
dict["b"] = "bbb";
dict["d"] = "ddd";

foreach( d in dict )
{
    someMethode(x[d]);
}

Body:
You should do it in this way to extend it ^^

using System;

    class Program
    {
        static void Main(string[] args)
        {
            Foobar x = new Foobar();
            Console.WriteLine(x.bla); //this works (prints hello world)
            Console.WriteLine(x["bla"]); //this wont work but is my achivment
        }
    }

    class Foobar : Class
    {
        public Foobar()
        {
            this.bla = "hello world";
        }

        public string bla { get; set; }
    }

    class Class
    {
        public string this[string name]
        {
            get
            {
                return this.GetType().GetProperty(name).GetValue(this).ToString();
            }
        }
    }


问:
html check if input is greater than other input after submit
I have two input fields and want to check if one field is greater than the other.
I want to check this before the submit-Button is clicked.

<input type="text" name = "minValue" pattern="(|-)?[0-9]{0,3}?" id="min_value" value="" required/>

<input type="text" name = "maxValue" pattern="(|-)?[0-9]{0,3}?" id="max_value" value="" required/>

<button type = "submit" name = "submitcheck" id = "submit_check"> Let´s Go </button>```

Do I need jquery? I want to do this check before checking the submt button.

答:
Try as below, it checks if value of first input is greater then second or not, but using blur event Listener before clicking submit button.

var frst = document.querySelector("#min_value");
var secnd = document.querySelector("#max_value");
var para = document.createElement("p");
function blr(){
  var ab = frst.value;
  var vc = secnd.value;
  if(ab == "" && vc == ""){
  para.textContent = "Please enter value in both.";
  document.body.appendChild(para);
  }
  else if(ab >= vc){
  para.textContent = "Value present in first input is greater then second.";
  document.body.appendChild(para);
  }
  else if(vc >= ab){
    para.textContent = "Value present in Second input is greater then First.";
  document.body.appendChild(para);
  }
}
secnd.addEventListener("blur",blr);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" name = "minValue" pattern="(|-)?[0-9]{0,3}?" id="min_value" value="" required/>

<input type="text" name = "maxValue" pattern="(|-)?[0-9]{0,3}?" id="max_value" value="" required/>

<button type = "submit" name = "submitcheck" id = "submit_check"> Let´s Go </button></code>```

Body:
I have two input fields and want to check if one field is greater than the other.
I want to check this before the submit-Button is clicked.

<input type="text" name = "minValue" pattern="(|-)?[0-9]{0,3}?" id="min_value" value="" required/>

<input type="text" name = "maxValue" pattern="(|-)?[0-9]{0,3}?" id="max_value" value="" required/>

<button type = "submit" name = "submitcheck" id = "submit_check"> Let´s Go </button>

Do I need jquery? I want to do this check before checking the submt button.

Body:
Try as below, it checks if value of first input is greater then second or not, but using blur event Listener before clicking submit button.

var frst = document.querySelector("#min_value");
var secnd = document.querySelector("#max_value");
var para = document.createElement("p");
function blr(){
  var ab = frst.value;
  var vc = secnd.value;
  if(ab == "" && vc == ""){
  para.textContent = "Please enter value in both.";
  document.body.appendChild(para);
  }
  else if(ab >= vc){
  para.textContent = "Value present in first input is greater then second.";
  document.body.appendChild(para);
  }
  else if(vc >= ab){
    para.textContent = "Value present in Second input is greater then First.";
  document.body.appendChild(para);
  }
}
secnd.addEventListener("blur",blr);

<input type="text" name = "minValue" pattern="(|-)?[0-9]{0,3}?" id="min_value" value="" required/>

<input type="text" name = "maxValue" pattern="(|-)?[0-9]{0,3}?" id="max_value" value="" required/>

<button type = "submit" name = "submitcheck" id = "submit_check"> Let´s Go </button>


问:
Newbie stuck on a jQuery question...conditional statement
So I'm a complete newbie and stuck on a conditional statement.  Here's my code:

```<code><script type="text/javascript">
$(document).ready(function(){
 if($('span.fc_cart_item_price_total') == 0) {
  $(span.fc_info).addClass('foo');
 };
});
</script>
</code>```

So I'm attempting to see if span with a class of "fc_cart_item_price_total" has a value of "0", to then add a class of "foo" to the span with a class of ".fc_info".  This code above is not working.  Here's the HTML:

```<code><span class="fc_info">Info 1</span><br />
<span class="fc_cart_item_price_total">$0.00</span><br />
<span class="fc_info">Info 2</span>
</code>```

Here's the other challenge I have.  I'm trying to select the span with the value of "fc_info" before the span with the class of "fc_cart_item_price_total" but have no idea of how to just select this one span.

答:
I think you need to get the HTML out of the span.  Something like:

```<code><script type="text/javascript">
$(document).ready(function(){
 if($('span.fc_cart_item_price_total').text() == 0) {
  $(span.fc_info).addClass('foo');
 };
});
</script>
</code>```

But then you need to compare it to "$0.00" or trim the $ off before comparing.

Body:
So I'm a complete newbie and stuck on a conditional statement.  Here's my code:

So I'm attempting to see if span with a class of "fc_cart_item_price_total" has a value of "0", to then add a class of "foo" to the span with a class of ".fc_info".  This code above is not working.  Here's the HTML:

Info 1

$0.00

Info 2

Here's the other challenge I have.  I'm trying to select the span with the value of "fc_info" before the span with the class of "fc_cart_item_price_total" but have no idea of how to just select this one span.

Body:
I think you need to get the HTML out of the span.  Something like:

<script type="text/javascript">
$(document).ready(function(){
 if($('span.fc_cart_item_price_total').text() == 0) {
  $(span.fc_info).addClass('foo');
 };
});
</script>

But then you need to compare it to "$0.00" or trim the $ off before comparing.


问:
Loop thru values code
This is what I’m trying to do:
When an order is created, click view link and and get redirected to the show page which contains the invoice.  I'm using the below code to loop thru values in the invoice. But its not working correctly, all invoices are showing up instead of only the selected one.
I already tried deleting the <% @orders.each do |order| %> but without any luck.

What am I missing here? Any idea?

```<code><% @orders.each do |order| %>
<% order.line_items.each do |line_item| %>
Order #<%= line_item.order_id %>
<%= order.first_name %> <%= order.last_name %>
<%= line_item.product.title %>
<%= number_to_currency line_item.product.price %>
<%= line_item.quantity %>
<%= number_to_currency line_item.total_price %>
<% end %>
<% end %>
</code>```

Update 1

route.rb: resources :orders, only: [:index, :new, :create, :show]

I don't have an invoice controller, everything is going thru the orders controller.

```<code>  def show
    @orders = Order.all
  end

 def new
    @cart = current_cart
    if @cart.line_items.empty?
    redirect_to root_url, notice: "Your cart is empty"
    return
    end

   @order = Order.new
    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @order }
   end
  end

  def create
    @order = Order.new(order_params)
    @order.add_line_items_from_cart(current_cart)
    @order.user_id = current_user.id

      if @order.save
      if @order.process
      redirect_to root_path, notice: "Successfully charged."
      and
      return
      end
    end
    render 'new'
  end
</code>```

答:
Could you please display your show method, the issue is likely to be from there. Use the ruby on rails debugger in the mean time, to ensure that @orders contains the invoice information for just the order placed. </p>

<p>try this: <%= debug @orders %> </p>

Title: Loop thru values code

Body:
This is what I’m trying to do:
When an order is created, click view link and and get redirected to the show page which contains the invoice.  I'm using the below code to loop thru values in the invoice. But its not working correctly, all invoices are showing up instead of only the selected one.
I already tried deleting the <% @orders.each do |order| %> but without any luck.

What am I missing here? Any idea?

<% @orders.each do |order| %>
<% order.line_items.each do |line_item| %>
Order #<%= line_item.order_id %>
<%= order.first_name %> <%= order.last_name %>
<%= line_item.product.title %>
<%= number_to_currency line_item.product.price %>
<%= line_item.quantity %>
<%= number_to_currency line_item.total_price %>
<% end %>
<% end %>

Update 1

route.rb: resources :orders, only: [:index, :new, :create, :show]

I don't have an invoice controller, everything is going thru the orders controller.

  def show
    @orders = Order.all
  end

 def new
    @cart = current_cart
    if @cart.line_items.empty?
    redirect_to root_url, notice: "Your cart is empty"
    return
    end

   @order = Order.new
    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @order }
   end
  end

  def create
    @order = Order.new(order_params)
    @order.add_line_items_from_cart(current_cart)
    @order.user_id = current_user.id

      if @order.save
      if @order.process
      redirect_to root_path, notice: "Successfully charged."
      and
      return
      end
    end
    render 'new'
  end

Body:
Could you please display your show method, the issue is likely to be from there. Use the ruby on rails debugger in the mean time, to ensure that @orders contains the invoice information for just the order placed.

try this: <%= debug @orders %>


问:
JDBC - ORA-01861: literal does not match format string 01861
I have problem with retrieving a data from oracle data base

I want to access data by using two JDatechoosers...

I use JDatechooser to store date value in database of type date.

```<code>chooser=new JDateChooser();
chooser.setBounds (200, 175, 175, 25);
chooser.setDateFormatString("dd-MM-yyyy");
pstmt.setDate(5, new java.sql.Date(chooser.getDate().getTime()));
</code>```

I want to access data between two dates using two JDatechooser values as fallows..

```<code>    chooser = new JDateChooser();
    chooser.setBounds (100, 15, 100, 25);
    chooser.setDateFormatString("dd-MM-yyyy");
    chooser.addFocusListener (this);

    chooser1 = new JDateChooser();
    chooser1.setBounds (220, 15, 100, 25);
    chooser1.setDateFormatString("dd-MM-yyyy");
    chooser1.addFocusListener (this);

   ResultSet rs = st.executeQuery("SELECT * FROM Bill WHERE B_DATE BETWEEN '"+new java.sql.Date(chooser.getDate().getTime())+"' AND '"+new java.sql.Date(chooser1.getDate().getTime())+"' ");
</code>```

I get the error as

SQL Error: ORA-01861: literal does not match format string 01861

please help me to solve this

答:
Never pass DATE or TIMESTAMP values as as Strings.

Use a PreparedStatement and pass an instance of java.sql.Date or java.sql.Timestamp

```<code>PreparedStatement pstmt = conn.prepareStatement(
    "SELECT * FROM Bill WHERE B_DATE BETWEEN ? and ?");

pstmt.setDate(1,new java.sql.Date(chooser.getDate().getTime()));
pstmt.setDate(2,new java.sql.Date(chooser1.getDate().getTime()));

ResultSet rs = st.executeQuery();
while (rs.next()) {
   ....
}
</code>```

That way you never have to worry about formatting a date or timestamp value.

As an Oracle DATE is actually a timestamp, you might be better off using a timestamp value.

Body:
I have problem with retrieving a data from oracle data base

I want to access data by using two JDatechoosers...

I use JDatechooser to store date value in database of type date.

chooser=new JDateChooser();
chooser.setBounds (200, 175, 175, 25);
chooser.setDateFormatString("dd-MM-yyyy");
pstmt.setDate(5, new java.sql.Date(chooser.getDate().getTime()));

I want to access data between two dates using two JDatechooser values as fallows..

    chooser = new JDateChooser();
    chooser.setBounds (100, 15, 100, 25);
    chooser.setDateFormatString("dd-MM-yyyy");
    chooser.addFocusListener (this);

    chooser1 = new JDateChooser();
    chooser1.setBounds (220, 15, 100, 25);
    chooser1.setDateFormatString("dd-MM-yyyy");
    chooser1.addFocusListener (this);

   ResultSet rs = st.executeQuery("SELECT * FROM Bill WHERE B_DATE BETWEEN '"+new java.sql.Date(chooser.getDate().getTime())+"' AND '"+new java.sql.Date(chooser1.getDate().getTime())+"' ");

I get the error as

SQL Error: ORA-01861: literal does not match format string 01861

please help me to solve this

Body:
Never pass DATE or TIMESTAMP values as as Strings.

Use a PreparedStatement and pass an instance of java.sql.Date or java.sql.Timestamp

PreparedStatement pstmt = conn.prepareStatement(
    "SELECT * FROM Bill WHERE B_DATE BETWEEN ? and ?");

pstmt.setDate(1,new java.sql.Date(chooser.getDate().getTime()));
pstmt.setDate(2,new java.sql.Date(chooser1.getDate().getTime()));

ResultSet rs = st.executeQuery();
while (rs.next()) {
   ....
}

That way you never have to worry about formatting a date or timestamp value.

As an Oracle DATE is actually a timestamp, you might be better off using a timestamp value.


问:
How to deal with time zones between Android and PHP/MySQL?
I am building backend queue system. My app's users need to automatically fetch data from server around 08:00:00 AM, individually for each time zone.

Every user needs to be assigned to a specific time a day. He can fetch data only at this time as the app uses API that has specific calls-per-minute limits.

How do I synchronize clients with server?

NOTE

I ran into specific problems, and solved it already. I am posting the solution right away as a complete answer that combines many answers I found on SO while solving it.

答:
Core of the solution

For clarity use time values in UTC that is supported in each Java/PHP/MySQL, because:

Although GMT and UTC share the same current time in practice, there is a basic difference between the two:
  GMT is a time zone officially used in some European and African countries. The time can be displayed using both the 24-hour format (0 - 24) or the 12-hour format (1 - 12 am/pm).
  UTC is not a time zone, but a time standard that is the basis for civil time and time zones worldwide. This means that no country or territory officially uses UTC as a local time.

source

It gives you simple solution as once you use UTC, you only need to convert it to server's or clients' time zone for display purposes.

Managing client's time zone

You need to send client's time zone to backend to calculate what time do you want him to call API. You want to convert 08:00:00 local time to UTC, but here's a trick, because there are incompatible time zones' strings between Java and PHP.

```<code>// Java/Android
SimpleDateFormat sdf = new SimpleDateFormat("z");
</code>```

I live in Poland, and using the code above I get 2 different values depending on seasons (CET for winter time and CEST for summer time).

```<code>// PHP
$tz1 = new DateTimeZone('CET');
$tz2 = new DateTimeZone('CEST');
</code>```

The problem is that when I pass it to PHP, CET works perfectly as it's supported time zone string, but CEST is not.

To unify your code, you need to use:

```<code>// Java/Android
SimpleDateFormat sdf = new SimpleDateFormat("ZZZZ");
</code>```

which gives you a time zone likethis:

```<code>GMT+01:00 // for CET
GMT+02:00 // for CEST
</code>```

Remember that when you send it in URL like http://api.domain.com?timezone=GTM+02:00, you need to change + into %2B as timezone converted to GTM 02:00 won't work in PHP.

Calculating queue time for users

Once you get client's time zone, in PHP you convert 08:00:00 AM local time to UTC.

```<code>$tz = new DateTimeZone('GMT+02:00');
$dt = new DateTime('2017-03-30 08:00:00', $tz);
$dt->setTimezone(new DateTimeZone('UTC'));
echo $dt->format('H:i:s');

// echoes 06:00:00
</code>```

Then you store calculated value in MySQL at type TIME column. You don't need to care about time zone in the database as TIME and DATE types are time zone independent.

Setting alarm at calculated UTC time

You get 06:00:00 as a response in the app, and you set AlarmManager using Calendar object like this:

```<code>// set UTC as a time zone
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
cal.setTime(new Date());

long timeNow = cal.getTimeInMillis();

// set 06:00:00
cal.set(Calendar.MILLISECOND, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.HOUR_OF_DAY, 6);

// make sure to set alarm in future
long timeAlarm = cal.getTimeInMillis();
if (timeAlarm <= timeNow) {
    cal.add(Calendar.HOUR_OF_DAY, 24);
}

alarm.setRepeating(AlarmManager.RTC_WAKEUP,
    cal.getTimeInMillis(),
    24*60*60*1000, pintent);
</code>```

Body:
Core of the solution

For clarity use time values in UTC that is supported in each Java/PHP/MySQL, because:

Although GMT and UTC share the same current time in practice, there is a basic difference between the two:
  GMT is a time zone officially used in some European and African countries. The time can be displayed using both the 24-hour format (0 - 24) or the 12-hour format (1 - 12 am/pm).
  UTC is not a time zone, but a time standard that is the basis for civil time and time zones worldwide. This means that no country or territory officially uses UTC as a local time.

source

It gives you simple solution as once you use UTC, you only need to convert it to server's or clients' time zone for display purposes.

Managing client's time zone

You need to send client's time zone to backend to calculate what time do you want him to call API. You want to convert 08:00:00 local time to UTC, but here's a trick, because there are incompatible time zones' strings between Java and PHP.

// Java/Android
SimpleDateFormat sdf = new SimpleDateFormat("z");

I live in Poland, and using the code above I get 2 different values depending on seasons (CET for winter time and CEST for summer time).

// PHP
$tz1 = new DateTimeZone('CET');
$tz2 = new DateTimeZone('CEST');

The problem is that when I pass it to PHP, CET works perfectly as it's supported time zone string, but CEST is not.

To unify your code, you need to use:

// Java/Android
SimpleDateFormat sdf = new SimpleDateFormat("ZZZZ");

which gives you a time zone likethis:

GMT+01:00 // for CET
GMT+02:00 // for CEST

Remember that when you send it in URL like http://api.domain.com?timezone=GTM+02:00, you need to change + into %2B as timezone converted to GTM 02:00 won't work in PHP.

Calculating queue time for users

Once you get client's time zone, in PHP you convert 08:00:00 AM local time to UTC.

$tz = new DateTimeZone('GMT+02:00');
$dt = new DateTime('2017-03-30 08:00:00', $tz);
$dt->setTimezone(new DateTimeZone('UTC'));
echo $dt->format('H:i:s');

// echoes 06:00:00

Then you store calculated value in MySQL at type TIME column. You don't need to care about time zone in the database as TIME and DATE types are time zone independent.

Setting alarm at calculated UTC time

You get 06:00:00 as a response in the app, and you set AlarmManager using Calendar object like this:

// set UTC as a time zone
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
cal.setTime(new Date());

long timeNow = cal.getTimeInMillis();

// set 06:00:00
cal.set(Calendar.MILLISECOND, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.HOUR_OF_DAY, 6);

// make sure to set alarm in future
long timeAlarm = cal.getTimeInMillis();
if (timeAlarm <= timeNow) {
    cal.add(Calendar.HOUR_OF_DAY, 24);
}

alarm.setRepeating(AlarmManager.RTC_WAKEUP,
    cal.getTimeInMillis(),
    24*60*60*1000, pintent);


问:
Only parameterless constructors and initializers are supported in LINQ to Entities
I have this error in this linq expression :

```<code>var naleznosci = (from nalTmp in db.Naleznosci
                              where nalTmp.idDziecko == idDziec
                              select new Payments
                              (
                                  nalTmp.Dziecko.Imie,
                                  nalTmp.Dziecko.Nazwisko,
                                  nalTmp.Miesiace.Nazwa,
                                  nalTmp.Kwota,
                                  nalTmp.RodzajeOplat.NazwaRodzajuOplaty,
                                  nalTmp.RodzajeOplat.TypyOplat.NazwaTypuOplaty,
                                  nalTmp.DataRozliczenia,
                                  nalTmp.TerminPlatnosci
                              )).ToList();
</code>```

Any idea how solve this problem? I try with any combination of expression... :/

答:
Sorry for being late to the party, but I after finding this, I thought this should be shared as it's the cleanest, fastest and also memory-saving implementation I could find.

Adapted to your example, you'd write:

```<code>public static IQueryable<Payments> ToPayments(this IQueryable<Naleznosci> source)
{
  Expression<Func<Naleznosci, Payments>> createPayments = naleznosci => new Payments
  {
    Imie = source.Dziecko.Imie,
    Nazwisko = source.Dziecko.Nazwisko,
    Nazwa= source.Miesiace.Nazwa,
    Kwota = source.Kwota,
    NazwaRodzajuOplaty = source.RodzajeOplat.NazwaRodzajuOplaty,
    NazwaTypuOplaty = source.RodzajeOplat.TypyOplat.NazwaTypuOplaty,
    DataRozliczenia = source.DataRozliczenia,
    TerminPlatnosci = source.TerminPlatnosci,
  };

  return source.Select(createPayments);
}
</code>```

The big advantages here (as Damien Guard pointed out in the comments at the link) are:

Safes you from using initialization pattern on each occurrence.

Usage via var foo = createPayments(bar); as well as myIQueryable.ToPayments() is possible.

Body:
I have this error in this linq expression :

var naleznosci = (from nalTmp in db.Naleznosci
                              where nalTmp.idDziecko == idDziec
                              select new Payments
                              (
                                  nalTmp.Dziecko.Imie,
                                  nalTmp.Dziecko.Nazwisko,
                                  nalTmp.Miesiace.Nazwa,
                                  nalTmp.Kwota,
                                  nalTmp.RodzajeOplat.NazwaRodzajuOplaty,
                                  nalTmp.RodzajeOplat.TypyOplat.NazwaTypuOplaty,
                                  nalTmp.DataRozliczenia,
                                  nalTmp.TerminPlatnosci
                              )).ToList();

Any idea how solve this problem? I try with any combination of expression... :/

Body:
Sorry for being late to the party, but I after finding this, I thought this should be shared as it's the cleanest, fastest and also memory-saving implementation I could find.

Adapted to your example, you'd write:

public static IQueryable<Payments> ToPayments(this IQueryable<Naleznosci> source)
{
  Expression<Func<Naleznosci, Payments>> createPayments = naleznosci => new Payments
  {
    Imie = source.Dziecko.Imie,
    Nazwisko = source.Dziecko.Nazwisko,
    Nazwa= source.Miesiace.Nazwa,
    Kwota = source.Kwota,
    NazwaRodzajuOplaty = source.RodzajeOplat.NazwaRodzajuOplaty,
    NazwaTypuOplaty = source.RodzajeOplat.TypyOplat.NazwaTypuOplaty,
    DataRozliczenia = source.DataRozliczenia,
    TerminPlatnosci = source.TerminPlatnosci,
  };

  return source.Select(createPayments);
}

The big advantages here (as Damien Guard pointed out in the comments at the link) are:

Safes you from using initialization pattern on each occurrence.

Usage via var foo = createPayments(bar); as well as myIQueryable.ToPayments() is possible.


问:
How to link a text area to a submit PHP
I'm having a little bit of an issue that I think is simple and I am missing something!

Techs in use:
PHP, HTML, SMARTY, MYSQL, JQUERY, JAVASCRIPT

What I am trying to achieve is the following:

HTML:

<form id="form" method="post" accept-charset="utf-8">
  {LOOP}

            <input type="radio" name="frm_verify[]" value="{$ID}" class="verified" >
Verified

            <input type="radio" name="frm_verifyno[]" value="{$ID}" checked multiple class="notverified">
not Verified

  <textarea class="NOTES" name="verifyno_notes[]" class="form-control"></textarea>
  {LOOP}
</form>
```

<p>From the above form I am (using PHP) trying to get the notes to correlate to a PHP function > MySQL storage. This form is LOOPED multiple times in output on page see {LOOP}</p>

<p>PHP:</p>

```if ( $_POST['submitit'] ) {
for ($x=0; $x<count($_POST['frm_verifyno']); $x++)
{
   $value = $_POST['frm_verifyno'][$x];

// get order details
$result         = $db->query("SELECT * FROM TABLE WHERE id = '".$value."'");
$sDeviceinfo = $result->fetch_assoc();

$result         = $db->query("SELECT claimref FROM SECONDTABLE WHERE id = '".$sDeviceinfo['orderid']."'");
$sClaimref = $result->fetch_assoc();

$userip = $_SERVER['REMOTE_ADDR'];
    $db->query("INSERT INTO
                  THIRDTABLE
                  SET
                  `state` = 'MISSING',
                  `notes` = 'MISSING',
                  `user` = '".addslashes($sAdminDetails['fname'] .' '. $sAdminDetails['lname'])."',
                  `ts` = NOW(),
                  `date` = NOW(),
                  `orderid` = '".addslashes($sDeviceinfo['orderid'])."',
                  `deviceid` = '".addslashes($sDeviceinfo['id'])."',
                  `imei` = '".addslashes($sDeviceinfo['imei'])."',
                  `serial` = '".addslashes($sDeviceinfo['serial'])."',
                  `claimref` = '".addslashes($sClaimref['claimref'])."',
                  `userip` = '".addslashes($userip)."'
                  ");
}
}
```

The above WORKS for the radio buttons.

So, my question is, how does one also link in the textareas into this?

I have tried (what i thought was) the same kind of process to get the input sent to PHP correctly so i 'know' which textarea correlates to which mysql row entry.

When this form runs it inserts multiple rows (as per count of the loop)

答:
Seeing the fields are in the same loop, you can just do</p>

```<code>$cnt = count($_POST['frm_verifyno']);
for ($x=0; $x<$cnt; $x++) {
   $value = $_POST['frm_verifyno'][$x];
   $note= $_POST['verifyno_notes'][$x];

.
.
.
</code>```

Title: How to link a text area to a submit PHP

Body:
I'm having a little bit of an issue that I think is simple and I am missing something!

Techs in use:
PHP, HTML, SMARTY, MYSQL, JQUERY, JAVASCRIPT

What I am trying to achieve is the following:

HTML:

<form id="form" method="post" accept-charset="utf-8">
  {LOOP}

            <input type="radio" name="frm_verify[]" value="{$ID}" class="verified" >
Verified

            <input type="radio" name="frm_verifyno[]" value="{$ID}" checked multiple class="notverified">
not Verified

  <textarea class="NOTES" name="verifyno_notes[]" class="form-control"></textarea>
  {LOOP}
</form>

From the above form I am (using PHP) trying to get the notes to correlate to a PHP function > MySQL storage. This form is LOOPED multiple times in output on page see {LOOP}

PHP:

if ( $_POST['submitit'] ) {
for ($x=0; $x<count($_POST['frm_verifyno']); $x++)
{
   $value = $_POST['frm_verifyno'][$x];

// get order details
$result         = $db->query("SELECT * FROM TABLE WHERE id = '".$value."'");
$sDeviceinfo = $result->fetch_assoc();

$result         = $db->query("SELECT claimref FROM SECONDTABLE WHERE id = '".$sDeviceinfo['orderid']."'");
$sClaimref = $result->fetch_assoc();

$userip = $_SERVER['REMOTE_ADDR'];
    $db->query("INSERT INTO
                  THIRDTABLE
                  SET
                  `state` = 'MISSING',
                  `notes` = 'MISSING',
                  `user` = '".addslashes($sAdminDetails['fname'] .' '. $sAdminDetails['lname'])."',
                  `ts` = NOW(),
                  `date` = NOW(),
                  `orderid` = '".addslashes($sDeviceinfo['orderid'])."',
                  `deviceid` = '".addslashes($sDeviceinfo['id'])."',
                  `imei` = '".addslashes($sDeviceinfo['imei'])."',
                  `serial` = '".addslashes($sDeviceinfo['serial'])."',
                  `claimref` = '".addslashes($sClaimref['claimref'])."',
                  `userip` = '".addslashes($userip)."'
                  ");
}
}

The above WORKS for the radio buttons.

So, my question is, how does one also link in the textareas into this?

I have tried (what i thought was) the same kind of process to get the input sent to PHP correctly so i 'know' which textarea correlates to which mysql row entry.

When this form runs it inserts multiple rows (as per count of the loop)

Body:
Seeing the fields are in the same loop, you can just do

$cnt = count($_POST['frm_verifyno']);
for ($x=0; $x<$cnt; $x++) {
   $value = $_POST['frm_verifyno'][$x];
   $note= $_POST['verifyno_notes'][$x];

.
.
.


问:
Devextreme multiple form submitted
I am using Devextreme forms with angular 2.
I have two separate forms, but when i call submit button of first form or second form, both forms get validated. why?

Here is two different forms in html,

```<code>  <form action="your-action" (submit)="onFormSubmit($event)">
        <diav class="dx-fieldset">
            <div class="dx-fieldset-header">Credentials</div>
            <div class="dx-field">
                <div class="dx-field-label">Login</div>
                <div class="dx-field-value">
                    <dx-text-box>
                        <dx-validator>
                            <dxi-validation-rule type="required" message="Login is required"></dxi-validation-rule>
                        </dx-validator>
                    </dx-text-box>
                </div>
            </div>
                  </div>
        <dx-validation-summary id="summary"></dx-validation-summary>
        <dx-button
            id="button"
            text="Register"
            type="success"
            [useSubmitBehavior]="true">
        </dx-button>
    </form>
    <form action="your-action" (submit)="onFormSubmit1($event)">
        <div class="dx-fieldset">
            <div class="dx-fieldset-header">Credentials</div>
            <div class="dx-field">
                <div class="dx-field-label">Login</div>
                <div class="dx-field-value">
                    <dx-text-box>
                        <dx-validator>
                            <dxi-validation-rule type="required" message="Login is required"></dxi-validation-rule>
                        </dx-validator>
                    </dx-text-box>
                </div>
            </div>
                  </div>
              <dx-validation-summary id="summary"></dx-validation-summary>
                <dx-button
            id="button"
            text="Register"
            type="success"
            [useSubmitBehavior]="true">
        </dx-button>
    </form>
</code>```

答:
According to documentation [useSubmitBehavior]="true" will validate and submit html form. You will need to set validation group to group your form controls and then button onClick you can execute DevExpress.validationEngine.validateGroup(group); to validate your from controls. Adding link to the document.

validate group doc

Title: Devextreme multiple form submitted

Body:
I am using Devextreme forms with angular 2.
I have two separate forms, but when i call submit button of first form or second form, both forms get validated. why?

Here is two different forms in html,

  <form action="your-action" (submit)="onFormSubmit($event)">
        <diav class="dx-fieldset">

Credentials

Login

                    <dx-text-box>
                        <dx-validator>
                            <dxi-validation-rule type="required" message="Login is required"></dxi-validation-rule>
                        </dx-validator>
                    </dx-text-box>

        <dx-validation-summary id="summary"></dx-validation-summary>
        <dx-button
            id="button"
            text="Register"
            type="success"
            [useSubmitBehavior]="true">
        </dx-button>
    </form>
    <form action="your-action" (submit)="onFormSubmit1($event)">

Credentials

Login

                    <dx-text-box>
                        <dx-validator>
                            <dxi-validation-rule type="required" message="Login is required"></dxi-validation-rule>
                        </dx-validator>
                    </dx-text-box>

              <dx-validation-summary id="summary"></dx-validation-summary>
                <dx-button
            id="button"
            text="Register"
            type="success"
            [useSubmitBehavior]="true">
        </dx-button>
    </form>


问:
How can i distinguish which UIAlertView's button was clicked from multiple alertview
In my appln I m using multiple UIAlertView and to determine which between was clicked in alertview i use the method

```<code>- (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)buttonIndex{
</code>```

}

but i need only for the one alertview but it was responding for all alertviews. how to restrict to only to one alertview or to alertview to which i need determine the button action

答:
Common practice is to use a unique number for the tag property of each UIAlertView, and then check the tag in your delegate callbacks. An easy way to do this is with an enum:

```<code> enum {
     kServiceErrorAlert = 1,
     kFailedToSaveAlert = 2
 };

 ...

 alertView.tag = kServiceErrorAlert;
 [alertView show];
</code>```

Body:
In my appln I m using multiple UIAlertView and to determine which between was clicked in alertview i use the method

- (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)buttonIndex{

}

but i need only for the one alertview but it was responding for all alertviews. how to restrict to only to one alertview or to alertview to which i need determine the button action

Body:
Common practice is to use a unique number for the tag property of each UIAlertView, and then check the tag in your delegate callbacks. An easy way to do this is with an enum:

 enum {
     kServiceErrorAlert = 1,
     kFailedToSaveAlert = 2
 };

 ...

 alertView.tag = kServiceErrorAlert;
 [alertView show];


问:
Unable to get Oauth2 working in latest version of Spring boot
I am trying to get a simple oauth2 application running using the latest Spring boot version 1.5.2.RELEASE.

I followed all the steps spring-boot-oauth2 till they tell you "What Just Happened" but after configuring application.yml, running the application didn't work and gave following error -

```<code>WARN 27759 [main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanDefinitionStoreException: Failed to process import candidates for configuration class [com.opentable.DemoApplication]; nested exception is java.lang.IllegalStateException: Could not evaluate condition on org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2SsoDefaultConfiguration due to org/springframework/security/config/annotation/web/configuration/WebSecurityConfigurerAdapter not found. Make sure your own configuration does not rely on that class. This can also happen if you are @ComponentScanning a springframework package (e.g. if you put a @ComponentScan in the default package by mistake)
ERROR 27759 [main] o.s.b.f.s.DefaultListableBeanFactory: Destroy method on bean with name 'org.springframework.boot.autoconfigure.internalCachingMetadataReaderFactory' threw an exception

java.lang.IllegalStateException: ApplicationEventMulticaster not initialized - call 'refresh' before multicasting events via the context: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@3b07a0d6: startup date [Thu Mar 30 15:06:55 IST 2017]; root of context hierarchy
</code>```

Do I need to create a configuration class explicitly?

答:
It required following dependency to be added

```<code><dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</code>```

The tutorial is wrong. The two ways it mentioned to obtain spring boot application to start with generated wrong pom.xml.

After I added above actuator dependency, things worked out fine.

Body:
I am trying to get a simple oauth2 application running using the latest Spring boot version 1.5.2.RELEASE.

I followed all the steps spring-boot-oauth2 till they tell you "What Just Happened" but after configuring application.yml, running the application didn't work and gave following error -

WARN 27759 [main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanDefinitionStoreException: Failed to process import candidates for configuration class [com.opentable.DemoApplication]; nested exception is java.lang.IllegalStateException: Could not evaluate condition on org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2SsoDefaultConfiguration due to org/springframework/security/config/annotation/web/configuration/WebSecurityConfigurerAdapter not found. Make sure your own configuration does not rely on that class. This can also happen if you are @ComponentScanning a springframework package (e.g. if you put a @ComponentScan in the default package by mistake)
ERROR 27759 [main] o.s.b.f.s.DefaultListableBeanFactory: Destroy method on bean with name 'org.springframework.boot.autoconfigure.internalCachingMetadataReaderFactory' threw an exception

java.lang.IllegalStateException: ApplicationEventMulticaster not initialized - call 'refresh' before multicasting events via the context: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@3b07a0d6: startup date [Thu Mar 30 15:06:55 IST 2017]; root of context hierarchy

Do I need to create a configuration class explicitly?

Body:
It required following dependency to be added

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

The tutorial is wrong. The two ways it mentioned to obtain spring boot application to start with generated wrong pom.xml.

After I added above actuator dependency, things worked out fine.


问:
QStyledItemDelegate drawing custom widget failed
In one of my projects I'm using a QTableWidget in order to display some complex computational results. In order to increase the readability of the table I'm in need to display two aligned values inside of a single table cell.

Later on I want to customize the widget even more by using colors or arrows etc..

For this I derived from QStyledItemDelegate and I called table ->setItemDelegate(new TwoNumbersDelegate) on my QTableWidget instance.

For some reasons the QFrame is never display. I really tried everything. Strangely, a call to drawLine gives some result, but only in the left cell on the top.

My idea is, that calling mFrame->render(...) is not the correct way to do it, but what is the correct way?

My include file is:

```<code>#pragma once

#include <QStyledItemDelegate>
class QLabel;

    class TwoNumbersDelegate : public QStyledItemDelegate {
    public:
        TwoNumbersDelegate(QObject* parent = nullptr);

        virtual void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override;

        virtual QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const override;

    private:
        QLabel* mLeft;
        QLabel* mRight;
        QFrame* mFrame;
    };
</code>```

My cpp-File is:

```<code>#include "TwoNumbersDelegate.h"
#include <QLabel>
#include <QPainter>
#include <QHBoxLayout>

TwoNumbersDelegate::TwoNumbersDelegate(QObject* parent /*= nullptr*/) : QStyledItemDelegate(parent)
{
    mLeft = new QLabel("%1");
    mRight = new QLabel("%2");
    mFrame = new QFrame;
    mFrame->setLayout(new QHBoxLayout);
    mFrame->layout()->addWidget(mLeft);
    mFrame->layout()->addWidget(mRight);
}

void TwoNumbersDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    auto data=index.data(Qt::EditRole);
    auto list=data.toList();
    if (list.size() != 2) {
        QStyledItemDelegate::paint(painter, option, index);
    }
    auto leftValue=list.at(0).toDouble();
    auto rightValue=list.at(1).toDouble();
    mLeft->setText(QString("%1").arg(leftValue));
    mRight->setText(QString("%2").arg(rightValue));
    mLeft->render(painter, QPoint(), option.rect);
    painter->drawLine(4, 4, 7, 7); // Draws Line, but not in every cell of my table?
}

QSize TwoNumbersDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    return mFrame->minimumSizeHint();
}
</code>```

答:
A few potential issues here:

Layout

Since the widget is invisible, the layout isn't being calculated, so things might be drawn out of place, calls to resize ignored, etc.

To ensure the layout is updated, in the constructor, add

```<code>mFrame->setAttribute(Qt::WA_DontShowOnScreen, true);
mFrame->show();
</code>```

This makes the widget behave as if it is visible (which we want), but doesnt draw anything to the screen directly.

Paint location

Drawing with a delegate is clipped to the cell, so if you draw in the wrong place, you won't see anything at all.
The bounds of the cell are given by options.rect, and these coordinates are in terms of the qtableview. So your drawline command only draws in the top-left cell.

This clipping also means you don't need to worry about what region of the widget to render, just translate the painter to use the cell's coordinates, and paint the whole widget.

```<code>painter->save();
painter->translate(option.rect.topLeft());
mFrame->render(painter, QPoint(), QRegion(), QWidget::DrawChildren );
painter->restore();
</code>```

All together, here is an updated .cpp file:

```<code>TwoNumbersDelegate::TwoNumbersDelegate(QObject* parent /*= nullptr*/) : QStyledItemDelegate(parent)
{
    mLeft = new QLabel("%1");
    mRight = new QLabel("%2");
    mFrame = new QFrame;
    mFrame->setLayout(new QHBoxLayout);
    mFrame->layout()->addWidget(mLeft);
// you could add a spacer here maybe
    mFrame->layout()->addWidget(mRight);

    mFrame->setAttribute(Qt::WA_DontShowOnScreen, true);
    mFrame->show();
}

void TwoNumbersDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    auto data=index.data(Qt::EditRole);
    auto list=data.toList();
    if (list.size() != 2) {
        QStyledItemDelegate::paint(painter, option, index);
    }

    mLeft->setText(list.at(0).toString());
    mRight->setText(list.at(1).toString());
    mFrame->resize(opt.rect.size());

    // if there are still layout problems maybe try adding:
    // mFrame->layout()->invalidate();
    // mFrame->layout()->activate();

    painter->save();
    painter->translate(option.rect.topLeft());
    mFrame->render(painter, QPoint(), QRegion(), QWidget::DrawChildren );
    // painter->drawLine(4, 4, 7, 7); // Draws Line in every cell now
    painter->restore();
}

QSize TwoNumbersDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    return mFrame->minimumSizeHint();
}
</code>```

Let me know if you need any more help. Also, a warning: I haven't so much as run this through a compiler, so let me know if you still need help, or if there are any little errors to correct.

Body:
In one of my projects I'm using a QTableWidget in order to display some complex computational results. In order to increase the readability of the table I'm in need to display two aligned values inside of a single table cell.

Later on I want to customize the widget even more by using colors or arrows etc..

For this I derived from QStyledItemDelegate and I called table ->setItemDelegate(new TwoNumbersDelegate) on my QTableWidget instance.

For some reasons the QFrame is never display. I really tried everything. Strangely, a call to drawLine gives some result, but only in the left cell on the top.

My idea is, that calling mFrame->render(...) is not the correct way to do it, but what is the correct way?

My include file is:

#pragma once

#include <QStyledItemDelegate>
class QLabel;

    class TwoNumbersDelegate : public QStyledItemDelegate {
    public:
        TwoNumbersDelegate(QObject* parent = nullptr);

        virtual void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override;

        virtual QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const override;

    private:
        QLabel* mLeft;
        QLabel* mRight;
        QFrame* mFrame;
    };

My cpp-File is:

#include "TwoNumbersDelegate.h"
#include <QLabel>
#include <QPainter>
#include <QHBoxLayout>

TwoNumbersDelegate::TwoNumbersDelegate(QObject* parent /*= nullptr*/) : QStyledItemDelegate(parent)
{
    mLeft = new QLabel("%1");
    mRight = new QLabel("%2");
    mFrame = new QFrame;
    mFrame->setLayout(new QHBoxLayout);
    mFrame->layout()->addWidget(mLeft);
    mFrame->layout()->addWidget(mRight);
}

void TwoNumbersDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    auto data=index.data(Qt::EditRole);
    auto list=data.toList();
    if (list.size() != 2) {
        QStyledItemDelegate::paint(painter, option, index);
    }
    auto leftValue=list.at(0).toDouble();
    auto rightValue=list.at(1).toDouble();
    mLeft->setText(QString("%1").arg(leftValue));
    mRight->setText(QString("%2").arg(rightValue));
    mLeft->render(painter, QPoint(), option.rect);
    painter->drawLine(4, 4, 7, 7); // Draws Line, but not in every cell of my table?
}

QSize TwoNumbersDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    return mFrame->minimumSizeHint();
}

Body:
A few potential issues here:

Layout

Since the widget is invisible, the layout isn't being calculated, so things might be drawn out of place, calls to resize ignored, etc.

To ensure the layout is updated, in the constructor, add

mFrame->setAttribute(Qt::WA_DontShowOnScreen, true);
mFrame->show();

This makes the widget behave as if it is visible (which we want), but doesnt draw anything to the screen directly.

Paint location

Drawing with a delegate is clipped to the cell, so if you draw in the wrong place, you won't see anything at all.
The bounds of the cell are given by options.rect, and these coordinates are in terms of the qtableview. So your drawline command only draws in the top-left cell.

This clipping also means you don't need to worry about what region of the widget to render, just translate the painter to use the cell's coordinates, and paint the whole widget.

painter->save();
painter->translate(option.rect.topLeft());
mFrame->render(painter, QPoint(), QRegion(), QWidget::DrawChildren );
painter->restore();

All together, here is an updated .cpp file:

TwoNumbersDelegate::TwoNumbersDelegate(QObject* parent /*= nullptr*/) : QStyledItemDelegate(parent)
{
    mLeft = new QLabel("%1");
    mRight = new QLabel("%2");
    mFrame = new QFrame;
    mFrame->setLayout(new QHBoxLayout);
    mFrame->layout()->addWidget(mLeft);
// you could add a spacer here maybe
    mFrame->layout()->addWidget(mRight);

    mFrame->setAttribute(Qt::WA_DontShowOnScreen, true);
    mFrame->show();
}

void TwoNumbersDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    auto data=index.data(Qt::EditRole);
    auto list=data.toList();
    if (list.size() != 2) {
        QStyledItemDelegate::paint(painter, option, index);
    }

    mLeft->setText(list.at(0).toString());
    mRight->setText(list.at(1).toString());
    mFrame->resize(opt.rect.size());

    // if there are still layout problems maybe try adding:
    // mFrame->layout()->invalidate();
    // mFrame->layout()->activate();

    painter->save();
    painter->translate(option.rect.topLeft());
    mFrame->render(painter, QPoint(), QRegion(), QWidget::DrawChildren );
    // painter->drawLine(4, 4, 7, 7); // Draws Line in every cell now
    painter->restore();
}

QSize TwoNumbersDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    return mFrame->minimumSizeHint();
}

Let me know if you need any more help. Also, a warning: I haven't so much as run this through a compiler, so let me know if you still need help, or if there are any little errors to correct.


问:
Csc/ CoreCompile fails for PCL/ Xamarin project
my Xamarin app doesn't build anymore since I added Akavache to it.
Csc/ CoreCompile fails. If I remove Akavache, It builds fine. There aren't any errors, but I could find the following error in the output window:

```<code>8>  Output Item(s): CscCommandLineArgs= (TaskId:201)
8>Done executing task "Csc" -- FAILED. (TaskId:201)
8>Done building target "CoreCompile" in project "My.App.csproj" -- FAILED.: (TargetId:242)
8>Target "_CheckForCompileOutputs: (TargetId:243)" in file "C:\Program Files (x86)\MSBuild\14.0\bin\Microsoft.Common.CurrentVersion.targets" from project "C:\git\Apps\My.App\My.App.csproj" (target "_CleanGetCurrentAndPriorFileWrites" depends on it):
8>Set Property: _DocumentationFileProduced=false
8>Set Property: _DebugSymbolsProduced=false
8>Done building target "_CheckForCompileOutputs" in project "My.App.csproj".: (TargetId:243)
</code>```

I'm using Akavache 5.0 in a PCL-project for Xamarin. Only my app's PCL project fails to build. But Akavache is used in another/ a referenced PCL-project called My.App.Data. The target frameworks are Xamarin standards: .NET framework 4.5, ASP.NET Core 1.0, Windows 8, Windows Phone 8.1, Xamarin.Android, Xamarin.iOS (Classic) and Xamarin.Mac.

The build fails as soon as Akavache is used by "C:\Program Files (x86)\MSBuild\14.0\bin\csc.exe":

C:\Program Files (x86)\MSBuild\14.0\bin\csc.exe /noconfig /nowarn:1701,1702,2008 /nostdlib+ /errorreport:prompt /warn:4 /define:DEBUG;TRACE /errorendlocation /preferreduilang:en-US /reference:C:\git\App\Packages\akavache.core.5.0.0\lib\Portable-Net45+Win8+WP8+Wpa81\Akavache.dll /reference:C:\git\App\Packages\akavache.sqlite3.5.0.0\lib\Portable-Net45+Win8+WP8+Wpa81\Akavache.Sqlite3.dll ...

答: I could solve the issue. I used Splat in version 2.0 instead of 1.6.</p>

Body:
my Xamarin app doesn't build anymore since I added Akavache to it.
Csc/ CoreCompile fails. If I remove Akavache, It builds fine. There aren't any errors, but I could find the following error in the output window:

8>  Output Item(s): CscCommandLineArgs= (TaskId:201)
8>Done executing task "Csc" -- FAILED. (TaskId:201)
8>Done building target "CoreCompile" in project "My.App.csproj" -- FAILED.: (TargetId:242)
8>Target "_CheckForCompileOutputs: (TargetId:243)" in file "C:\Program Files (x86)\MSBuild\14.0\bin\Microsoft.Common.CurrentVersion.targets" from project "C:\git\Apps\My.App\My.App.csproj" (target "_CleanGetCurrentAndPriorFileWrites" depends on it):
8>Set Property: _DocumentationFileProduced=false
8>Set Property: _DebugSymbolsProduced=false
8>Done building target "_CheckForCompileOutputs" in project "My.App.csproj".: (TargetId:243)

I'm using Akavache 5.0 in a PCL-project for Xamarin. Only my app's PCL project fails to build. But Akavache is used in another/ a referenced PCL-project called My.App.Data. The target frameworks are Xamarin standards: .NET framework 4.5, ASP.NET Core 1.0, Windows 8, Windows Phone 8.1, Xamarin.Android, Xamarin.iOS (Classic) and Xamarin.Mac.

The build fails as soon as Akavache is used by "C:\Program Files (x86)\MSBuild\14.0\bin\csc.exe":

C:\Program Files (x86)\MSBuild\14.0\bin\csc.exe /noconfig /nowarn:1701,1702,2008 /nostdlib+ /errorreport:prompt /warn:4 /define:DEBUG;TRACE /errorendlocation /preferreduilang:en-US /reference:C:\git\App\Packages\akavache.core.5.0.0\lib\Portable-Net45+Win8+WP8+Wpa81\Akavache.dll /reference:C:\git\App\Packages\akavache.sqlite3.5.0.0\lib\Portable-Net45+Win8+WP8+Wpa81\Akavache.Sqlite3.dll ...