问:
Window functions to count distinct records
The query below is based on a complicated view and the view works as I want it to (I'm not going to include the view because I don't think it will help with the question at hand).  What I can't get right is the drugCountsinFamilies column.  I need it to show me the number of distinct drugNames for each drug family.  You can see from the first screencap that there are three different H3A rows.  The drugCountsInFamilies for H3A should be 3 (there are three different  H3A drugs.  )

You can see from the second screen cap that what's happening is the drugCountsInFamilies in the first screen cap is catching the number of rows that the drug name is listed on.

Below is my question, with comments on the part that is incorrect

```<code>select distinct
     rx.patid
    ,d2.fillDate
    ,d2.scriptEndDate
    ,rx.drugName
    ,rx.drugClass
    --the line directly below is the one that I can't figure out why it's wrong
    ,COUNT(rx.drugClass) over(partition by rx.patid,rx.drugclass,rx.drugname) as drugCountsInFamilies
from
(
select
    ROW_NUMBER() over(partition by d.patid order by d.patid,d.uniquedrugsintimeframe desc) as rn
    ,d.patid
    ,d.fillDate
    ,d.scriptEndDate
    ,d.uniqueDrugsInTimeFrame
    from DrugsPerTimeFrame as d
)d2
inner join rx on rx.patid = d2.patid
inner join DrugTable as dt on dt.drugClass=rx.drugClass
where d2.rn=1 and rx.fillDate between d2.fillDate and d2.scriptEndDate
and dt.drugClass in ('h3a','h6h','h4b','h2f','h2s','j7c','h2e')
order by rx.patid
</code>```

SSMS gets mad if I try to add a distinct to the count(rx.drugClass) clause.  Can it be done using window functions?

答:
I came across this question in search for a solution to my problem of counting distinct values. In searching for an answer I came across this post. See last comment. I've tested it and used the SQL. It works really well for me and I figured that I would provide another solution here.

In summary, using DENSE_RANK(), with PARTITION BY the grouped columns, and ORDER BY both ASC and DESC on the columns to count:

```<code>DENSE_RANK() OVER (PARTITION BY drugClass ORDER BY drugName ASC) +
DENSE_RANK() OVER (PARTITION BY drugClass ORDER BY drugName DESC) - 1 AS drugCountsInFamilies
</code>```

I use this as a template for myself.

```<code>DENSE_RANK() OVER (PARTITION BY PartitionByFields ORDER BY OrderByFields ASC ) +
DENSE_RANK() OVER (PARTITION BY PartitionByFields ORDER BY OrderByFields DESC) - 1 AS DistinctCount
</code>```

I hope this helps!

Body:
The query below is based on a complicated view and the view works as I want it to (I'm not going to include the view because I don't think it will help with the question at hand).  What I can't get right is the drugCountsinFamilies column.  I need it to show me the number of distinct drugNames for each drug family.  You can see from the first screencap that there are three different H3A rows.  The drugCountsInFamilies for H3A should be 3 (there are three different  H3A drugs.  )

You can see from the second screen cap that what's happening is the drugCountsInFamilies in the first screen cap is catching the number of rows that the drug name is listed on.

Below is my question, with comments on the part that is incorrect

select distinct
     rx.patid
    ,d2.fillDate
    ,d2.scriptEndDate
    ,rx.drugName
    ,rx.drugClass
    --the line directly below is the one that I can't figure out why it's wrong
    ,COUNT(rx.drugClass) over(partition by rx.patid,rx.drugclass,rx.drugname) as drugCountsInFamilies
from
(
select
    ROW_NUMBER() over(partition by d.patid order by d.patid,d.uniquedrugsintimeframe desc) as rn
    ,d.patid
    ,d.fillDate
    ,d.scriptEndDate
    ,d.uniqueDrugsInTimeFrame
    from DrugsPerTimeFrame as d
)d2
inner join rx on rx.patid = d2.patid
inner join DrugTable as dt on dt.drugClass=rx.drugClass
where d2.rn=1 and rx.fillDate between d2.fillDate and d2.scriptEndDate
and dt.drugClass in ('h3a','h6h','h4b','h2f','h2s','j7c','h2e')
order by rx.patid

SSMS gets mad if I try to add a distinct to the count(rx.drugClass) clause.  Can it be done using window functions?

Body:
I came across this question in search for a solution to my problem of counting distinct values. In searching for an answer I came across this post. See last comment. I've tested it and used the SQL. It works really well for me and I figured that I would provide another solution here.

In summary, using DENSE_RANK(), with PARTITION BY the grouped columns, and ORDER BY both ASC and DESC on the columns to count:

DENSE_RANK() OVER (PARTITION BY drugClass ORDER BY drugName ASC) +
DENSE_RANK() OVER (PARTITION BY drugClass ORDER BY drugName DESC) - 1 AS drugCountsInFamilies

I use this as a template for myself.

DENSE_RANK() OVER (PARTITION BY PartitionByFields ORDER BY OrderByFields ASC ) +
DENSE_RANK() OVER (PARTITION BY PartitionByFields ORDER BY OrderByFields DESC) - 1 AS DistinctCount

I hope this helps!

ContentLicense: CC BY-SA 4.0


来源: stackexchange

问:
Create one list with two ajax calls
I am trying to create a dynamically generated list for each item in my inventory using two API's. The part I am having a hard time figuring out is how to get the value from different calls, and merging them into the same list using a pk and fk.

The lists I am trying to create.

```<code><ul>
 <li>id</li>
 <li>description</li>
 <li>quantity</li>
</ul>
</code>```

Also, the Item doesn't have to have a quantity listed.

```<code> function getItems(){
$.ajax({
    method: 'GET',
  url: 'item/item',
    success: function(response){
    var items = response.detail;
    html = '';
   for (var i=0;i < items.length; i++){
        html += '<ul>'
        html += '<li>' + items[i].id + '</li>'
        html += '<li>' + items[i].description + '</li>'
        html += '</ul>'
   }
 }
})
}
//The Inventory has a FK item_id to the ID in item.

    function getInventory(){
    $.ajax({
    method: 'GET',
    url: 'item/inventory',
    success: function(response){
        var inventory = response.detail;
      html = '';
      for (var j=0; j < inventory.length; j++){
           html += '<li>' + inventory[j].quantity + '</li>'
      }
    }
  })
}
</code>```

答:
You can call one ajax in success of another. </p>

```<code>jQuery(document).ready(function ($) {

function getItems(){
    $.ajax({
       method: 'GET',
       url: 'item.php',
       success: function(response1)
       {
       var items = JSON.parse(response1);

       $.ajax({
     method: 'GET',
     url: 'inv.php',
     success: function(response2){
        var inventory = JSON.parse(response2);
        html = '';

           for (var i=0;i < items.length; i++)
           {
             html += '<ul>';
             html += '<li>' + items[i].id + '</li>';
             html += '<li>' + items[i].description + '</li>';
             html += '<li>' + inventory[i].quantity + '</li>';
             html += '</ul>';
           }

           $('body').append(html);
       }
        });
       }
     });
}

getItems();
});
</code>```

ContentLicense: CC BY-SA 3.0

Title: Create one list with two ajax calls

Body:
I am trying to create a dynamically generated list for each item in my inventory using two API's. The part I am having a hard time figuring out is how to get the value from different calls, and merging them into the same list using a pk and fk.

The lists I am trying to create.

id

description

quantity

Also, the Item doesn't have to have a quantity listed.

 function getItems(){
$.ajax({
    method: 'GET',
  url: 'item/item',
    success: function(response){
    var items = response.detail;
    html = '';
   for (var i=0;i < items.length; i++){
        html += '
'
        html += '
' + items[i].id + '
'
        html += '
' + items[i].description + '
'
        html += '
'
   }
 }
})
}
//The Inventory has a FK item_id to the ID in item.

    function getInventory(){
    $.ajax({
    method: 'GET',
    url: 'item/inventory',
    success: function(response){
        var inventory = response.detail;
      html = '';
      for (var j=0; j < inventory.length; j++){
           html += '
' + inventory[j].quantity + '
'
      }
    }
  })
}

Body:
You can call one ajax in success of another.

jQuery(document).ready(function ($) {

function getItems(){
    $.ajax({
       method: 'GET',
       url: 'item.php',
       success: function(response1)
       {
       var items = JSON.parse(response1);

       $.ajax({
     method: 'GET',
     url: 'inv.php',
     success: function(response2){
        var inventory = JSON.parse(response2);
        html = '';

           for (var i=0;i < items.length; i++)
           {
             html += '<ul>';
             html += '<li>' + items[i].id + '</li>';
             html += '<li>' + items[i].description + '</li>';
             html += '<li>' + inventory[i].quantity + '</li>';
             html += '</ul>';
           }

           $('body').append(html);
       }
        });
       }
     });
}

getItems();
});


问:
Removing punctuation and placing it at the end of a string
I'm trying to write a function that upon execution will remove punctuation marks from a word and place the mark at the end. The removal bit was working fine until I appended the part which adds that same mark at the end; now instead of removing the punc. inside of the string, it leaves it there and adds it to the end, which is not what I want. My code is the following:

```<code>function containsPunctuation(word) {
    var new_word;
    new_word = word.replace(".", "");
    new_word = word.replace("!", "");
    new_word = word.replace(";", "");
    new_word = word.replace(",", "");
    new_word = word.replace("?", "");
    if (word.includes(".") === true) {
        new_word = new_word + ".";
    }
    return new_word;
}
</code>```

答:
There are three main issues with your code:

1

After the first replacement you have to operate on new_world

```<code>var new_word;
new_word = word.replace(".", "");
new_word = new_word.replace("!", "");
</code>```

or more simply you may operate directly on the received parameter without using an additional variable:

```<code>word = word.replace(".", "");
word = word.replace("!", "");
</code>```

2

keep in mind that replace() replaces only on the first occurrence.

If it's not the desired behaviour you may use this function:

```<code>function StringReplace( str, fnd, rep ) {
    return str.split(fnd).join(rep);
}
</code>```

then

```<code>    word = StringReplace( word, ".", "");
    /* ...and so on */
</code>```

3

Whether the string includes a punctuation mark . or not must be checked before you start the replacement (and remove every .) So at the beginning...

```<code>var addPunctuation;
addPunctuation = word.includes(".");
</code>```

then before the function returns:

```<code>if( addPunctuation ) {
    word += '.';
}
</code>```

The whole thing becomes

```<code>function StringReplace( str, fnd, rep ) {
    return str.split(fnd).join(rep);
}

function containsPunctuation(word) {
    var addPunctuation;
    addPunctuation = word.includes(".");

    word = StringReplace(word, ".", "");
    word = StringReplace(word, "!", "");
    word = StringReplace(word, ";", "");
    word = StringReplace(word, ",", "");
    word = StringReplace(word, "?", "");

    if( addPunctuation ) {
        word += ".";
    }

    return word;
}
</code>```

Body:
I'm trying to write a function that upon execution will remove punctuation marks from a word and place the mark at the end. The removal bit was working fine until I appended the part which adds that same mark at the end; now instead of removing the punc. inside of the string, it leaves it there and adds it to the end, which is not what I want. My code is the following:

