问:
Ignoring Duplicate Records SQL
In need of some help :)

So I have a table of records with the following columns:

```<code>Key (PK, FK, int) DT (smalldatetime) Value (real)
</code>```

The DT is a datetime for every half hour of the day with an associated value

E.g.

```<code>Key       DT                       VALUE
1000      2010-01-01 08:00:00      80
1000      2010-01-01 08:30:00      75
1000      2010-01-01 09:00:00      100
</code>```

I have a Query that finds the max value every 24 hour period and its associated time however, on one day the max value occurs twice and hence duplicates the date which is causing processing issues. I have tried using rownumber() which works but I can't use a calculated column in my where clause?
Currently I have:

```<code>SELECT       cast(T1.DT as date) as 'Date',Cast(T1.DT as time(0)) as 'HH', ROW_NUMBER() over (PARTITION BY  cast(DT as date) ORDER BY DT) AS 'RowNumber'
FROM        TABLE_1 AS T1
INNER JOIN  (
                SELECT CAST([DT] as date) as 'DATE'
                ,       MAX([VALUE]) as 'MAX_HH'
                FROM    TABLE_1
                WHERE   DT > '6-nov-2016' and [KEY] = '1000'
                GROUP BY CAST([DT] as date)
            ) AS MAX_DT
        ON  MAX_DT.[DATE] = CAST(T1.[DT] as date)
        AND T1.VALUE = MAX_DT.MAX_HH
WHERE       DT > '6-nov-2016' and [KEY] = '1000'
ORDER BY DT
</code>```

This results in

```<code>Key       DT               VALUE       HH
1000      2010-01-01       80          07:00:00
1000      2010-02-01       100         17:30:00
1000      2010-02-01       100         18:00:00
</code>```

I need to remove the duplicate date (I Have no preference which HH it takes)

I think I've explained that terribly, let me know if it makes no sense and i'll try and re write

Any ideas?

答:
Can you try this the new code is in ** **:

```<code> SELECT       cast(T1.DT as date) as 'Date', ** MIN(Cast(T1.DT as time(0))) as 'HH' **
    FROM        TABLE_1 AS T1
    INNER JOIN  (
                    SELECT CAST([DT] as date) as 'DATE'
                    ,       MAX([VALUE]) as 'MAX_HH'
                FROM    TABLE_1
                WHERE   DT > '6-nov-2016' and [KEY] = '1000'
                GROUP BY CAST([DT] as date)
            ) AS MAX_DT
        ON  MAX_DT.[DATE] = CAST(T1.[DT] as date)
        AND T1.VALUE = MAX_DT.MAX_HH
WHERE       DT > '6-nov-2016' and [KEY] = '1000'
</code>```

here put the group by

```<code>GROUP BY cast(T1.DT as date)
ORDER BY DT
</code>```

Title: Ignoring Duplicate Records SQL

Body:
In need of some help :)

So I have a table of records with the following columns:

Key (PK, FK, int) DT (smalldatetime) Value (real)

The DT is a datetime for every half hour of the day with an associated value

E.g.

Key       DT                       VALUE
1000      2010-01-01 08:00:00      80
1000      2010-01-01 08:30:00      75
1000      2010-01-01 09:00:00      100

I have a Query that finds the max value every 24 hour period and its associated time however, on one day the max value occurs twice and hence duplicates the date which is causing processing issues. I have tried using rownumber() which works but I can't use a calculated column in my where clause?
Currently I have:

SELECT       cast(T1.DT as date) as 'Date',Cast(T1.DT as time(0)) as 'HH', ROW_NUMBER() over (PARTITION BY  cast(DT as date) ORDER BY DT) AS 'RowNumber'
FROM        TABLE_1 AS T1
INNER JOIN  (
                SELECT CAST([DT] as date) as 'DATE'
                ,       MAX([VALUE]) as 'MAX_HH'
                FROM    TABLE_1
                WHERE   DT > '6-nov-2016' and [KEY] = '1000'
                GROUP BY CAST([DT] as date)
            ) AS MAX_DT
        ON  MAX_DT.[DATE] = CAST(T1.[DT] as date)
        AND T1.VALUE = MAX_DT.MAX_HH
WHERE       DT > '6-nov-2016' and [KEY] = '1000'
ORDER BY DT

This results in

Key       DT               VALUE       HH
1000      2010-01-01       80          07:00:00
1000      2010-02-01       100         17:30:00
1000      2010-02-01       100         18:00:00

I need to remove the duplicate date (I Have no preference which HH it takes)

I think I've explained that terribly, let me know if it makes no sense and i'll try and re write

Any ideas?

Body:
Can you try this the new code is in ** **:

 SELECT       cast(T1.DT as date) as 'Date', ** MIN(Cast(T1.DT as time(0))) as 'HH' **
    FROM        TABLE_1 AS T1
    INNER JOIN  (
                    SELECT CAST([DT] as date) as 'DATE'
                    ,       MAX([VALUE]) as 'MAX_HH'
                FROM    TABLE_1
                WHERE   DT > '6-nov-2016' and [KEY] = '1000'
                GROUP BY CAST([DT] as date)
            ) AS MAX_DT
        ON  MAX_DT.[DATE] = CAST(T1.[DT] as date)
        AND T1.VALUE = MAX_DT.MAX_HH
WHERE       DT > '6-nov-2016' and [KEY] = '1000'

here put the group by

GROUP BY cast(T1.DT as date)
ORDER BY DT


来源: stackexchange

问:
How to declare an array of strings in C++?
I am trying to iterate over all the elements of a static array of strings in the best possible way. I want to be able to declare it on one line and easily add/remove elements from it without having to keep track of the number. Sounds really simple, doesn't it?

Possible non-solutions:

```<code>vector<string> v;
v.push_back("abc");
b.push_back("xyz");

for(int i = 0; i < v.size(); i++)
    cout << v[i] << endl;
</code>```

Problems - no way to create the vector on one line with a list of strings

Possible non-solution 2:

```<code>string list[] = {"abc", "xyz"};
</code>```

Problems - no way to get the number of strings automatically (that I know of).

There must be an easy way of doing this.

