问:
Remove non-business days rows from pandas dataframe
I have a dataframe with a timeseries data of wheat in df.

```<code>df = wt["WHEAT_USD"]

2016-05-02 02:00:00+02:00    4.780
2016-05-02 02:01:00+02:00    4.777
2016-05-02 02:02:00+02:00    4.780
2016-05-02 02:03:00+02:00    4.780
2016-05-02 02:04:00+02:00    4.780
Name: closeAsk, dtype: float64
</code>```

When I plot the data it has these annoying horizontal lines because of weekends. Is there a simple way of removing the non-business days from the dataframe itself?

Something like

```<code>df = df.BDays()
</code>```

答:
Pandas BDay just ends up using .dayofweek<5 like the chosen answer, but can be extended to account for bank holidays, etc.

```<code>import pandas as pd
from pandas.tseries.offsets import BDay

isBusinessDay = BDay().onOffset
csv_path = 'C:\\Python27\\Lib\\site-packages\\bokeh\\sampledata\\daylight_warsaw_2013.csv'
dates_df = pd.read_csv(csv_path)
match_series = pd.to_datetime(dates_df['Date']).map(isBusinessDay)
dates_df[match_series]
</code>```

Body:
I have a dataframe with a timeseries data of wheat in df.

df = wt["WHEAT_USD"]

2016-05-02 02:00:00+02:00    4.780
2016-05-02 02:01:00+02:00    4.777
2016-05-02 02:02:00+02:00    4.780
2016-05-02 02:03:00+02:00    4.780
2016-05-02 02:04:00+02:00    4.780
Name: closeAsk, dtype: float64

When I plot the data it has these annoying horizontal lines because of weekends. Is there a simple way of removing the non-business days from the dataframe itself?

Something like

df = df.BDays()

Body:
Pandas BDay just ends up using .dayofweek<5 like the chosen answer, but can be extended to account for bank holidays, etc.

import pandas as pd
from pandas.tseries.offsets import BDay

isBusinessDay = BDay().onOffset
csv_path = 'C:\\Python27\\Lib\\site-packages\\bokeh\\sampledata\\daylight_warsaw_2013.csv'
dates_df = pd.read_csv(csv_path)
match_series = pd.to_datetime(dates_df['Date']).map(isBusinessDay)
dates_df[match_series]


来源: stackexchange

问:
SQL Server Profiler?
I am looking for SQL Server Profiler in SQL Server 2008 express edition.I have an instance of SQL Server 2008 running in my machine but I want the profiler too.Does it come with the installation or do I have to install it separately?</p>

答: you need to install the dev version for profiler or get this one here: http://sqlprofiler.googlepages.com/</p>

OwnerDisplayName: kjayakum

ContentLicense: CC BY-SA 2.5

Title: SQL Server Profiler?

OwnerDisplayName: SQLMenace


问:
Trouble getting working directory
This is how I am trying to get the current working directory:

```<code>    char* ch;
    if( (ch = _getcwd( NULL, 0 )) == NULL )
    {
        cout << "Could not get working directory!" << endl;
    }
    // skonvertujme char* na string, s tym sa nizsie bude lahsie pracovat
    stringstream ss;
    string workingDirectory;
    ss << ch;
    ss >> workingDirectory;

    cout << workingDirectory << endl;
    cin.get();
    cin.get();
</code>```

Which prints out:

```<code>C:\Users\Richard\Documents\Visual
</code>```

Instead of the actual working directory:

```<code>C:\Users\Richard\Documents\Visual Studio 2010\Projects\Client\Debug
</code>```

It seems like ti cuts everything after a space.

How can I get the working directory correctly even if there are spaces in the path?

答:
Just replace this:

```<code>stringstream ss;
string workingDirectory;
ss << ch;
ss >> workingDirectory;
</code>```

with this:

```<code>string workingDirectory(ch);
</code>```

Title: Trouble getting working directory

Body:
This is how I am trying to get the current working directory:

    char* ch;
    if( (ch = _getcwd( NULL, 0 )) == NULL )
    {
        cout << "Could not get working directory!" << endl;
    }
    // skonvertujme char* na string, s tym sa nizsie bude lahsie pracovat
    stringstream ss;
    string workingDirectory;
    ss << ch;
    ss >> workingDirectory;

    cout << workingDirectory << endl;
    cin.get();
    cin.get();

Which prints out:

C:\Users\Richard\Documents\Visual

Instead of the actual working directory:

C:\Users\Richard\Documents\Visual Studio 2010\Projects\Client\Debug

It seems like ti cuts everything after a space.

How can I get the working directory correctly even if there are spaces in the path?

Body:
Just replace this:

stringstream ss;
string workingDirectory;
ss << ch;
ss >> workingDirectory;

with this:

string workingDirectory(ch);


问:
DELETE & INSERT or UPDATE best practice in SQL PDO
I'm trying to find an answer which is the best practice for following parts of code:

Let's say I have a single action for add and edit products

DELETE & INSERT

```<code>$product_id = 1;
$this->db->query("DELETE FROM `product_description` WHERE `product_id` = :product_id");
$this->db->bind(array(":product_id" => $product_id));
$this->db->execute();

$updateset = array(
    ":product_id" => $product_id,
    ":name" => $_POST["name"]
);
$this->db->query("INSERT INTO `product_description` SET `product_id` = :product_id, `name` = :name");
$this->db->bind($updateset);
$this->db->execute();
</code>```

UPDATE or INSERT

```<code>$product_id = 1;
$updateset = array(
    ":name" => $_POST["name"]
    ":product_id" => $product_id
);
$this->db->query("UPDATE `product_description` SET `name` = :name WHERE `product_id` = :product_id");
$this->db->bind($params);
$this->db->execute();
if(!$this->db->row_count()) {
    $this->db->query("INSERT INTO `product_description` SET `product_id` = :product_id, `name` = :name");
    $this->db->bind($updateset);
    $this->db->execute();
}
</code>```

so which is better?

答:
The question is quite unclear but the second option looks much better.
The main reason is if your schema evolve and you end up with more columns than you already have, the first option will deleted existing data.

The second option on the other hand will make sure that any existing data will be kept in your database.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to find an answer which is the best practice for following parts of code:

Let's say I have a single action for add and edit products

DELETE & INSERT

$product_id = 1;
$this->db->query("DELETE FROM `product_description` WHERE `product_id` = :product_id");
$this->db->bind(array(":product_id" => $product_id));
$this->db->execute();

$updateset = array(
    ":product_id" => $product_id,
    ":name" => $_POST["name"]
);
$this->db->query("INSERT INTO `product_description` SET `product_id` = :product_id, `name` = :name");
$this->db->bind($updateset);
$this->db->execute();

UPDATE or INSERT

$product_id = 1;
$updateset = array(
    ":name" => $_POST["name"]
    ":product_id" => $product_id
);
$this->db->query("UPDATE `product_description` SET `name` = :name WHERE `product_id` = :product_id");
$this->db->bind($params);
$this->db->execute();
if(!$this->db->row_count()) {
    $this->db->query("INSERT INTO `product_description` SET `product_id` = :product_id, `name` = :name");
    $this->db->bind($updateset);
    $this->db->execute();
}

so which is better?


问:
Access NUnit Test Name within TestCaseSource
I have a series of tests where I want to use the same testcase data for a bunch of different tests.

eg:

```<code>[Test, TestCaseSource("TestData")]
public void Test1(Foo foo)
{
    // test 1
}

[Test, TestCaseSource("TestData")]
public void Test2(Foo foo)
{
    // test 2
}

private static IEnumerable TestData()
{
   TestCaseData data;

   data = new TestCaseData(new Foo("aaa"));
   yield return data;

   data = new TestCaseData(new Foo("bbb"));
   yield return data;
}
</code>```

This leads to a series of tests that report like so:

```<code>Namespace.That.Is.Very.Long.TestClass.Test1(Namespace.That.Is.Very.Long.Foo)
Namespace.That.Is.Very.Long.TestClass.Test1(Namespace.That.Is.Very.Long.Foo)
Namespace.That.Is.Very.Long.TestClass.Test2(Namespace.That.Is.Very.Long.Foo)
Namespace.That.Is.Very.Long.TestClass.Test2(Namespace.That.Is.Very.Long.Foo)
</code>```

...which isn't hugely meaningful when you don't know what 'foo' failed..

If as suggested in this SO question I set the name like this:

```<code>   data = new TestCaseData(new Foo("aaa"));
   data.SetName("foo=aaa");
   yield return data;
</code>```

...then all my tests come out looking like this:

```<code>foo=aaa
foo=bbb
foo=aaa
foo=bbb
</code>```

So I'm trying to figure out how to get the current test method name. That would appear, as described in this other SO question be done via TestContext.

However, while TestContext.Current.Test exists, all the properties (like Name) throw a NullReferenceException when trying to access them.

Is there some other way to achieve this goal of providing more useful information in the test name?

答:
The property TestName has a support in NUnit 3 for string formatting.

Here's an example usage:

```<code>private static IEnumerable TestData()
{
    TestCaseData data;

    data = new TestCaseData(new Foo("aaa"))
                            .SetName("case 1 {m}");
    yield return data;

    data = new TestCaseData(new Foo("bbb"));
    yield return data;
}
</code>```

Will generate the following out put:

As you can see the test names the of the first case contains the custom prefix + the method name.

Use this link for more information about NUnit's string formating capability.

2 classes are resposable for this action NUnitTestCaseBuilder (line 83) and TestNameGenerator method .GetDisplayName().

Body:
I have a series of tests where I want to use the same testcase data for a bunch of different tests.

eg:

[Test, TestCaseSource("TestData")]
public void Test1(Foo foo)
{
    // test 1
}

[Test, TestCaseSource("TestData")]
public void Test2(Foo foo)
{
    // test 2
}

private static IEnumerable TestData()
{
   TestCaseData data;

   data = new TestCaseData(new Foo("aaa"));
   yield return data;

   data = new TestCaseData(new Foo("bbb"));
   yield return data;
}

This leads to a series of tests that report like so:

Namespace.That.Is.Very.Long.TestClass.Test1(Namespace.That.Is.Very.Long.Foo)
Namespace.That.Is.Very.Long.TestClass.Test1(Namespace.That.Is.Very.Long.Foo)
Namespace.That.Is.Very.Long.TestClass.Test2(Namespace.That.Is.Very.Long.Foo)
Namespace.That.Is.Very.Long.TestClass.Test2(Namespace.That.Is.Very.Long.Foo)

...which isn't hugely meaningful when you don't know what 'foo' failed..

If as suggested in this SO question I set the name like this:

   data = new TestCaseData(new Foo("aaa"));
   data.SetName("foo=aaa");
   yield return data;

...then all my tests come out looking like this:

foo=aaa
foo=bbb
foo=aaa
foo=bbb

So I'm trying to figure out how to get the current test method name. That would appear, as described in this other SO question be done via TestContext.

However, while TestContext.Current.Test exists, all the properties (like Name) throw a NullReferenceException when trying to access them.

Is there some other way to achieve this goal of providing more useful information in the test name?

Body:
The property TestName has a support in NUnit 3 for string formatting.

Here's an example usage:

private static IEnumerable TestData()
{
    TestCaseData data;

    data = new TestCaseData(new Foo("aaa"))
                            .SetName("case 1 {m}");
    yield return data;

    data = new TestCaseData(new Foo("bbb"));
    yield return data;
}

Will generate the following out put:

As you can see the test names the of the first case contains the custom prefix + the method name.

Use this link for more information about NUnit's string formating capability.