function containsPunctuation(word) {
    var new_word;
    new_word = word.replace(".", "");
    new_word = word.replace("!", "");
    new_word = word.replace(";", "");
    new_word = word.replace(",", "");
    new_word = word.replace("?", "");
    if (word.includes(".") === true) {
        new_word = new_word + ".";
    }
    return new_word;
}

Body:
There are three main issues with your code:

1

After the first replacement you have to operate on new_world

var new_word;
new_word = word.replace(".", "");
new_word = new_word.replace("!", "");

or more simply you may operate directly on the received parameter without using an additional variable:

word = word.replace(".", "");
word = word.replace("!", "");

2

keep in mind that replace() replaces only on the first occurrence.

If it's not the desired behaviour you may use this function:

function StringReplace( str, fnd, rep ) {
    return str.split(fnd).join(rep);
}

then

    word = StringReplace( word, ".", "");
    /* ...and so on */

3

Whether the string includes a punctuation mark . or not must be checked before you start the replacement (and remove every .) So at the beginning...

var addPunctuation;
addPunctuation = word.includes(".");

then before the function returns:

if( addPunctuation ) {
    word += '.';
}

The whole thing becomes

function StringReplace( str, fnd, rep ) {
    return str.split(fnd).join(rep);
}

function containsPunctuation(word) {
    var addPunctuation;
    addPunctuation = word.includes(".");

    word = StringReplace(word, ".", "");
    word = StringReplace(word, "!", "");
    word = StringReplace(word, ";", "");
    word = StringReplace(word, ",", "");
    word = StringReplace(word, "?", "");

    if( addPunctuation ) {
        word += ".";
    }

    return word;
}


问:
Magento 2.1 admin panel login not working after installation
I know this question were asked multiple times on stackoverflow, but I could not find any proper solution.
I am using Magento 2.1.7. After successfully installing Magento, I clicked on "Launch Magento Admin", They told me to enter username and password. But the problem is that I find Admin Panel Login crashed, as shown below:
Crashes Magento Login Admin PAnel </p>

<p>**EDIT2: This is what i got when you to me to run this command:php bin/magento setup:static-content:deploy  ** Image</p>

答:
You should check that you have the .htaccess file in the pub/static directory:

https://github.com/magento/magento2/blob/2.1.4/pub/static/.htaccess

This will add the rewrite for version URLS.

Versions are for cache busting static assets, you can read about cachebusting here: https://css-tricks.com/strategies-for-cache-busting-css/

Hope this helps

Body:
I know this question were asked multiple times on stackoverflow, but I could not find any proper solution.
I am using Magento 2.1.7. After successfully installing Magento, I clicked on "Launch Magento Admin", They told me to enter username and password. But the problem is that I find Admin Panel Login crashed, as shown below:
Crashes Magento Login Admin PAnel

**EDIT2: This is what i got when you to me to run this command:php bin/magento setup:static-content:deploy  ** Image


问:
How can I establish connectivity between Tableau and SQL Server?
I have a Windows machine with SQL Server Management Studio (SSMS) and Tableau Desktop installed. From SSMS I can connect to a database on another machine. However, when I try to connect to the same database from Tableau Desktop I get the following error.

Could not connect to server

[Microsoft][ODBC Driver 13 for SQL Server]SSL Provider: The client and
  server cannot communicate, because they do not possess a common
  algorithm.

[Microsoft][ODBC Driver 13 for SQL Server]Client unable to establish
  connection

I tried to update the SQL Server drivers on the machine but they are already updated to the latest version. How can I establish connectivity between Tableau and SQL Server?

答:
The problem is actually on the SQL Server side.  Your ODBC driver is trying to use a trusted protocol version (TLS 1.1 or TLS 1.2) but your SQL server is only supporting deprecated protocol versions (SSL 3.0 or TLS 1.0).

You need to get your SQL Server upgraded to one of the versions or CUs referred to in Microsoft's KnowledgeBase article 3135244.

supporting documentation:

SQL's previous lack of support for TLS 1.1+

SQL Server compatibility with new TLS standards


问:
Using two WHERE conditions when extracting data from a Nested SELECT query
I am currently stuck with a relatively straight-forward SQL query.

Working_schedule table is

```<code>Work_ID   Work_grade   Work_shift       Work_Process    pay_grade
-----------------------------------------------------------------
1         senior       day              manual          1
2         mid          day              auto            5
3         mid          day              auto            2
4         junior       night            manual          1
</code>```

Query:

```<code>SELECT COUNT(Work_shift)
FROM Working_schedule
WHERE Work_shift = 'night'
  AND Work_grade = 'senior'
(SELECT Work_id
FROM Working_schedule ws
INNER JOIN Area_branch ab
  ON ab.Area_Branch_ID = ws.FK_Area_Branch_ID
INNER JOIN regional_branch rb
  ON rb.regional_branch_id = ab.FK_regional_branch_id
INNER JOIN Country c
  ON.c.country_location = rb.FK_country_location
WHERE c.Company_origin = 'Spain')
</code>```

I have to count how many night workers, who are also seniors work companies of Spanish origin.

Currently I am able to filter for all night workers who are seniors, but I am unsure of how to check to see if they work for companies of Spanish origin.

I can also get filter for all companies of Spanish origin and (through a series of inner joins) find out the work_ids in the Working schedule table.

My question is how do I connect the two queries (or even can I)? If not, how should I resolve this problem? I have attempted this with INTERSECT, UNION and UNION ALL but nothing has worked.

The output anticipated is a number - number of work_shifts at night that are also work_grade senior.

答:
A small tweak in your query should be enough.

SELECT count(ws.Work_id)
FROM Working_schedule ws
INNERJOIN Area_branch ab
  ON ab.Area_Branch_ID = ws.FK_Area_Branch_ID
INNERJOIN regional_branch rb
  ON rb.regional_branch_id = ab.FK_regional_branch_id
INNERJOIN Country c
  ON.c.country_location = rb.FK_country_location
WHERE c.Company_origin = 'Spain' and ws.work_shift='night' and ws.work_grade='senior'

Body:
I am currently stuck with a relatively straight-forward SQL query.

Working_schedule table is

Work_ID   Work_grade   Work_shift       Work_Process    pay_grade
-----------------------------------------------------------------
1         senior       day              manual          1
2         mid          day              auto            5
3         mid          day              auto            2
4         junior       night            manual          1

Query:

SELECT COUNT(Work_shift)
FROM Working_schedule
WHERE Work_shift = 'night'
  AND Work_grade = 'senior'
(SELECT Work_id
FROM Working_schedule ws
INNER JOIN Area_branch ab
  ON ab.Area_Branch_ID = ws.FK_Area_Branch_ID
INNER JOIN regional_branch rb
  ON rb.regional_branch_id = ab.FK_regional_branch_id
INNER JOIN Country c
  ON.c.country_location = rb.FK_country_location
WHERE c.Company_origin = 'Spain')

I have to count how many night workers, who are also seniors work companies of Spanish origin.

Currently I am able to filter for all night workers who are seniors, but I am unsure of how to check to see if they work for companies of Spanish origin.

I can also get filter for all companies of Spanish origin and (through a series of inner joins) find out the work_ids in the Working schedule table.

My question is how do I connect the two queries (or even can I)? If not, how should I resolve this problem? I have attempted this with INTERSECT, UNION and UNION ALL but nothing has worked.

The output anticipated is a number - number of work_shifts at night that are also work_grade senior.


问:
FigVirtualFramebufferServer: Unsupported Operation
I'm trying ARKit and get a black screen with the following error message. The WWDC 2017 sample PlacingObjects is running on the same device without problems.

```<code>[] <<<< FigVirtualFramebufferServer >>>> FigVirtualFramebufferGetMaxCount: unsupported operation
[] <<<< FigVirtualFramebufferServer >>>> FigVirtualFramebufferGetFramebufs: unsupported operation
[] <<<< FigVirtualFramebufferInstallation >>>> FigInstallVirtualDisplay_block_invoke: FigVirtualFramebufferGetFramebufs failed (0 framebufs)
[MC] System group container for systemgroup.com.apple.configurationprofiles path is /private/var/containers/Shared/SystemGroup/systemgroup.com.apple.configurationprofiles
[MC] Reading from public effective user settings.
</code>```

What is missing?

答: It happened because of the setting "PrefersOpenGL" in info plist.</p>

Body:
I'm trying ARKit and get a black screen with the following error message. The WWDC 2017 sample PlacingObjects is running on the same device without problems.

[] <<<< FigVirtualFramebufferServer >>>> FigVirtualFramebufferGetMaxCount: unsupported operation
[] <<<< FigVirtualFramebufferServer >>>> FigVirtualFramebufferGetFramebufs: unsupported operation
[] <<<< FigVirtualFramebufferInstallation >>>> FigInstallVirtualDisplay_block_invoke: FigVirtualFramebufferGetFramebufs failed (0 framebufs)
[MC] System group container for systemgroup.com.apple.configurationprofiles path is /private/var/containers/Shared/SystemGroup/systemgroup.com.apple.configurationprofiles
[MC] Reading from public effective user settings.

What is missing?


答:
I think the operator you are looking for is IN:</p>

```<code>SELECT COUNT(Work_shift)
FROM Working_schedule
WHERE Work_shift = 'night'
AND Work_grade = 'senior'
AND Work_id in
(SELECT Work_id
FROM Working_schedule ws
INNERJOIN Area_branch ab
  ON ab.Area_Branch_ID = ws.FK_Area_Branch_ID
INNERJOIN regional_branch rb
  ON rb.regional_branch_id = ab.FK_regional_branch_id
INNERJOIN Country c
  ON.c.country_location = rb.FK_country_location
WHERE c.Company_origin = 'Spain')
</code>```

Title: Using two WHERE conditions when extracting data from a Nested SELECT query

Body:
I think the operator you are looking for is IN:

SELECT COUNT(Work_shift)
FROM Working_schedule
WHERE Work_shift = 'night'
AND Work_grade = 'senior'
AND Work_id in
(SELECT Work_id
FROM Working_schedule ws
INNERJOIN Area_branch ab
  ON ab.Area_Branch_ID = ws.FK_Area_Branch_ID
INNERJOIN regional_branch rb
  ON rb.regional_branch_id = ab.FK_regional_branch_id
INNERJOIN Country c
  ON.c.country_location = rb.FK_country_location
WHERE c.Company_origin = 'Spain')


问:
Fitting damped sine wave dataset with gnuplot, getting lot of errors
I was trying to fit this dataset:

```<code>#Mydataset damped sine wave data
#X ---- Y
45.80   320.0
91.60   -254.0
137.4   198.0
183.2   -156.0
229.0   126.0
274.8   -100.0
320.6   80.0
366.4   -64.0
412.2   52.0
458.0   -40.0
503.8   34.0
549.6   -26.0
595.4   22.0
641.2   -18.0
</code>```

which, as you can see by the plot below, has the classical trend of a  damped sine wave:

So i first set the macro for the fit

```<code>f(x) = exp(-a*x)*sin(b*x)
</code>```

then i made the proper fit

```<code>fit f(x) 'data.txt' via a,b
iter      chisq       delta/lim  lambda   a             b
   0 2.7377200000e+05   0.00e+00  1.10e-19    1.000000e+00   1.000000e+00

Current data point
=========================
#               = 1 out of 14
x               = -5.12818e+20
z               = 320

Current set of parameters
=========================
a               = -5.12818e+20
b               = -1.44204e+20

         Function evaluation yields NaN ("not a number")
</code>```