答:
```<code>#include <boost/foreach.hpp>

const char* list[] = {"abc", "xyz"};
BOOST_FOREACH(const char* str, list)
{
    cout << str << endl;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to iterate over all the elements of a static array of strings in the best possible way. I want to be able to declare it on one line and easily add/remove elements from it without having to keep track of the number. Sounds really simple, doesn't it?

Possible non-solutions:

vector<string> v;
v.push_back("abc");
b.push_back("xyz");

for(int i = 0; i < v.size(); i++)
    cout << v[i] << endl;

Problems - no way to create the vector on one line with a list of strings

Possible non-solution 2:

string list[] = {"abc", "xyz"};

Problems - no way to get the number of strings automatically (that I know of).

There must be an easy way of doing this.

OwnerDisplayName: Ben Straub

ContentLicense: CC BY-SA 2.5


问:
Detecting drop into textarea with Javascript
All I need is to be able to detect when text is dropped into a Textarea.  I then take that text and do stuff with it and clear the textarea.  There may be many of these textareas and very high UI expectations, so polling is a last resort.

For IE, "onfocus" does the trick, since this event is fired after the user drops stuff into the textarea.

For Firefox, I can't find an event that works.  I've tried onmouseup and onchange.. don't know what else to try from there.  I'd hate to have to poll the textarea for content.  Help much appreciated.  Thanks.

Edit:  For clarification, "dropped" means the user selects text (usually) from the page, but it doesn't matter where, drags it, and drops it into the textarea.  This is not the same as Ctrl+V, or right click pasting (which take two different methods of detection, BTW), or (obviously) typing into the textarea.  Specifically, it is the "drop" aspect of drag and drop.  I really don't know how else to phrase it.

I feel this question was stated rather accurately.  To humor me, assume that I meant any of the other operations on a textarea that you all have chosen to share.  If I meant "pasting", don't you think I would have mentioned something about pasting in the title or content of my question?  Same goes for typing in a textarea.  But, perhaps, you all just don't know me well enough to know that I type what I mean, rather than mistakingly typing things only somewhat related to what I mean.

答:
What do you mean by "dropped"? Are you talking about a paste (^V) operation? If so Aron's answer is indeed correct, you will get keydown/keyup (and the value will be readable in keyup).

A generic callback that will happen on any update to an input is 'onchange' - you could try that. Note that when typing, it doesn't get called until you finish and unfocus the input, so if you need instant updates on both typing and other forms of input, you still need 'onkeyup' as well.

Edit re clarification: IMO 'onchange' should be fired when a drag-and-drop causes content to be added to a text area; I consider it a browser bug that it is not (in Firefox at least). I can only concur in this case that polling is all you have left.

OwnerDisplayName: sam

LastEditorDisplayName: sam

OwnerDisplayName: bobince

LastEditorDisplayName: bobince


问:
How to combine UPDATE query with subquery?
In my Mysql database I want to update a field fup for all records which I found using this select statement:

```<code>SELECT ic.hash
FROM incompany as ic, app
WHERE ic.id = app.ic_id;
</code>```

So I created the following combined query:

```<code>UPDATE incompany
SET fup = 'x'
WHERE hash IN (SELECT ic.hash
FROM incompany as ic, app
WHERE ic.id = app.ic_id);
</code>```

But this query gives me the following error:

You can't specify target table 'incompany' for update in FROM clause

Does anybody know how I can make this work? All tips are welcome!

答:
You do not need a subquery. You might use INNER JOIN to set the criteria to link the incompany table to the app table and to the another alias for incompany table.

```<code>UPDATE incompany I
INNER JOIN app A ON I.id = A.ic_id
INNER JOIN incompany I2 ON I.hash = I2.hash
SET I.fup = 'x'
</code>```

Body:
In my Mysql database I want to update a field fup for all records which I found using this select statement:

SELECT ic.hash
FROM incompany as ic, app
WHERE ic.id = app.ic_id;

So I created the following combined query:

UPDATE incompany
SET fup = 'x'
WHERE hash IN (SELECT ic.hash
FROM incompany as ic, app
WHERE ic.id = app.ic_id);

But this query gives me the following error:

You can't specify target table 'incompany' for update in FROM clause

Does anybody know how I can make this work? All tips are welcome!

Body:
You do not need a subquery. You might use INNER JOIN to set the criteria to link the incompany table to the app table and to the another alias for incompany table.

UPDATE incompany I
INNER JOIN app A ON I.id = A.ic_id
INNER JOIN incompany I2 ON I.hash = I2.hash
SET I.fup = 'x'


问:
Unable to get Clickable button in UI Automator Viewer
I am trying to automate clickable button for a react-native based Application. I was stopped getting clickable button as in UI Automator Viewer displaying clickable button status FALSE. So, can you suggest me any other alternative way to automate the clickable action using Appium.

Using Selenium 3.5.3 version, Appium for Windows 1_4_16_1.

Image 1

Image2

答:
First: start using appium-desktop and not an old appium server 1.4.16, but 1.7.x

Second: ReactNative app is interpreted as Native application, so you need to use Appium on client side, not Selenium

Final: In appium-desktop you can directly try to click your button to see if it works.


问:
Pandoc - Can you change margins and fontsize simultaneously?
Sample Markdown used as a Reproducible Example (GitHub hyperlink)

I pasted the markdown from the hyperlink above into the Atom text editor and saved it as a documentation.md file. I can run the following two seperate Pandoc commands and each of them works to reduce the margins on my pdf -and- increase the font size to 12 on the output pdf.

pandoc -s -V documentation.md geometry:margin=1in -o documentation.pdf

pandoc -s -V documentation.md fontsize=12 -o documentation.pdf

When I combine the two commands into the following I get the error shown below. Is there a problem in my Pandoc syntax?

pandoc -s -V documentation.md geometry:margin=1in fontsize=12 -o documentation.pdf

pandoc geometry:margin=1in openBinaryFile: does not exist (No such file or
  directory)

答:
You have to write the -V twice as well, directly in front of the variable options you want to set:

```<code>pandoc -s documentation.md -V geometry:margin=1in -V fontsize=12 -o documentation.pdf
</code>```

see http://pandoc.org/getting-started.html and http://pandoc.org/MANUAL.html

Body:
You have to write the -V twice as well, directly in front of the variable options you want to set:

pandoc -s documentation.md -V geometry:margin=1in -V fontsize=12 -o documentation.pdf

see http://pandoc.org/getting-started.html and http://pandoc.org/MANUAL.html


问:
Objective-C How to get unicode character
I want to get unicode code point for a given unicode character in Objective-C. NSString said it internal use UTF-16 encoding and said,

The NSString class has two primitive methods—length and characterAtIndex:—that provide the basis for all other methods in its interface. The length method returns the total number of Unicode characters in the string. characterAtIndex: gives access to each character in the string by index, with index values starting at 0.

That seems assume characterAtIndex method is unicode aware. However it return unichar is a 16 bits unsigned int type.

```<code>- (unichar)characterAtIndex:(NSUInteger)index
</code>```

The questions are:

Q1: How it present unicode code point above UFFFF?

Q2: If Q1 make sense, is there method to get unicode code point for a given unicode character in Objective-C.

Thx.

答:
From the documentation of length:

The number returned includes the
  individual characters of composed
  character sequences, so you cannot use
  this method to determine if a string
  will be visible when printed or how
  long it will appear.

From this, I would infer that any characters above U+FFFF would be counted as two characters and would be encoded as a Surrogate Pair (see the relevant entry at http://unicode.org/glossary/).

If you have a UTF-32 encoded string with the character you wish to convert, you could create a new NSString with initWithBytesNoCopy:length:encoding:freeWhenDone: and use the result of that to determine how the character is encoded in UTF-16, but if you're going to be doing much heavy Unicode processing, your best bet is probably to get familiar with ICU (http://site.icu-project.org/).

Body:
I want to get unicode code point for a given unicode character in Objective-C. NSString said it internal use UTF-16 encoding and said,

The NSString class has two primitive methods—length and characterAtIndex:—that provide the basis for all other methods in its interface. The length method returns the total number of Unicode characters in the string. characterAtIndex: gives access to each character in the string by index, with index values starting at 0.

That seems assume characterAtIndex method is unicode aware. However it return unichar is a 16 bits unsigned int type.

- (unichar)characterAtIndex:(NSUInteger)index

The questions are:

Q1: How it present unicode code point above UFFFF?

Q2: If Q1 make sense, is there method to get unicode code point for a given unicode character in Objective-C.

Thx.


问:
SQL getting sum and all rows in one go
I am trying to get the total sum of the column amount and all the rows at the same time.

```<code>SELECT sum(orders.amount) as total, orders.transactionID, orders.itemid, products.id,
products.category, products.price
FROM db.orders
INNER JOIN db.products
ON orders.itemid = products.id
WHERE transactionID = '012906ea51c14b0881c4785527c606dd'
</code>```

The query above only gives me the total value and only one row (I also want to have all the rows)

```<code>SELECT sum(orders.amount) as total, orders.transactionID, orders.itemid, products.id,
products.category, products.price
FROM db.orders
INNER JOIN db.products
ON orders.itemid = products.id
WHERE transactionID = '012906ea51c14b0881c4785527c606dd'
GROUP BY orders.id
</code>```

While the second query gives me every row but incorrect total of orders.amount

Can this be done?

(I made the two queries a little shorter)

Thanks

答:
You can use a "running total", meaning, using a variable and summarize the values yourself. The correct sum will appear in the last row of your result set.

```<code>SELECT @my_sum := @my_sum + orders.amount as running_total,
orders.transactionID,
orders.itemid,
products.id,
products.category,
products.price
FROM db.orders
INNER JOIN db.products
ON orders.itemid = products.id
CROSS JOIN (SELECT @my_sum:=0) AS var_init_subquery
WHERE transactionID = '012906ea51c14b0881c4785527c606dd'
</code>```

read more about user variables here

Also have a look at Raymond Nijland's comment:

Query 1.. SUM without GROUP BY always generates 1 row. Query 2 is a invalid use off GROUP BY read https://www.psce.com/en/blog/2012/05/15/mysql-mistakes-do-you-use-group-by-correctly/

Title: SQL getting sum and all rows in one go

Body:
I am trying to get the total sum of the column amount and all the rows at the same time.

SELECT sum(orders.amount) as total, orders.transactionID, orders.itemid, products.id,
products.category, products.price
FROM db.orders
INNER JOIN db.products
ON orders.itemid = products.id
WHERE transactionID = '012906ea51c14b0881c4785527c606dd'

The query above only gives me the total value and only one row (I also want to have all the rows)

SELECT sum(orders.amount) as total, orders.transactionID, orders.itemid, products.id,
products.category, products.price
FROM db.orders
INNER JOIN db.products
ON orders.itemid = products.id
WHERE transactionID = '012906ea51c14b0881c4785527c606dd'
GROUP BY orders.id

While the second query gives me every row but incorrect total of orders.amount

Can this be done?

(I made the two queries a little shorter)

Thanks

Body:
You can use a "running total", meaning, using a variable and summarize the values yourself. The correct sum will appear in the last row of your result set.

SELECT @my_sum := @my_sum + orders.amount as running_total,
orders.transactionID,
orders.itemid,
products.id,
products.category,
products.price
FROM db.orders
INNER JOIN db.products
ON orders.itemid = products.id
CROSS JOIN (SELECT @my_sum:=0) AS var_init_subquery
WHERE transactionID = '012906ea51c14b0881c4785527c606dd'

read more about user variables here

Also have a look at Raymond Nijland's comment:

Query 1.. SUM without GROUP BY always generates 1 row. Query 2 is a invalid use off GROUP BY read https://www.psce.com/en/blog/2012/05/15/mysql-mistakes-do-you-use-group-by-correctly/


问:
How to zoom chart specific area in Excel Using Macro
Hy Everyone,

I have a sheet with chart that has many values with X-Axis. These values are many in numbers some time I feel difficult to view them, So I want to zoom the any area of the chart by selecting any where in the chart. I used recorded macro that only zoom  sheet not Chart / Graph. But I want a macro that can zoom any specific area of the chart or graph any where I click or select..

Here is pictures of the sheets...

答:
My suggestion is to limit the x-axis (minimum and maximum) and probably limit the max value of the y-axis. This way it will only show a part of the data within the chart which might result in a better resolution to view then. But there is no built-in zoom like you described. Therefore you will need to code that on your own.

(Sorry for the german screenshot …)

As you see in the example above. I have total data in x-axis from 0 to 450 and in the second chart I limited the x-axis from 100 to 200. Both charts have the same source data, but the second only shows a part of the first.


问:
SVN/Tortoise SVN - can connect to repository, but not create folders
I'm missing a step somewhere, I just don't know where.

I have SVN set up and running on a remote server (svn.mydomain.com/svn) and I can browse the repository from my local machine using repo-browser, but when I try to create a new directory or add a new file I get an "Authorization Failed!" message.

But I was never asked to input my credentials! I have a user/pass set up on the server in the passwd file, if I could just figure out how to supply those credentials from my local machine.

I've tried the trick of going into TortoiseSVN Settings/Saved Data/Authentication Data to clear the cache, but that button is grayed out, so apparently I have no stored authentication data to delete. So why isn't TortoiseSVN prompting me to supply credentials, instead of just throwing up an "Authorization Failed!" message?

答:
As stated in the comments of the question, you need to check the casing of your URL, for example svn.mydomain.com/svn vs svn.MyDomain.com/SVN.

To change your URL, you can right click in your working copy's folder, go to TortoiseSVN -> Relocate... and change the casing as required:


问:
Aligning an image with text
I'm creating a very basic placeholder site. Centered, in the middle of the page, it should read:

(COMPANY LOGO) WEBSITE COMING IN 2018

The company logo uses the same font as the text.

By default the image sits alongside the text nicely, however this changes when I attempt to align it centrally.

body {
  background-color: #fff;
  background-size: cover;
  text-align: center;
}

img {
  float: left;
  width: 350px;
}

h1 {
  position: relative;
  top: 18px;
  left: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div class="header">
    <img src="http://via.placeholder.com/350x100" alt="logo" />
    <h1>WEBSITE COMING IN 2018</h1>
  </div>
</body></code>```

What would be the most effective way to do this?

答:
You can use display: flex; as follows on your .headerelement

body {
  background-color: #fff;
}

img {
  width: 200px;
}

h1 {
  margin-left: 10px;
  line-height: 100%;
}