2 classes are resposable for this action NUnitTestCaseBuilder (line 83) and TestNameGenerator method .GetDisplayName().


问:
Html 5 required on radio button wil not reset
Why won't an html5 required on radio button group reset with form reset button if it was selected. for example you have a radio button group in a form with the html5 required set if you select one of the radio buttons then click the reset form button it doesn't reset the radio button group required validation so even though the form was reset. So basically you click submit button without selecting anything the radio buttons are given an outline in red then you select one and click reset you are then able to submit the form without selecting a radio button? any help on why it does this would be greatly appreciated. I may misunderstand how its supposed to work.
Simple test</p>

```<code>   <html>
   <form>
   <input type="radio" name="test" required>
   <input type="radio" name="test" required>
   <input type="submit" value="submit">
   <input type="reset" value="cancel">
   </form>
   </html>
</code>```

答:
You need to give them different value attributes (but the same name so it's clear that those are two different options for the same "question" and only one of them should be selectable):

<form>
    <input type="radio" name="test" value="1" required>1
    <input type="radio" name="test" value="2" required>2

  <input type="submit" value="submit">
  <input type="reset" value="cancel">
</form>

```

Body:
Why won't an html5 required on radio button group reset with form reset button if it was selected. for example you have a radio button group in a form with the html5 required set if you select one of the radio buttons then click the reset form button it doesn't reset the radio button group required validation so even though the form was reset. So basically you click submit button without selecting anything the radio buttons are given an outline in red then you select one and click reset you are then able to submit the form without selecting a radio button? any help on why it does this would be greatly appreciated. I may misunderstand how its supposed to work.
Simple test

   <form>
   <input type="radio" name="test" required>
   <input type="radio" name="test" required>
   <input type="submit" value="submit">
   <input type="reset" value="cancel">
   </form>

Body:
You need to give them different value attributes (but the same name so it's clear that those are two different options for the same "question" and only one of them should be selectable):

<html>
<form>
    <input type="radio" name="test" value="1" required>1
    <input type="radio" name="test" value="2" required>2<br>
  <input type="submit" value="submit">
  <input type="reset" value="cancel">
</form>

</html>


问:
test performance on different methods of obtaining input in Python
Consider a line of input for Python 3 that looks like this:

```<code>1 4 99 8 7
</code>```

Code needs to treat these inputs as numbers, so the following different ways of getting this or like input from the user is devised:

method one:

```<code>inputLst = [int(i) for i in input().split()]
</code>```

method two:

```<code>inputLst = map(int, input().split())
</code>```

How do you get an accurate performance check on code using the two different methods when the user has to interact with the code like this during testing?  Is there an effective way?

答:
The input time is constant. It won't change the difference in speed if you replace it with a constant string.

If you use the timeit module, either replace input() with a constant in the statement, or declare the function in the setup
    import timeit
    import random

```<code>tests = []
random_input = ' '.join(str(random.randint(1000, 9999)) for _ in range(1000))
setup = 'def input():\n    return ' + repr(random_input)

tests.append(timeit.timeit('[int(i) for i in input().split()]', setup, number=10000))
tests.append(timeit.timeit('list(map(int, input().split()))', setup, number=10000))
for i, time in enumerate(tests, 1):
    print('Test #{} took {:.3f} seconds to run 10000 trials.'.format(i, time))
</code>```

Which the output is (Python2):

Test #1 took 2.477 seconds to run 10000 trials.
Test #2 took 2.079 seconds to run 10000 trials.
```

<p>(Python3):</p>

<pre class="lang-none prettyprint-override"><code>Test #1 took 1.448 seconds to run 10000 trials.
Test #2 took 1.152 seconds to run 10000 trials.
</code>```

so map() is indeed faster in both versions.

Body:
Consider a line of input for Python 3 that looks like this:

1 4 99 8 7

Code needs to treat these inputs as numbers, so the following different ways of getting this or like input from the user is devised:

method one:

inputLst = [int(i) for i in input().split()]

method two:

inputLst = map(int, input().split())

How do you get an accurate performance check on code using the two different methods when the user has to interact with the code like this during testing?  Is there an effective way?

Body:
The input time is constant. It won't change the difference in speed if you replace it with a constant string.

If you use the timeit module, either replace input() with a constant in the statement, or declare the function in the setup
    import timeit
    import random

tests = []
random_input = ' '.join(str(random.randint(1000, 9999)) for _ in range(1000))
setup = 'def input():\n    return ' + repr(random_input)

tests.append(timeit.timeit('[int(i) for i in input().split()]', setup, number=10000))
tests.append(timeit.timeit('list(map(int, input().split()))', setup, number=10000))
for i, time in enumerate(tests, 1):
    print('Test #{} took {:.3f} seconds to run 10000 trials.'.format(i, time))

Which the output is (Python2):

Test #1 took 2.477 seconds to run 10000 trials.
Test #2 took 2.079 seconds to run 10000 trials.

(Python3):

Test #1 took 1.448 seconds to run 10000 trials.
Test #2 took 1.152 seconds to run 10000 trials.

so map() is indeed faster in both versions.


问:
Not sure how to build this bell-curve chart
Here is problem I'm trying to solve. It's for logistics company. I got all other inputs/variations taken care of so I have 1 straight-forward thing to do.

There is table with historical orders and prices paid per/mile. I need to present/visualize pricing distribution. Let's say prices vary from 0.80 to 1.80 per mile. Most loads done at around 1.40 per mile.

There is no special requirement HOW I should visualize that but the way I see it -
X axis will show price
Y axis will show loads count
I will show it as a curved line.

To make it look nice - I probably need to aggregate gata into 5c buckets so I don't have many points on X axis.

Does it sound right? I don't want' to reinvent wheel and maybe there is built-in function to take care of all that in 4.0 chart control?

Thanks in advance.

答:
The MSCharting samples has a "HistogramChartHelper" utility class that can make histograms easier.
I copied and made some minor edits to use in my project.</p>


问:
xml signature DS prefix?
Is there a way to sign an XML file with RSA and to have the namespace prefix "ds:Signature" instead of "Signature"? I spent many hourstrying to solve this and from what I can see there is no solution.

It seems that it is hard-coded in the class System.Security.Cryptography.Xml.Signature.

```<code>XmlElement element = document.CreateElement("Signature", "http://www.w3.org/2000/09/xmldsig#");
</code>```

If anyone knows a solution, I need to sign it like that cause the software importing it verifies it with "ds:signature", so with "ds" prefix the software verifies it like this:

```<code>    public static bool VerifySignature(XmlDocument doc, RSA key, string prefix)
    {
        SignedXml xml = new SignedXml(doc);
        string str = "Signature";
        if (!string.IsNullOrEmpty(prefix))
        {
            str = string.Format("{0}:{1}", prefix, str);
        }
        XmlNodeList elementsByTagName = doc.GetElementsByTagName(str);
        xml.LoadXml((XmlElement)elementsByTagName[0]);
        return xml.CheckSignature(key);
    }

  VerifySignature(xmlDoc, rsa, "ds");
</code>```

normally it signs like this:

```<code><kk>blabla<Signature xmlns="http://www.w3.org/2000/09/xmldsig#"><SignedInfo><CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" /><SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" /><Reference URI=""><Transforms><Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" /></Transforms><DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" /><DigestValue>rVL2nKjPTBhL9IDHYpu69OiE8gI=</DigestValue></Reference></SignedInfo><SignatureValue>CfXW9D/ErmHjzxIjy0/54/V3nst6j/XXcu7keR17LApfOZEpxjEvAlG3VnBZIi3jxQzU6t9RkmfDyngcRZccJByuuA6YDwFTQxZNRgu2GRoZxMKWnkm+MtQ0jH0Fo78GivCxV+iIewZvsrUQLzG01cXuZSH/k2eeMUaEooJaLQiYpO2aNVn5xbosTPtGlsACzFWz34E69/ZeeLZbXLc3jpDO+opxdYJ5e+Tnk/UM2Klt+N+m7Gh/sUNTPgkDiwP3q3y3O9tvCT0G2XmQaWBP4rw9TIoYHQtucm2b8R2JeggbeRKOetbRYV218RT8CK2Yuy0FIUlQXdabKyp9F96Yc55g8eNe10FGtgietH2iqquIVFLCA8fu3SZNLDPMoyHnVNKdBvI35+S8hrAaybEkMvo7iYnUSY5KrlGSfGGtfQXdaISutAzcnGPDFXgZXPNzNy7eL0u+Lt3yWWkj7wh6Zeh4fH2+nXDWYCWbLpegAEX4ZWSI5Ts6D1TplMJTGH1F0GyflehH4u+W4Lc3TvkB4dWjEuiKgnpl3hcvoj2CWFaeAxXMd/64tU/YMm8+1gSBjkVH6oV+QlI/m0z6M8FPVEVC2as0wLG2woVwmzVLcaQKyPi7NN4eO9ea7QNfaRHaofU4LQO/Y3FNJOP+uMfYlGJKWSr3qv29+BQjeNldNJY=</SignatureValue></Signature></kk>
</code>```

and I need it to do it like this:

```<code><kk>blabla<ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#"><ds:SignedInfo><ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" /><ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" /><ds:Reference URI=""><ds:Transforms><ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" /></ds:Transforms><ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" /><ds:DigestValue>rVL2nKjPTBhL9IDHYpu69OiE8gI=</ds:DigestValue></ds:Reference></ds:SignedInfo><ds:SignatureValue>CfXW9D/ErmHjzxIjy0/54/V3nst6j/XXcu7keR17LApfOZEpxjEvAlG3VnBZIi3jxQzU6t9RkmfDyngcRZccJByuuA6YDwFTQxZNRgu2GRoZxMKWnkm+MtQ0jH0Fo78GivCxV+iIewZvsrUQLzG01cXuZSH/k2eeMUaEooJaLQiYpO2aNVn5xbosTPtGlsACzFWz34E69/ZeeLZbXLc3jpDO+opxdYJ5e+Tnk/UM2Klt+N+m7Gh/sUNTPgkDiwP3q3y3O9tvCT0G2XmQaWBP4rw9TIoYHQtucm2b8R2JeggbeRKOetbRYV218RT8CK2Yuy0FIUlQXdabKyp9F96Yc55g8eNe10FGtgietH2iqquIVFLCA8fu3SZNLDPMoyHnVNKdBvI35+S8hrAaybEkMvo7iYnUSY5KrlGSfGGtfQXdaISutAzcnGPDFXgZXPNzNy7eL0u+Lt3yWWkj7wh6Zeh4fH2+nXDWYCWbLpegAEX4ZWSI5Ts6D1TplMJTGH1F0GyflehH4u+W4Lc3TvkB4dWjEuiKgnpl3hcvoj2CWFaeAxXMd/64tU/YMm8+1gSBjkVH6oV+QlI/m0z6M8FPVEVC2as0wLG2woVwmzVLcaQKyPi7NN4eO9ea7QNfaRHaofU4LQO/Y3FNJOP+uMfYlGJKWSr3qv29+BQjeNldNJY=</ds:SignatureValue></ds:Signature></kk>
</code>```

答:
The code George Dima provide works.

I will explain how it works.

When you call the ComputeSignature method this will generate the Signature Value by digesting the value of the SignedInfo node.

The code provided by George Dima adds the Prefix to the SignedInfo node and its children BEFORE getting the digest value. This won't add the prefix to the whole xml structure

this is the method that generates the digest value of the signedinfo node

```<code>private byte[] GetC14NDigest(HashAlgorithm hash, string prefix)
{
    XmlDocument document = new XmlDocument();
    document.PreserveWhitespace = true;
    XmlElement e = this.SignedInfo.GetXml();
    document.AppendChild(document.ImportNode(e, true));
    Transform canonicalizationMethodObject = this.SignedInfo.CanonicalizationMethodObject;

    SetPrefix(prefix, document.DocumentElement); //HERE'S WHERE THE PREFIX IS ADDED TO GET THE DIGEST VALUE
    canonicalizationMethodObject.LoadInput(document);
    return canonicalizationMethodObject.GetDigestedOutput(hash);
}
</code>```

So you now have the digest value of the SignedInfo node WITH the prefix, and this value will be use to get the Signature Value, but you still DON'T have the xml with the prefix yet, so if you just do this

```<code>signedXml.GetXml();
</code>```

you will get the xml without the prefix and of course because the signature value was calculated considering the ds prefix you will have an invalid signature so what you have to do is call the GetXml passing it the value of the prefix, in this case "ds" like this

```<code>signedXml.GetXml("ds");
</code>```

Title: xml signature DS prefix?

Body:
Is there a way to sign an XML file with RSA and to have the namespace prefix "ds:Signature" instead of "Signature"? I spent many hourstrying to solve this and from what I can see there is no solution.

It seems that it is hard-coded in the class System.Security.Cryptography.Xml.Signature.

XmlElement element = document.CreateElement("Signature", "http://www.w3.org/2000/09/xmldsig#");

If anyone knows a solution, I need to sign it like that cause the software importing it verifies it with "ds:signature", so with "ds" prefix the software verifies it like this:

    public static bool VerifySignature(XmlDocument doc, RSA key, string prefix)
    {
        SignedXml xml = new SignedXml(doc);
        string str = "Signature";
        if (!string.IsNullOrEmpty(prefix))
        {
            str = string.Format("{0}:{1}", prefix, str);
        }
        XmlNodeList elementsByTagName = doc.GetElementsByTagName(str);
        xml.LoadXml((XmlElement)elementsByTagName[0]);
        return xml.CheckSignature(key);
    }

  VerifySignature(xmlDoc, rsa, "ds");

normally it signs like this:

<kk>blabla<Signature xmlns="http://www.w3.org/2000/09/xmldsig#"><SignedInfo><CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" /><SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" /><Reference URI=""><Transforms><Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" /></Transforms><DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" /><DigestValue>rVL2nKjPTBhL9IDHYpu69OiE8gI=</DigestValue></Reference></SignedInfo><SignatureValue>CfXW9D/ErmHjzxIjy0/54/V3nst6j/XXcu7keR17LApfOZEpxjEvAlG3VnBZIi3jxQzU6t9RkmfDyngcRZccJByuuA6YDwFTQxZNRgu2GRoZxMKWnkm+MtQ0jH0Fo78GivCxV+iIewZvsrUQLzG01cXuZSH/k2eeMUaEooJaLQiYpO2aNVn5xbosTPtGlsACzFWz34E69/ZeeLZbXLc3jpDO+opxdYJ5e+Tnk/UM2Klt+N+m7Gh/sUNTPgkDiwP3q3y3O9tvCT0G2XmQaWBP4rw9TIoYHQtucm2b8R2JeggbeRKOetbRYV218RT8CK2Yuy0FIUlQXdabKyp9F96Yc55g8eNe10FGtgietH2iqquIVFLCA8fu3SZNLDPMoyHnVNKdBvI35+S8hrAaybEkMvo7iYnUSY5KrlGSfGGtfQXdaISutAzcnGPDFXgZXPNzNy7eL0u+Lt3yWWkj7wh6Zeh4fH2+nXDWYCWbLpegAEX4ZWSI5Ts6D1TplMJTGH1F0GyflehH4u+W4Lc3TvkB4dWjEuiKgnpl3hcvoj2CWFaeAxXMd/64tU/YMm8+1gSBjkVH6oV+QlI/m0z6M8FPVEVC2as0wLG2woVwmzVLcaQKyPi7NN4eO9ea7QNfaRHaofU4LQO/Y3FNJOP+uMfYlGJKWSr3qv29+BQjeNldNJY=</SignatureValue></Signature></kk>

and I need it to do it like this:

<kk>blabla<ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#"><ds:SignedInfo><ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" /><ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" /><ds:Reference URI=""><ds:Transforms><ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" /></ds:Transforms><ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" /><ds:DigestValue>rVL2nKjPTBhL9IDHYpu69OiE8gI=</ds:DigestValue></ds:Reference></ds:SignedInfo><ds:SignatureValue>CfXW9D/ErmHjzxIjy0/54/V3nst6j/XXcu7keR17LApfOZEpxjEvAlG3VnBZIi3jxQzU6t9RkmfDyngcRZccJByuuA6YDwFTQxZNRgu2GRoZxMKWnkm+MtQ0jH0Fo78GivCxV+iIewZvsrUQLzG01cXuZSH/k2eeMUaEooJaLQiYpO2aNVn5xbosTPtGlsACzFWz34E69/ZeeLZbXLc3jpDO+opxdYJ5e+Tnk/UM2Klt+N+m7Gh/sUNTPgkDiwP3q3y3O9tvCT0G2XmQaWBP4rw9TIoYHQtucm2b8R2JeggbeRKOetbRYV218RT8CK2Yuy0FIUlQXdabKyp9F96Yc55g8eNe10FGtgietH2iqquIVFLCA8fu3SZNLDPMoyHnVNKdBvI35+S8hrAaybEkMvo7iYnUSY5KrlGSfGGtfQXdaISutAzcnGPDFXgZXPNzNy7eL0u+Lt3yWWkj7wh6Zeh4fH2+nXDWYCWbLpegAEX4ZWSI5Ts6D1TplMJTGH1F0GyflehH4u+W4Lc3TvkB4dWjEuiKgnpl3hcvoj2CWFaeAxXMd/64tU/YMm8+1gSBjkVH6oV+QlI/m0z6M8FPVEVC2as0wLG2woVwmzVLcaQKyPi7NN4eO9ea7QNfaRHaofU4LQO/Y3FNJOP+uMfYlGJKWSr3qv29+BQjeNldNJY=</ds:SignatureValue></ds:Signature></kk>

Body:
The code George Dima provide works.

I will explain how it works.

When you call the ComputeSignature method this will generate the Signature Value by digesting the value of the SignedInfo node.

The code provided by George Dima adds the Prefix to the SignedInfo node and its children BEFORE getting the digest value. This won't add the prefix to the whole xml structure

this is the method that generates the digest value of the signedinfo node

private byte[] GetC14NDigest(HashAlgorithm hash, string prefix)
{
    XmlDocument document = new XmlDocument();
    document.PreserveWhitespace = true;
    XmlElement e = this.SignedInfo.GetXml();
    document.AppendChild(document.ImportNode(e, true));
    Transform canonicalizationMethodObject = this.SignedInfo.CanonicalizationMethodObject;

    SetPrefix(prefix, document.DocumentElement); //HERE'S WHERE THE PREFIX IS ADDED TO GET THE DIGEST VALUE
    canonicalizationMethodObject.LoadInput(document);
    return canonicalizationMethodObject.GetDigestedOutput(hash);
}

So you now have the digest value of the SignedInfo node WITH the prefix, and this value will be use to get the Signature Value, but you still DON'T have the xml with the prefix yet, so if you just do this

signedXml.GetXml();

you will get the xml without the prefix and of course because the signature value was calculated considering the ds prefix you will have an invalid signature so what you have to do is call the GetXml passing it the value of the prefix, in this case "ds" like this

signedXml.GetXml("ds");


问:
swiftyjson - Call can throw, but it is marked with 'try' and the error is not handled
I am trying to use swiftyjson and I am getting an Error:

Call can throw, but it is marked with 'try' and the error is not
  handled.

I have validated that my source JSON is good. I've been searching and cannot find a solution to this problem

```<code>import Foundation

class lenderDetails
{

func loadLender()
{

    let lenders = ""

    let url = URL(string: lenders)!
    let session =  URLSession.shared.dataTask(with: url)
    {
        (data, response, error) in

        guard let data = data else
        {
            print ("data was nil?")
            return
        }

        let json = JSON(data: data)
        print(json)
    }

    session.resume()
}
}
</code>```

Thank you for all the help!

答:
You should wrap it into a do-catch block. In your case:

```<code>do {
    let session =  URLSession.shared.dataTask(with: url) {
        (data, response, error) in
            guard let data = data else {
            print ("data was nil?")
            return
        }

        let json = JSON(data: data)
        print(json)
    }
} catch let error as NSError {
    // error
}
</code>```

Body:
I am trying to use swiftyjson and I am getting an Error:

Call can throw, but it is marked with 'try' and the error is not
  handled.

I have validated that my source JSON is good. I've been searching and cannot find a solution to this problem

import Foundation

class lenderDetails
{

func loadLender()
{

    let lenders = ""

    let url = URL(string: lenders)!
    let session =  URLSession.shared.dataTask(with: url)
    {
        (data, response, error) in

        guard let data = data else
        {
            print ("data was nil?")
            return
        }

        let json = JSON(data: data)
        print(json)
    }

    session.resume()
}
}

Thank you for all the help!

Body:
You should wrap it into a do-catch block. In your case:

do {
    let session =  URLSession.shared.dataTask(with: url) {
        (data, response, error) in
            guard let data = data else {
            print ("data was nil?")
            return
        }

        let json = JSON(data: data)
        print(json)
    }
} catch let error as NSError {
    // error
}


问:
A file does not exist in the file system but .gitignore still lists that file
I had a few files which I added to .git Ignore when they existed but they do not exist anymore. However, they are still listed in .gitignore.

when I do command git rm --cached it says that file does not exist for the obvious reasons.

Is there a way that I can tell .gitignore so stop ignoring files that just do not exist anymore?

答:
.gitignore is just a file which is in your repository.
Edit the file, remove the lines which specify the files you don't want, and commit .gitigore.</p>


问:
how to find totally duplicate object in array?
Here is an example js array:

```<code>var arr = [
  {
    name: 'test1',
    price: 20,
    otherKey: 123,
    yetAnotherKey: 'val'
  },
  {
    name: 'test2',
    price: 10,
    otherKey: 11,
    yetAnotherKey: 'erewrwert'
  },
  {
    name: 'test1',
    price: 20,
    otherKey: 123,
    yetAnotherKey: 'val'
  }
]
</code>```

Is there a way to find duplicate object (by all key/value pairs)?
If so - how to do that?
Thanks in advance.

答:
Have you tried the Undescore JS library?

uniq_.uniq(array, [isSorted], [iteratee]) Alias: unique
  Produces a duplicate-free version of the array, using === to test object equality. In particular only the first occurence of each value is kept. If you know in advance that the array is sorted, passing true for isSorted will run a much faster algorithm. If you want to compute unique items based on a transformation, pass an iteratee function.

_.uniq([1, 2, 1, 4, 1, 3]);

=> [1, 2, 4, 3]

Since you want to implement for objects, here are plenty solutions using _.uniq() which you might want to have a look at - Removing duplicate objects with Underscore for Javascript

Body:
Here is an example js array:

var arr = [
  {
    name: 'test1',
    price: 20,
    otherKey: 123,
    yetAnotherKey: 'val'
  },
  {
    name: 'test2',
    price: 10,
    otherKey: 11,
    yetAnotherKey: 'erewrwert'
  },
  {
    name: 'test1',
    price: 20,
    otherKey: 123,
    yetAnotherKey: 'val'
  }
]

Is there a way to find duplicate object (by all key/value pairs)?
If so - how to do that?
Thanks in advance.


问:
How to pass generic class objects with a different type to one List?
Hello I need some inspiration,

I have a waypoint class like so:

```<code>public class Waypoint<T> {

}
</code>```

and I would like to add all my waypoints to one list like so:

```<code>var w1 = new Waypoint<Item>();
var w2 = new Waypoint<Player>();
var waypoints = new List<Waypoint<?>>();
</code>```

Problem is, they are not all of the same Type.
Is there a way that I can add different types to one list?

Anybody know an easy workaround?
Language: C#

Kind regards,

Venomous

答:
Instead of a generic base class, you could define Waypoint as an interface and have Item and Player implement it. That way you can have a list of IWaypoints like you want.</p>

```<code>interface IWaypoint
{
    Point GetPosition();//whatever a waypoint should do
}

class Item : IWaypoint
{
    Point location;
    public Point GetPosition()
    {
       return location;
    }
}

class Player : IWaypoint
{
    Point position;
    float movespeed;
    public Point GetPosition()
    {
        return position * movespeed;
    }
}

void main()
{
    List<IWaypoint> waypoints = new List<IWaypoint>();
    waypoints.Add(new Player());
    waypoints.Add(new Item());
    foreach (IWaypoint wp in waypoints)
    {
        Console.WriteLine(wp.GetPosition());
    }
}
</code>```

Body:
Hello I need some inspiration,

I have a waypoint class like so:

public class Waypoint<T> {

}

and I would like to add all my waypoints to one list like so:

var w1 = new Waypoint<Item>();
var w2 = new Waypoint<Player>();
var waypoints = new List<Waypoint<?>>();

Problem is, they are not all of the same Type.
Is there a way that I can add different types to one list?

Anybody know an easy workaround?
Language: C#

Kind regards,

Venomous

Body:
Instead of a generic base class, you could define Waypoint as an interface and have Item and Player implement it. That way you can have a list of IWaypoints like you want.

interface IWaypoint
{
    Point GetPosition();//whatever a waypoint should do
}

class Item : IWaypoint
{
    Point location;
    public Point GetPosition()
    {
       return location;
    }
}

class Player : IWaypoint
{
    Point position;
    float movespeed;
    public Point GetPosition()
    {
        return position * movespeed;
    }
}

void main()
{
    List<IWaypoint> waypoints = new List<IWaypoint>();
    waypoints.Add(new Player());
    waypoints.Add(new Item());
    foreach (IWaypoint wp in waypoints)
    {
        Console.WriteLine(wp.GetPosition());
    }
}


问:
If i am making a image sharing service website using the standard file upload form what images can i say it supports, other then jpg, png, gif
If i am making a image sharing service website using the standard file upload form what images can i say it supports, other then jpg, png, gif. Is there a list that shows what browsers supports what? I know that jpg png and gif are most common but what are the others. I want to be sure.</p>

答: Honestly, that's pretty much all you should be concerned with. Any other file formats (like svg) are not widely supported enough.</p>


问:
How can I resize a parent layout when its children scale?
I have a HorizontalScrollView that contains a horizontal LinearLayout that contains a series of custom views (ToolbarButton):

```<code><HorizontalScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ToolbarButton/>
        <ToolbarButton/>
        ...

    </LinearLayout>

</HorizontalScrollView>
</code>```

Now, at run time, I want to scale the ToolbarButtons to be smaller using setScaleX and setScaleY.  The scaling works, but the positions of the ToolbarButtons does not change, nor does the size of the LinearLayout.

When I use scaleX and scaleY in the ToolbarButtons in xml (not runtime) I get the same result.

My goal is to dynamically shrink the ToolbarButtons and have the space around them also shrink.  How do I do this?  Thank you.

答:
You need to tell the parent to redraw itself:

```<code>if (getParent() instanceof View)
    ((View) getParent()).invalidate();
</code>```

See here.

Body:
I have a HorizontalScrollView that contains a horizontal LinearLayout that contains a series of custom views (ToolbarButton):

<HorizontalScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ToolbarButton/>
        <ToolbarButton/>
        ...

    </LinearLayout>

</HorizontalScrollView>

Now, at run time, I want to scale the ToolbarButtons to be smaller using setScaleX and setScaleY.  The scaling works, but the positions of the ToolbarButtons does not change, nor does the size of the LinearLayout.

When I use scaleX and scaleY in the ToolbarButtons in xml (not runtime) I get the same result.

My goal is to dynamically shrink the ToolbarButtons and have the space around them also shrink.  How do I do this?  Thank you.

Body:
You need to tell the parent to redraw itself:

if (getParent() instanceof View)
    ((View) getParent()).invalidate();

See here.


问:
Do SELECT query based on statement returned from other SELECT
I have two tables:

```<code>notifications
- email_address
- notification_email

users
- username
- domain
- notifications
</code>```

My question is if I can build MySQL query which can do SELECT query based on statement returned from other SELECT without using scripting (Perl, Python, etc) and IF...ELSE statement?

Current code logic is set for queries below

```<code>SELECT notifications FROM users WHERE (username LIKE 'tester') AND (domain LIKE 'my.testdomain.com')

If notifications='Y' then

SELECT notification_email FROM notifications WHERE email_address = 'tester@my.testdomain.com'
</code>```

答:
Ideally you should have a foreign key link between notifications and users table.

Then your query would look like this:

```<code>SELECT
    notifications.notification_email
FROM
    notifications
        JOIN
    users ON (users.id = notifications.user_id)
WHERE
    users.username = 'tester'
        AND
    users.domain = 'my.testdomain.com'
        AND
    users.notifications = 'Y'
        AND
    notifications.email_address = 'tester@my.testdomain.com'
</code>```

If there is no foreign key, there must be another way how the two tables are linked together (e.g. email). In such case you need to update the ON clause to connect the two tables together using columns containing equal data.

You might then not even need the notifications.email_address = 'tester@my.testdomain.com' condition.

Body:
I have two tables:

notifications
- email_address
- notification_email

users
- username
- domain
- notifications

My question is if I can build MySQL query which can do SELECT query based on statement returned from other SELECT without using scripting (Perl, Python, etc) and IF...ELSE statement?

Current code logic is set for queries below

SELECT notifications FROM users WHERE (username LIKE 'tester') AND (domain LIKE 'my.testdomain.com')

If notifications='Y' then

SELECT notification_email FROM notifications WHERE email_address = 'tester@my.testdomain.com'

Body:
Ideally you should have a foreign key link between notifications and users table.

Then your query would look like this:

SELECT
    notifications.notification_email
FROM
    notifications
        JOIN
    users ON (users.id = notifications.user_id)
WHERE
    users.username = 'tester'
        AND
    users.domain = 'my.testdomain.com'
        AND
    users.notifications = 'Y'
        AND
    notifications.email_address = 'tester@my.testdomain.com'

If there is no foreign key, there must be another way how the two tables are linked together (e.g. email). In such case you need to update the ON clause to connect the two tables together using columns containing equal data.

You might then not even need the notifications.email_address = 'tester@my.testdomain.com' condition.


问:
Android Shared Preference check value
I'm working on android application that have 2 activities A and B . I have a button in B Activity with event that save the current time of android device, the time save in Shared Preferences:

```<code>long TimeMillis = date.getTime();
editor = sharedpreferences.edit();
editor.putString("TimeMillis", String.valueOf(TimeMillis));
</code>```

I need to check the value of the previous Shared Preferences in A Activity

Note: the Date save on B then check it in A . A come before B.

答:
You can get your value from shared preferences anywhere you want like this:</p>

```<code>SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String mSharedDate= prefs.getString("TimeMillis", "");
if(mSharedDate!=null){
// do something
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Android Shared Preference check value

Body:
I'm working on android application that have 2 activities A and B . I have a button in B Activity with event that save the current time of android device, the time save in Shared Preferences:

long TimeMillis = date.getTime();
editor = sharedpreferences.edit();
editor.putString("TimeMillis", String.valueOf(TimeMillis));

I need to check the value of the previous Shared Preferences in A Activity

Note: the Date save on B then check it in A . A come before B.

Body:
You can get your value from shared preferences anywhere you want like this:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String mSharedDate= prefs.getString("TimeMillis", "");
if(mSharedDate!=null){
// do something
}


问:
python selenium search query provides multiple results. how choose which is mine search query?
I made a search query with selenium. after that i get multiple results. Now the problem is, only one link is right.how can i select the link from multiple results?  and parse the data from the results.
i have a list and every time a search query is made results may change sometimes its 10 or 15.

the following code will select the first result always, But in this case i am looking for 4 link:

code:

```<code>from selenium import webdriver
from bs4 import BeautifulSoup
import time

driver = webdriver.Chrome()
driver.get("url")
#time.sleep(5)

username = driver.find_element_by_name("p_name")
#time.sleep(1)
username.send_keys("xxxxx)
#username.clear()
driver.find_element_by_xpath("html/body/form/table[6]/tbody/tr/td[2]/input").click()
driver.find_element_by_xpath("html/body/form/table[3]/tbody/tr[2]/td[4]/a").click()

html = driver.page_source

soup =BeautifulSoup(html)

for tag in soup.find_all('table'):
    print tag.text
</code>```

答:
The answer is to use better selectors that only return one result. I prefer CSS Selectors but the process is largely the same for XPath if you prefer.

To get a CSS Selector in Chrome:

Right-click on the element and select 'Inspect'

Right-click on the element in the DOM explorer of DevTools

Select "Copy" > "Copy selector" (Alternatively you could get the XPath here too)

driver.find_element_by_css_selector(("body > form > table:nth-child(4) > tbody > tr:nth-child(2) > td:nth-child(2) > input[type='text']")).sendKeys("Timothy")

driver.find_element_by_css_selector(("body > form > table:nth-child(5) > tbody > tr > td:nth-child(2) > input[type='text']")).sendKeys("Cope")

Body:
I made a search query with selenium. after that i get multiple results. Now the problem is, only one link is right.how can i select the link from multiple results?  and parse the data from the results.
i have a list and every time a search query is made results may change sometimes its 10 or 15.

the following code will select the first result always, But in this case i am looking for 4 link:

code:

from selenium import webdriver
from bs4 import BeautifulSoup
import time

driver = webdriver.Chrome()
driver.get("url")
#time.sleep(5)

username = driver.find_element_by_name("p_name")
#time.sleep(1)
username.send_keys("xxxxx)
#username.clear()
driver.find_element_by_xpath("html/body/form/table[6]/tbody/tr/td[2]/input").click()
driver.find_element_by_xpath("html/body/form/table[3]/tbody/tr[2]/td[4]/a").click()

html = driver.page_source

soup =BeautifulSoup(html)

for tag in soup.find_all('table'):
    print tag.text


答:
Also with data.table and dplyr, you can do

```<code>library(data.table)
setDT(df)[, mean(Value), by = TestNum]

library(dplyr)
df %>% group_by(TestNum) %>% summarise(mean(Value))
</code>```

If there are other columns, you can use the other columns' first value in each TestNum. Like this:

```<code>df2<-data.frame(FileName = "File1",
                Version = paste0("1.0.", rep(c(1,2,4,5,8), each = 3)),
                Value, TestNum, RepNum)

## data.table
keep_cols <- c("FileName", "Version")
setDT(df2)[, c(lapply(.SD, function(x) x[1]), mean_Value = mean(Value)),
           by = TestNum, .SDcols = keep_cols]

## dplyr
df2 %>% group_by(TestNum) %>% summarise(FileName = FileName[1],
                                        Version = Version[1],
                                        mean_Value = mean(Value))
</code>```

Title: Finding the average for certain unique categories in a data frame

Body:
If I have an R data frame that looks like this:

| Value | TestNum | RepNum |
|:-----:|:-------:|:------:|
| 104   |       1 |      1 |
| 101   |       1 |      2 |
| 101   |       1 |      3 |
| 100   |       2 |      1 |
| 100   |       2 |      2 |
| 100   |       2 |      3 |
| 90    |       3 |      1 |
| 90    |       3 |      2 |
| 90    |       3 |      3 |
| 91    |       4 |      1 |
| 94    |       4 |      2 |
| 94    |       4 |      3 |
| 105   |       5 |      1 |
| 105   |       5 |      2 |
| 108   |       5 |      3 |

Is there a way that I can modify this data frame to find the average for the 3 RepNum Values for each unique TestNum so that it looks like this:

| Mean | TestNum |
|:----:|:-------:|
| 102  |       1 |
| 100  |       2 |
| 90   |       3 |
| 93   |       4 |
| 106  |       5 |

You can create this example data frame in R by copying and pasting this code and executing it.

Value<-c(100,101,100,100,100,100,90,90,90,93,94,94,105,105,108)
TestNum<-c(1,1,1,2,2,2,3,3,3,4,4,4,5,5,5)
RepNum<-c(1,2,3,1,2,3,1,2,3,1,2,3,1,2,3)

df<-data.frame(Value,TestNum,RepNum)

EDIT: Here's a "more complete" example of the data frame I'm starting with an what I'm hoping to end up with:

| FileName | Version |  Category | Value | TestNum | RepNum |
|:--------:|:-------:|:---------:|:-----:|:-------:|:------:|
| File1    | 1.0.1   | Category1 |   104 |       1 |      1 |
| File1    | 1.0.1   | Category1 |   101 |       1 |      2 |
| File1    | 1.0.1   | Category1 |   101 |       1 |      3 |
| File1    | 1.0.2   | Category1 |   100 |       2 |      1 |
| File1    | 1.0.2   | Category1 |   100 |       2 |      2 |
| File1    | 1.0.2   | Category1 |   100 |       2 |      3 |
| File1    | 1.0.4   | Category1 |    90 |       3 |      1 |
| File1    | 1.0.4   | Category1 |    90 |       3 |      2 |
| File1    | 1.0.4   | Category1 |    90 |       3 |      3 |
| File1    | 1.0.5   | Category1 |    94 |       4 |      1 |
| File1    | 1.0.5   | Category1 |    91 |       4 |      2 |
| File1    | 1.0.5   | Category1 |    94 |       4 |      3 |
| File1    | 1.0.8   | Category1 |   105 |       5 |      1 |
| File1    | 1.0.8   | Category1 |   105 |       5 |      2 |
| File1    | 1.0.8   | Category1 |   108 |       5 |      3 |

And ending with this:

| FileName | Version |  Category | Mean_Value | TestNum |
|:--------:|:-------:|:---------:|:----------:|:-------:|
| File1    | 1.0.1   | Category1 |        102 |       1 |
| File1    | 1.0.2   | Category1 |        100 |       2 |
| File1    | 1.0.4   | Category1 |         90 |       3 |
| File1    | 1.0.5   | Category1 |         93 |       4 |
| File1    | 1.0.8   | Category1 |        106 |       5 |

As you've probably noticed, there is only 1 unique entry for both the FileName column and the Category column. The Version column is changing along with the TestNum column. So it seems like it might be easiest to simply add in these other columns after I've found the mean.

In the "full" code that I'm working on, I'm getting the mean values for several different files and many unique categories but I've been creating multiple data frames that are created by subsetting an original data frame  on the FileName and Category (and an additional "Case" column).

Body:
Also with data.table and dplyr, you can do

library(data.table)
setDT(df)[, mean(Value), by = TestNum]

library(dplyr)
df %>% group_by(TestNum) %>% summarise(mean(Value))

If there are other columns, you can use the other columns' first value in each TestNum. Like this:

df2<-data.frame(FileName = "File1",
                Version = paste0("1.0.", rep(c(1,2,4,5,8), each = 3)),
                Value, TestNum, RepNum)

## data.table
keep_cols <- c("FileName", "Version")
setDT(df2)[, c(lapply(.SD, function(x) x[1]), mean_Value = mean(Value)),
           by = TestNum, .SDcols = keep_cols]

## dplyr
df2 %>% group_by(TestNum) %>% summarise(FileName = FileName[1],
                                        Version = Version[1],
                                        mean_Value = mean(Value))


问:
Lookup between two ranges
Afternoon all, I'm working with two columns of data - one of these has an author name and the second has a publish date-time value. I'm looking to build up a UDF to take these two ranges, search the author column for a particular string and if found to return the value from the publish column.

Data looks similar to this;

Once it has found the author I'm looking for i want it to look at the publish time and find the minimum value for this.

For example, if i was looking for the author Ben in the above then the value returned should be 08/06/2014 17:15.

If the data i was working with was always in the same format then i would build up an array formula to create a MINIF but the columns these ranges show in are always different and the easiest option will be a UDF that the end user can just put the two ranges into.

Thanks in advance for any help.

Cheers

答:
It's suppose to look like that, just change this row:

```<code>If Cells(x,1).Value="ben" Then 'or whatever name you chose
</code>```

if you want it to be some other Author

```<code> Dim x As Integer
 Dim y As Integer
 Dim a As Date

      Application.ScreenUpdating = False
      ' Set numrows = number of rows of data.
      NumRows1 = Range("A1", Range("A1").End(xlDown)).Rows.Count
      NumRows2 = Range("B1", Range("B1").End(xlDown)).Rows.Count

      Range("A1").Select

      For x = 1 To NumRows1
           If Cells(x,1).Value="ben" Then 'or whatever name you chose
             If IsEmpty(a) Then
                A = Cells(x,2)
             End If
             If DateValue(Cells(x,2))<A Then
                  A = Cells(x,2)
             End If
           End If
      Next
</code>```

Title: Lookup between two ranges

Body:
It's suppose to look like that, just change this row:

If Cells(x,1).Value="ben" Then 'or whatever name you chose

if you want it to be some other Author

 Dim x As Integer
 Dim y As Integer
 Dim a As Date

      Application.ScreenUpdating = False
      ' Set numrows = number of rows of data.
      NumRows1 = Range("A1", Range("A1").End(xlDown)).Rows.Count
      NumRows2 = Range("B1", Range("B1").End(xlDown)).Rows.Count

      Range("A1").Select

      For x = 1 To NumRows1
           If Cells(x,1).Value="ben" Then 'or whatever name you chose
             If IsEmpty(a) Then
                A = Cells(x,2)
             End If
             If DateValue(Cells(x,2))<A Then
                  A = Cells(x,2)
             End If
           End If
      Next


问:
JavaFX: background overflow on button's border
I have a button with custom CSS. The white background is overflowing and is seen past the black border (as shown in the picture).

I'm not sure how to fix this issue as I have experience only with web version of CSS.

Thanks for any help!

```<code>.root {
 -fx-font-family: verdana;
 -fx-background-color: rgb(16, 118, 252);

}

#head {
  -fx-font-size: 30;
  -fx-fill: black;
  -fx-font-weight: bold;
}

.button {
  -fx-background-radius: 50;
  -fx-border-radius: 25px;
  -fx-text-fill: black;
  -fx-background-color: white;
  -fx-font-size: 25;
  -fx-border-style: solid;
  -fx-border-color: black;
  -fx-border-width: 5px;
}

#footer {
  -fx-font-size: 18;
}
</code>```

答:
It seems there are some rounding errors for ...-radius styles.
You can hide background under the border by using insets:

```<code>  -fx-background-insets: 5px;
</code>```

Body:
I have a button with custom CSS. The white background is overflowing and is seen past the black border (as shown in the picture).

I'm not sure how to fix this issue as I have experience only with web version of CSS.

Thanks for any help!

.root {
 -fx-font-family: verdana;
 -fx-background-color: rgb(16, 118, 252);

}

#head {
  -fx-font-size: 30;
  -fx-fill: black;
  -fx-font-weight: bold;
}

.button {
  -fx-background-radius: 50;
  -fx-border-radius: 25px;
  -fx-text-fill: black;
  -fx-background-color: white;
  -fx-font-size: 25;
  -fx-border-style: solid;
  -fx-border-color: black;
  -fx-border-width: 5px;
}

#footer {
  -fx-font-size: 18;
}

Body:
It seems there are some rounding errors for ...-radius styles.
You can hide background under the border by using insets:

  -fx-background-insets: 5px;


问:
Best and worst case runtimes of my search algorithm (similar to bubble sort)?
So I know this algorithm is pretty simple, but I can't wrap my head around the time complexity of the code. It takes in an array (say 5 numbers) and sorts it in increasing order and in a similar manner to bubble sort (but not quite the same). What are the best and worst case runtimes of this algorithm?

```<code>int sort(int arr[1...n]){
  while(i <= n){
    k = n;
    while(k >= i+1){
      if (arr[k-1] > arr[k]){
        tmp = arr[k-1];
        arr[k-1] = arr[k];
        arr[k] = tmp;
      }
      k--;
    }
    i++;
  }
}
</code>```

My reasoning:

The worst case would be if the array was in reverse sorted order, say [5,4,3,2,1]. I know the outer while loop would be executed n times, but the inner while loop is what throws me off. For each iteration of the outer while, I think the inner while executes i+1 times, so with the array I gave, it would execute the inner while 4,3,2,and then finally 1 time (that's a total of (n-1) executions of the inner while loop)...Putting it together I have n*(n-1), so does that mean worst case is O(n^2)?

The best case is when the array is already sorted, say [1,2,3,4,5].So in that case we would never need to do nay swapping of numbers, and the if statement in the inner while is never executed. But the code seems to loop through everything despite the fact that the array is already sorted. We still go through both while loops which leads me to believe it's still n*(n-1), but that seems off to me. Any help is appreciated.

答:
In the worst case there will be 1+2+3+...(n-1) iterations, so that's n(n-1)/2 => n^2/2 - n/2.

Neglecting the constants, the algorithm is of worst case O(n^2 - n) complexity, which is just O(n^2).

Body:
So I know this algorithm is pretty simple, but I can't wrap my head around the time complexity of the code. It takes in an array (say 5 numbers) and sorts it in increasing order and in a similar manner to bubble sort (but not quite the same). What are the best and worst case runtimes of this algorithm?

int sort(int arr[1...n]){
  while(i <= n){
    k = n;
    while(k >= i+1){
      if (arr[k-1] > arr[k]){
        tmp = arr[k-1];
        arr[k-1] = arr[k];
        arr[k] = tmp;
      }
      k--;
    }
    i++;
  }
}

My reasoning:

The worst case would be if the array was in reverse sorted order, say [5,4,3,2,1]. I know the outer while loop would be executed n times, but the inner while loop is what throws me off. For each iteration of the outer while, I think the inner while executes i+1 times, so with the array I gave, it would execute the inner while 4,3,2,and then finally 1 time (that's a total of (n-1) executions of the inner while loop)...Putting it together I have n*(n-1), so does that mean worst case is O(n^2)?

The best case is when the array is already sorted, say [1,2,3,4,5].So in that case we would never need to do nay swapping of numbers, and the if statement in the inner while is never executed. But the code seems to loop through everything despite the fact that the array is already sorted. We still go through both while loops which leads me to believe it's still n*(n-1), but that seems off to me. Any help is appreciated.


问:
Arithmetic overflow w/ bigints in SQL Server 2008
I'm having a problem with arithmetic overflow when converting to bigint in SQL Server 2008.  The following is confusing me.

This works:

```<code>select 58356453 * 228204732751
</code>```

Answer: 13317218761161292203

But, all other attempts that involve explicit conversion fail.

```<code>select convert(bigint, 58356453 * 228204732751)
</code>```

result: arithmetic overflow

```<code>begin
    declare @key bigint = 58356453,
        @workingVal bigint,
        @primeMultiplier1 bigint = 228204732751;
    set @workingVal = @key * @primeMultiplier1;
end;
</code>```

result: arithmetic overflow

What am I missing here?  I've also tried "cast(BigNumber as bigint)" (don't think it's any different from convert), and various combinations of conversion before/after arithmetic operations.

And, this is on Windows Server 2008 x64

答:
You should use the numeric datatype.</p>

```<code>select cast(13317218761161292203 as numeric(38))
</code>```

Body:
I'm having a problem with arithmetic overflow when converting to bigint in SQL Server 2008.  The following is confusing me.

This works:

select 58356453 * 228204732751

Answer: 13317218761161292203

But, all other attempts that involve explicit conversion fail.

select convert(bigint, 58356453 * 228204732751)

result: arithmetic overflow

begin
    declare @key bigint = 58356453,
        @workingVal bigint,
        @primeMultiplier1 bigint = 228204732751;
    set @workingVal = @key * @primeMultiplier1;
end;

result: arithmetic overflow

What am I missing here?  I've also tried "cast(BigNumber as bigint)" (don't think it's any different from convert), and various combinations of conversion before/after arithmetic operations.

And, this is on Windows Server 2008 x64

Body:
You should use the numeric datatype.

select cast(13317218761161292203 as numeric(38))


问:
Is there ever a reason not to wrap InputStreamReader with BufferedReader?
I have the following code to read from a CSV:

```<code>InputStream inp = getClass().getResourceAsStream(filename);
InputStreamReader r = new InputStreamReader(inp);
BufferedReader reader = new BufferedReader(r);
</code>```

On answered questions:
Java BufferedReader,
Convert InputStream to BufferedReader, What is the difference between Java's BufferedReader and InputStreamReader classes?

BufferedReader[BR] and InputStreamReader[ISR] both implement the same interfaces. BR has every method that ISR has with the additional methods including the ever so useful readLine() method and less useful but still relevant skip() method. You don't necessarily need BR to read single characters although BR can do the same more efficiently than ISR in this respect. The only significant difference is that FileReader is a subclass of ISR but not BR, although I have had sources on this website say that FileReader isn't really used anymore due to alternatives.

My research says that everything ISR can do is done better by BR. I am a young developer so every defined or imported class to me seems relevant. What I am trying to grasp is if some classes are no longer used, with new versions or frameworks replacing them. I want to know what more experienced developers have to say. SO, is there a reason to not use BR when using ISR?

QuickLinks to API:

BufferedReader

InputStreamReader

答:
I see some confusion in your post about ISR and BR.

1) You are saying that

My research says that everything ISR can do is done better by BR

But lets look at JavaDoc for each of them:

ISR

public class InputStreamReader extends Reader

An InputStreamReader is a bridge from byte streams to character
  streams:

BR

Reads text from a character-input stream, buffering characters so as
  to provide for the efficient reading of characters, arrays, and lines.

As you can see ISR converts bytes to chars. BR on other hand needs chars. Thats why BR needs to use ISR to read from InputStream.

2) As to the original question why not to just use ISR. You can definately do that, but in order to gain performance you want to use BR. You might ask why ISR was not implemented using buffering? Because ISR is designed to do one thing good and that is to read and convert bytes to chars. The buffering part is moved into the Decorator class that is BR. This is done in order to be able to add buffering capabilities to any Reader and not only ISR.

Body:
I have the following code to read from a CSV:

InputStream inp = getClass().getResourceAsStream(filename);
InputStreamReader r = new InputStreamReader(inp);
BufferedReader reader = new BufferedReader(r);

On answered questions:
Java BufferedReader,
Convert InputStream to BufferedReader, What is the difference between Java's BufferedReader and InputStreamReader classes?

BufferedReader[BR] and InputStreamReader[ISR] both implement the same interfaces. BR has every method that ISR has with the additional methods including the ever so useful readLine() method and less useful but still relevant skip() method. You don't necessarily need BR to read single characters although BR can do the same more efficiently than ISR in this respect. The only significant difference is that FileReader is a subclass of ISR but not BR, although I have had sources on this website say that FileReader isn't really used anymore due to alternatives.

My research says that everything ISR can do is done better by BR. I am a young developer so every defined or imported class to me seems relevant. What I am trying to grasp is if some classes are no longer used, with new versions or frameworks replacing them. I want to know what more experienced developers have to say. SO, is there a reason to not use BR when using ISR?

QuickLinks to API:

BufferedReader

InputStreamReader


问:
Perl installation using docker
I am trying to build the docker image with perl installation. but facing issues with the make command. it says No makefile found.
Dockerfile:

```<code>FROM amazonlinux
WORKDIR /shared
RUN yum -y install gcc
ADD http://www.cpan.org/src/5.0/perl-5.22.1.tar.gz /shared
RUN tar -xzf perl-5.22.1.tar.gz
RUN /shared/perl-5.22.1/Configure -des -Dprefix=/opt/perl-5.22.1/localperl
RUN make -C /shared/perl-5.22.1
RUN make -C /shared/perl-5.22.1 test
RUN make -C /shared/perl-5.22.1 install
</code>```

Error:

```<code>Step 14/20 : ADD http://www.cpan.org/src/5.0/perl-5.22.1.tar.gz /shared
Downloading 15.92 MB/15.92 MB
 ---> Using cache
 ---> 24f3b38dee5f
Step 15/20 : RUN tar -xzf perl-5.22.1.tar.gz
 ---> Using cache
 ---> 42ecf82ce73d
Step 16/20 : RUN /shared/perl-5.22.1/Configure -des -Dprefix=/opt/perl-5.22.1/localperl
 ---> Using cache
 ---> dfe8d71f5ff1
Step 17/20 : RUN make -C /shared/perl-5.22.1/
 ---> Running in 2766b0c8e9a5
make: Entering directory `/shared/perl-5.22.1'
make: Leaving directory `/shared/perl-5.22.1'
make: *** No targets specified and no makefile found.  Stop.
The command '/bin/sh -c make -C /shared/perl-5.22.1/' returned a non-zero code: 2
ish-mac:testanalyse ish$ ls -l
</code>```

Can anyone help me fix it.

答:
As the README says, simply run make, but change directory to the root of the source code (/shared/perl-5.22.1):

```<code>FROM amazonlinux
WORKDIR /shared
RUN yum -y install gcc
ADD http://www.cpan.org/src/5.0/perl-5.22.1.tar.gz /shared
RUN tar -xzf perl-5.22.1.tar.gz

WORKDIR /shared/perl-5.22.1
RUN ./Configure -des -Dprefix=/opt/perl-5.22.1/localperl

RUN make
RUN make test
RUN make install
</code>```

README:

```<code>INSTALLATION
============

If you're using a relatively modern operating system and want to
install this version of Perl locally, run the following commands:

  ./Configure -des -Dprefix=$HOME/localperl
  make test
  make install
</code>```

Title: Perl installation using docker

Body:
I am trying to build the docker image with perl installation. but facing issues with the make command. it says No makefile found.
Dockerfile:

FROM amazonlinux
WORKDIR /shared
RUN yum -y install gcc
ADD http://www.cpan.org/src/5.0/perl-5.22.1.tar.gz /shared
RUN tar -xzf perl-5.22.1.tar.gz
RUN /shared/perl-5.22.1/Configure -des -Dprefix=/opt/perl-5.22.1/localperl
RUN make -C /shared/perl-5.22.1
RUN make -C /shared/perl-5.22.1 test
RUN make -C /shared/perl-5.22.1 install

Error:

Step 14/20 : ADD http://www.cpan.org/src/5.0/perl-5.22.1.tar.gz /shared
Downloading 15.92 MB/15.92 MB
 ---> Using cache
 ---> 24f3b38dee5f
Step 15/20 : RUN tar -xzf perl-5.22.1.tar.gz
 ---> Using cache
 ---> 42ecf82ce73d
Step 16/20 : RUN /shared/perl-5.22.1/Configure -des -Dprefix=/opt/perl-5.22.1/localperl
 ---> Using cache
 ---> dfe8d71f5ff1
Step 17/20 : RUN make -C /shared/perl-5.22.1/
 ---> Running in 2766b0c8e9a5
make: Entering directory `/shared/perl-5.22.1'
make: Leaving directory `/shared/perl-5.22.1'
make: *** No targets specified and no makefile found.  Stop.
The command '/bin/sh -c make -C /shared/perl-5.22.1/' returned a non-zero code: 2
ish-mac:testanalyse ish$ ls -l

Can anyone help me fix it.

Body:
As the README says, simply run make, but change directory to the root of the source code (/shared/perl-5.22.1):

FROM amazonlinux
WORKDIR /shared
RUN yum -y install gcc
ADD http://www.cpan.org/src/5.0/perl-5.22.1.tar.gz /shared
RUN tar -xzf perl-5.22.1.tar.gz

WORKDIR /shared/perl-5.22.1
RUN ./Configure -des -Dprefix=/opt/perl-5.22.1/localperl

RUN make
RUN make test
RUN make install

README:

INSTALLATION
============

If you're using a relatively modern operating system and want to
install this version of Perl locally, run the following commands:

  ./Configure -des -Dprefix=$HOME/localperl
  make test
  make install


问:
Dynamics CRM 365 - Exporting / importing solution error due to dependencies
I've developed a solution on a developer Dynamics 365 CRM instance. Actually, it's a trial version which contains all proposed modules during installation.
Now that I've created my solution, I've exported it as a managed solution and gave it to the customer.
He cannot install it because there are some missing dependencies on his instance, which are the following:

So it says that on the USER form that I've adding to my solution, there are some dependencies with some other solutions named "Project Service" and "Field Service".

When I go to the form included in my solution, and hit "Show dependencies", it's written that the solution won't be installed on a system that doesn't have a given list of components. Among them, many components (relations, entities, fields) are from the above two solutions.

As I cannot delete the dependent solutions (FieldService and Project Service), how can I resolve these dependencies ?

答: I think you should only add this items from the User entity to the Solution which you has customized, not add the complete Entity. (Also add to your solution only items which you have customized). If you export the solution and the system show's you the missing dependencies, don't select them. But you must be sure that you have not forget something in your solution. </p>


问:
Console Application as continuous Azure webjob does not convert Time.ToUniversalTime() in UTC
I have a simple console application running as continuous webjob in Azure, Locally when I debug it gives proper output time in UTC when I convert time using
    new DateTime(Time).ToUniversalTime()
but when I run it in webjob it still gives local time instead of universal time.

Console.WriteLine(MyData.Time.ToUniversalTime() + " "+ DateTime.Now.ToUniversalTime());

at 3:43 PM PST

Kudu console (webjob): 6/7/2017 3:38:46 PM 6/7/2017 10:43:52 PM

on local Console: 6/7/2017 10:38:46 PM 6/7/2017 10:43:52 PM

答: I changed the timezone of the website on Azure portal. Thanks for all the help. </p>


问:
Choose between Auto Mapping and Fluent mapping with Fluent NHibernate (S#arp Architecture)
I have a application using NHibernate Auto Mapping... All working fine so far...

My Fluent Global.asax config:

```<code>private void InitializeNHibernateSession()
{
    NHibernateSession.Init(
         webSessionStorage,
         new string[] { Server.MapPath("~/bin/Proj.Data.dll") },
         new AutoPersistenceModelGenerator().Generate(),
         Server.MapPath("~/NHibernate.config"));
}
</code>```

But I need to map a class with Fluent mapping... I created the class :

```<code>namespace Proj.Data.NHibernateMaps
{
  public class CategoryMap : IAutoMappingOverride<Category>
  {
    public void Override(AutoMapping<Category> mapping)
    {
        mapping.Id(x => x.Id)
            .GeneratedBy.Identity();

        mapping.Map(x => x.Description);
        mapping.Map(x => x.UrlName);

        mapping.References(x => x.ParentCategory)
            .Not.LazyLoad();
    }
  }
}
</code>```

The problem is that this mapping is never used by the NHibernate... Instead it uses the Auto Mapping generated Category...

How can I use my Fluent Mapping ?

Thanks

Paul

答:
Wherever you're configuring the AutoPersistenceModel you need to reference the mapping overrides.  I find the easiest way to do this is to just point it at the assembly containing the mapping overrides and let it discover all of them.  That way you can add new IAutoMappingOverride implementations and it will be automatically picked up.  You do this using the UseOverridesFromAssemblyOf extension method.</p>

```<code>public class AutoPersistenceModelGenerator {
    public AutoPersistenceModel Generate() {
        return AutoMap.AssemblyOf<Category>()
            .UseOverridesFromAssemblyOf<CategoryMap>();
    }
}
</code>```

Body:
I have a application using NHibernate Auto Mapping... All working fine so far...

My Fluent Global.asax config:

private void InitializeNHibernateSession()
{
    NHibernateSession.Init(
         webSessionStorage,
         new string[] { Server.MapPath("~/bin/Proj.Data.dll") },
         new AutoPersistenceModelGenerator().Generate(),
         Server.MapPath("~/NHibernate.config"));
}

But I need to map a class with Fluent mapping... I created the class :

namespace Proj.Data.NHibernateMaps
{
  public class CategoryMap : IAutoMappingOverride<Category>
  {
    public void Override(AutoMapping<Category> mapping)
    {
        mapping.Id(x => x.Id)
            .GeneratedBy.Identity();

        mapping.Map(x => x.Description);
        mapping.Map(x => x.UrlName);

        mapping.References(x => x.ParentCategory)
            .Not.LazyLoad();
    }
  }
}

The problem is that this mapping is never used by the NHibernate... Instead it uses the Auto Mapping generated Category...

How can I use my Fluent Mapping ?

Thanks

Paul

Body:
Wherever you're configuring the AutoPersistenceModel you need to reference the mapping overrides.  I find the easiest way to do this is to just point it at the assembly containing the mapping overrides and let it discover all of them.  That way you can add new IAutoMappingOverride implementations and it will be automatically picked up.  You do this using the UseOverridesFromAssemblyOf extension method.

public class AutoPersistenceModelGenerator {
    public AutoPersistenceModel Generate() {
        return AutoMap.AssemblyOf<Category>()
            .UseOverridesFromAssemblyOf<CategoryMap>();
    }
}


答:
A naive approach: Note the inefficiency of using forEach. A force iteration over all the item even if a match was found.

```<code>var arr = [
      {
        name: 'test1',
        price: 20,
        otherKey: 123,
        yetAnotherKey: 'val'
      },
      {
        name: 'test2',
        price: 10,
        otherKey: 11,
        yetAnotherKey: 'erewrwert'
      },
      {
        name: 'test1',
        price: 20,
        otherKey: 123,
        yetAnotherKey: 'val'
      }
    ]

    function findFirstDuplicate(arr) {
      var retval = null
      arr.forEach(function(item) {
        arr.forEach(function(item2) {
            if(JSON.stringify(item) == JSON.stringify(item2)) {
            retval = item;
          }
        });
      });

      return retval;
    }

    console.log(findFirstDuplicate(arr));
</code>```

Title: how to find totally duplicate object in array?

Body:
Here is an example js array:

var arr = [
  {
    name: 'test1',
    price: 20,
    otherKey: 123,
    yetAnotherKey: 'val'
  },
  {
    name: 'test2',
    price: 10,
    otherKey: 11,
    yetAnotherKey: 'erewrwert'
  },
  {
    name: 'test1',
    price: 20,
    otherKey: 123,
    yetAnotherKey: 'val'
  }
]

Is there a way to find duplicate object (by all key/value pairs)?
If so - how to do that?
Thanks in advance.

Body:
A naive approach: Note the inefficiency of using forEach. A force iteration over all the item even if a match was found.

var arr = [
      {
        name: 'test1',
        price: 20,
        otherKey: 123,
        yetAnotherKey: 'val'
      },
      {
        name: 'test2',
        price: 10,
        otherKey: 11,
        yetAnotherKey: 'erewrwert'
      },
      {
        name: 'test1',
        price: 20,
        otherKey: 123,
        yetAnotherKey: 'val'
      }
    ]

    function findFirstDuplicate(arr) {
      var retval = null
      arr.forEach(function(item) {
        arr.forEach(function(item2) {
            if(JSON.stringify(item) == JSON.stringify(item2)) {
            retval = item;
          }
        });
      });

      return retval;
    }

    console.log(findFirstDuplicate(arr));


问:
Release Branch and Continuous Delivery
Requirements

We have got 2 environments.
-- Test and Prod

We want to do Continuous Deployment.

We are using Git Flow.

With git-flow we are supposed to deploy the release (or master) branch in production. ( two different pipelines,one for continuous integration (branch develop) and one for continuous delivery (branch master).

How should I use my release branch ?

What I have in mind is if the tests pass in develop. I would make the CI server create a release branch commit. And deploy the updated release branch points to my productions staging slot. After business approval one of the release points would get deployed to production.

This means I am letting CI server automatically create a release-branch and re-run all the tests on staging slots of production environment. If it fails, it will report and delete the release branch, otherwise it will create the release point,trigger network swap and merge it to master.

What is the pros and cons to this approach ? What is the best practice ?

Do we really need the release branch especially where we are not using feature toggles to separate releases ? ( there are multiple people working on the same project )

][2

Reference

Feature Toggling, Youtube, https://www.youtube.com/watch?v=gxm1C92XhCQ

Successful Git Branching Model, http://nvie.com/posts/a-successful-git-branching-model/

答:
git-flow says about release branches:

Release branches support preparation of a new production release. They allow for last-minute dotting of i’s and crossing t’s. Furthermore, they allow for minor bug fixes and preparing meta-data for a release (version number, build dates, etc.). By doing all of this work on a release branch, the develop branch is cleared to receive features for the next big release.

If your group's workflow doesn't match the use case for release branches, don't use them. If you find you need them later, start using them.

We use git-flow in one of the groups where I work. Often we only have one or maybe two developers working on a project doing maintenance, and it's rare that we need to simultaneously bug fix and add features. We don't use release branches unless we have that specific scenario.

Overall I like the pipelines you're setting up.

Title: Release Branch and Continuous Delivery


问:
TinyOS not compiling/uploading to TelosB mote
I'm running into a problem attempting to upload the "blink" app onto the motes. I can't seem to run the command make telosb reinstall bsl,/dev/ttUSB0 or make telosb reinstall while in the apps/Blink directory, which is preventing me from moving on with my project. I've tried as a user, superuser, and as root. I've outlined below the responses from variable commands. [Running Ubuntu 16.04, TinyOS 2.1.2, ncc version 1.4.2, nescc version 1.3.6]

(A)With root and the make telosb command I get back:

mkdir -p build/telosb
    compiling BlinkAppC to a telosb binary
ncc -o build/telosb/main.exe  -Os -fnesc-separator=__ -Wall -Wshadow -Wnesc-all -target=telosb -fnesc-cfile=build/telosb/app.c -board= -DDEFINED_TOS_AM_GROUP=0x22 -DIDENT_APPNAME=\"BlinkAppC\" -DIDENT_USERNAME=\"root\" -DIDENT_HOSTNAME=\"liam-Latitude-E\" -DIDENT_USERHASH=0x9236fe46L -DIDENT_TIMESTAMP=0x59384a62L -DIDENT_UIDHASH=0xdc08609fL  BlinkAppC.nc -lm
    compiled BlinkAppC to build/telosb/main.exe
            2538 bytes in ROM
              56 bytes in RAM
msp430-objcopy --output-target=ihex build/telosb/main.exe build/telosb/main.ihex
    writing TOS image

(B)With regular user and the make telosb command I get back:

mkdir -p build/telosb
/bin/sh: 1: cannot create build/telosb/ident_flags.txt: Permission denied
/home/liam/tinyos-main/support/make/ident_flags.extra:13: recipe for target 'ident_cache' failed
make: *** [ident_cache] Error 2

(C)With a super user and the sudo make telosb command I get back:

make: *** No rule to make target 'telosb'. Stop.

(D)With root and the make telosb reinstall command I get back:

cp build/telosb/main.ihex build/telosb/main.ihex.out
    found mote on /dev/ttyUSB0 (using bsl,auto)
    installing telosb binary using bsl
tos-bsl --telosb -c /dev/ttyUSB0 -r -e -I -p build/telosb/main.ihex.out
MSP430 Bootstrap Loader Version: 1.39-goodfet-8
Mass Erase...
Transmit default password ...
Invoking BSL...
Transmit default password ...
Current bootstrap loader version: 1.61 (Device ID: f16c)
Changing baudrate to 38400 ...
MSP430 Bootstrap Loader Version: 1.39-goodfet-8
Mass Erase...
Transmit default password ...
Invoking BSL...
Transmit default password ...
Current bootstrap loader version: 1.61 (Device ID: f16c)
Changing baudrate to 38400 ...
Traceback (most recent call last):
  File "/usr/bin/tos-bsl", line 1918, in <module>
    main(0);
  File "/usr/bin/tos-bsl", line 1843, in main
    speed=speed,
  File "/usr/bin/tos-bsl", line 1218, in actionStartBSL
    self.actionChangeBaudrate(speed)            #change baudrate
  File "/usr/bin/tos-bsl", line 1345, in actionChangeBaudrate
    self.serialport.setBaudrate(baudrate)
AttributeError: 'Serial' object has no attribute 'setBaudrate'
/home/liam/tinyos-main/support/make/msp/bsl.extra:45: recipe for target 'program' failed
make: *** [program] Error 1

(E)Whereas with a regular user and make telosb reinstall I get back:

cp build/telosb/main.ihex build/telosb/main.ihex.out
cp: cannot create regular file 'build/telosb/main.ihex.out': Permission denied
/home/liam/tinyos-main/support/make/msp/msp.rules:92: recipe for target 'setid' failed
make: *** [setid] Error 1

I have been all over the internet and online forums and haven't found a fix yet. I researched around (D) and found that perhaps python 2 might have changed the name of 'setBaudRate' variable. I'm not sure how to change that either.

Thank you for your time and help!

edit: added ncc and nescc versions.

答:
This stack overflow answer is applicable to TinyOS.

So it turns out that pyserial 3.0.1 is not compatible with the TinyOS app, Blink. I'm fairly certain that pyserial 3.0.1 came with the package for TinyOS.  To fix this, use the command sudo pip install "pySerial>=2.0,<=2.99999". For me, it kicked back:

The directory '/home/liam/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory '/home/liam/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Collecting pySerial<=2.99999,>=2.0
Installing collected packages: pySerial
  Found existing installation: pyserial 3.0.1
    DEPRECATION: Uninstalling a distutils installed project (pySerial) has been deprecated and will be removed in a future version. This is due to the fact that uninstalling a distutils project will only partially uninstall the project.
    Uninstalling pyserial-3.0.1:
      Successfully uninstalled pyserial-3.0.1
Successfully installed pySerial-2.7

But the blink app still uploaded and worked fine.


问:
VB.NET Addin How do I select current worksheet
I'm trying to create an Excel VSTO Addin with VS2015 for a handful of VBA macros that I have.  I could do this using VBA, but want to get my feet wet in VB.NET.  The problem I'm facing though is how to get the active worksheet and assign it to a variable.  Then, I need to pass in a range that I converted to text previous.

The macro essentially enables a user to compare two lists of data by selecting the ranges and then highlighting items that appear in both lists.

Here's the code that executes when a user tries to select the range (works fine)

```<code>    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Try
        Me.Hide()
        Dim R As Microsoft.Office.Interop.Excel.Range
        Dim A As String
        'note how the Application.InputBox brings up different settings to just InputBox
        R = Globals.ThisAddIn.Application.InputBox(Prompt:="Please select the reference range", Type:=8)
        A = R.Address
        Me.TextBox1.Text = A
        Me.Show()
        Me.TopMost = True
        Exit Sub

    Catch
        MsgBox("Please select a valid range!")
        Me.Show()
    End Try
End Sub
</code>```

Here's the code behind the "Search and Highlight" button, that should compare the two ranges and highlight duplicates.  However, when I run this it highlights cells in a different workbook, presumable the first one that I have open.  How do I make sure it's opening the current workbook that I'm operating in?

```<code>    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    Dim xlApp As New Excel.Application
    Dim ws As Excel.Worksheet
    Dim sheetName As String
    Dim cell_1 As Excel.Range
    Dim cell_2 As Excel.Range
    Dim rng_1 As Excel.Range
    Dim rng_2 As Excel.Range

    xlApp = GetObject(, "Excel.Application")
    ws = xlApp.ActiveSheet
    sheetName = ws.Name

    rng_1 = ws.Range(Me.TextBox2.Text)
    rng_2 = ws.Range(Me.TextBox1.Text)

    For Each cell_1 In rng_1
        For Each cell_2 In rng_2
            If cell_2.Text = cell_1.Text Then
                cell_2.Interior.ColorIndex = 6

            End If
        Next cell_2
    Next cell_1

    Me.Close()

End Sub
</code>```

答:
I found the answer, so I'm posting it for the next time I have to search for this. In the code below just make sure to change ThisAddIn to the name of your actual add-in.

```<code>    Dim wb As Excel.Workbook = Globals.ThisAddIn.Application.ActiveWorkbook
    Dim ws As Excel.Worksheet = Globals.ThisAddIn.Application.ActiveSheet
</code>```

Body:
I'm trying to create an Excel VSTO Addin with VS2015 for a handful of VBA macros that I have.  I could do this using VBA, but want to get my feet wet in VB.NET.  The problem I'm facing though is how to get the active worksheet and assign it to a variable.  Then, I need to pass in a range that I converted to text previous.

The macro essentially enables a user to compare two lists of data by selecting the ranges and then highlighting items that appear in both lists.

Here's the code that executes when a user tries to select the range (works fine)

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Try
        Me.Hide()
        Dim R As Microsoft.Office.Interop.Excel.Range
        Dim A As String
        'note how the Application.InputBox brings up different settings to just InputBox
        R = Globals.ThisAddIn.Application.InputBox(Prompt:="Please select the reference range", Type:=8)
        A = R.Address
        Me.TextBox1.Text = A
        Me.Show()
        Me.TopMost = True
        Exit Sub

    Catch
        MsgBox("Please select a valid range!")
        Me.Show()
    End Try
End Sub

Here's the code behind the "Search and Highlight" button, that should compare the two ranges and highlight duplicates.  However, when I run this it highlights cells in a different workbook, presumable the first one that I have open.  How do I make sure it's opening the current workbook that I'm operating in?

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    Dim xlApp As New Excel.Application
    Dim ws As Excel.Worksheet
    Dim sheetName As String
    Dim cell_1 As Excel.Range
    Dim cell_2 As Excel.Range
    Dim rng_1 As Excel.Range
    Dim rng_2 As Excel.Range

    xlApp = GetObject(, "Excel.Application")
    ws = xlApp.ActiveSheet
    sheetName = ws.Name

    rng_1 = ws.Range(Me.TextBox2.Text)
    rng_2 = ws.Range(Me.TextBox1.Text)

    For Each cell_1 In rng_1
        For Each cell_2 In rng_2
            If cell_2.Text = cell_1.Text Then
                cell_2.Interior.ColorIndex = 6

            End If
        Next cell_2
    Next cell_1

    Me.Close()

End Sub

Body:
I found the answer, so I'm posting it for the next time I have to search for this. In the code below just make sure to change ThisAddIn to the name of your actual add-in.

    Dim wb As Excel.Workbook = Globals.ThisAddIn.Application.ActiveWorkbook
    Dim ws As Excel.Worksheet = Globals.ThisAddIn.Application.ActiveSheet


问:
Trouble getting working directory
This is how I am trying to get the current working directory:

```<code>    char* ch;
    if( (ch = _getcwd( NULL, 0 )) == NULL )
    {
        cout << "Could not get working directory!" << endl;
    }
    // skonvertujme char* na string, s tym sa nizsie bude lahsie pracovat
    stringstream ss;
    string workingDirectory;
    ss << ch;
    ss >> workingDirectory;

    cout << workingDirectory << endl;
    cin.get();
    cin.get();
</code>```

Which prints out:

```<code>C:\Users\Richard\Documents\Visual
</code>```

Instead of the actual working directory:

```<code>C:\Users\Richard\Documents\Visual Studio 2010\Projects\Client\Debug
</code>```

It seems like ti cuts everything after a space.

How can I get the working directory correctly even if there are spaces in the path?

答:
Use getline(ss, workingDirectory)

The reason that happens is that the << operator in stringstream stops reading when it encounters whitespace.

Title: Trouble getting working directory

Body:
This is how I am trying to get the current working directory:

    char* ch;
    if( (ch = _getcwd( NULL, 0 )) == NULL )
    {
        cout << "Could not get working directory!" << endl;
    }
    // skonvertujme char* na string, s tym sa nizsie bude lahsie pracovat
    stringstream ss;
    string workingDirectory;
    ss << ch;
    ss >> workingDirectory;

    cout << workingDirectory << endl;
    cin.get();
    cin.get();

Which prints out:

C:\Users\Richard\Documents\Visual

Instead of the actual working directory:

C:\Users\Richard\Documents\Visual Studio 2010\Projects\Client\Debug

It seems like ti cuts everything after a space.

How can I get the working directory correctly even if there are spaces in the path?


问:
how to get the days and exact minutes,exact hours from two dates in javascript?
I have start date time and end time,i need to split how many days , hours ,minutes in the two dates

for example ,
    startdatetime = "09-06-2017 10:30"
    enddatetime = "10-06-2017 11:45"

i need this result : 1 day 1 hour and 15 minutes

I try this one

```<code>var t = end - start;
var z = parseInt(t / 1000 / 60);
var time = display(z);
function display(a)
{
    console.log(a);
    var hours = Math.trunc(a/60);
    var minutes = a % 60;
    var one_day=1000*60*60*24
    var days = Math.ceil(a/one_day)
    var time = [hours,minutes,days];
    return time;
}
</code>```

i get the following 1day 24 hours and 15 minutes , can anyone help me , if its new logic means i will change into it,thanks in advance

答:
Try the following:

var t = end - start;
var z = parseInt(t / 1000 / 60);
var time = display(z);
function display(minutes)
{
    var hours = (minutes / 60 | 0) % 24;
    var minutes = (minutes | 0) % 60;
    var days = minutes / 60 / 24 | 0;
    return [hours, minutes, days];
}
```

Note that in javascript, doing x | 0 is the same as Math.floor(x).

Body:
I have start date time and end time,i need to split how many days , hours ,minutes in the two dates

for example ,
    startdatetime = "09-06-2017 10:30"
    enddatetime = "10-06-2017 11:45"

i need this result : 1 day 1 hour and 15 minutes

I try this one

var t = end - start;
var z = parseInt(t / 1000 / 60);
var time = display(z);
function display(a)
{
    console.log(a);
    var hours = Math.trunc(a/60);
    var minutes = a % 60;
    var one_day=1000*60*60*24
    var days = Math.ceil(a/one_day)
    var time = [hours,minutes,days];
    return time;
}

i get the following 1day 24 hours and 15 minutes , can anyone help me , if its new logic means i will change into it,thanks in advance

Body:
Try the following:

var t = end - start;
var z = parseInt(t / 1000 / 60);
var time = display(z);
function display(minutes)
{
    var hours = (minutes / 60 | 0) % 24;
    var minutes = (minutes | 0) % 60;
    var days = minutes / 60 / 24 | 0;
    return [hours, minutes, days];
}

Note that in javascript, doing x | 0 is the same as Math.floor(x).


答:
You can get a value from SharedPreferences like this:

```<code>String time = sharedpreferences.getString("TimeMillis", "default_Value_Here");
</code>```

"sharedpreferences" has to be an object of class SharedPreferences.
The second String ("default_Value_Here") should be something that gets set as String time when there is no key in sharedpreferences named "TimeMillis".

Another hint: You must call editor.commit() to save your changes in activity B.

Title: Android Shared Preference check value

Body:
I'm working on android application that have 2 activities A and B . I have a button in B Activity with event that save the current time of android device, the time save in Shared Preferences:

long TimeMillis = date.getTime();
editor = sharedpreferences.edit();
editor.putString("TimeMillis", String.valueOf(TimeMillis));

I need to check the value of the previous Shared Preferences in A Activity

Note: the Date save on B then check it in A . A come before B.

Body:
You can get a value from SharedPreferences like this:

String time = sharedpreferences.getString("TimeMillis", "default_Value_Here");

"sharedpreferences" has to be an object of class SharedPreferences.
The second String ("default_Value_Here") should be something that gets set as String time when there is no key in sharedpreferences named "TimeMillis".

Another hint: You must call editor.commit() to save your changes in activity B.


问:
Changing voice using Cordova?
I am building a voip calling app for android using apache cordova and ionic framework with angular2, my question is how to change the pitch of the voice during call and how to add background voice also with it?</p>

答:
To my knowledge there is no such Cordova plugin, nor is it likely to ever be one.

While Cordova is good for most applications, what you are looking for is called signal processing and is a very low level, highly mathematical set of procedures that is only suited for native app development.

I strongly suggest you reconsider your approach, or design in general.

Sorry to be a buzzkill.

Title: Changing voice using Cordova?


问:
How to wait for same browser tab title text with Selenide?
I would like to find out how to make waiter for assertion with window title text in selenide / selenium

something like this:

```<code>waitUntil(assertion.true(Selenide.title().toLowerCase().startsWith("text")), timeout);
</code>```

may be you could help me?

答:
Solved like this:   </p>

```<code>{ ...
     await().atMost(timeOut, SECONDS).until(assertionWaitForTitle("text"));
}

private Callable<Boolean> assertionWaitForTitle(String start) {
     return () -> Selenide.title().toLowerCase().startsWith(start);
}
</code>```

Body:
I would like to find out how to make waiter for assertion with window title text in selenide / selenium

something like this:

waitUntil(assertion.true(Selenide.title().toLowerCase().startsWith("text")), timeout);

may be you could help me?

Body:
Solved like this:

{ ...
     await().atMost(timeOut, SECONDS).until(assertionWaitForTitle("text"));
}

private Callable<Boolean> assertionWaitForTitle(String start) {
     return () -> Selenide.title().toLowerCase().startsWith(start);
}