getting a NaN as result. So I looked around on STackOverflow and I remembered I've already have had in the past problems by fitting exponential due to their fast growth/decay which requires you to set initial parameters in order not to get this error (as I've asked here). So I tried by setting as starting parameters a and b  as the ones expected, a = 9000, b=146000, but the result was more frustrating than the one before:

```<code>fit f(x) 'data.txt' via a,b
iter      chisq       delta/lim  lambda   a             b
   0 2.7377200000e+05   0.00e+00  0.00e+00    9.000000e+03   1.460000e+05
         Singular matrix in Givens()
</code>```

I've thought: "these are too much large numbers, let's try with smaller ones".
So i entered the values for a and b and started fitting again

```<code>a = 0.01
b = 2
fit f(x) 'data.txt' via a,b
iter      chisq       delta/lim  lambda   a             b
   0 2.7429059500e+05   0.00e+00  1.71e+01    1.000000e-02   2.000000e+00
   1 2.7346318324e+05  -3.03e+02  1.71e+00    1.813940e-02  -9.254913e-02
   * 1.0680927157e+137  1.00e+05  1.71e+01   -2.493611e-01   5.321099e+00
   2 2.7344431789e+05  -6.90e+00  1.71e+00    1.542835e-02   4.310193e+00
   * 6.1148639318e+81   1.00e+05  1.71e+01   -1.481123e-01  -1.024914e+01
   3 2.7337226343e+05  -2.64e+01  1.71e+00    1.349852e-02  -9.008087e+00
   * 6.4751980241e+136  1.00e+05  1.71e+01   -2.458835e-01  -4.089511e+00
   4 2.7334273482e+05  -1.08e+01  1.71e+00    1.075319e-02  -4.346296e+00
   * 1.8228530731e+121  1.00e+05  1.71e+01   -2.180542e-01  -1.407646e+00
   * 2.7379223634e+05   1.64e+02  1.71e+02    8.277720e-03  -1.440256e+00
   * 2.7379193486e+05   1.64e+02  1.71e+03    1.072342e-02  -3.706519e+00
   5 2.7326800742e+05  -2.73e+01  1.71e+02    1.075288e-02  -4.338196e+00
   * 2.7344116255e+05   6.33e+01  1.71e+03    1.069793e-02  -3.915375e+00
   * 2.7327905718e+05   4.04e+00  1.71e+04    1.075232e-02  -4.332930e+00
   6 2.7326776014e+05  -9.05e-02  1.71e+03    1.075288e-02  -4.338144e+00
iter      chisq       delta/lim  lambda   a             b

After 6 iterations the fit converged.
final sum of squares of residuals : 273268
rel. change during last iteration : -9.0493e-07

degrees of freedom    (FIT_NDF)                        : 12
rms of residuals      (FIT_STDFIT) = sqrt(WSSR/ndf)    : 150.905
variance of residuals (reduced chisquare) = WSSR/ndf   : 22772.3

Final set of parameters            Asymptotic Standard Error
=======================            ==========================
a               = 0.0107529        +/- 3.114        (2.896e+04%)
b               = -4.33814         +/- 3.678        (84.78%)

correlation matrix of the fit parameters:
                a      b
a               1.000
b               0.274  1.000
</code>```

I saw it produced some result, so I thought it was all ok, but my happiness lasted seconds, just until I plotted the output:
Wow. A really good one.

And I'm still here wondering what's wrong and how to get a proper fit of a  damped sine wave dataset with gnuplot.
Hope someone knows the answer :)

答:
The function you are fitting the data to is not a good match for the data. The envelope of the data is a decaying function, so you want a positive damping parameter a. But then your fitting function cannot be bigger than 1 for positive x, unlike your data. Also, by using a sine function in your fit you assume something about the phase behavior -- the fitted function will  always be zero at x=0. However, your data looks like it should have a large, negative amplitude.

So let's choose a better fitting function, and give gnuplot a hand by choosing some reasonable initial guesses for the parameters:

```<code>f(x)=c*exp(-a*x)*cos(b*x)
a=1./500
b=2*pi/100.
c=-400.
fit f(x) 'data.txt' via a,b,c
plot f(x), "data.txt" w p
</code>```

gives

Body:
I was trying to fit this dataset:

#Mydataset damped sine wave data
#X ---- Y
45.80   320.0
91.60   -254.0
137.4   198.0
183.2   -156.0
229.0   126.0
274.8   -100.0
320.6   80.0
366.4   -64.0
412.2   52.0
458.0   -40.0
503.8   34.0
549.6   -26.0
595.4   22.0
641.2   -18.0

which, as you can see by the plot below, has the classical trend of a  damped sine wave:

So i first set the macro for the fit

f(x) = exp(-a*x)*sin(b*x)

then i made the proper fit

fit f(x) 'data.txt' via a,b
iter      chisq       delta/lim  lambda   a             b
   0 2.7377200000e+05   0.00e+00  1.10e-19    1.000000e+00   1.000000e+00

Current data point
=========================
#               = 1 out of 14
x               = -5.12818e+20
z               = 320

Current set of parameters
=========================
a               = -5.12818e+20
b               = -1.44204e+20

         Function evaluation yields NaN ("not a number")

getting a NaN as result. So I looked around on STackOverflow and I remembered I've already have had in the past problems by fitting exponential due to their fast growth/decay which requires you to set initial parameters in order not to get this error (as I've asked here). So I tried by setting as starting parameters a and b  as the ones expected, a = 9000, b=146000, but the result was more frustrating than the one before:

fit f(x) 'data.txt' via a,b
iter      chisq       delta/lim  lambda   a             b
   0 2.7377200000e+05   0.00e+00  0.00e+00    9.000000e+03   1.460000e+05
         Singular matrix in Givens()

I've thought: "these are too much large numbers, let's try with smaller ones".
So i entered the values for a and b and started fitting again

a = 0.01
b = 2
fit f(x) 'data.txt' via a,b
iter      chisq       delta/lim  lambda   a             b
   0 2.7429059500e+05   0.00e+00  1.71e+01    1.000000e-02   2.000000e+00
   1 2.7346318324e+05  -3.03e+02  1.71e+00    1.813940e-02  -9.254913e-02
   * 1.0680927157e+137  1.00e+05  1.71e+01   -2.493611e-01   5.321099e+00
   2 2.7344431789e+05  -6.90e+00  1.71e+00    1.542835e-02   4.310193e+00
   * 6.1148639318e+81   1.00e+05  1.71e+01   -1.481123e-01  -1.024914e+01
   3 2.7337226343e+05  -2.64e+01  1.71e+00    1.349852e-02  -9.008087e+00
   * 6.4751980241e+136  1.00e+05  1.71e+01   -2.458835e-01  -4.089511e+00
   4 2.7334273482e+05  -1.08e+01  1.71e+00    1.075319e-02  -4.346296e+00
   * 1.8228530731e+121  1.00e+05  1.71e+01   -2.180542e-01  -1.407646e+00
   * 2.7379223634e+05   1.64e+02  1.71e+02    8.277720e-03  -1.440256e+00
   * 2.7379193486e+05   1.64e+02  1.71e+03    1.072342e-02  -3.706519e+00
   5 2.7326800742e+05  -2.73e+01  1.71e+02    1.075288e-02  -4.338196e+00
   * 2.7344116255e+05   6.33e+01  1.71e+03    1.069793e-02  -3.915375e+00
   * 2.7327905718e+05   4.04e+00  1.71e+04    1.075232e-02  -4.332930e+00
   6 2.7326776014e+05  -9.05e-02  1.71e+03    1.075288e-02  -4.338144e+00
iter      chisq       delta/lim  lambda   a             b

After 6 iterations the fit converged.
final sum of squares of residuals : 273268
rel. change during last iteration : -9.0493e-07

degrees of freedom    (FIT_NDF)                        : 12
rms of residuals      (FIT_STDFIT) = sqrt(WSSR/ndf)    : 150.905
variance of residuals (reduced chisquare) = WSSR/ndf   : 22772.3

Final set of parameters            Asymptotic Standard Error
=======================            ==========================
a               = 0.0107529        +/- 3.114        (2.896e+04%)
b               = -4.33814         +/- 3.678        (84.78%)

correlation matrix of the fit parameters:
                a      b
a               1.000
b               0.274  1.000

I saw it produced some result, so I thought it was all ok, but my happiness lasted seconds, just until I plotted the output:
Wow. A really good one.

And I'm still here wondering what's wrong and how to get a proper fit of a  damped sine wave dataset with gnuplot.
Hope someone knows the answer :)

Body:
The function you are fitting the data to is not a good match for the data. The envelope of the data is a decaying function, so you want a positive damping parameter a. But then your fitting function cannot be bigger than 1 for positive x, unlike your data. Also, by using a sine function in your fit you assume something about the phase behavior -- the fitted function will  always be zero at x=0. However, your data looks like it should have a large, negative amplitude.

So let's choose a better fitting function, and give gnuplot a hand by choosing some reasonable initial guesses for the parameters:

f(x)=c*exp(-a*x)*cos(b*x)
a=1./500
b=2*pi/100.
c=-400.
fit f(x) 'data.txt' via a,b,c
plot f(x), "data.txt" w p

gives


问:
Serverless / AWS API Gateway CORS Unable to Access Headers
My function's config:

```<code>register:
  handler: handlers.register
  events:
    - http:
        integration: lambda-proxy
        path: register
        method: post
        cors: true
</code>```

OPTIONS is returning these headers to the browser:

```<code>access-control-allow-credentials:false
access-control-allow-headers:Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,X-Amz-User-Agent
access-control-allow-methods:OPTIONS,POST
access-control-allow-origin:*
</code>```

My POST method is returning these headers to the browser:

```<code>access-control-allow-credentials:true
access-control-allow-headers:Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token
access-control-allow-methods:*
access-control-allow-origin:*
...
x-amzn-remapped-authorization:Bearer {MY_TOKEN}
</code>```

I send back a response from my handler with an Authorization header containing Bearer {MY_TOKEN}. I'm still, however, unable to access x-amzn-remapped-authorization from my JS client using axios. All I get back in JS is content-type.

答:
Access-Control-Allow-Headers is returned in a preflight response (from OPTIONS) by the server (in this case, API Gateway) for specifying which headers the client can use when making a request.

Access-Control-Expose-Headers is specified in your handler's response indicating which headers you want the browser to expose to the client.

I added 'Access-Control-Expose-Headers': 'X-Amzn-Remapped-Authorization' to my handler's response and everything is now working as expected.

Body:
My function's config:

register:
  handler: handlers.register
  events:
    - http:
        integration: lambda-proxy
        path: register
        method: post
        cors: true

OPTIONS is returning these headers to the browser:

access-control-allow-credentials:false
access-control-allow-headers:Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,X-Amz-User-Agent
access-control-allow-methods:OPTIONS,POST
access-control-allow-origin:*

My POST method is returning these headers to the browser:

access-control-allow-credentials:true
access-control-allow-headers:Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token
access-control-allow-methods:*
access-control-allow-origin:*
...
x-amzn-remapped-authorization:Bearer {MY_TOKEN}