.header {
  display: flex;
  justify-content: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div class="header">
    <img src="http://via.placeholder.com/350x100" alt="logo" />
    <h1>Website Coming in 2018</h1>
  </div>
</body></code>```

Note: the slight vertical offset of the text is due to the space below its baseline which is reserved for letters like j, g , p etc. which extend below the baseline. As soon as you use any of these letters in your text it will be perfectly centered. I changed the uppercase letters to regular text mode to demonstrate this.

Title: Aligning an image with text

Body:
I'm creating a very basic placeholder site. Centered, in the middle of the page, it should read:

(COMPANY LOGO) WEBSITE COMING IN 2018

The company logo uses the same font as the text.

By default the image sits alongside the text nicely, however this changes when I attempt to align it centrally.

body {
  background-color: #fff;
  background-size: cover;
  text-align: center;
}

img {
  float: left;
  width: 350px;
}

h1 {
  position: relative;
  top: 18px;
  left: 10px;
}

WEBSITE COMING IN 2018

What would be the most effective way to do this?

Body:
You can use display: flex; as follows on your .headerelement

body {
  background-color: #fff;
}

img {
  width: 200px;
}

h1 {
  margin-left: 10px;
  line-height: 100%;
}

.header {
  display: flex;
  justify-content: center;
}

<body>
  <div class="header">
    <img src="http://via.placeholder.com/350x100" alt="logo" />
    <h1>Website Coming in 2018</h1>
  </div>
</body>

Note: the slight vertical offset of the text is due to the space below its baseline which is reserved for letters like j, g , p etc. which extend below the baseline. As soon as you use any of these letters in your text it will be perfectly centered. I changed the uppercase letters to regular text mode to demonstrate this.


问:
Generic async HttpClient method sometimes doesn't work?
I'm creating an application with Xamarin.Forms which consume from SOAP services using POST method; I have a bunch of services that work correctly, indeed, one of these methods is used to send information in multiple cases and my problem is related with this.

I have the following HttpClient method, but sometimes doesn't work... unfortunately I don't have access to back-end code and they are not for the labour of help me with that.

Any idea about how to improve my method or get any approach to the real error? I'm stuck here, since I send the same fields each time.

```<code>public async Task<string> InvokeAsync (string uri, string xmlSOAP) {
try {
    using (var handler = new HttpClientHandler () { UseCookies = false })

    using (var client = new HttpClient (new NativeMessageHandler ())) {
        client.DefaultRequestHeaders.Accept.Add (new MediaTypeWithQualityHeaderValue ("application/xml"));
        client.DefaultRequestHeaders.Add ("Cache-Control", "no-cache, no-store, must-revalidate");
        client.DefaultRequestHeaders.Add ("Pragma", "no-cache");
        client.Timeout = TimeSpan.FromSeconds (timeout);
        client.DefaultRequestHeaders.CacheControl.NoCache = true;

        var req = new HttpRequestMessage (HttpMethod.Post, uri)
        {
            Content = new StringContent (xmlSOAP, Encoding.UTF8)
        };
        req.Content.Headers.ContentType = MediaTypeHeaderValue.Parse ("text/xml; charset=utf-8");

        if (uri.ToLowerInvariant ().Equals (jsessionUrlCheck)) {
            if (jsession != null && jsession.Count > 0) {
                foreach (var cookie in jsession) {
                    req.Headers.Add ("JSESSIONID", cookie);
                }
            }
            jsession = null;
        }

        HttpResponseMessage response = await client.SendAsync (req);
        string responseBodyAsText = response.IsSuccessStatusCode ? await response.Content.ReadAsStringAsync () : string.Empty;

        if (!string.IsNullOrEmpty (responseBodyAsText))
        {
            return responseBodyAsText;
        }

        return null;
    }
} catch (Exception e) {
    Debug.WriteLine ("========= InvokeAsync Exception =========");
    Debug.WriteLine ("Error: " + e.Message);
    return null;
}}
</code>```

答:
Any idea about how to [...] get any approach to the real error?

It sounds like you don't really know what exactly happens when it "doesn't work". The way you approach the real error is by finding out what exactly happens in this code when it is reported not to work.

Do you have logs? Check the logs. If the exception is there, that should point you in the right direction. Exception not there? Maybe start logging the data received too. No logs? Start logging; there's no better way to handle intermittent failures that you can't reproduce on demand.

Body:
I'm creating an application with Xamarin.Forms which consume from SOAP services using POST method; I have a bunch of services that work correctly, indeed, one of these methods is used to send information in multiple cases and my problem is related with this.

I have the following HttpClient method, but sometimes doesn't work... unfortunately I don't have access to back-end code and they are not for the labour of help me with that.

Any idea about how to improve my method or get any approach to the real error? I'm stuck here, since I send the same fields each time.

public async Task<string> InvokeAsync (string uri, string xmlSOAP) {
try {
    using (var handler = new HttpClientHandler () { UseCookies = false })

    using (var client = new HttpClient (new NativeMessageHandler ())) {
        client.DefaultRequestHeaders.Accept.Add (new MediaTypeWithQualityHeaderValue ("application/xml"));
        client.DefaultRequestHeaders.Add ("Cache-Control", "no-cache, no-store, must-revalidate");
        client.DefaultRequestHeaders.Add ("Pragma", "no-cache");
        client.Timeout = TimeSpan.FromSeconds (timeout);
        client.DefaultRequestHeaders.CacheControl.NoCache = true;

        var req = new HttpRequestMessage (HttpMethod.Post, uri)
        {
            Content = new StringContent (xmlSOAP, Encoding.UTF8)
        };
        req.Content.Headers.ContentType = MediaTypeHeaderValue.Parse ("text/xml; charset=utf-8");

        if (uri.ToLowerInvariant ().Equals (jsessionUrlCheck)) {
            if (jsession != null && jsession.Count > 0) {
                foreach (var cookie in jsession) {
                    req.Headers.Add ("JSESSIONID", cookie);
                }
            }
            jsession = null;
        }

        HttpResponseMessage response = await client.SendAsync (req);
        string responseBodyAsText = response.IsSuccessStatusCode ? await response.Content.ReadAsStringAsync () : string.Empty;

        if (!string.IsNullOrEmpty (responseBodyAsText))
        {
            return responseBodyAsText;
        }

        return null;
    }
} catch (Exception e) {
    Debug.WriteLine ("========= InvokeAsync Exception =========");
    Debug.WriteLine ("Error: " + e.Message);
    return null;
}}


问:
Nesting a http request inside list of promises
I have a service function that returns a list of promises:

```<code>getData(user) {
     return this.$q.all({
        userInfo: this.$http.get(this.buildUrl('user.getinfo', user)),
        userTopArtists: this.$http.get(this.buildUrl('user.gettopartists', user)),
        userChart: this.$http.get(this.buildUrl('user.getWeeklyChartList', user))
    }).then(resp => {
        return resp;
    }).catch(err => {
        this.$q.reject('Error' + err.status);
    })
}
</code>```

, which I'm calling inside my controller:

```<code>validateUser() {
     this.error = null;
     this.service.getData(this.$scope.username)
        .then(resp => {
            if (resp.userInfo.data.user) {
                this.service.storeUserData('userData', JSON.stringify(resp));
                this.$location.path('/profile');
            } else {
                this.error = resp.userInfo.data.message;
            }
        })
}
</code>```

Works fine until now but what I'm looking for is manipulating what data I get from the userChart request in particular.

I want to manipulate the json I get from calling userChart, store some of it inside of an array and make another request that returns data using the stored array object values from the initial request as parameters.

So basically I don't need the json from userChart, I just need to use to it make a nested(?) request using some of its data.

答:
I haven't tried this, but maybe you could do something with the result of that call as soon as it comes back?  Something like this?</p>

```<code>getData(user) {
     return this.$q.all({
        userInfo: this.$http.get(this.buildUrl('user.getinfo', user)),
        userTopArtists: this.$http.get(this.buildUrl('user.gettopartists', user)),
        userChart: this.$http.get(this.buildUrl('user.getWeeklyChartList', user)).
          then(function(response) {
            // Do something with the successful response
          }, function(response) {
            // Do something for the failed response
          })
    }).then(resp => {
        return resp;
    }).catch(err => {
        this.$q.reject('Error' + err.status);
    })
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a service function that returns a list of promises:

getData(user) {
     return this.$q.all({
        userInfo: this.$http.get(this.buildUrl('user.getinfo', user)),
        userTopArtists: this.$http.get(this.buildUrl('user.gettopartists', user)),
        userChart: this.$http.get(this.buildUrl('user.getWeeklyChartList', user))
    }).then(resp => {
        return resp;
    }).catch(err => {
        this.$q.reject('Error' + err.status);
    })
}

, which I'm calling inside my controller:

validateUser() {
     this.error = null;
     this.service.getData(this.$scope.username)
        .then(resp => {
            if (resp.userInfo.data.user) {
                this.service.storeUserData('userData', JSON.stringify(resp));
                this.$location.path('/profile');
            } else {
                this.error = resp.userInfo.data.message;
            }
        })
}

Works fine until now but what I'm looking for is manipulating what data I get from the userChart request in particular.

I want to manipulate the json I get from calling userChart, store some of it inside of an array and make another request that returns data using the stored array object values from the initial request as parameters.

So basically I don't need the json from userChart, I just need to use to it make a nested(?) request using some of its data.

Body:
I haven't tried this, but maybe you could do something with the result of that call as soon as it comes back?  Something like this?

getData(user) {
     return this.$q.all({
        userInfo: this.$http.get(this.buildUrl('user.getinfo', user)),
        userTopArtists: this.$http.get(this.buildUrl('user.gettopartists', user)),
        userChart: this.$http.get(this.buildUrl('user.getWeeklyChartList', user)).
          then(function(response) {
            // Do something with the successful response
          }, function(response) {
            // Do something for the failed response
          })
    }).then(resp => {
        return resp;
    }).catch(err => {
        this.$q.reject('Error' + err.status);
    })
}


问:
Automated way to update a view code using sql script?
Lets suppose i have a table A with 4 columns and I've created a view for the same table which consists of all 4 columns. Now i want to write a script/stored procedure which should update the view code whenever new column is added to Table A in a same physical order.

For Example:
Table  A has following columns

```<code>'Name','Age','Gender','Address'
</code>```

Supposed view code is:

```<code>Select Name,Age,Gender,Address from Table A
</code>```

Now i add an additional column PhoneNumber on Table A. When i run script/Stored Procedure this new column should automatically be added to the query as follows:

Desired view code generated after i run script should be like this:

```<code>Select Name,Age,Gender,Address,PhoneNumber from Table A
</code>```

答:
Side note as a caution from using select * in views:

repro:

```<code>CREATE TABLE t (id INT, NAME VARCHAR(10))
GO
INSERT INTO t VALUES (1, 'a')
GO
CREATE VIEW v AS SELECT * FROM t
GO
SELECT * FROM v
GO
ALTER TABLE t ADD d DATE NOT NULL DEFAULT (GETDATE())
GO
ALTER TABLE t DROP COLUMN id
GO
SELECT * FROM v
GO

DROP VIEW v
GO
DROP TABLE t
GO
</code>```

now put before drops this:

```<code>SELECT * FROM v
WHERE id = 3
</code>```

you'll get

Conversion failed when converting the varchar value 'a' to data type int.

Instead of invalid object name id. Which means than in some cases your solution will keep working relying on absolutely wrong data!

Replace 'a' in sample data with '3' to make implicit conversion succeed and this code will work, will return some data. Whilst there never was id=3 and at the time of running this select there is physically even no id column at all.

Body:
Lets suppose i have a table A with 4 columns and I've created a view for the same table which consists of all 4 columns. Now i want to write a script/stored procedure which should update the view code whenever new column is added to Table A in a same physical order.

For Example:
Table  A has following columns

'Name','Age','Gender','Address'

Supposed view code is:

Select Name,Age,Gender,Address from Table A

Now i add an additional column PhoneNumber on Table A. When i run script/Stored Procedure this new column should automatically be added to the query as follows:

Desired view code generated after i run script should be like this:

Select Name,Age,Gender,Address,PhoneNumber from Table A

Body:
Side note as a caution from using select * in views:

repro:

CREATE TABLE t (id INT, NAME VARCHAR(10))
GO
INSERT INTO t VALUES (1, 'a')
GO
CREATE VIEW v AS SELECT * FROM t
GO
SELECT * FROM v
GO
ALTER TABLE t ADD d DATE NOT NULL DEFAULT (GETDATE())
GO
ALTER TABLE t DROP COLUMN id
GO
SELECT * FROM v
GO

DROP VIEW v
GO
DROP TABLE t
GO

now put before drops this:

SELECT * FROM v
WHERE id = 3

you'll get

Conversion failed when converting the varchar value 'a' to data type int.

Instead of invalid object name id. Which means than in some cases your solution will keep working relying on absolutely wrong data!

Replace 'a' in sample data with '3' to make implicit conversion succeed and this code will work, will return some data. Whilst there never was id=3 and at the time of running this select there is physically even no id column at all.


问:
Eclipse Browser not showing back/front with Plug-in Development
I am trying to populate a url in eclipse browser through plug-in development, but I am not getting back/fw button as it normally shows in the browser of eclipse.
My code snippet looks -</p>

```<code>     Browser browser = new Browser(parent, 0);
   browser.setUrl("http://www.google.com"));
</code>```

答:
Try below API </p>

```<code>org.eclipse.ui.IWorkbench.getBrowserSupport().createBrowser(null).openURL
</code>```

Body:
I am trying to populate a url in eclipse browser through plug-in development, but I am not getting back/fw button as it normally shows in the browser of eclipse.
My code snippet looks -

     Browser browser = new Browser(parent, 0);
   browser.setUrl("http://www.google.com"));

Body:
Try below API

org.eclipse.ui.IWorkbench.getBrowserSupport().createBrowser(null).openURL


问:
Iterating through an arraylist in a hashmap based on key in JSTL
I have a hashmap as Map<String, List<String>> coverageDataMap.
I need to iterate through the list returned by it based on a key.

I'm doing it the following way:

```<code>    <c:forEach items="${bean.coverageDataMap['my_key']}"
            var="entry" varStatus="loop">
        <tr>
            <td><h:outputText value="#{loop.index+1}"/></td>
            <td><h:outputText value="#{entry}"/></td>
        </tr>
    </c:forEach>
</code>```

Unfortunately it doesn't work. I've looked around but couldn't find anything. Please let me know what did I get wrong here! Thanks.

答:
Please try to use </p>

```<code>$
</code>```

<p>instead if </p>

```<code>#
</code>```

Body:
I have a hashmap as Map<String, List<String>> coverageDataMap.
I need to iterate through the list returned by it based on a key.

I'm doing it the following way:

    <c:forEach items="${bean.coverageDataMap['my_key']}"
            var="entry" varStatus="loop">

            <h:outputText value="#{loop.index+1}"/>
            <h:outputText value="#{entry}"/>

    </c:forEach>

Unfortunately it doesn't work. I've looked around but couldn't find anything. Please let me know what did I get wrong here! Thanks.

Body:
Please try to use

$

instead if

#


问:
Load a subset of all custom commands in a nightwatch test suite
Is it possible to load only a subset of all custom commands in a nightwatch test suite?

E.g:
Test suites/test files:

component1Tests1.js

component1Tests2.js

component2Tests1.js

component2Tests2.js

Custom commands:

component1Commands.js

component2Commands.js

Component1TestsX files/tests should see only component1Commands. The situation for Component2TestsX is analogical. This is needed because of the eventual naming collision of the commands.

Thank you all in advance!

答:
As far as I know, it is not possible, and looks more like a bad naming practice.

How would someone else know what does the component1Commands.js do?

What if component1Commands.js already do the same thing that component2Commands.js do?

You would be breaking the DRY principle, the main idea of the commands its to reuse the code for multiple tests. You should name it correctly. If its needed, its better to separate the whole tests into two differentes projects instead.


问:
Atomic sequence counters in Google Datastore
We have an application running in Google App Engine that, as part of its operation generates sequence numbers.  These numbers must meet the following criteria:

They must fall between a specified start and end range

They must be unique (until the end of the range is reached for some cases, in which case we can start from the beginning of the sequence again)

They must be sequential (Random numbers are no good, even if they meet the other two criteria)

We did write code that attempts to ensure that the generated numbers are globally unique, but I can't share that code because a) it's rather convoluted, b) it's the property of my employer and c) it doesn't appear to work under heavy load.