I send back a response from my handler with an Authorization header containing Bearer {MY_TOKEN}. I'm still, however, unable to access x-amzn-remapped-authorization from my JS client using axios. All I get back in JS is content-type.


问:
Elastic beanstalk + Spring Boot + Array properties
I need to pass some configuration to my Spring Boot app, which is deployed using elastic beanstalk.

Unfortunately, I need to update these variables without recompilation of the artifact, so I want to use the uppercase with underscore notation (http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/java-configuration.html). Unfortuanatelly the configuration is more complex, in fact I am trying to pass array of objects into it (which is supported in the properties files/yaml - https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-loading-yaml). But the properties syntax requires brackets ([ ]).

Is there any way, how to workaround this (without rewriting the application)?

答:
According to me, following should work:

Add all your external properties as documented on aws documentation

Use these properties in your spring boot application with @value annotation. If you see the spring documentation the property source at order 9/10  should get the values of your properties.


问:
C++ passing a file to a string
Hi i am trying to pass a whole file into a string. This is my Code but the program is always exiting on the first if(). I just can't get behind what i am doing wrong here.

```<code>#include <iostream>
#include <fstream>
#include <string>

std::string readFile (std::string filename);

int main() {
    std::string filename;
    std::string Eingabestring;

    std::cout << "Geben Sie eine Datei an" << std::endl;
    std::cin >> filename;
    Eingabestring = readFile(filename);

    std::cout << Eingabestring << std::endl;

    return 0;
}

std::string readFile (std::string filename)
{
    std::string zeile,inhalt ;
    std::ifstream quelle;
    quelle.open(filename.c_str());

    if (!quelle)
    {
        std::cerr << filename << " kann nicht geöffnet werden!\n";
        return exit(-1);
    }

    while (!quelle.eof())
    {
        getline(quelle,zeile);
        inhalt = inhalt + zeile;
    }

    return inhalt;

}
</code>```

Already thanks for your help!

Edit: I just noticed that i put the file into a wrong folder.. But the code still isn't reading the whole file. Just the first line, but i thought with the loop i could get every line of my file into the string?

And i fixed the second return 0 to exit(-1). Thats better right?

答:
Try something like this to read your file instead: </p>

```<code>std::string readFile (std::string filename)
{
   std::ifstream quelle(filename);

   std::string content( (std::istreambuf_iterator<char>(quelle) ),
                      (std::istreambuf_iterator<char>()) );
   return content;
}
</code>```

Title: C++ passing a file to a string

Body:
Hi i am trying to pass a whole file into a string. This is my Code but the program is always exiting on the first if(). I just can't get behind what i am doing wrong here.

#include <iostream>
#include <fstream>
#include <string>

std::string readFile (std::string filename);

int main() {
    std::string filename;
    std::string Eingabestring;

    std::cout << "Geben Sie eine Datei an" << std::endl;
    std::cin >> filename;
    Eingabestring = readFile(filename);

    std::cout << Eingabestring << std::endl;

    return 0;
}

std::string readFile (std::string filename)
{
    std::string zeile,inhalt ;
    std::ifstream quelle;
    quelle.open(filename.c_str());

    if (!quelle)
    {
        std::cerr << filename << " kann nicht geöffnet werden!\n";
        return exit(-1);
    }

    while (!quelle.eof())
    {
        getline(quelle,zeile);
        inhalt = inhalt + zeile;
    }

    return inhalt;

}

Already thanks for your help!

Edit: I just noticed that i put the file into a wrong folder.. But the code still isn't reading the whole file. Just the first line, but i thought with the loop i could get every line of my file into the string?

And i fixed the second return 0 to exit(-1). Thats better right?

Body:
Try something like this to read your file instead:

std::string readFile (std::string filename)
{
   std::ifstream quelle(filename);

   std::string content( (std::istreambuf_iterator<char>(quelle) ),
                      (std::istreambuf_iterator<char>()) );
   return content;
}


问:
angular-in-memory-web-api not responding
I am trying to complete the famous tour of heroes tutorial for Angular (not js!) but using angular-cli to create the project.
Everything was fine until the section to use the angular-in-memory-web-api.
Yes I did use the command "npm install angular-in-memory-web-api --save" and the dependency is now in my package.json.

There is no error at all when running the app. No compilation error. No run time error in the js console.
Nothing is happening. Like if there was no response from the "api server".

I even added some console.debug to be sure that "createDb()" and my "getHeroes()" function are executed.

Any idea where to look at?
Here is some of my files.

package.json:

```<code>{
"name": "angular-tour-of-heroe",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/common": "^4.0.0",
    "@angular/compiler": "^4.0.0",
    "@angular/core": "^4.0.0",
    "@angular/forms": "^4.0.0",
    "@angular/http": "^4.0.0",
    "@angular/platform-browser": "^4.0.0",
    "@angular/platform-browser-dynamic": "^4.0.0",
    "@angular/router": "^4.0.0",
    "angular-in-memory-web-api": "latest",
    "core-js": "^2.4.1",
    "rxjs": "^5.1.0",
    "zone.js": "^0.8.4"
  },
  "devDependencies": {
    "@angular/cli": "1.0.6",
    "@angular/compiler-cli": "^4.0.0",
    "@types/jasmine": "2.5.38",
    "@types/node": "~6.0.60",
    "codelyzer": "~2.0.0",
    "jasmine-core": "~2.5.2",
    "jasmine-spec-reporter": "~3.2.0",
    "karma": "~1.4.1",
    "karma-chrome-launcher": "~2.1.1",
    "karma-cli": "~1.0.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "karma-coverage-istanbul-reporter": "^0.2.0",
    "protractor": "~5.1.0",
    "ts-node": "~2.0.0",
    "tslint": "~4.5.0",
    "typescript": "~2.2.0"
  }
}
</code>```

app.module.ts:

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import {AppRoutingModule} from "./app-routing/app-routing.module";

// Imports for loading & configuring the in-memory web api
import { InMemoryWebApiModule } from 'angular-in-memory-web-api';
// import { InMemoryWebApiModule } from 'angular-in-memory-web-api/in-memory-web-api.module';
import {InMemoryDataService} from "./in-memory-data.service";

import { AppComponent } from './app.component';
import { HeroDetailComponent } from './hero-detail/hero-detail.component';
import { HeroesComponent } from './heroes/heroes.component';
import { HeroService } from "./hero.service";
import { DashboardComponent } from './dashboard/dashboard.component';

@NgModule({
  declarations: [
    AppComponent,
    HeroDetailComponent,
    HeroesComponent,
    DashboardComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    AppRoutingModule,
    HttpModule,
    InMemoryWebApiModule.forRoot(InMemoryDataService)
  ],
  providers: [HeroService],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

in-memory-data.service.ts:

```<code>import { InMemoryDbService } from 'angular-in-memory-web-api';
// import { InMemoryDbService } from 'angular-in-memory-web-api/in-memory-backend.service';

export class InMemoryDataService implements InMemoryDbService {
  createDb() {

    console.debug("createDb");

    let heroes = [
      {id: 11, name: 'Mr. Nice'},
      {id: 12, name: 'Narco'},
      {id: 13, name: 'Bombasto'},
      {id: 14, name: 'Celeritas'},
      {id: 15, name: 'Magneta'},
      {id: 16, name: 'RubberMan'},
      {id: 17, name: 'Dynama'},
      {id: 18, name: 'Dr IQ'},
      {id: 19, name: 'Magma'},
      {id: 20, name: 'Tornado'}
    ];
    return {heroes};
  }
}
</code>```

hero.service.ts:

```<code>import { Injectable } from '@angular/core';
import {Hero} from "./hero";
import {Http} from "@angular/http";
import "rxjs/add/operator/toPromise";

@Injectable()
export class HeroService {

  private heroesUrl = 'api/heroes';  // URL to web api

  constructor(private http: Http) { }

  getHeroes(): Promise<Hero[]> {

    console.debug("getHeroes method");

    return new Promise(resolve => {
      return this.http.get(this.heroesUrl)
        .toPromise()
        .then(response => response.json().data as Hero[])
        .catch(this.handleError);
    });
  }

  getHero(id: number): Promise<Hero> {

    return this.getHeroes()
      .then(heroes => heroes.find( hero => hero.id === id));
  }

  private handleError(error: any): Promise<any> {
    console.error('An error occurred', error); // for demo purposes only
    return Promise.reject(error.message || error);
  }
}
</code>```

答:
The problem was caused by my IDE (IntelliJ) that replace the "return this.http..." by a "return new Promise(..."!!

My getHeroes function should be:

```<code>getHeroes(): Promise<Hero[]> {

    console.debug("getHeroes method");

    return this.http.get(this.heroesUrl)
      .toPromise()
      .then(response => response.json() as Hero[])
      .catch(this.handleError);
  }
</code>```

Body:
I am trying to complete the famous tour of heroes tutorial for Angular (not js!) but using angular-cli to create the project.
Everything was fine until the section to use the angular-in-memory-web-api.
Yes I did use the command "npm install angular-in-memory-web-api --save" and the dependency is now in my package.json.

There is no error at all when running the app. No compilation error. No run time error in the js console.
Nothing is happening. Like if there was no response from the "api server".

I even added some console.debug to be sure that "createDb()" and my "getHeroes()" function are executed.

Any idea where to look at?
Here is some of my files.

package.json:

{
"name": "angular-tour-of-heroe",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/common": "^4.0.0",
    "@angular/compiler": "^4.0.0",
    "@angular/core": "^4.0.0",
    "@angular/forms": "^4.0.0",
    "@angular/http": "^4.0.0",
    "@angular/platform-browser": "^4.0.0",
    "@angular/platform-browser-dynamic": "^4.0.0",
    "@angular/router": "^4.0.0",
    "angular-in-memory-web-api": "latest",
    "core-js": "^2.4.1",
    "rxjs": "^5.1.0",
    "zone.js": "^0.8.4"
  },
  "devDependencies": {
    "@angular/cli": "1.0.6",
    "@angular/compiler-cli": "^4.0.0",
    "@types/jasmine": "2.5.38",
    "@types/node": "~6.0.60",
    "codelyzer": "~2.0.0",
    "jasmine-core": "~2.5.2",
    "jasmine-spec-reporter": "~3.2.0",
    "karma": "~1.4.1",
    "karma-chrome-launcher": "~2.1.1",
    "karma-cli": "~1.0.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "karma-coverage-istanbul-reporter": "^0.2.0",
    "protractor": "~5.1.0",
    "ts-node": "~2.0.0",
    "tslint": "~4.5.0",
    "typescript": "~2.2.0"
  }
}

app.module.ts:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import {AppRoutingModule} from "./app-routing/app-routing.module";

// Imports for loading & configuring the in-memory web api
import { InMemoryWebApiModule } from 'angular-in-memory-web-api';
// import { InMemoryWebApiModule } from 'angular-in-memory-web-api/in-memory-web-api.module';
import {InMemoryDataService} from "./in-memory-data.service";

import { AppComponent } from './app.component';
import { HeroDetailComponent } from './hero-detail/hero-detail.component';
import { HeroesComponent } from './heroes/heroes.component';
import { HeroService } from "./hero.service";
import { DashboardComponent } from './dashboard/dashboard.component';

@NgModule({
  declarations: [
    AppComponent,
    HeroDetailComponent,
    HeroesComponent,
    DashboardComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    AppRoutingModule,
    HttpModule,
    InMemoryWebApiModule.forRoot(InMemoryDataService)
  ],
  providers: [HeroService],
  bootstrap: [AppComponent]
})
export class AppModule { }

in-memory-data.service.ts:

import { InMemoryDbService } from 'angular-in-memory-web-api';
// import { InMemoryDbService } from 'angular-in-memory-web-api/in-memory-backend.service';

export class InMemoryDataService implements InMemoryDbService {
  createDb() {

    console.debug("createDb");

    let heroes = [
      {id: 11, name: 'Mr. Nice'},
      {id: 12, name: 'Narco'},
      {id: 13, name: 'Bombasto'},
      {id: 14, name: 'Celeritas'},
      {id: 15, name: 'Magneta'},
      {id: 16, name: 'RubberMan'},
      {id: 17, name: 'Dynama'},
      {id: 18, name: 'Dr IQ'},
      {id: 19, name: 'Magma'},
      {id: 20, name: 'Tornado'}
    ];
    return {heroes};
  }
}

hero.service.ts:

import { Injectable } from '@angular/core';
import {Hero} from "./hero";
import {Http} from "@angular/http";
import "rxjs/add/operator/toPromise";

@Injectable()
export class HeroService {

  private heroesUrl = 'api/heroes';  // URL to web api

  constructor(private http: Http) { }

  getHeroes(): Promise<Hero[]> {

    console.debug("getHeroes method");

    return new Promise(resolve => {
      return this.http.get(this.heroesUrl)
        .toPromise()
        .then(response => response.json().data as Hero[])
        .catch(this.handleError);
    });
  }

  getHero(id: number): Promise<Hero> {

    return this.getHeroes()
      .then(heroes => heroes.find( hero => hero.id === id));
  }

  private handleError(error: any): Promise<any> {
    console.error('An error occurred', error); // for demo purposes only
    return Promise.reject(error.message || error);
  }
}

Body:
The problem was caused by my IDE (IntelliJ) that replace the "return this.http..." by a "return new Promise(..."!!

My getHeroes function should be:

getHeroes(): Promise<Hero[]> {

    console.debug("getHeroes method");

    return this.http.get(this.heroesUrl)
      .toPromise()
      .then(response => response.json() as Hero[])
      .catch(this.handleError);
  }


Title: convert csv to dictionary

Body:
I have the following csv file(total 20000 lines)

ozone,paricullate_matter,carbon_monoxide,sulfure_dioxide,nitrogen_dioxide,longitude,latitude,timestamp,avg_measured_time,avg_speed,median_measured_time,timestamp:1,vehicle_count,lat1,long1,lat2,long2,distance_between_2_points,duration_of_measurement,ndt_in_kmh
99,99,98,116,118,10.09351660921,56.1671665604395,1407575099.99998,0,0,0,1407575099.99998,0,56.1089513576227,10.1823955595246,56.1048021343541,10.1988040846558,1124,65,62
99,99,98,116,118,10.09351660921,56.1671665604395,1407575099.99998,0,0,0,1407575099.99998,0,56.10986429895,10.1627288048935,56.1089513576227,10.1823955595246,1254,71,64
99,99,98,116,118,10.09351660921,56.1671665604395,1407575099.99998,0,0,0,1407575099.99998,0,56.1425188527673,10.1868802625656,56.1417522836526,10.1927236478157,521,62,30
99,99,98,116,118,10.09351660921,56.1671665604395,1407575099.99998,18,84,18,1407575099.99998,1,56.1395320665735,10.1772034087371,56.1384485157567,10.1791506011887,422,50,30

I want to convert this into a dictionary like

{'ozone': [99,99,99,99], 'paricullate_matter': [99,99,99,99],'carbon_monoxide': [98,98,98,98],etc....}

What i have tried

import csv

reader = csv.DictReader(open('resulttable.csv'))

output = open("finalprojdata.py","w")

result = {}
for row in reader:
    for column, value in row.iteritems():
        result.setdefault(column, []).append(float(value))
output.write(str(result))

The output am getting is consisting of only few dictionaries. Like from

{'vehicle_count': [0,0,0,1], 'lat1': etc}

The whole csv file is not getting converted to dictionary.

Body:
$ cat tst.awk
BEGIN { FS=OFS=","; ORS="}\n" }
NR==1 {split($0,hdr); next }
{
    for (i=1; i<=NF; i++) {
        vals[i] = (i in vals ? vals[i] "," : "") $i
    }
}
END {
    printf "{"
    for (i=1; i<=NF; i++) {
        printf "\047%s\047: [%s]%s", hdr[i], vals[i], (i<NF?OFS:ORS)
    }
}

$ awk -f tst.awk file
{'ozone': [99,99,99,99],'paricullate_matter': [99,99,99,99],'carbon_monoxide': [98,98,98,98],'sulfure_dioxide': [116,116,116,116],'nitrogen_dioxide': [118,118,118,118],'longitude': [10.09351660921,10.09351660921,10.09351660921,10.09351660921],'latitude': [56.1671665604395,56.1671665604395,56.1671665604395,56.1671665604395],'timestamp': [1407575099.99998,1407575099.99998,1407575099.99998,1407575099.99998],'avg_measured_time': [0,0,0,18],'avg_speed': [0,0,0,84],'median_measured_time': [0,0,0,18],'timestamp:1': [1407575099.99998,1407575099.99998,1407575099.99998,1407575099.99998],'vehicle_count': [0,0,0,1],'lat1': [56.1089513576227,56.10986429895,56.1425188527673,56.1395320665735],'long1': [10.1823955595246,10.1627288048935,10.1868802625656,10.1772034087371],'lat2': [56.1048021343541,56.1089513576227,56.1417522836526,56.1384485157567],'long2': [10.1988040846558,10.1823955595246,10.1927236478157,10.1791506011887],'distance_between_2_points': [1124,1254,521,422],'duration_of_measurement': [65,71,62,50],'ndt_in_kmh': [62,64,30,30]}


问:
sql group by sum of all sums
I have a query (formatted for Oracle):

```<code>select sum(inv.quantity * inv.price), spn.salesperson_name
from invoice inv
inner join salesperson spn on spn.spn_id = inv.spn_id
where inc.invoice_date between to_date('05/01/2017', 'MM/dd/YYYY') and to_date('05/31/2017', 'MM/dd/YYYY')
group by spn.salesperson_name
</code>```

To add up invoices for the month of May. The result is similar to:

```<code>$446,088.62     Bob
$443,439.29     Sally
$275,097.00     Tom
 $95,170.00     George
 $53,150.00     Jill
</code>```

But, I need to divide each sum to the sum of the sums ($1,312,944.91), so that the result is:

```<code>$446,088.62     34%  Bob
$443,439.29     34%  Sally
$275,097.00     21%  Tom
 $95,170.00      7%  George
 $53,150.00      4%  Jill
</code>```

(The sum of the percentage column should be 100%)

Is there a way to accomplish this in the query?

答:
Just use analytic functions:</p>

```<code>select spn.salesperson_name, sum(inv.quantity * inv.price),
       sum(inv.quantity * inv.price)  / sum(sum(inv.quantity * inv.price)) over () as ratio
from invoice inv inner join
     salesperson spn
     on spn.spn_id = inv.spn_id
where inc.invoice_date between date '2017-05-01' and date '2017-05-31'
group by spn.salesperson_name;
</code>```

Title: sql group by sum of all sums

Body:
I have a query (formatted for Oracle):

select sum(inv.quantity * inv.price), spn.salesperson_name
from invoice inv
inner join salesperson spn on spn.spn_id = inv.spn_id
where inc.invoice_date between to_date('05/01/2017', 'MM/dd/YYYY') and to_date('05/31/2017', 'MM/dd/YYYY')
group by spn.salesperson_name

To add up invoices for the month of May. The result is similar to:

$446,088.62     Bob
$443,439.29     Sally
$275,097.00     Tom
 $95,170.00     George
 $53,150.00     Jill

But, I need to divide each sum to the sum of the sums ($1,312,944.91), so that the result is:

$446,088.62     34%  Bob
$443,439.29     34%  Sally
$275,097.00     21%  Tom
 $95,170.00      7%  George
 $53,150.00      4%  Jill

(The sum of the percentage column should be 100%)

Is there a way to accomplish this in the query?

Body:
Just use analytic functions:

select spn.salesperson_name, sum(inv.quantity * inv.price),
       sum(inv.quantity * inv.price)  / sum(sum(inv.quantity * inv.price)) over () as ratio
from invoice inv inner join
     salesperson spn
     on spn.spn_id = inv.spn_id
where inc.invoice_date between date '2017-05-01' and date '2017-05-31'
group by spn.salesperson_name;


问:
The operation couldn’t be completed. (OSStatus error -600.) Cant run app in simulator
Using XCode 6.3.1 , SDK 8.3

Suddenly my app stopped running in (any) simulator and Xcode throws error

The operation couldn’t be completed. (OSStatus error -600.)

Tried cleaning, reset content and setting and even restarting my Mac.

Is there anything I can do to run my app in simulator.

答: Solved it just by restarting the computer. Don't know what it means, but it can be fixed that way! Cheers</p>


答:
Other than checking to see why the open() failed as explained in the comments also keep in mind that there are easier ways to check for when you have hit the end of file in a while loop where you are reading from an istream.

The idiomatic way to loop and read from an istream in C++ is to embed the read expression that returns a reference to the istream in the loop condition, so change your code to

```<code>#include <iostream>
#include <string>

using std::cin;
using std::cout;
using std::endl;
using std::string;

int main() {
    auto character = char{};
    auto file_string = string{};
    while (cin.get(character)) {
        file_string += character;
    }

    cout << file_string << endl;
    return 0;
}
</code>```

I've used cin above but just replace cin with your file stream object and everything should work normally.

Note that the while terminating condition is now an istream reference, and that is convertible to bool, so the loop will exit when the istream object is done reading or when the stream encounters any errors besides EOF.  You don't have to check for eof() yourself.

Also another thing is to pass strings that you do not intend to modify by const reference instead of by value, so the readFile() function should accept a const string& instead of a string, this will help save you string copying.  When C++17 is available replace that const string& with std::string_view

Title: C++ passing a file to a string

Body:
Other than checking to see why the open() failed as explained in the comments also keep in mind that there are easier ways to check for when you have hit the end of file in a while loop where you are reading from an istream.

The idiomatic way to loop and read from an istream in C++ is to embed the read expression that returns a reference to the istream in the loop condition, so change your code to

#include <iostream>
#include <string>

using std::cin;
using std::cout;
using std::endl;
using std::string;

int main() {
    auto character = char{};
    auto file_string = string{};
    while (cin.get(character)) {
        file_string += character;
    }

    cout << file_string << endl;
    return 0;
}

I've used cin above but just replace cin with your file stream object and everything should work normally.

Note that the while terminating condition is now an istream reference, and that is convertible to bool, so the loop will exit when the istream object is done reading or when the stream encounters any errors besides EOF.  You don't have to check for eof() yourself.

Also another thing is to pass strings that you do not intend to modify by const reference instead of by value, so the readFile() function should accept a const string& instead of a string, this will help save you string copying.  When C++17 is available replace that const string& with std::string_view


问:
WordPress database error with using wpdb->query
I have a query that is using $wpdb->query but every time I run it, it doesn't seem to work and is providing me with the following error message:

```<code>WordPress database error You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''4'' at line 1 for query SELECT * FROM wp_mytable OFFSET '4'
</code>```

This is the code that is causing the error:

```<code>$query = $wpdb->prepare("SELECT * FROM " . $wpdb->prefix . MY_TABLE . " OFFSET %s", $offset);
$fetch = $wpdb->get_results($query, 'ARRAY_A');
</code>```

What am I doing wrong here? I've looked at some other questions but nothing seems to be similar to my issue so I don't know what I'm missing.

答:
Offset should be integer not a string. Also offset comes along with limit

Replace

```<code>$query = $wpdb->prepare("SELECT * FROM " . $wpdb->prefix . MY_TABLE . "  OFFSET %s", $offset);
</code>```

with

```<code>$query = $wpdb->prepare("SELECT * FROM " . $wpdb->prefix . MY_TABLE . " LIMIT %d OFFSET %d", $limit,$offset);
</code>```

Not tested.

Body:
I have a query that is using $wpdb->query but every time I run it, it doesn't seem to work and is providing me with the following error message:

WordPress database error You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''4'' at line 1 for query SELECT * FROM wp_mytable OFFSET '4'

This is the code that is causing the error:

$query = $wpdb->prepare("SELECT * FROM " . $wpdb->prefix . MY_TABLE . " OFFSET %s", $offset);
$fetch = $wpdb->get_results($query, 'ARRAY_A');

What am I doing wrong here? I've looked at some other questions but nothing seems to be similar to my issue so I don't know what I'm missing.

Body:
Offset should be integer not a string. Also offset comes along with limit

Replace

$query = $wpdb->prepare("SELECT * FROM " . $wpdb->prefix . MY_TABLE . "  OFFSET %s", $offset);

with

$query = $wpdb->prepare("SELECT * FROM " . $wpdb->prefix . MY_TABLE . " LIMIT %d OFFSET %d", $limit,$offset);

Not tested.


问:
How to add dynamic roles managment to JHipster uaa project?
I've generated a jhipster 4 project with uaa, a microservice and a gateway. I'd like to add new roles and assign them to users without manually modify the source code. I've explore deepu105's code but it not seems completed. Any help will be welcomed.</p>

答:
currently, the authorities in JHipster come from the source code.
If you need to make authorities stored in your database. In detail, these are the steps:

add a new entity Authority (you can use jhipster entity for that)

if not already done by the generator, add a AuthorityResource @RestController, exposing that entity via a REST API

you can either enforce a user authority being set via UserResource to exist, or create it on-demand

add the default roles (like ROLE_USER and ROLE_ADMIN) in a CSV file, and load it using loadData in a Liquibase migration, like it is done with users

for a better UX, you can even add PUT/DELETE /api/user/{login}/authorities/{authorityName} to your UserResource


问:
Class Lock And Object Lock In Multithreading
I tried an interview question with static functions and non static functions as synchronized and one function was non synchronized. As in below code:

```<code>public class Resource {

public static synchronized void m1() throws InterruptedException {
    System.out.println("Entering m1 method");
    Thread.sleep(10000);
    System.out.println("Leaving m1 method");
    System.out.println();
}

public synchronized void m2() throws InterruptedException {
    System.out.println("Entering m2 method");
    Thread.sleep(2000);
    System.out.println("Leaving m2 method");
    System.out.println();
}

public void m3() throws InterruptedException {
    System.out.println("Entering m3 method");
    Thread.sleep(2000);
    System.out.println("Leaving m3 method");
    System.out.println();
}

public synchronized void m4() throws InterruptedException {
    System.out.println("Entering m4 method");
    Thread.sleep(2000);
    System.out.println("Leaving m4 method");
    System.out.println();
}

}

public class ThreadDemo {

public static void main(String[] args) {

    final Resource resource = new Resource();

    Thread t1 = new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                resource.m1();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    });

    Thread t2 = new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                resource.m2();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    });

    Thread t3 = new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                resource.m3();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    });

    Thread t4 = new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                resource.m4();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    });

    t1.start();
    t2.start();
    t3.start();
    t4.start();
}

}
</code>```

Here four threads are created.

T1 is calling static synchronized(m1)

T2, T4 are calling synchronized(m2, m4) and

T3 is calling non synnchronized(m3).

It's output is:

```<code>Entering m1 method
Entering m3 method
Entering m2 method
Leaving m3 method

Leaving m2 method

Entering m4 method
Leaving m4 method

Leaving m1 method
</code>```

My question is:

1) static synchronized method make class level lock. Here what is the meaning of class level locking? If one thread has taken lock and class level lock is occupied then why thread T2 and T3 starts execution?