I've done some reading up since the failure to ensure we're meeting the unique criteria and have found some information regarding sharded counters, but whilst I think this approach might help I still don't think it can guarantee that we are 100% certain to produce unique sequences.  My suspicion is that there's some latency in Datastore when it comes to upserts and that a delay between a counter being updated and that update reflecting in subsequent reads is to blame.  Besides there are not PHP examples of handling sharding (though we could probably figure it out from the other examples it would be nice if there was a working PHP example).

My proposed solution to this problem is as follows:

Maintain the current value in the counter in both Memcache (which supports atomic incrementing of integers) and in Datastore (for persistence).  We might try to shard the counter in Datastore as well.

When a request for a new number from a given sequence comes in:

Check Memcache for the current value.  If the data isn't in Memcache, populate it from Datastore

Do an atomic increment in Memcache

Use the value returned from Memcache for our process

Write the new counter value back to Datastore to ensure persistence

On the face of it this seems a reasonable solution but I'm worried there could still be edge cases where we end up with inconsistent counter values, especially if a lot of updates happen simultaneously.  While Memcache would ensure the atomicity of the returned values, I'm not certain the writes to Datastore would happen in the order of the requests and that at the end of it Datastore might not reflect the value in Memcache which could lead to problems if the app goes down and the incorrect value is loaded from Datastore when service is restored.

Are Datastore writes applied in the order they're received?  Can I guarantee that after all writes have been executed that the value in Datastore would match the value in Memcache?  Is there a better solution to this problem (other than switching to an SQL database with autoincrement/sequence support)?

答:
Sequential IDs in AppEngine datastore is a hard problem to tackle.

If you try do it one by one with persistence to datastore you'll hit transactions  throughput limit.

The best approach I can think of:

Use sharding to keep last N counter values.

Start transaction

Lock memcache entries before updating datastore shard (you can use nds package in Go or do in similar way) and get all shard values from datastore by keys. Basically in Go just call nds.GetMulti() for all shards. The lock should have reasonable expiration value. For nds package it's 30 seconds.

Get shard ID and value for a shard with maximum value.

Update appropriate shard value in datastore first - store to db just single entity. For example you can have 10 shards with numbers 0-9 where shard number correspond to the last digit in counter value. So 23 would be mapped to shard 3.

Commit transaction (exit out of transaction func/context)