2) T4 is waiting to complete T2. Although synchronization is applied on two different methods, then why T4 has to wait? If object level lock is working in T2, T4 then in above point why class level locking is not working?

答:
Regarding your queries:

1) static synchronized method make class level lock. Here what is the meaning of class level locking? If one thread has taken lock and class level lock is occupied then why thread T2 and T3 starts execution?

in case of static synchronized methods, only one thread acquire lock on these methods among multiple instances of class. If you have two different instances : resource1 and resource2 for Resource class, only one thread will succeed in getting lock on m1().

if resource1.m1() method execution is in progress by one thread, other thread can't execute resource2.m1() unless first thread finish the execution of m1().

Since method m3() is non-synchronized method, any thread can invoke this method without wait and getting lock.

Since both m2() and m4() are synchronized, only one thread will succeed in getting lock on same object ( resource in your example). Other thread has to wait until first thread completes the execution of synchrnozied method and release object level lock.

2) T4 is waiting to complete T2. Although synchronization is applied on two different methods, then why T4 has to wait?If object level lock is working in T2, T4 then in above point why class level locking is not working?

synchronized methods:

Making these methods synchronized has two effects:

First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.

Second, when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible to all threads.

static synchronized methods:

The thread acquires the intrinsic lock for the Class object associated with the class. Thus access to class's static fields is controlled by a lock that's distinct from the lock for any instance of the class.

Body:
I tried an interview question with static functions and non static functions as synchronized and one function was non synchronized. As in below code:

public class Resource {

public static synchronized void m1() throws InterruptedException {
    System.out.println("Entering m1 method");
    Thread.sleep(10000);
    System.out.println("Leaving m1 method");
    System.out.println();
}

public synchronized void m2() throws InterruptedException {
    System.out.println("Entering m2 method");
    Thread.sleep(2000);
    System.out.println("Leaving m2 method");
    System.out.println();
}

public void m3() throws InterruptedException {
    System.out.println("Entering m3 method");
    Thread.sleep(2000);
    System.out.println("Leaving m3 method");
    System.out.println();
}

public synchronized void m4() throws InterruptedException {
    System.out.println("Entering m4 method");
    Thread.sleep(2000);
    System.out.println("Leaving m4 method");
    System.out.println();
}

}

public class ThreadDemo {

public static void main(String[] args) {

    final Resource resource = new Resource();

    Thread t1 = new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                resource.m1();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    });

    Thread t2 = new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                resource.m2();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    });

    Thread t3 = new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                resource.m3();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    });

    Thread t4 = new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                resource.m4();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    });

    t1.start();
    t2.start();
    t3.start();
    t4.start();
}

}

Here four threads are created.

T1 is calling static synchronized(m1)

T2, T4 are calling synchronized(m2, m4) and

T3 is calling non synnchronized(m3).

It's output is:

Entering m1 method
Entering m3 method
Entering m2 method
Leaving m3 method

Leaving m2 method

Entering m4 method
Leaving m4 method

Leaving m1 method

My question is:

1) static synchronized method make class level lock. Here what is the meaning of class level locking? If one thread has taken lock and class level lock is occupied then why thread T2 and T3 starts execution?

2) T4 is waiting to complete T2. Although synchronization is applied on two different methods, then why T4 has to wait? If object level lock is working in T2, T4 then in above point why class level locking is not working?


问:
Rails testing: ensure authorization (Pundit) is enforced in all controllers and actions
I'm writing RSpec tests for a Rails 4.2 application which uses Pundit for authorization.

I'd like to test whether authorization is enforced in all actions of all controllers, to avoid unintentionally providing public access to sensitive data in case a developer forgets to call policy_scope (on #index actions) and authorize (on all other actions).

One possible solution is to mock these methods in all controller unit tests. Something like expect(controller).to receive(:authorize).and_return(true) and expect(controller).to receive(:policy_scope).and_call_original. However, that would lead to a lot of code repetition. This line could be placed within a custom matcher or a helper method in spec/support but calling it in every spec of every controller also seems repetitive. Any ideas on how to achieve this in a DRY way?

In case you are wondering, Pundit's policy classes are tested separately, as shown in this post.

答:
I feel like you could use something like this up in spec_helper. Note that I'm assuming a naming convention where you have the word "index" in the index level answers, so that your spec might look like this:

```<code>describe MyNewFeaturesController, :type => :controller do

  describe "index" do
    # all of the index tests under here have policy_scope applied
  end

  # and these other tests have authorize applied
  describe 'show' do
  end

  describe 'destroy' do
  end
end
</code>```

and here is the overall configuration:

```<code>RSpec.configure do |config|
  config.before(:each, :type => :controller) do |spec|
    # if the spec description has "index" in the name, then use policy-level authorization
    if spec.metadata[:full_description] =~ /\bindex\b/
      expect(controller).to receive(:policy_scope).and_call_original
    else
      expect(controller).to receive(:authorize).and_call_original
    end
  end
end
</code>```

Body:
I feel like you could use something like this up in spec_helper. Note that I'm assuming a naming convention where you have the word "index" in the index level answers, so that your spec might look like this:

describe MyNewFeaturesController, :type => :controller do

  describe "index" do
    # all of the index tests under here have policy_scope applied
  end

  # and these other tests have authorize applied
  describe 'show' do
  end

  describe 'destroy' do
  end
end

and here is the overall configuration:

RSpec.configure do |config|
  config.before(:each, :type => :controller) do |spec|
    # if the spec description has "index" in the name, then use policy-level authorization
    if spec.metadata[:full_description] =~ /\bindex\b/
      expect(controller).to receive(:policy_scope).and_call_original
    else
      expect(controller).to receive(:authorize).and_call_original
    end
  end
end


问:
Why is RouterModule exported in the Angular document example?
In the documentation for Angular routing it shows a feature module and how to use the forChild static function.

In that example, it shows RouterModule being imported and exported by the feature module.

```<code>import { NgModule }              from '@angular/core';
import { RouterModule, Routes }  from '@angular/router';

import { CrisisListComponent }   from './crisis-list.component';
// import { HeroListComponent }  from './hero-list.component';  // <-- delete this line
import { PageNotFoundComponent } from './not-found.component';

const appRoutes: Routes = [
    { path: 'crisis-center', component: CrisisListComponent },
    // { path: 'heroes',     component: HeroListComponent }, // <-- delete this line
    { path: '',   redirectTo: '/heroes', pathMatch: 'full' },
    { path: '**', component: PageNotFoundComponent }
];

@NgModule({
    imports: [
        RouterModule.forRoot(appRoutes)
    ],
    exports: [
        RouterModule
    ]
})
export class AppRoutingModule {}
</code>```

https://angular.io/docs/ts/latest/guide/router.html#!#remove-duplicate-hero-routes

I don't understand why RouterModule is exported or see in the documentation any reason for this.

答:
Exporting a module essentially exports all declarations (directives, components, pipes) defined on this module.

Routing module defines a set of router specific directives:

```<code>const ROUTER_DIRECTIVES = [RouterOutlet, RouterLink, RouterLinkWithHref, RouterLinkActive];
</code>```

They are registered on the RouterModule:

```<code>@NgModule({declarations: ROUTER_DIRECTIVES, exports: ROUTER_DIRECTIVES})
export class RouterModule {
</code>```

If you want to use them inside your module components' templates, you have to import that module into your feature module. However, you can also import RouterModule just once into your shared module AppRoutingModule and then import this shared module elsewhere without importing RouterModule.

Body:
In the documentation for Angular routing it shows a feature module and how to use the forChild static function.

In that example, it shows RouterModule being imported and exported by the feature module.

import { NgModule }              from '@angular/core';
import { RouterModule, Routes }  from '@angular/router';

import { CrisisListComponent }   from './crisis-list.component';
// import { HeroListComponent }  from './hero-list.component';  // <-- delete this line
import { PageNotFoundComponent } from './not-found.component';

const appRoutes: Routes = [
    { path: 'crisis-center', component: CrisisListComponent },
    // { path: 'heroes',     component: HeroListComponent }, // <-- delete this line
    { path: '',   redirectTo: '/heroes', pathMatch: 'full' },
    { path: '**', component: PageNotFoundComponent }
];

@NgModule({
    imports: [
        RouterModule.forRoot(appRoutes)
    ],
    exports: [
        RouterModule
    ]
})
export class AppRoutingModule {}

https://angular.io/docs/ts/latest/guide/router.html#!#remove-duplicate-hero-routes

I don't understand why RouterModule is exported or see in the documentation any reason for this.

Body:
Exporting a module essentially exports all declarations (directives, components, pipes) defined on this module.

Routing module defines a set of router specific directives:

const ROUTER_DIRECTIVES = [RouterOutlet, RouterLink, RouterLinkWithHref, RouterLinkActive];

They are registered on the RouterModule:

@NgModule({declarations: ROUTER_DIRECTIVES, exports: ROUTER_DIRECTIVES})
export class RouterModule {

If you want to use them inside your module components' templates, you have to import that module into your feature module. However, you can also import RouterModule just once into your shared module AppRoutingModule and then import this shared module elsewhere without importing RouterModule.


问:
How to generate date range sequence without temp table in SQL
I want to convert some line of code from Oracle query to MSSQL.

```<code>   WITH DATE_MONTHS AS
(
  SELECT TO_CHAR(ADD_MONTHS(TO_DATE(TRUNC(TO_DATE(P_REQUIRED_DATE),'MON')), - LEVEL
  +1),'DD-MON-YYYY') MONTHS FROM DUAL
  CONNECT BY LEVEL <= P_MONTH_RANG
)
SELECT * from DATE_MONTHS
</code>```

Parameters:

P_REQUIRED_DATE i.e sysdate

P_MONTH_RANG  i.e 4

Result:

01-05-2017

01-04-2017

01-03-2017

01-02-2017

答:
Another option using Stacked Ctes

```<code>declare @fromdate date = '20150501';
declare @months int = 4;

;with n as (select n from (values(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) t(n))
, dates as (
  select top (@months)
      [Date]=convert(date,dateadd(month,-(row_number() over(order by (select 1))-1),@fromdate))
  from n as deka cross join n as hecto cross join n as kilo cross join n as tenK
  order by [Date] desc
)
select [Date] = convert(char(10),[date],105)
from dates;
</code>```

rextester demo: http://rextester.com/UUW2271

returns:

```<code>+------------+
|    Date    |
+------------+
| 01-05-2015 |
| 01-04-2015 |
| 01-03-2015 |
| 01-02-2015 |
+------------+
</code>```

Benchmarks & Performance testing: Generate a set or sequence without loops - 2 - Aaron Bertrand

Body:
I want to convert some line of code from Oracle query to MSSQL.