(Use memcache CAS (compare and swap) operations to update appropriate memcache value or delete it from memcache. Though it's not trivial task to do it right. You can read discussion I started on nds package - https://github.com/qedus/nds/issues/58

Basically you can do without memcache at all but memcache would save you money and may decrease latency (or not).

The important point is to lock memcache and update datastore first and then either delete from memcache or update using CAS. You plan does opposite.


问:
How see the difference in scala test result?
I have written a Scala testcase and run it through:

```<code>sbt > test
</code>```

It fails, which is fine. I have issue with the output of the diff though as it is basically just:

```<code>[String] did not match [String]
</code>```

leaving it up to me to find the difference. Esp. when comparing two Seq it becomes hard to read and find the problem, e.g.:

```<code>[info]   List(CruisePrice(aid,de,Wed Feb 15 00:00:00 CET 2017,Wed Mar 01 00:00:00 CET 2017,sailId,2000,3000,true,2,0,0,0,1000,2500.0,3000.0,SOME_RATE_CODE,SOME_RATE_DESCRIPTION,EUR,Sun Jan 01 00:00:00 CET 2017), CruisePrice(aid,de,Wed Feb 15 00:00:00 CET 2017,Wed Mar 01 00:00:00 CET 2017,sailId,9001,3000,true,2,0,0,0,9000,2500.0,3000.0,SOME_RATE_CODE,SOME_RATE_DESCRIPTION,EUR,Sun Jan 01 00:00:00 CET 2017)) did not equal List(CruisePrice(aid,de,Wed Feb 15 00:00:00 CET 2017,Wed Mar 01 00:00:00 CET 2017,sailId,9001,3000,true,2,0,0,0,9000,2500.0,3000.0,SOME_RATE_CODE,SOME_RATE_DESCRIPTION,EUR,Sun Jan 01 00:00:00 CET 2017)) (OverrideTest.scala:104)
</code>```

Is there a way to configure for scala test to become more human readable so that they provide a more word-diff-like experience without having to parse huge chunk of text?

Or can I use a different way to assert it? As right now, I am using FlatSpec with:

```<code>assert(seq1 == seq2)
</code>```

答:
You can use assertEquals(obj1, obj2) to compare two strings .
assertEquals uses the equals method for comparison. There is a different assert, assertSame, which uses the == operator.

To understand why == shouldn't be used with strings you need to understand what == does: it does an identity check. That is, a == b checks to see if a and b refer to the same object. It is built into the language, and its behavior cannot be changed by different classes. The equals method, on the other hand, can be overridden by classes. While its default behavior (in the Object class) is to do an identity check using the == operator, many classes, including String, override it to instead do an "equivalence" check. In the case of String, instead of checking if a and b refer to the same object, a.equals(b) checks to see if the objects they refer to are both strings that contain exactly the same characters.

Body:
I have written a Scala testcase and run it through:

sbt > test

It fails, which is fine. I have issue with the output of the diff though as it is basically just:

[String] did not match [String]

leaving it up to me to find the difference. Esp. when comparing two Seq it becomes hard to read and find the problem, e.g.:

[info]   List(CruisePrice(aid,de,Wed Feb 15 00:00:00 CET 2017,Wed Mar 01 00:00:00 CET 2017,sailId,2000,3000,true,2,0,0,0,1000,2500.0,3000.0,SOME_RATE_CODE,SOME_RATE_DESCRIPTION,EUR,Sun Jan 01 00:00:00 CET 2017), CruisePrice(aid,de,Wed Feb 15 00:00:00 CET 2017,Wed Mar 01 00:00:00 CET 2017,sailId,9001,3000,true,2,0,0,0,9000,2500.0,3000.0,SOME_RATE_CODE,SOME_RATE_DESCRIPTION,EUR,Sun Jan 01 00:00:00 CET 2017)) did not equal List(CruisePrice(aid,de,Wed Feb 15 00:00:00 CET 2017,Wed Mar 01 00:00:00 CET 2017,sailId,9001,3000,true,2,0,0,0,9000,2500.0,3000.0,SOME_RATE_CODE,SOME_RATE_DESCRIPTION,EUR,Sun Jan 01 00:00:00 CET 2017)) (OverrideTest.scala:104)

Is there a way to configure for scala test to become more human readable so that they provide a more word-diff-like experience without having to parse huge chunk of text?

Or can I use a different way to assert it? As right now, I am using FlatSpec with:

assert(seq1 == seq2)


问:
jQuery UI dialog width & height based on screen width & height
Currently (jQuery 1.4.4 and UI 1.8.8) I used the following to set a dialog's properties:
(I'm trying to set the dialog to be 180px less than the height and width of the screen.)

```<code>$("#dialog").dialog({
            bgiframe: true,
            position: 'center',
            width: $(window).width()-180,
            height: $(window).height()-180,
            title: ititle,
            modal: true,
            buttons: { "Close": function() { $(this).dialog("destroy"); }}
});
</code>```

The above works fine in FF but in IE 8 it fails.

Is this the right way to set width and height or should I be doing something differently?

答: You probably need to specify the DOCTYPE and use standards mode for it to work correctly.</p>

Body:
Currently (jQuery 1.4.4 and UI 1.8.8) I used the following to set a dialog's properties:
(I'm trying to set the dialog to be 180px less than the height and width of the screen.)

$("#dialog").dialog({
            bgiframe: true,
            position: 'center',
            width: $(window).width()-180,
            height: $(window).height()-180,
            title: ititle,
            modal: true,
            buttons: { "Close": function() { $(this).dialog("destroy"); }}
});

The above works fine in FF but in IE 8 it fails.

Is this the right way to set width and height or should I be doing something differently?


问:
Angular checkbox labels not firing change events
i have implemented a group checkbox component as explained in this SO post:
Angular how to get the multiple checkbox value?

All is working well except i have one issue, the labels of the check boxes do not trigger change events, only the actual checkbox portion. In the plunker below, try clicking both the checkbox square and the label, both trigger the checkbox and update the data model but only the checkbox portion fires a change. I suspect its something to do with the transcluded value.

See this plunker
http://plnkr.co/edit/BAhzLYo9e4H8PdAt9lGR?p=preview

Code

```<code><checkbox-group [(ngModel)]="selectedItems">
   <checkbox *ngFor="let item of availableItems"
             [value]="item"
             (change)="onItemChange($event, item)">
             {{item}}
   </checkbox>
 </checkbox-group>
 <p>Selected items - {{selectedItems | json}}</p>
</code>```

答:
Use on click event listener instead of on change. like this</p>

```<code>(click)="onItemChange($event, item)"
</code>```

Body:
i have implemented a group checkbox component as explained in this SO post:
Angular how to get the multiple checkbox value?

All is working well except i have one issue, the labels of the check boxes do not trigger change events, only the actual checkbox portion. In the plunker below, try clicking both the checkbox square and the label, both trigger the checkbox and update the data model but only the checkbox portion fires a change. I suspect its something to do with the transcluded value.

See this plunker
http://plnkr.co/edit/BAhzLYo9e4H8PdAt9lGR?p=preview

Code

<checkbox-group [(ngModel)]="selectedItems">
   <checkbox *ngFor="let item of availableItems"
             [value]="item"
             (change)="onItemChange($event, item)">
             {{item}}
   </checkbox>
 </checkbox-group>

Selected items - {{selectedItems | json}}

Body:
Use on click event listener instead of on change. like this

(click)="onItemChange($event, item)"


问:
(Can I?) How can I access the int value of the next node (tree recursion)
So I have a tree defined as follows:

```<code>data Tree = Node Tree Int Tree | Leaf Int
</code>```

The Int for a Node in this case is the value at that Node. I am trying to check that a tree is balanced, and that the tree is increasing as it's traversed left to right.

To do so I have a recursive function that takes a (Node left x right) and checks that the difference in height of left and right (the nodes below it) is no more than one. I then call balanced again for left and right.

Is it possible to access the Int value of left and right?

答:
Yes, you can write a function that returns the integer at the top node:

```<code>getInt (Node _ i _) = i
getInt (Leaf i) = i
</code>```

E.g.

```<code>Prelude> getInt $ Leaf 42
42
Prelude> getInt $ Node (Leaf 42) 123 (Leaf 1337)
123
</code>```

Body:
So I have a tree defined as follows:

data Tree = Node Tree Int Tree | Leaf Int

The Int for a Node in this case is the value at that Node. I am trying to check that a tree is balanced, and that the tree is increasing as it's traversed left to right.

To do so I have a recursive function that takes a (Node left x right) and checks that the difference in height of left and right (the nodes below it) is no more than one. I then call balanced again for left and right.

Is it possible to access the Int value of left and right?

Body:
Yes, you can write a function that returns the integer at the top node:

getInt (Node _ i _) = i
getInt (Leaf i) = i

E.g.

Prelude> getInt $ Leaf 42
42
Prelude> getInt $ Node (Leaf 42) 123 (Leaf 1337)
123


问:
SQL Server - Dynamic number of columns in Insert statement
I will not go into the reasons for this requirement (too long and not relevant).

I have a rather wide table Table_1 with 256 columns, all NVARCHAR(512) and accepting null.

On the other hand, I have a string into which a dynamic select is built and, depending on the case, it generates each time a different number of columns.

The results of the query need to be inserted into the Table_1.

The problem is that either I explicitly mention the columns into which results are to be inserted or the results of the query must match the structure of the target table.

For instance, let's have:

```<code>DECLARE @Table_1 TABLE (Field_1 NVARCHAR(512) ,
                        Field_2 NVARCHAR(512) ,
                        Field_3 NVARCHAR(512) ,
                        Field_4 NVARCHAR(512) ,
                        Field_5 NVARCHAR(512) ,
                        Field_6 NVARCHAR(512)   ) ;
</code>```

And a query like:

```<code>DECLARE @_My_Query NVARCHAR(1000) = '
SELECT Name    Field_1 ,
       Street  Field_2 ,
       Phone   Field_3
 FROM My_Table
 ';
</code>```

Now, I can't do:

```<code>INSERT INTO @Table_1
  EXECUTE sp_executesql @_My_Query ;
</code>```

because it would complain about mismatching columns. Neither can I hardcode (Field_1,Field_2,Field_3) because other queries would need a different number of columns.

Edit

Answers to the comments posted by KrazzyNefarious, Jeroen Mostert and  Damien_The_Unbeliever:

I do have a clear view of the fields returned by the query as well as their count.

The functionality I'm trying to implement is as follows:

The system I'm working on should support the generation of CSV files with a variable number of columns and contents.

The idea is that the query that generates the result data is prepared at a higher layer and sent to a Stored Procedure (as a string) along with a table that describes all the columns of the result (e.g. ordinal position, field name, data type, title in the Excel's first row, etc.).

The Procedure I'm working on would take the query string and run a combined INSERT INTO Table_1 EXECUTE sp_executesql @_My_Query. Once this is done, the mechanism that examines each and every field (for instance, to add " whenever needed) can handle the contents of Table_1 without any concern about the origin of the data.

I would prefer to avoid using temporary tables since, besides the ugliness of the approach, it affects performance and additional issues (need to delete records after use, collisions, etc.).

答:
This:

The system I'm working on should support the generation of CSV files with a variable number of columns and contents.

is the crux of your problem. You have chosen a path that doesn't really match/support this requirement. You have ruled out temp tables. So the only other option is to create a (temp or permanent) table for each export "situation" - which is ugly and prone to lots of other issues. Because a table in a rdbms has a fixed structure. More than just a different number of columns, you also need to consider different datatypes. Are you ignoring that issue as well or did you make a very simplifying assumption? If you only look at one situation you often lose sight of the complexity you face.

In addition, you can search for the many discussions about exporting CSV data from a stored procedure (or script). It is simply a nest of problems and constraints even without the variability of the source data structure.

I suggest you are using the wrong tool to implement your requirement. TSQL is simply not intended and does not really support ETL. If you intend to go down this path, you will need some advanced skills.

Body:
I will not go into the reasons for this requirement (too long and not relevant).

I have a rather wide table Table_1 with 256 columns, all NVARCHAR(512) and accepting null.

On the other hand, I have a string into which a dynamic select is built and, depending on the case, it generates each time a different number of columns.

The results of the query need to be inserted into the Table_1.

The problem is that either I explicitly mention the columns into which results are to be inserted or the results of the query must match the structure of the target table.

For instance, let's have:

DECLARE @Table_1 TABLE (Field_1 NVARCHAR(512) ,
                        Field_2 NVARCHAR(512) ,
                        Field_3 NVARCHAR(512) ,
                        Field_4 NVARCHAR(512) ,
                        Field_5 NVARCHAR(512) ,
                        Field_6 NVARCHAR(512)   ) ;

And a query like:

DECLARE @_My_Query NVARCHAR(1000) = '
SELECT Name    Field_1 ,
       Street  Field_2 ,
       Phone   Field_3
 FROM My_Table
 ';

Now, I can't do:

INSERT INTO @Table_1
  EXECUTE sp_executesql @_My_Query ;

because it would complain about mismatching columns. Neither can I hardcode (Field_1,Field_2,Field_3) because other queries would need a different number of columns.

Edit

Answers to the comments posted by KrazzyNefarious, Jeroen Mostert and  Damien_The_Unbeliever:

I do have a clear view of the fields returned by the query as well as their count.

The functionality I'm trying to implement is as follows:

The system I'm working on should support the generation of CSV files with a variable number of columns and contents.

The idea is that the query that generates the result data is prepared at a higher layer and sent to a Stored Procedure (as a string) along with a table that describes all the columns of the result (e.g. ordinal position, field name, data type, title in the Excel's first row, etc.).

The Procedure I'm working on would take the query string and run a combined INSERT INTO Table_1 EXECUTE sp_executesql @_My_Query. Once this is done, the mechanism that examines each and every field (for instance, to add " whenever needed) can handle the contents of Table_1 without any concern about the origin of the data.

I would prefer to avoid using temporary tables since, besides the ugliness of the approach, it affects performance and additional issues (need to delete records after use, collisions, etc.).


问:
How can I load Child entities dynamically in Entity Framework 6
I have a Provider class and an Article one. Article has a int ProviderId{get;set} and a public virtual Provider Provider {get;set;} properties.

I know about Lazy loading and why I can't access the Provider property in Article outside the context but I have a generic method that returns the next T like this:

```<code>public static T Next<T>(T currentElement) where T : class, IModel {
    T data;

    if (currentElement.Id >= GetLastId<T>())
        return currentElement;

    using (DatabaseEntities context = new DatabaseEntities()) {
        data = context.Set<T>().Single(el => el.Id == currentElement.Id + 1);
    }

    return data;
}
</code>```

But I can't retrieve Child entities like Provider in Articles Class. How can I include all entities? Should I update the method and make one per entity?

I read about Eager loading and Explicit loading but I don't know how can I implement these in my method.

Note:

Not all my entities have entity children and I have more methods like Previous<T>(), First<T>() or Last<T>() that do the work you expect.

答:
You could extend your method to take a list of possible includes. For example:

```<code>public static T Next<T>(T currentElement, params Expression<Func<T, object>>[] includes)
    where T : class, IModel
{
    if (currentElement.Id >= GetLastId<T>())
        return currentElement;

    using (DatabaseEntities context = new DatabaseEntities())
    {
        IQueryable<T> query = context.Set<T>();

        //Deferred execution allows us to build up the query
        foreach (var include in includes)
        {
            query = query.Include(include);
        }

        return query.Single(el => el.Id == currentElement.Id + 1);
    }
}
</code>```

And use it like this:

```<code>var someEntity = ...;

var nextEntity = Next(someEntity,
    e => e.Childcollection1,
    e => e.Childcollection2,
    //
    e => e.ChildcollectionN)
</code>```

As an additional point, to get your next entity, you shouldn't rely on the ID values being sequential, for example, they will get out of sequence if entries are deleted. Instead, consider something like this:

```<code>return query.OrderBy(el => el.Id).First(el => el.Id > currentElement.Id);
</code>```

Body:
I have a Provider class and an Article one. Article has a int ProviderId{get;set} and a public virtual Provider Provider {get;set;} properties.

I know about Lazy loading and why I can't access the Provider property in Article outside the context but I have a generic method that returns the next T like this:

public static T Next<T>(T currentElement) where T : class, IModel {
    T data;

    if (currentElement.Id >= GetLastId<T>())
        return currentElement;

    using (DatabaseEntities context = new DatabaseEntities()) {
        data = context.Set<T>().Single(el => el.Id == currentElement.Id + 1);
    }

    return data;
}

But I can't retrieve Child entities like Provider in Articles Class. How can I include all entities? Should I update the method and make one per entity?

I read about Eager loading and Explicit loading but I don't know how can I implement these in my method.

Note:

Not all my entities have entity children and I have more methods like Previous<T>(), First<T>() or Last<T>() that do the work you expect.

Body:
You could extend your method to take a list of possible includes. For example:

public static T Next<T>(T currentElement, params Expression<Func<T, object>>[] includes)
    where T : class, IModel
{
    if (currentElement.Id >= GetLastId<T>())
        return currentElement;

    using (DatabaseEntities context = new DatabaseEntities())
    {
        IQueryable<T> query = context.Set<T>();

        //Deferred execution allows us to build up the query
        foreach (var include in includes)
        {
            query = query.Include(include);
        }

        return query.Single(el => el.Id == currentElement.Id + 1);
    }
}

And use it like this:

var someEntity = ...;

var nextEntity = Next(someEntity,
    e => e.Childcollection1,
    e => e.Childcollection2,
    //
    e => e.ChildcollectionN)

As an additional point, to get your next entity, you shouldn't rely on the ID values being sequential, for example, they will get out of sequence if entries are deleted. Instead, consider something like this:

return query.OrderBy(el => el.Id).First(el => el.Id > currentElement.Id);


问:
How do I filter certaing condition on a specific subtype of an inherited entity object in a query?
I have three tables in my SQL 2008 database: User, CutomerUser and SalesUser. They represent different type of users. In my conceptual model these are modelled so that CustomerUser and SalesUser entities are inherited from User. On the database level CustomerUser and SalesUser have their primary key that are at the same time a foreign key into User. Thus the relationship is one to zero or one.

CustomerUser table has a CustomerNumber column and SalesUser table has a RepresentativeCode column. I want to write a query that return whatever Users, CustomerUsers or SalesUsers are there based on a selection criteria. Please note that there are Users that neither CustomerUsers nor SalesUsers.

I want no return all users that have their login equals to specified string regardless of type. In additions if the a CustomerUser has customer number equals to the specified string I want to return it, and similarily I want to return SalesUsers that have representative code equals to the string specified.

I write the following query:

```<code>var users = from u in Context.Users
where (((u is CustomerUser) &&  ((CustomerUser)u).CustomerNumber.Equals(criteria))
|| ((u is SalesUser) && ((SalesUser)u).RepresentativeCode.Equals(criteria)))
|| u.Login.Equals(criteria)
select u;
</code>```

The query compiles, but in runtime when the query gets executed, the following exception is thrown:

"Unable to cast the type 'MyDb.Models.User' to type 'MyDb.Models.CustomerUser'. LINQ to Entities only supports casting Entity Data Model primitive types."

How do I write my query so it works?

NOTE: I'm going to apply sorting/paging to the query down the pipeline, so doing ToList() and then casting kind of solution won't work for me here.

答:
You have to use as casts. You can also take advantage of the fact that L2E coalesces nulls:

```<code>var users = from u in Context.Users
            let customerNumber = (u as CustomerUser).CustomerNumber
            let representativeCode = (u as SalesUser).RepresentativeCode
            where customerNumber.Equals(criteria)
                  || representativeCode.Equals(criteria)
                  || u.Login.Equals(criteria)
            select u;
</code>```

Body:
I have three tables in my SQL 2008 database: User, CutomerUser and SalesUser. They represent different type of users. In my conceptual model these are modelled so that CustomerUser and SalesUser entities are inherited from User. On the database level CustomerUser and SalesUser have their primary key that are at the same time a foreign key into User. Thus the relationship is one to zero or one.

CustomerUser table has a CustomerNumber column and SalesUser table has a RepresentativeCode column. I want to write a query that return whatever Users, CustomerUsers or SalesUsers are there based on a selection criteria. Please note that there are Users that neither CustomerUsers nor SalesUsers.

I want no return all users that have their login equals to specified string regardless of type. In additions if the a CustomerUser has customer number equals to the specified string I want to return it, and similarily I want to return SalesUsers that have representative code equals to the string specified.

I write the following query:

var users = from u in Context.Users
where (((u is CustomerUser) &&  ((CustomerUser)u).CustomerNumber.Equals(criteria))
|| ((u is SalesUser) && ((SalesUser)u).RepresentativeCode.Equals(criteria)))
|| u.Login.Equals(criteria)
select u;

The query compiles, but in runtime when the query gets executed, the following exception is thrown:

"Unable to cast the type 'MyDb.Models.User' to type 'MyDb.Models.CustomerUser'. LINQ to Entities only supports casting Entity Data Model primitive types."

How do I write my query so it works?

NOTE: I'm going to apply sorting/paging to the query down the pipeline, so doing ToList() and then casting kind of solution won't work for me here.

Body:
You have to use as casts. You can also take advantage of the fact that L2E coalesces nulls:

var users = from u in Context.Users
            let customerNumber = (u as CustomerUser).CustomerNumber
            let representativeCode = (u as SalesUser).RepresentativeCode
            where customerNumber.Equals(criteria)
                  || representativeCode.Equals(criteria)
                  || u.Login.Equals(criteria)
            select u;


问:
I want to filter files between data range pattern
I tried

```<code>awk '$6 ~ /^2017-04-01/,/^2017-04-11/' filename
</code>```

and another way

```<code>awk '$6~/^2017-07-04/, $6~/^2017-07-10/' filename
</code>```

But it displayed all month data. what changes should done to filter range dated files.

答:
you can write it this way

```<code>awk '"2017-04-01" <= $6  && $6 <= "2017-04-11"'  file
</code>```

for regex you should implement the range as patterns

```<code>awk '$6~/^2017-04-(0[1-9]|1[01])/' file
</code>```

however, I think the first alternative is cleaner, faster as well.

Body:
I tried

awk '$6 ~ /^2017-04-01/,/^2017-04-11/' filename

and another way

awk '$6~/^2017-07-04/, $6~/^2017-07-10/' filename

But it displayed all month data. what changes should done to filter range dated files.

Body:
you can write it this way

awk '"2017-04-01" <= $6  && $6 <= "2017-04-11"'  file

for regex you should implement the range as patterns

awk '$6~/^2017-04-(0[1-9]|1[01])/' file

however, I think the first alternative is cleaner, faster as well.


问:
Replace nan with empty in Table with Multiple Data Types
I 'm running MATLAB R2016a. I 'm working on a table like this. It contains multiple data types. Fillmissing function runs in R2016b Edition. What I want to achieve is to replace NaN's with blanks only in numerical data types. The goal is to Export a csv without NaN's in numerical columns. Any idea?</p>

```<code>    Var1           Var2             Var3
_____________    _________    _____________________

'2101PV'         'QZ'         6,13
'2102PV'         'QZ'         6,13
'2103PV'         'QZ'         NaN
'2104PV'         'QZ'         NaN
</code>```

答:
```<code>tab(ismissing(tab)) = {''};
</code>```

But it's not clear how you managed to mix datatypes in your rows...

Body:
I 'm running MATLAB R2016a. I 'm working on a table like this. It contains multiple data types. Fillmissing function runs in R2016b Edition. What I want to achieve is to replace NaN's with blanks only in numerical data types. The goal is to Export a csv without NaN's in numerical columns. Any idea?

    Var1           Var2             Var3
_____________    _________    _____________________

'2101PV'         'QZ'         6,13
'2102PV'         'QZ'         6,13
'2103PV'         'QZ'         NaN
'2104PV'         'QZ'         NaN

Body:
tab(ismissing(tab)) = {''};

But it's not clear how you managed to mix datatypes in your rows...


问:
How do you compare user input to values inside an array?
I am wanting to create a very simple script that checks user's input to a pre-existing array. However, it doesn't seem to work and I'm not sure why. Please, keep in mind I'm new to this and trying to learn.</p>

```<code><script>
    var usernumber = prompt('What is your number?');
    var numbers = ['1', '2', '3'];
    if (usernumber == 'numbers') //If the user number matches one of preset numbers
    {
        alert('Match');
    } else {
        alert('No match found.');
    }
</script>
</code>```

答:
array.indexof(item) return -1 if the item does not exist on the array else return item's  index

```

Body:
array.indexof(item) return -1 if the item does not exist on the array else return item's  index

<script>
    var usernumber = prompt('What is your number?');
    var numbers = ['1', '2', '3'];
    if (numbers.indexOf(usernumber) >=0 ) // check if the item exists on the array
    {
        alert('Match');
    } else {
        alert('No match found.');
    }
</script>


问:
NPM install stucks
in last few days I noticed I basically cannot use npm. It get stuck every time I try to install the deps of a project.
For example https://github.com/electron/electron-quick-start

It gets stuck every time on the message finalize: sill finalize \node_modules\ajv

I tried to turn on http log and turn off spin

```<code>$ npm set spin false
$ npm set loglevel http
</code>```

windows 7 x64

node v8.4.0

npm v5.5.1

here the console error

答:
Downgrade npm, clearing cache, forced uninstall none worked.

Eventually I solved manually deleting

```<code>%APPDATA%\Roaming\npm
%APPDATA%\Roaming\npm-cache
</code>```

then

```<code>npm --force uninstall npm -g
npm install npm@5.0.3 -g
</code>```

Title: NPM install stucks

Body:
in last few days I noticed I basically cannot use npm. It get stuck every time I try to install the deps of a project.
For example https://github.com/electron/electron-quick-start

It gets stuck every time on the message finalize: sill finalize \node_modules\ajv

I tried to turn on http log and turn off spin

$ npm set spin false
$ npm set loglevel http

windows 7 x64

node v8.4.0

npm v5.5.1

here the console error

Body:
Downgrade npm, clearing cache, forced uninstall none worked.

Eventually I solved manually deleting

%APPDATA%\Roaming\npm
%APPDATA%\Roaming\npm-cache

then

npm --force uninstall npm -g
npm install npm@5.0.3 -g


问:
What does Sync Do in Team Explorer?
I am currently in a project that uses TFS Git as the code repository. In Visual Studio, under Team Explorer -> Sync, there is an option called Sync. Now I am familiar with the Fetch, Pull, and Push actions but Sync is new to me.

Any ideas what this does behind the scenes?

答: Sync is a combination of a Pull Command followed by a Push command. It will 1st perform a Pull, and if there are no conflicts, will then Push the current branch. It is meant as a quick way to just get your current branch into sync with the remote branch.</p>

Title: What does Sync Do in Team Explorer?


问:
Retrieve input from multiple text fields with JavaFX
Using JavaFX, Ive created 4 text fields a user can input information. I then have a button, when pressed, will save the user's input to a text file where the user can select the location to save to.
I can't figure out how to retrieve the user's input from each of the individual fields.
Im using a fxml with a controller class which is here.

```<code>package application;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.Group;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

public class MainController {

@FXML
private Button Button1;
@FXML
private Button Button2;

@FXML
private ListView listview;
@FXML
private TextField Name;
@FXML
private TextField DoB;
@FXML
private TextField Address;
@FXML
private TextField Exp;

public void Button1Action(ActionEvent event) {
    FileChooser fc = new FileChooser();
    File selectedFile = fc.showOpenDialog(null);

    if (selectedFile != null) {
        listview.getItems().add(selectedFile.getName());
    } else {
        System.out.println("File is not valid");
    }

}

public void Button2Action(ActionEvent e) {
    String name = name.getText(Name);
}

}
</code>```

Here is the fxml

```<code><?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.ListView?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.AnchorPane?>

<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity"
minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0"
xmlns="http://javafx.com/javafx/9.0.1" xmlns:fx="http://javafx.com/fxml/1"
fx:controller="application.MainController">
<children>
  <Button fx:id="Button1" layoutX="90.0" layoutY="72.0"
mnemonicParsing="false" onAction="#Button1Action" text="File Explorer" />
  <ListView fx:id="listview" layoutX="300.0" layoutY="27.0"
prefHeight="346.0" prefWidth="200.0" />
  <TextField fx:id="DoB" layoutX="131.0" layoutY="238.0" />
  <TextField fx:id="Address" layoutX="131.0" layoutY="274.0" />
  <TextField fx:id="Exp" layoutX="131.0" layoutY="310.0" />
  <TextField fx:id="Name" layoutX="131.0" layoutY="200.0" />
  <Button fx:id="Button2" layoutX="159.0" layoutY="348.0"
mnemonicParsing="false" onAction="#Button2Action" text="Print Paycheck" />
  <Label layoutX="15.0" layoutY="204.0" text="Name" />
  <Label layoutX="14.0" layoutY="242.0" text="Date of Birth" />
  <Label layoutX="15.0" layoutY="278.0" text="Address" />
  <Label layoutX="15.0" layoutY="314.0" text="Years of Experience" />
</children>
</AnchorPane>
</code>```

EDIT:

I have been able to write the input to a text and save it per the user's desire.
but the text in the file isnt on new lines and not spaced

```<code>    FileChooser fileChooser = new FileChooser();
    fileChooser.setTitle("Save file");
    fileChooser.getExtensionFilters().add(new ExtensionFilter("Text Files",
"*.txt"));
    File saveFile = fileChooser.showSaveDialog(window);

    FileWriter writer;
    try {
        writer = new FileWriter(saveFile);
        BufferedWriter buf = new BufferedWriter(writer);

        buf.write(name.getText() + "\n ");
        buf.write(dob.getText() + "\n ");
        buf.write(address.getText() + "\n ");
        buf.write(exp.getText() + "\n ");
        buf.flush();
        buf.close();

    } catch (IOException e) {

    }
</code>```

答:
You can create an array of Text Fields. create a vbox instead of ListView then add text fields to vbox children in a for loop.

another option is using listview. [if you have few text fields use vbox instead of listview]

Body:
Using JavaFX, Ive created 4 text fields a user can input information. I then have a button, when pressed, will save the user's input to a text file where the user can select the location to save to.
I can't figure out how to retrieve the user's input from each of the individual fields.
Im using a fxml with a controller class which is here.

package application;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.Group;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

public class MainController {

@FXML
private Button Button1;
@FXML
private Button Button2;

@FXML
private ListView listview;
@FXML
private TextField Name;
@FXML
private TextField DoB;
@FXML
private TextField Address;
@FXML
private TextField Exp;

public void Button1Action(ActionEvent event) {
    FileChooser fc = new FileChooser();
    File selectedFile = fc.showOpenDialog(null);

    if (selectedFile != null) {
        listview.getItems().add(selectedFile.getName());
    } else {
        System.out.println("File is not valid");
    }

}

public void Button2Action(ActionEvent e) {
    String name = name.getText(Name);
}

}

Here is the fxml

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.ListView?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.AnchorPane?>

<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity"
minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0"
xmlns="http://javafx.com/javafx/9.0.1" xmlns:fx="http://javafx.com/fxml/1"
fx:controller="application.MainController">
<children>
  <Button fx:id="Button1" layoutX="90.0" layoutY="72.0"
mnemonicParsing="false" onAction="#Button1Action" text="File Explorer" />
  <ListView fx:id="listview" layoutX="300.0" layoutY="27.0"
prefHeight="346.0" prefWidth="200.0" />
  <TextField fx:id="DoB" layoutX="131.0" layoutY="238.0" />
  <TextField fx:id="Address" layoutX="131.0" layoutY="274.0" />
  <TextField fx:id="Exp" layoutX="131.0" layoutY="310.0" />
  <TextField fx:id="Name" layoutX="131.0" layoutY="200.0" />
  <Button fx:id="Button2" layoutX="159.0" layoutY="348.0"
mnemonicParsing="false" onAction="#Button2Action" text="Print Paycheck" />

</children>
</AnchorPane>

EDIT:

I have been able to write the input to a text and save it per the user's desire.
but the text in the file isnt on new lines and not spaced

    FileChooser fileChooser = new FileChooser();
    fileChooser.setTitle("Save file");
    fileChooser.getExtensionFilters().add(new ExtensionFilter("Text Files",
"*.txt"));
    File saveFile = fileChooser.showSaveDialog(window);

    FileWriter writer;
    try {
        writer = new FileWriter(saveFile);
        BufferedWriter buf = new BufferedWriter(writer);

        buf.write(name.getText() + "\n ");
        buf.write(dob.getText() + "\n ");
        buf.write(address.getText() + "\n ");
        buf.write(exp.getText() + "\n ");
        buf.flush();
        buf.close();

    } catch (IOException e) {

    }


问:
Overriding META-INF\services\org.hibernate.integrator.spi.Integrator
I am working with hibernate envers (4.3.5 version). Using Conditional auditing (15.8. hibernate envers doc) I inherited EnversIntegrator creating my own customerEnversIntegrator. for making envers to use this one, I added to META-INF\services\org.hibernate.integrator.spi.Integrator the customerEnversIntegrator path. it worked fine! When i left it as default, but changed the application META-INF\services\org.hibernate.integrator.spi.Integrator to point the customerEnversIntegrator was not used fully. so it actually didn't work But i don't want this declaration to be in the jar level. i need to override it from the application. cause as a project - i can't control the jar, it could be updated and etc.

Any ideas how to override this file without changing anything in the Jar?

答:
Unfortunately the Envers conditional auditing setup is invasive, this is precisely why Envers 6 wants to take a different approach that is less intrusive.

What you can do is to turn off the standard Envers Integrator implementation by specifying the Hibernate configuration property which will cause the standard integrator for envers to not start and not register the standard event listeners, etc.

```<code>hibernate.listeners.envers.autoRegister=false
</code>```

Then you register your own custom Integrator that mimics the standard implementation but instead does not check for the existance of the above configuration property for obvious reasons and that registers your custom listeners rather than the standard ones.

That should avoid having to manually change the hibernate-envers artifact or do any build time library manipulation.

I most likely will remove this configuration option in the future as the annotated conditional auditing approach will become the preferred choice here and to avoid having to force users who want this to duplicate internal code in order to use such functionality.

Body:
Unfortunately the Envers conditional auditing setup is invasive, this is precisely why Envers 6 wants to take a different approach that is less intrusive.

What you can do is to turn off the standard Envers Integrator implementation by specifying the Hibernate configuration property which will cause the standard integrator for envers to not start and not register the standard event listeners, etc.

hibernate.listeners.envers.autoRegister=false

Then you register your own custom Integrator that mimics the standard implementation but instead does not check for the existance of the above configuration property for obvious reasons and that registers your custom listeners rather than the standard ones.

That should avoid having to manually change the hibernate-envers artifact or do any build time library manipulation.

I most likely will remove this configuration option in the future as the annotated conditional auditing approach will become the preferred choice here and to avoid having to force users who want this to duplicate internal code in order to use such functionality.


Title: Matching with time and picking up different values from the dataset

Body:
I have a dataset like this (whole January, 2016). Analysis time is going every three hours and it creates values for 54 hours ahead.

new_data_frame <-
analysis_time       forecast_time       value
2016-01-01 00:00:00 2016-01-01 00:00:00 26918.20
2016-01-01 00:00:00 2016-01-01 01:00:00 28769.50
2016-01-01 00:00:00 2016-01-01 02:00:00 46015.40
2016-01-01 00:00:00 2016-01-01 03:00:00 50000.00
2016-01-01 00:00:00 2016-01-01 03:00:00 45705.50
2016-01-01 00:00:00 2016-01-01 03:00:00 23097.60
..lot of values..
2016-01-01 03:00:00 2016-01-01 03:00:00 50000.00
2016-01-01 03:00:00 2016-01-01 04:00:00 50000.00
2016-01-01 03:00:00 2016-01-01 05:00:00 50000.00
2016-01-01 03:00:00 2016-01-01 06:00:00 50000.00
2016-01-01 03:00:00 2016-01-01 07:00:00 50000.00
..lot of values..
2016-01-01 06:00:00 2016-01-01 06:00:00 14594.500
2016-01-01 06:00:00 2016-01-01 07:00:00 50000.00
2016-01-01 06:00:00 2016-01-01 08:00:00 50000.00
2016-01-01 06:00:00 2016-01-01 09:00:00 50000.00
......

> dput(head(new_data_frame))
structure(list(station_id = c(8L, 8L, 8L, 8L, 8L, 8L), analysis_time = structure(c(1451606400,
1451606400, 1451606400, 1451606400, 1451606400, 1451606400), class = c("POSIXct",
"POSIXt"), tzone = "GMT"), forecast_time = structure(c(1451606400,
1451610000, 1451613600, 1451617200, 1451620800, 1451624400), class = c("POSIXct",
"POSIXt"), tzone = "GMT"), model_id = c(5L, 5L, 5L, 5L, 5L, 5L
), parameter_id = c(407L, 407L, 407L, 407L, 407L, 407L), value = c(26918.2,
28769.5, 46015.4, 50000, 45705.5, 23097.6)), .Names = c("station_id",
"analysis_time", "forecast_time", "model_id", "parameter_id",
"value"), row.names = c("1", "2", "3", "4", "5", "6"), class = "data.frame")

Because some values are missing from the dataset I have to make a time vector (in order to mark missing values as NA) which goes from 2016-01-01 to 2016-02-01.

table <-
analysis_time
2016-01-01 00:00:00
2016-01-01 00:00:00
2016-01-01 00:00:00
2016-01-01 03:00:00
2016-01-01 03:00:00
2016-01-01 03:00:00
2016-01-01 06:00:00
2016-01-01 06:00:00
2016-01-01 06:00:00
2016-01-01 09:00:00
2016-01-01 09:00:00
2016-01-01 09:00:00
.....

Then I would always like to pick up first three values beginning from the new analysis time.

So it would look like this:

analysis_time       forecast_time       value
2016-01-01 00:00:00 2016-01-01 00:00:00 26918.20
2016-01-01 00:00:00 2016-01-01 01:00:00 28769.50
2016-01-01 00:00:00 2016-01-01 02:00:00 46015.40
2016-01-01 03:00:00 2016-01-01 03:00:00 50000.00
2016-01-01 03:00:00 2016-01-01 04:00:00 50000.00
2016-01-01 03:00:00 2016-01-01 05:00:00 50000.00
2016-01-01 06:00:00 2016-01-01 06:00:00 14594.500
2016-01-01 06:00:00 2016-01-01 07:00:00 50000.00
2016-01-01 06:00:00 2016-01-01 08:00:00 50000.00

My code now looks like this:

table[,3] <- new_data_frame$value[match(table$analysis_time,new_data_frame$analysis_time)]

But it gives me now the same values from the same analysis time which I don't want. How could I pick up always the next value like above?

2016-01-01 00:00:00 2016-01-01 00:00:00 26918.200
2016-01-01 00:00:00 2016-01-01 01:00:00 26918.200
2016-01-01 00:00:00 2016-01-01 02:00:00 26918.200
2016-01-01 03:00:00 2016-01-01 03:00:00 50000.000
2016-01-01 03:00:00 2016-01-01 04:00:00 50000.000
2016-01-01 03:00:00 2016-01-01 05:00:00 50000.000
2016-01-01 06:00:00 2016-01-01 06:00:00 14594.500
2016-01-01 06:00:00 2016-01-01 07:00:00 14594.500
2016-01-01 06:00:00 2016-01-01 08:00:00 14594.500

Body:
If I understand OP's intention correctly, it is requested to return the first 3 rows of forecasted values which belong to each analysis_time.

This can be solved by ordering new_data_frame by analysis_time and forecast_time, grouping by analysis_time, and picking the first three rows within each group.

This can be done in base R, dplyr, or data.table which I do prefer:

library(data.table)
setDT(new_data_frame)[order(analysis_time, forecast_time)][
  , head(.SD, 3L), by = analysis_time]

         analysis_time       forecast_time   value
1: 2016-01-01 00:00:00 2016-01-01 00:00:00 26918.2
2: 2016-01-01 00:00:00 2016-01-01 01:00:00 28769.5
3: 2016-01-01 00:00:00 2016-01-01 02:00:00 46015.4
4: 2016-01-01 03:00:00 2016-01-01 03:00:00 50000.0
5: 2016-01-01 03:00:00 2016-01-01 04:00:00 50000.0
6: 2016-01-01 03:00:00 2016-01-01 05:00:00 50000.0
7: 2016-01-01 06:00:00 2016-01-01 06:00:00 14594.5
8: 2016-01-01 06:00:00 2016-01-01 07:00:00 50000.0
9: 2016-01-01 06:00:00 2016-01-01 08:00:00 50000.0

Now, the OP has mentioned that some values are missing from the dataset which needs to be shown.

This can be achieved by joining with a sequence of time stamps covering the whole period:

start_time <- as.POSIXct("2016-01-01")
library(lubridate)
time_seq <- seq(start_time, start_time + months(1L), by = "3 hours")
result <- setDT(new_data_frame)[order(analysis_time, forecast_time)][
  , head(.SD, 3L), by = analysis_time][
    .(time_seq), on = .(analysis_time = V1)]
head(result, 12L)

          analysis_time       forecast_time   value
 1: 2016-01-01 00:00:00 2016-01-01 00:00:00 26918.2
 2: 2016-01-01 00:00:00 2016-01-01 01:00:00 28769.5
 3: 2016-01-01 00:00:00 2016-01-01 02:00:00 46015.4
 4: 2016-01-01 03:00:00 2016-01-01 03:00:00 50000.0
 5: 2016-01-01 03:00:00 2016-01-01 04:00:00 50000.0
 6: 2016-01-01 03:00:00 2016-01-01 05:00:00 50000.0
 7: 2016-01-01 06:00:00 2016-01-01 06:00:00 14594.5
 8: 2016-01-01 06:00:00 2016-01-01 07:00:00 50000.0
 9: 2016-01-01 06:00:00 2016-01-01 08:00:00 50000.0
10: 2016-01-01 09:00:00                <NA>      NA
11: 2016-01-01 12:00:00                <NA>      NA
12: 2016-01-01 15:00:00                <NA>      NA

Analysis times which do not appear in new_data_frame are now indicated by a single NA row.


问:
Cannot Post CSV file in Python
I'm having problems with a CSV file upload with requests.post method in python 3.

```<code>from requests.auth import HTTPBasicAuth
import csv
import requests

user='myuser'
pw='mypass'
advertiserid='10550'
campaignid='12394'
url='http://example.example.com/api/edc/upload/'+advertiserid+'/'+campaignid+'/'+'?encoding=utf-8&fieldsep=%3B&decimalsep=.&date=DD%2FMM%2FYYYY&info=1&process=1'
csv="myfile.csv"

with open(csv, 'r') as f:
    r = requests.post(url, files={csv: f})
    print(r)
</code>```

The output is 'Response [502]'

Any idea of what could be the problem?

Many thanks!

答:
You can refer the documentation of Requests library here: post-a-multipart-encoded-file

Change your request line to:

```<code>r = requests.post(url, files={'report.csv': f})
</code>```

Title: Cannot Post CSV file in Python

Body:
I'm having problems with a CSV file upload with requests.post method in python 3.

from requests.auth import HTTPBasicAuth
import csv
import requests

user='myuser'
pw='mypass'
advertiserid='10550'
campaignid='12394'
url='http://example.example.com/api/edc/upload/'+advertiserid+'/'+campaignid+'/'+'?encoding=utf-8&fieldsep=%3B&decimalsep=.&date=DD%2FMM%2FYYYY&info=1&process=1'
csv="myfile.csv"

with open(csv, 'r') as f:
    r = requests.post(url, files={csv: f})
    print(r)

The output is 'Response [502]'

Any idea of what could be the problem?

Many thanks!

Body:
You can refer the documentation of Requests library here: post-a-multipart-encoded-file

Change your request line to:

r = requests.post(url, files={'report.csv': f})


问:
Ruby on Rails using incorrect layout partial
I have a RoR app that has some bits under /admin/ which uses it's own styles and layouts to the root.

I have created a controller and view under /admin/active_vulnerabilities but this is using the layouts for root not the admin layouts and CSS etc

I did originally create the controller and view under root but I have moved it under /admin/ and the routes work fine but it seems to have cached the layouts and CSS for the root and not updating to the admin ones. I have tried to use rails assets:precompile but its still pulling the incorrect bits through.

答:
The reason why your controllers in admin is inhereting from ApplicationController. If you are not explicitly point layout's name first time Rails search layout by controller's name, then by its ancestors' names. Docs

You can do like @AntonTkachov showed:

```<code>class Admin::ActiveVulnerabilitiesController < ApplicationController
  layout :admin

  ...
end
</code>```

Or you can create AdminController:

```<code>class AdminController < ApplicationController
  # some shared code for admin namespace
end
</code>```

and inherit from it every controller in admin namespace:

```<code>class Admin::ActiveVulnerabilitiesController < AdminController
  #some code
end
</code>```

Body:
The reason why your controllers in admin is inhereting from ApplicationController. If you are not explicitly point layout's name first time Rails search layout by controller's name, then by its ancestors' names. Docs

You can do like @AntonTkachov showed:

class Admin::ActiveVulnerabilitiesController < ApplicationController
  layout :admin

  ...
end

Or you can create AdminController:

class AdminController < ApplicationController
  # some shared code for admin namespace
end

and inherit from it every controller in admin namespace:

class Admin::ActiveVulnerabilitiesController < AdminController
  #some code
end


答:
String name = name.getText(Name); should be changed to String name = Name.getText(). If you do something similar to that with each textfield, you should be able to get their contents.

Edit:

to prompt the user for where they want to save their text file and what to call it, you can use a FileChooser, which you can use like this:

```<code>FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Save File");
fileChooser.getExtensionFilters().add(new ExtensionFilter("Text Files", "*.txt"));
Window window = Button1.getScene().getWindow();
File saveFile = fileChooser.showSaveDialog(window);
</code>```

and then use normal file IO stuff to write what you want to the file.

Code Review sidenote, which you are free to ignore:

It's considered good practice in Java to name your variables starting with lowercase letters and your Classes with uppercase letters. This makes it obvious at first glance whether a method is being called on an instance of an object or on a class.

Title: Retrieve input from multiple text fields with JavaFX

Body:
String name = name.getText(Name); should be changed to String name = Name.getText(). If you do something similar to that with each textfield, you should be able to get their contents.

Edit:

to prompt the user for where they want to save their text file and what to call it, you can use a FileChooser, which you can use like this:

FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Save File");
fileChooser.getExtensionFilters().add(new ExtensionFilter("Text Files", "*.txt"));
Window window = Button1.getScene().getWindow();
File saveFile = fileChooser.showSaveDialog(window);

and then use normal file IO stuff to write what you want to the file.

Code Review sidenote, which you are free to ignore:

It's considered good practice in Java to name your variables starting with lowercase letters and your Classes with uppercase letters. This makes it obvious at first glance whether a method is being called on an instance of an object or on a class.