   WITH DATE_MONTHS AS
(
  SELECT TO_CHAR(ADD_MONTHS(TO_DATE(TRUNC(TO_DATE(P_REQUIRED_DATE),'MON')), - LEVEL
  +1),'DD-MON-YYYY') MONTHS FROM DUAL
  CONNECT BY LEVEL <= P_MONTH_RANG
)
SELECT * from DATE_MONTHS

Parameters:

P_REQUIRED_DATE i.e sysdate

P_MONTH_RANG  i.e 4

Result:

01-05-2017

01-04-2017

01-03-2017

01-02-2017

Body:
Another option using Stacked Ctes

declare @fromdate date = '20150501';
declare @months int = 4;

;with n as (select n from (values(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) t(n))
, dates as (
  select top (@months)
      [Date]=convert(date,dateadd(month,-(row_number() over(order by (select 1))-1),@fromdate))
  from n as deka cross join n as hecto cross join n as kilo cross join n as tenK
  order by [Date] desc
)
select [Date] = convert(char(10),[date],105)
from dates;

rextester demo: http://rextester.com/UUW2271

returns:

+------------+
|    Date    |
+------------+
| 01-05-2015 |
| 01-04-2015 |
| 01-03-2015 |
| 01-02-2015 |
+------------+

Benchmarks & Performance testing: Generate a set or sequence without loops - 2 - Aaron Bertrand


问:
Get an array of all dates between 2 dates from every row in one array
I'm trying to get an array of all dates between the 2 dates which im getting out the database for each row. for example there is 3 rows with 2017-02-02 and 2017-02-03 and a row with 2017-02-18 and 2017-02-20 I would like to get an array with the output [2017-02-02, 2017-02-03, 2017-02-18, 2017-02-19, 2017-02-20]

So far I have a query which gets all of the dates and echo's the start and end date and a script to get an array with the dates between 2 dates.

How can I make it work so it's getting all the dates of every row into one array?

```<code><?php
    $result = mysqli_query($con, "SELECT * FROM invoice_line WHERE car_car_id = $id");
    while ($auto = mysqli_fetch_array($result)) {
    ?>
          <h2 class="title_car">
            <?php echo $auto['start_date'] . ' - ' . $auto['end_date'];?>
          </h2>
        <hr>
        <?php $dateRange = getDateRange($auto['start_date'], $auto['end_date']); ?>
    <?php } ?>

    <?php
    function getDateRange($startDate, $endDate, $format="Y-m-d")
{
    //Create output variable
    $datesArray = array();
    //Calculate number of days in the range
    $total_days = round(abs(strtotime($endDate) - strtotime($startDate)) / 86400, 0) + 1;
    //Populate array of weekdays and counts
    for($day=0; $day<$total_days; $day++)
    {
        $datesArray[] = date($format, strtotime("{$startDate} + {$day} days"));
    }
    //Return results array
    return $datesArray;
}

print_r($dateRange);
?>
</code>```

答:
You can use DatePeriod class.

Your code would something like this:

```<code><?php
$rows = [
    [ new DateTime(), (new DateTime())->modify('+3 days') ],
    [ (new DateTime())->modify('+20 days'), (new DateTime())->modify('+30 days') ],
];

$dates = [];

foreach ($rows as $row) {
    $dateRange = new DatePeriod($row[0], new DateInterval('P1D'), $row[1]);

    foreach ($dateRange as $date) {
        $dates[] = $date;
    }
}

var_dump($dates);
</code>```

Body:
I'm trying to get an array of all dates between the 2 dates which im getting out the database for each row. for example there is 3 rows with 2017-02-02 and 2017-02-03 and a row with 2017-02-18 and 2017-02-20 I would like to get an array with the output [2017-02-02, 2017-02-03, 2017-02-18, 2017-02-19, 2017-02-20]

So far I have a query which gets all of the dates and echo's the start and end date and a script to get an array with the dates between 2 dates.

How can I make it work so it's getting all the dates of every row into one array?

<?php
    $result = mysqli_query($con, "SELECT * FROM invoice_line WHERE car_car_id = $id");
    while ($auto = mysqli_fetch_array($result)) {
    ?>

            <?php echo $auto['start_date'] . ' - ' . $auto['end_date'];?>

        <?php $dateRange = getDateRange($auto['start_date'], $auto['end_date']); ?>
    <?php } ?>

    <?php
    function getDateRange($startDate, $endDate, $format="Y-m-d")
{
    //Create output variable
    $datesArray = array();
    //Calculate number of days in the range
    $total_days = round(abs(strtotime($endDate) - strtotime($startDate)) / 86400, 0) + 1;
    //Populate array of weekdays and counts
    for($day=0; $day<$total_days; $day++)
    {
        $datesArray[] = date($format, strtotime("{$startDate} + {$day} days"));
    }
    //Return results array
    return $datesArray;
}

print_r($dateRange);
?>

Body:
You can use DatePeriod class.

Your code would something like this:

<?php
$rows = [
    [ new DateTime(), (new DateTime())->modify('+3 days') ],
    [ (new DateTime())->modify('+20 days'), (new DateTime())->modify('+30 days') ],
];

$dates = [];

foreach ($rows as $row) {
    $dateRange = new DatePeriod($row[0], new DateInterval('P1D'), $row[1]);

    foreach ($dateRange as $date) {
        $dates[] = $date;
    }
}

var_dump($dates);


问:
Is it legit to sign two apps with two different keystores, if need to be distributed under one company name?
I have a situation, where I might use two keystores for two different applications made in the same company, one with Android and one with Unity. But I have never seen any company to use more than one Keystore for signing their apps, I have verified this comparing Google, Facebook, etc apps. So, is it legit according to the market and logical according to the devs to have two keystores for the two apps made by the same company.

Note : We need to distribute the apps over the world.

答: Google Play identifies your app using the key used to sign it. If you use two different keys to sign an APK generated from the same code base, Google Play will treat it as two different apps. I am not sure why you would do this, but I am not aware of any policies that prohibit it, either.</p>


问:
Run php script as daemon process
I need to run a php script as daemon process (wait for instructions and do stuff). cron job will not do it for me because actions need to be taken as soon as instruction arrives. I know PHP is not really the best option for daemon processes due to memory management issues, but due to various reasons I have to use PHP in this case. I came across a tool by libslack called Daemon (http://libslack.org/daemon) it seems to help me manage daemon processes, but there hasn't been any updates in the last 5 years, so I wonder if you know some other alternatives suitable for my case. Any information will be really appreciated.</p>

答:
With new  systemd you can create a service.

You must create a file or a symlink in  /etc/systemd/system/, eg. myphpdaemon.service and place content like this one, myphpdaemon will be the name of the service:

```<code>[Unit]
Description=My PHP Daemon Service
#May your script needs MySQL or other services to run, eg. MySQL Memcached
Requires=mysqld.service memcached.service
After=mysqld.service memcached.service

[Service]
User=root
Type=simple
TimeoutSec=0
PIDFile=/var/run/myphpdaemon.pid
ExecStart=/usr/bin/php -f /srv/www/myphpdaemon.php arg1 arg2> /dev/null 2>/dev/null
#ExecStop=/bin/kill -HUP $MAINPID #It's the default you can change whats happens on stop command
#ExecReload=/bin/kill -HUP $MAINPID
KillMode=process

Restart=on-failure
RestartSec=42s

StandardOutput=null #If you don't want to make toms of logs you can set it null if you sent a file or some other options it will send all PHP output to this one.
StandardError=/var/log/myphpdaemon.log
[Install]
WantedBy=default.target
</code>```

You will be able to start, get status, restart and stop  the services using the command

systemctl <start|status|restart|stop|enable> myphpdaemon

You can use the PHP native server using php -S 127.0.0.1:<port> or run it as a script. Using a PHP script you should have a kind of "forever loop" to continue running.

```<code><?php
gc_enable();//
while (!connection_aborted() || PHP_SAPI == "cli") {

  //Code Logic

  //sleep and usleep could be useful
    if (PHP_SAPI == "cli") {
        if (rand(5, 100) % 5 == 0) {
            gc_collect_cycles(); //Forces collection of any existing garbage cycles
        }
    }
}
</code>```

Working example:

```<code>[Unit]
Description=PHP APP Sync Service
Requires=mysqld.service memcached.service
After=mysqld.service memcached.service

[Service]
User=root
Type=simple
TimeoutSec=0
PIDFile=/var/run/php_app_sync.pid
ExecStart=/bin/sh -c '/usr/bin/php -f /var/www/app/private/server/cron/app_sync.php  2>&1 > /var/log/app_sync.log'
KillMode=mixed

Restart=on-failure
RestartSec=42s

[Install]
WantedBy=default.target
</code>```

If your PHP routine should be executed once in a cycle (like a diggest)  you may use a shell or bash script to be invoked into systemd service file instead of PHP directly, for example:

```<code>#!/usr/bin/env bash
script_path="/app/services/"

while [ : ]
do
#    clear
    php -f "$script_path"${1}".php" fixedparameter ${2}  > /dev/null 2>/dev/null
    sleep 1
done
</code>```

If you chose these option you should change the KillMode to mixed to processes, bash(main) and PHP(child) be killed.

```<code>ExecStart=/app/phpservice/runner.sh phpfile parameter  > /dev/null 2>/dev/null
KillMode=process
</code>```

This method also is effective if you're facing a memory leak.

Note: Every time that you change your "myphpdaemon.service" you must
run `systemctl daemon-reload', but do worry if you do not do, it will be
alerted when is needed.

ContentLicense: CC BY-SA 2.5

Title: Run php script as daemon process

Body:
With new  systemd you can create a service.

You must create a file or a symlink in  /etc/systemd/system/, eg. myphpdaemon.service and place content like this one, myphpdaemon will be the name of the service:

[Unit]
Description=My PHP Daemon Service
#May your script needs MySQL or other services to run, eg. MySQL Memcached
Requires=mysqld.service memcached.service
After=mysqld.service memcached.service

[Service]
User=root
Type=simple
TimeoutSec=0
PIDFile=/var/run/myphpdaemon.pid
ExecStart=/usr/bin/php -f /srv/www/myphpdaemon.php arg1 arg2> /dev/null 2>/dev/null
#ExecStop=/bin/kill -HUP $MAINPID #It's the default you can change whats happens on stop command
#ExecReload=/bin/kill -HUP $MAINPID
KillMode=process

Restart=on-failure
RestartSec=42s

StandardOutput=null #If you don't want to make toms of logs you can set it null if you sent a file or some other options it will send all PHP output to this one.
StandardError=/var/log/myphpdaemon.log
[Install]
WantedBy=default.target

You will be able to start, get status, restart and stop  the services using the command

systemctl <start|status|restart|stop|enable> myphpdaemon

You can use the PHP native server using php -S 127.0.0.1:<port> or run it as a script. Using a PHP script you should have a kind of "forever loop" to continue running.

<?php
gc_enable();//
while (!connection_aborted() || PHP_SAPI == "cli") {

  //Code Logic

  //sleep and usleep could be useful
    if (PHP_SAPI == "cli") {
        if (rand(5, 100) % 5 == 0) {
            gc_collect_cycles(); //Forces collection of any existing garbage cycles
        }
    }
}

Working example:

[Unit]
Description=PHP APP Sync Service
Requires=mysqld.service memcached.service
After=mysqld.service memcached.service

[Service]
User=root
Type=simple
TimeoutSec=0
PIDFile=/var/run/php_app_sync.pid
ExecStart=/bin/sh -c '/usr/bin/php -f /var/www/app/private/server/cron/app_sync.php  2>&1 > /var/log/app_sync.log'
KillMode=mixed

Restart=on-failure
RestartSec=42s

[Install]
WantedBy=default.target

If your PHP routine should be executed once in a cycle (like a diggest)  you may use a shell or bash script to be invoked into systemd service file instead of PHP directly, for example:

#!/usr/bin/env bash
script_path="/app/services/"

while [ : ]
do
#    clear
    php -f "$script_path"${1}".php" fixedparameter ${2}  > /dev/null 2>/dev/null
    sleep 1
done

If you chose these option you should change the KillMode to mixed to processes, bash(main) and PHP(child) be killed.

ExecStart=/app/phpservice/runner.sh phpfile parameter  > /dev/null 2>/dev/null
KillMode=process

This method also is effective if you're facing a memory leak.

Note: Every time that you change your "myphpdaemon.service" you must
run `systemctl daemon-reload', but do worry if you do not do, it will be
alerted when is needed.


问:
Curious behaviour of std::string::operator[] in MSVC
I've been using some semi-iterators to tokenize a std::string, and I've run into a curious problem with operator[]. When constructing a new string from a position using char*, I've used something like the following:

```<code>t.begin = i;
t.end = i + 1;
t.contents = std::string(&arg.second[t.begin], &arg.second[t.end]);
</code>```

where arg.second is a std::string. But, if i is the position of the last character, then arg.second[t.end] will throw a debugging assertion- even though taking a pointer of one-past-the-end is well defined behaviour and even common for primitive arrays, and since the constructor is being called using iterators I know that the end iterator will never be de-referenced. Doesn't it seem logical that arg.second[arg.second.size()] should be a valid expression, producing the equivalent of arg.second.end() as a char*?

答:
What is well-defined is creating an iterator one past the end. (Pointers might be iterators, too.) However, dereferencing such an iterator will yield Undefined Behavior.

Now, what you're doing is array subscription, and that is very different from forming iterators, because it returns a reference to the referred-to object (much akin to dereferencing an iterator). You are certainly not allowed to access an array one-past-the-end.

Body:
I've been using some semi-iterators to tokenize a std::string, and I've run into a curious problem with operator[]. When constructing a new string from a position using char*, I've used something like the following:

t.begin = i;
t.end = i + 1;
t.contents = std::string(&arg.second[t.begin], &arg.second[t.end]);

where arg.second is a std::string. But, if i is the position of the last character, then arg.second[t.end] will throw a debugging assertion- even though taking a pointer of one-past-the-end is well defined behaviour and even common for primitive arrays, and since the constructor is being called using iterators I know that the end iterator will never be de-referenced. Doesn't it seem logical that arg.second[arg.second.size()] should be a valid expression, producing the equivalent of arg.second.end() as a char*?


问:
Add two quotes in JavaScript
I have a code like this :

 var event = {
  "temperature" : 12.45,
  "humidite" : 45.78,
  "built" : "charone",
  "fire" : "chartwo",
  "topic" : "sk1_001/data"
 };

var keys = Object.keys(event);

 valeurs_d = "";
 for (var i = 0; i < keys.length -1 ; i++)
 valeurs_d += event[keys[i]] + ", ";
 var str5 = ",";
 var str6 = str5.concat(valeurs_d);
 var valeurs = str6.substring (0, str6.length - 2);  console.log(valeurs); ```
</div>
</div>
</p>

<p>I want to have everything between two quotes in variable <code>valeurs</code> like this:</p>

<pre class="lang-none prettyprint-override"><code>, '12 .45 ', '45 .78', 'charone', 'chartwo'
</code>```

Or, just have the character strings between two quotes:

, 12.45, 45.78, 'charone', 'chartwo'
```

I can have in my JSON other strings.

How can I do this in JavaScript?

答:
Quite simply,

 var event = {
  "temperature" : 12.45,
  "humidite" : 45.78,
  "built" : "charone",
  "fire" : "chartwo",
  "topic" : "sk1_001/data"
 };

var keys = Object.keys(event);

 valeurs_d = "";
 for (var i = 0; i < keys.length -1 ; i++)
 valeurs_d += "\'" + event[keys[i]]+ "\'" + ", ";
 var str5 = ",";
 var str6 = str5.concat(valeurs_d);
 var valeurs = str6.substring(0, str6.length - 2);  console.log(valeurs); ```

Just escape those single quotes and concatenate them to your values.

If you want a double quote in your string, then use "\"" instead of "\'".

Title: Add two quotes in JavaScript

Body:
I have a code like this :

 var event = {
  "temperature" : 12.45,
  "humidite" : 45.78,
  "built" : "charone",
  "fire" : "chartwo",
  "topic" : "sk1_001/data"
 };

var keys = Object.keys(event);

 valeurs_d = "";
 for (var i = 0; i < keys.length -1 ; i++)
 valeurs_d += event[keys[i]] + ", ";
 var str5 = ",";
 var str6 = str5.concat(valeurs_d);
 var valeurs = str6.substring (0, str6.length - 2);  console.log(valeurs);

I want to have everything between two quotes in variable valeurs like this:

, '12 .45 ', '45 .78', 'charone', 'chartwo'

Or, just have the character strings between two quotes:

, 12.45, 45.78, 'charone', 'chartwo'

I can have in my JSON other strings.

How can I do this in JavaScript?

Body:
Quite simply,

 var event = {
  "temperature" : 12.45,
  "humidite" : 45.78,
  "built" : "charone",
  "fire" : "chartwo",
  "topic" : "sk1_001/data"
 };

var keys = Object.keys(event);

 valeurs_d = "";
 for (var i = 0; i < keys.length -1 ; i++)
 valeurs_d += "\'" + event[keys[i]]+ "\'" + ", ";
 var str5 = ",";
 var str6 = str5.concat(valeurs_d);
 var valeurs = str6.substring(0, str6.length - 2);  console.log(valeurs);

Just escape those single quotes and concatenate them to your values.

If you want a double quote in your string, then use "\"" instead of "\'".


问:
Where to start with teaching an AI to play SNES games?
I have had an infatuation with a certain concept regarding machine learning that Sethbling proved with his Mar.io program: https://youtu.be/qv6UVOQ0F44

I have a decent amount of logical programming experience in a number of different languages and have read around a lot about machine learning and neural networking.

What I'm looking for is a good set of references that could teach me how to apply neural networks in code, rather than just as a mathematical teaching like most of what I have seen thus far.

Thanks in advance!

答:
Sentdex (https://www.youtube.com/user/sentdex) has incredible tutorials on Youtube and walks through teaching a model to play GTA. </p>

<p>It may seem daunting at first, but the rewards of overcoming such a challenging task will be worth it. </p>

Body:
Sentdex (https://www.youtube.com/user/sentdex) has incredible tutorials on Youtube and walks through teaching a model to play GTA.

It may seem daunting at first, but the rewards of overcoming such a challenging task will be worth it.