问:
Xamarin.Forms + HockeyApp - auto submit crash reports
I am trying to enable automatic (no user prompt) submission of hockey app crash reports on Xamarin.Forms (Android and iOS):

I have this for Android in MainActivity.cs:

```<code>var customCrashListener = new CustomCrashListener();
CrashManager.Register(this, "appId", customCrashListener);
</code>```

where CustomCrashListener is:

```<code>class CustomCrashListener : CrashManagerListener
{
    public bool ShouldAutoUploadCrashes()
    {
        return true;
    }
}
</code>```

This isn't sending any crash reports and HockeyApp with Xamarin documentation is thin. I am also trying to get this work on iOS.

答:
Included some example code below, with statements to enable debugging on the SDK's. With this enabled you can have a look at the application output to pinpoint the problem. If you are crashing directly on startup the SDK will not have time to send crash reports. Also if the App ID is incorrect you can see this behavior.

You'll need to include the override keyword in your listener callback, like in the example below. Otherwise autosend will not be enabled and a crash prompt will still appear.

```<code>Hockey.LogLevel = 3;
CrashManager.Register(this, AppID, new MyCrashManagerListener());

public class MyCrashManagerListener : CrashManagerListener
        {

            public override bool ShouldAutoUploadCrashes()
            {
                return true;
            }
        }
</code>```

For iOS, you just need to set BITCrashManagerStatus in your AppDelegate.cs before StartManager():

```<code>var manager = BITHockeyManager.SharedHockeyManager;
manager.Configure(App_ID);
manager.LogLevel = BITLogLevel.Debug;
manager.CrashManager.CrashManagerStatus = BITCrashManagerStatus.AutoSend;
manager.StartManager();
</code>```

Body:
I am trying to enable automatic (no user prompt) submission of hockey app crash reports on Xamarin.Forms (Android and iOS):

I have this for Android in MainActivity.cs:

var customCrashListener = new CustomCrashListener();
CrashManager.Register(this, "appId", customCrashListener);

where CustomCrashListener is:

class CustomCrashListener : CrashManagerListener
{
    public bool ShouldAutoUploadCrashes()
    {
        return true;
    }
}

This isn't sending any crash reports and HockeyApp with Xamarin documentation is thin. I am also trying to get this work on iOS.

Body:
Included some example code below, with statements to enable debugging on the SDK's. With this enabled you can have a look at the application output to pinpoint the problem. If you are crashing directly on startup the SDK will not have time to send crash reports. Also if the App ID is incorrect you can see this behavior.

You'll need to include the override keyword in your listener callback, like in the example below. Otherwise autosend will not be enabled and a crash prompt will still appear.

Hockey.LogLevel = 3;
CrashManager.Register(this, AppID, new MyCrashManagerListener());

public class MyCrashManagerListener : CrashManagerListener
        {

            public override bool ShouldAutoUploadCrashes()
            {
                return true;
            }
        }

For iOS, you just need to set BITCrashManagerStatus in your AppDelegate.cs before StartManager():

var manager = BITHockeyManager.SharedHockeyManager;
manager.Configure(App_ID);
manager.LogLevel = BITLogLevel.Debug;
manager.CrashManager.CrashManagerStatus = BITCrashManagerStatus.AutoSend;
manager.StartManager();


来源: stackexchange

问:
Devise current_user vs user_session
I'd like to limit a users scope, once authenticated, to a specific namespace. But they'll be dynamic (ie not a named route). example:

```<code>/rails/redteam/
/rails/blueteam/
/rails/greenteam/
</code>```

or perhaps simply:

```<code>/rails/
...or...
/
</code>```

if we know their 'team' then couldn't that somehow be assumed in the routing?

How best to set this up and handle this securely? should I store team name in user_session? Or, query the current_user for their group and verify it matches their known group(s) in a before_filter?

What about the routes themselves? basically glorified IDs, perhaps a permalink of sorts? dunno the "Rails way?"

btw- I'm aware of authorization gems like CanCan and decl_auth but trying to avoid their complexity, if possible, as I'm sorta a newb, if that wasn't obvious enough already.

答:
I'm aware of authorization gems like CanCan and decl_auth but trying to avoid their complexity, if possible

You're much better off taking the time to learn about one (or the other, or both) of these gems than to try rolling your own solution, IMO. Ultimately you'll run into complications as your requirements change, and without a good framework underlying your approach, problems are just bound to happen.

ContentLicense: CC BY-SA 2.5

Title: Devise current_user vs user_session

Body:
I'd like to limit a users scope, once authenticated, to a specific namespace. But they'll be dynamic (ie not a named route). example:

/rails/redteam/
/rails/blueteam/
/rails/greenteam/

or perhaps simply:

/rails/
...or...
/

if we know their 'team' then couldn't that somehow be assumed in the routing?

How best to set this up and handle this securely? should I store team name in user_session? Or, query the current_user for their group and verify it matches their known group(s) in a before_filter?

What about the routes themselves? basically glorified IDs, perhaps a permalink of sorts? dunno the "Rails way?"

btw- I'm aware of authorization gems like CanCan and decl_auth but trying to avoid their complexity, if possible, as I'm sorta a newb, if that wasn't obvious enough already.


问:
How do I use regex to take all numbers followed by the first digit of the identifier of a string using javascript?
I have the following string that needs to be converted to the following:</p>

```<code>3 Apples 5 Bananas 7 Oranges ===> 3A 5B 7O

3 Apple(s) 5 Banana(s) 7 Oranges, 19 Cherries ===> 3A 5B 7O 19C
</code>```

答:
```<code>string.replace(/(\d+)\s(\w)\S*/g,'$1$2')
</code>```

both variants would work

ContentLicense: CC BY-SA 3.0

Body:
I have the following string that needs to be converted to the following:

3 Apples 5 Bananas 7 Oranges ===> 3A 5B 7O

3 Apple(s) 5 Banana(s) 7 Oranges, 19 Cherries ===> 3A 5B 7O 19C

Body:
string.replace(/(\d+)\s(\w)\S*/g,'$1$2')

both variants would work


问:
Using jquery to get value of text area in closest table cell
I have the following table

```<code><tr>
<td data-toggle="tooltip" title="Not Started"><img  src="images/small_info_icon.png"></td>
<td>Demo Demo</td>
<td>January</td>
<td class="updaterow"><textarea class="form-control" rows="5" id="notes34455" name="editcomments">Not Started</textarea></td>
<td id="34455"><button type="button" id="updatestatus" class="btn btn-info btn-sm">Update</button> </td>
</tr>
</code>```

I want to use jquery to get the value of the textarea.
I am using the following, but it is giving undefined.

```<code>$("button#updatestatus").click(function(){
var id = $(this).closest('td').attr('id');
var data = $(this).closest("updaterow").text;
alert(data);
var data = {
            id: id,

            };
$.ajax({
type: "POST",
url: "updatestatus.php",
data: data
}).done(function(msg) {
console.log(msg);
});
</code>```

Is it possible to get the textvalue of the textarea?

答:
This is what you want

```<code>$("button#updatestatus").click(function(){

var data = $(this).parent().prev("td.updaterow").find("textarea").val();
alert(data);

});
</code>```

Here is an example

$("button#updatestatus").click(function(){

var data = $(this).parent().prev("td.updaterow").find("textarea").val();
alert(data);

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>

<table>
<tr>
<td data-toggle="tooltip" title="Not Started"><img  src="images/small_info_icon.png"></td>
<td>Demo Demo</td>
<td>January</td>
<td class="updaterow"><textarea class="form-control" rows="5" id="notes34455" name="editcomments">Not Started</textarea></td>
<td id="34455"><button type="button" id="updatestatus" class="btn btn-info btn-sm">Update</button> </td>
</tr>

</table>

</html></code>```

Body:
I have the following table

Demo Demo
January
<textarea class="form-control" rows="5" id="notes34455" name="editcomments">Not Started</textarea>
<button type="button" id="updatestatus" class="btn btn-info btn-sm">Update</button>

I want to use jquery to get the value of the textarea.
I am using the following, but it is giving undefined.

$("button#updatestatus").click(function(){
var id = $(this).closest('td').attr('id');
var data = $(this).closest("updaterow").text;
alert(data);
var data = {
            id: id,

            };
$.ajax({
type: "POST",
url: "updatestatus.php",
data: data
}).done(function(msg) {
console.log(msg);
});

Is it possible to get the textvalue of the textarea?

Body:
This is what you want

$("button#updatestatus").click(function(){

var data = $(this).parent().prev("td.updaterow").find("textarea").val();
alert(data);

});

Here is an example

$("button#updatestatus").click(function(){

var data = $(this).parent().prev("td.updaterow").find("textarea").val();
alert(data);

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>

<table>
<tr>
<td data-toggle="tooltip" title="Not Started"><img  src="images/small_info_icon.png"></td>
<td>Demo Demo</td>
<td>January</td>
<td class="updaterow"><textarea class="form-control" rows="5" id="notes34455" name="editcomments">Not Started</textarea></td>
<td id="34455"><button type="button" id="updatestatus" class="btn btn-info btn-sm">Update</button> </td>
</tr>

</table>

</html>


问:
How can I sort the result of array_merge() function?
Here is my code:

```<code><?php

$arr1 = ['o' => 'vote', 'u' => 'true'];
$arr2 = ['p' => '', 'v' => 'digit'];

print_r(array_merge($arr1, $arr2));

/* Array
   (
       [o] => vote
       [u] => true
       [p] =>
       [v] => digit
   )
</code>```

Always there is one item which has empty value. In example above, that item is p. Now I need to put that item as the last one. How can I do that?

Note: I don't care about the order of other items.

So this is expected result:

```<code>/* Array
   (
       [o] => vote
       [u] => true
       [v] => digit
       [p] =>
   )
</code>```

答:
One possible approach that preserves the order of non-empty elements would be:</p>

```<code>$arr1 = ['o' => 'vote', 'u' => 'true'];
$arr2 = ['p' => '', 'v' => 'digit'];

$merged = $arr1 + $arr2;

$empty = array_filter($merged, function($var) {
    return $var == "";
});

$nonEmpty = array_diff_assoc($merged, $empty);

$sorted = $nonEmpty + $empty;
</code>```

Body:
Here is my code:

<?php

$arr1 = ['o' => 'vote', 'u' => 'true'];
$arr2 = ['p' => '', 'v' => 'digit'];

print_r(array_merge($arr1, $arr2));

/* Array
   (
       [o] => vote
       [u] => true
       [p] =>
       [v] => digit
   )

Always there is one item which has empty value. In example above, that item is p. Now I need to put that item as the last one. How can I do that?

Note: I don't care about the order of other items.

So this is expected result:

/* Array
   (
       [o] => vote
       [u] => true
       [v] => digit
       [p] =>
   )

Body:
One possible approach that preserves the order of non-empty elements would be:

$arr1 = ['o' => 'vote', 'u' => 'true'];
$arr2 = ['p' => '', 'v' => 'digit'];

$merged = $arr1 + $arr2;

$empty = array_filter($merged, function($var) {
    return $var == "";
});

$nonEmpty = array_diff_assoc($merged, $empty);

$sorted = $nonEmpty + $empty;


问:
Find the cell that is closest to a certain value in Excel
In Excel, I have many products with different sizes listed in columns, such that the sizes "10x10 cm", "11x11 cm" and "15x15 cm" belongs to Product A, etc.

In some other cells, I am selecting a product (either Product A, Product B, or Product C) and a size.

I want, for each of the other products, to determine which size is closest to the selected product:

I don't know how to solve this. One solution might be to remove all non-numeric characters from the strings and add the two values on each side of the "x" and then select the size with the lowest absolute difference from the sum of the selected size.

But I guess it would be easier to do a mapping and use a VLOOKUP to choose the first found size in a given column.

However, the problem is that I do not only have 3 products with a few different sizes, but rather 15 different products with 10 different sizes, so I don't know how to do a mapping in a clever way.

答:
1) Creating a lookup table with the values extracted for each product,

Source sheet:

Code:

```<code>Sub lookup()
Dim i As Long, j As Long, prod As Integer, str As String
prod = InputBox("Enter Number of Products")
Sheets.Add.Name = "LookupSheet"
j = 1
For i = 1 To prod
    Columns(i).Copy Sheets("LookupSheet").Cells(1, j)
    j = j + 2
Next i
For j = 1 To prod * 2 Step 2
    For i = 2 To Sheets("LookupSheet").Cells(Rows.Count, j).End(xlUp).Row
        str = Replace(Replace(Sheets("LookupSheet").Cells(i, j), " ", ""), "cm", "")
        Sheets("LookupSheet").Cells(i, j + 1) = Left(str, InStr(str, "x") - 1) _
                            * Mid(str, InStr(str, "x") + 1, 999)
    Next i
Next j
End Sub
</code>```

This simple code creates a lookup sheet with the corresponding values. The code ignores any spaces present between the texts.

LookupSheet:

Since you have 15 different products, run this macro to extract the lookup data. This should be a one time activity unless you have additional products.

2) Assuming you enter the product and dimensions to F5 and F6, i would suggest you to data validation with dropdowns to select from the list,

3) Using a worksheet_change event, detect for changes in F5 and F6,

Code:

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
Dim str As String, result As Integer, i As Long
'F5 and F6 contains Product and Size repectively
    If (Target.Address = "$F$5" Or Target.Address = "$F$6") _
        And Range("F5") <> "" And Range("F6") <> "" Then
        str = Replace(Replace(Range("F6"), " ", ""), "cm", "")
        result = Left(str, InStr(str, "x") - 1) * Mid(str, InStr(str, "x") + 1, 999)
        j = 8
        For i = 1 To Cells(1, Columns.Count).End(xlToLeft).Column
            If Cells(1, i) <> Range("F5") Then
                Range("E" & j) = Cells(1, i)
                j = j + 1
            End If
        Next i
    End If
End Sub
</code>```

This code automatically populated the rest of the product types in the column E,

4) The variable result would contain the product/area of the value that you provide in F6. The only task pending would be to loop through the lookup sheet to find the nearest match. The Algorithm is below,

Algorithm:

Compare cell F5 with the data in  row 1 of lookup sheet (need to loop)

If they are equal, ignore and move to next value. If not, need to loop the immediate next column to find the next match, and populate the result in the corresponding cell in source sheet.

Algorithm for column wise looping is below,

Steps:

```<code>diff = cell.value - result
if diff < 0 then multiply diff by -1
loop:
nextdiff = nextcell.value - result (multiply by -1 if negative)
if nextdiff < diff then
diff = nextdiff
end if
end loop:
</code>```

The cell value with the least difference would be your best match for that particular product type.

Bit lengthier explanation, hope this helps.

Body:
1) Creating a lookup table with the values extracted for each product,

Source sheet:

Code:

Sub lookup()
Dim i As Long, j As Long, prod As Integer, str As String
prod = InputBox("Enter Number of Products")
Sheets.Add.Name = "LookupSheet"
j = 1
For i = 1 To prod
    Columns(i).Copy Sheets("LookupSheet").Cells(1, j)
    j = j + 2
Next i
For j = 1 To prod * 2 Step 2
    For i = 2 To Sheets("LookupSheet").Cells(Rows.Count, j).End(xlUp).Row
        str = Replace(Replace(Sheets("LookupSheet").Cells(i, j), " ", ""), "cm", "")
        Sheets("LookupSheet").Cells(i, j + 1) = Left(str, InStr(str, "x") - 1) _
                            * Mid(str, InStr(str, "x") + 1, 999)
    Next i
Next j
End Sub

This simple code creates a lookup sheet with the corresponding values. The code ignores any spaces present between the texts.

LookupSheet:

Since you have 15 different products, run this macro to extract the lookup data. This should be a one time activity unless you have additional products.

2) Assuming you enter the product and dimensions to F5 and F6, i would suggest you to data validation with dropdowns to select from the list,

3) Using a worksheet_change event, detect for changes in F5 and F6,

Code:

Private Sub Worksheet_Change(ByVal Target As Range)
Dim str As String, result As Integer, i As Long
'F5 and F6 contains Product and Size repectively
    If (Target.Address = "$F$5" Or Target.Address = "$F$6") _
        And Range("F5") <> "" And Range("F6") <> "" Then
        str = Replace(Replace(Range("F6"), " ", ""), "cm", "")
        result = Left(str, InStr(str, "x") - 1) * Mid(str, InStr(str, "x") + 1, 999)
        j = 8
        For i = 1 To Cells(1, Columns.Count).End(xlToLeft).Column
            If Cells(1, i) <> Range("F5") Then
                Range("E" & j) = Cells(1, i)
                j = j + 1
            End If
        Next i
    End If
End Sub

This code automatically populated the rest of the product types in the column E,

4) The variable result would contain the product/area of the value that you provide in F6. The only task pending would be to loop through the lookup sheet to find the nearest match. The Algorithm is below,

Algorithm:

Compare cell F5 with the data in  row 1 of lookup sheet (need to loop)

If they are equal, ignore and move to next value. If not, need to loop the immediate next column to find the next match, and populate the result in the corresponding cell in source sheet.

Algorithm for column wise looping is below,

Steps:

diff = cell.value - result
if diff < 0 then multiply diff by -1
loop:
nextdiff = nextcell.value - result (multiply by -1 if negative)
if nextdiff < diff then
diff = nextdiff
end if
end loop:

The cell value with the least difference would be your best match for that particular product type.

Bit lengthier explanation, hope this helps.


问:
Store data from twitter api javascript (nodejs)
I seem to be having an issue. I'm trying to export data from the twitter api but I can't. Here's what my code looks like :

```<code>/// Twitter.js
module.exports = Twitter

function Twitter(twitter) {
    this.twitter = twitter
}

Twitter.prototype.friends = function(params) {
    this.twitter.get('friends/list', params, (err, data) => {
        if (err)
            console.log(err)

        console.log(data) // this prints data to the console but
                          // I want to export and save in a data structure
                          // array or object
    }
}

///bot.js
var Twit = require('twit')
var config = require('/path_to_config.js')
var init = Twit(config)
var Twitter = require('/path_to_Twitter.js')

var bot = new Twitter(config)
bot.friends({ screen_name: 'myscreenname'})
</code>```

If I try returning the data parameter it returns undefined and if I push data.users to an array it returns an empty array. Any help is and will be appreciated.

答:
I suggest using Promises to allow the calling code to work with the returned data:</p>

```<code>Twitter.prototype.friends = function(params) {
    return new Promise((resolve, reject) => {
        this.twitter.get('friends/list', params, (err, data) => {
           if (err) {
               reject(err);
           } else {
               resolve(data);
           }
        });
     });
}

...
var bot = new Twitter(config)
bot.friends({ screen_name: 'myscreenname'}).then((data) => {
    // do something with data
    console.log(data);
}).catch((err) => {
    console.error(err);
});
</code>```

Body:
I seem to be having an issue. I'm trying to export data from the twitter api but I can't. Here's what my code looks like :

/// Twitter.js
module.exports = Twitter

function Twitter(twitter) {
    this.twitter = twitter
}

Twitter.prototype.friends = function(params) {
    this.twitter.get('friends/list', params, (err, data) => {
        if (err)
            console.log(err)

        console.log(data) // this prints data to the console but
                          // I want to export and save in a data structure
                          // array or object
    }
}

///bot.js
var Twit = require('twit')
var config = require('/path_to_config.js')
var init = Twit(config)
var Twitter = require('/path_to_Twitter.js')

var bot = new Twitter(config)
bot.friends({ screen_name: 'myscreenname'})

If I try returning the data parameter it returns undefined and if I push data.users to an array it returns an empty array. Any help is and will be appreciated.

Body:
I suggest using Promises to allow the calling code to work with the returned data:

Twitter.prototype.friends = function(params) {
    return new Promise((resolve, reject) => {
        this.twitter.get('friends/list', params, (err, data) => {
           if (err) {
               reject(err);
           } else {
               resolve(data);
           }
        });
     });
}

...
var bot = new Twitter(config)
bot.friends({ screen_name: 'myscreenname'}).then((data) => {
    // do something with data
    console.log(data);
}).catch((err) => {
    console.error(err);
});


问:
How to create private RSA key using modulus, D, exponent in C#?
I have 3 byte arrays of length 128, 128, 3 bytes respectively. I don't know what it is, but I expect them to be Modulus, D, Exponent.
Now how can I use these arrays in C# to decrypt a byte array using RSA?
When I create an RSAParameters and assign the 3 byte arrays to Modulus, D, Exponent and try to use that RSAParameters in RSACryptoServiceProvider.ImportParameters, decryption fails stating corrupt keys. I guess the other entries also need to be filled DQ,DP,...etc...

How do I do that in C#? I don't have that values, is there an easy way to decrypt a byte array using only Modulus, D, Exponent in C#, as in other languages?

答:
The Windows implementations seem to only be willing to do RSA via the CRT parameters, leaving D as a potentially ignored value.  At the very least, the CRT parameters are required inputs.

First, we need to turn your arrays into BigInteger values. I'm assuming here that you have Big-Endian encoded values.  If they're Little-Endian, don't call Array.Reverse() and change the copy-to index from 1 to 0.

```<code>private static BigInteger GetBigInteger(byte[] bytes)
{
    byte[] signPadded = new byte[bytes.Length + 1];
    Buffer.BlockCopy(bytes, 0, signPadded, 1, bytes.Length);
    Array.Reverse(signPadded);
    return new BigInteger(signPadded);
}
</code>```

Adding the extra byte prevents numbers from being treated as negative. (One could avoid the allocation and memory copy by testing for the sign bit in the  last byte, if one wanted).

So now you have three BigInteger values, n, e, d.  Not sure which of n and d is which?

```<code>// Unless someone tried really hard to make this break it'll work.
if (n < d)
{
    BigInteger tmp = n;
    n = d;
    d = tmp;
}
</code>```

Now, using the algorithm from NIST Special Publication 800-56B Recommendation for Pair-Wise August 2009 Key Establishment Schemes Using Integer Factorization Cryptography, Appendix C (as shared in https://stackoverflow.com/a/28299742/6535399) we can calculate the BigInteger values. There's a tricky subtlety, though.  RSAParameters values have to have a correct amount of padding, and RSACryptoServiceProvider doesn't do it for you.

```<code>private static RSAParameters RecoverRSAParameters(BigInteger n, BigInteger e, BigInteger d)
{
    using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
    {
        BigInteger k = d * e - 1;

        if (!k.IsEven)
        {
            throw new InvalidOperationException("d*e - 1 is odd");
        }

        BigInteger two = 2;
        BigInteger t = BigInteger.One;

        BigInteger r = k / two;

        while (r.IsEven)
        {
            t++;
            r /= two;
        }

        byte[] rndBuf = n.ToByteArray();

        if (rndBuf[rndBuf.Length - 1] == 0)
        {
            rndBuf = new byte[rndBuf.Length - 1];
        }

        BigInteger nMinusOne = n - BigInteger.One;

        bool cracked = false;
        BigInteger y = BigInteger.Zero;

        for (int i = 0; i < 100 && !cracked; i++)
        {
            BigInteger g;

            do
            {
                rng.GetBytes(rndBuf);
                g = GetBigInteger(rndBuf);
            }
            while (g >= n);

            y = BigInteger.ModPow(g, r, n);

            if (y.IsOne || y == nMinusOne)
            {
                i--;
                continue;
            }

            for (BigInteger j = BigInteger.One; j < t; j++)
            {
                BigInteger x = BigInteger.ModPow(y, two, n);

                if (x.IsOne)
                {
                    cracked = true;
                    break;
                }

                if (x == nMinusOne)
                {
                    break;
                }

                y = x;
            }
        }

        if (!cracked)
        {
            throw new InvalidOperationException("Prime factors not found");
        }

        BigInteger p = BigInteger.GreatestCommonDivisor(y - BigInteger.One, n);
        BigInteger q = n / p;
        BigInteger dp = d % (p - BigInteger.One);
        BigInteger dq = d % (q - BigInteger.One);
        BigInteger inverseQ = ModInverse(q, p);

        int modLen = rndBuf.Length;
        int halfModLen = (modLen + 1) / 2;

        return new RSAParameters
        {
            Modulus = GetBytes(n, modLen),
            Exponent = GetBytes(e, -1),
            D = GetBytes(d, modLen),
            P = GetBytes(p, halfModLen),
            Q = GetBytes(q, halfModLen),
            DP = GetBytes(dp, halfModLen),
            DQ = GetBytes(dq, halfModLen),
            InverseQ = GetBytes(inverseQ, halfModLen),
        };
    }
}
</code>```

With the "tricky" BigInteger-to-suitable-for-RSAParameters-byte[] method:

```<code>private static byte[] GetBytes(BigInteger value, int size)
{
    byte[] bytes = value.ToByteArray();

    if (size == -1)
    {
        size = bytes.Length;
    }

    if (bytes.Length > size + 1)
    {
        throw new InvalidOperationException($"Cannot squeeze value {value} to {size} bytes from {bytes.Length}.");
    }

    if (bytes.Length == size + 1 && bytes[bytes.Length - 1] != 0)
    {
        throw new InvalidOperationException($"Cannot squeeze value {value} to {size} bytes from {bytes.Length}.");
    }

    Array.Resize(ref bytes, size);
    Array.Reverse(bytes);
    return bytes;
}
</code>```

And for computing InverseQ you need ModInverse:

```<code>private static BigInteger ModInverse(BigInteger e, BigInteger n)
{
    BigInteger r = n;
    BigInteger newR = e;
    BigInteger t = 0;
    BigInteger newT = 1;

    while (newR != 0)
    {
        BigInteger quotient = r / newR;
        BigInteger temp;

        temp = t;
        t = newT;
        newT = temp - quotient * newT;

        temp = r;
        r = newR;
        newR = temp - quotient * newR;
    }

    if (t < 0)
    {
        t = t + n;
    }

    return t;
}
</code>```

On my computer I'm recovering P and Q from (n, e, d) in ~50ms for a 1024-bit key.  ~2-4 seconds for a 4096-bit key.

Note to implementers who like unit tests: There's not really a defined order for P and Q (like a convention that P always be the larger), so your P and Q values may be backwards from an RSAParameters structure that you started with. DP and DQ will thus also be reversed.

Body:
The Windows implementations seem to only be willing to do RSA via the CRT parameters, leaving D as a potentially ignored value.  At the very least, the CRT parameters are required inputs.

First, we need to turn your arrays into BigInteger values. I'm assuming here that you have Big-Endian encoded values.  If they're Little-Endian, don't call Array.Reverse() and change the copy-to index from 1 to 0.

private static BigInteger GetBigInteger(byte[] bytes)
{
    byte[] signPadded = new byte[bytes.Length + 1];
    Buffer.BlockCopy(bytes, 0, signPadded, 1, bytes.Length);
    Array.Reverse(signPadded);
    return new BigInteger(signPadded);
}

Adding the extra byte prevents numbers from being treated as negative. (One could avoid the allocation and memory copy by testing for the sign bit in the  last byte, if one wanted).

So now you have three BigInteger values, n, e, d.  Not sure which of n and d is which?

// Unless someone tried really hard to make this break it'll work.
if (n < d)
{
    BigInteger tmp = n;
    n = d;
    d = tmp;
}

Now, using the algorithm from NIST Special Publication 800-56B Recommendation for Pair-Wise August 2009 Key Establishment Schemes Using Integer Factorization Cryptography, Appendix C (as shared in https://stackoverflow.com/a/28299742/6535399) we can calculate the BigInteger values. There's a tricky subtlety, though.  RSAParameters values have to have a correct amount of padding, and RSACryptoServiceProvider doesn't do it for you.

private static RSAParameters RecoverRSAParameters(BigInteger n, BigInteger e, BigInteger d)
{
    using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
    {
        BigInteger k = d * e - 1;

        if (!k.IsEven)
        {
            throw new InvalidOperationException("d*e - 1 is odd");
        }

        BigInteger two = 2;
        BigInteger t = BigInteger.One;

        BigInteger r = k / two;

        while (r.IsEven)
        {
            t++;
            r /= two;
        }

        byte[] rndBuf = n.ToByteArray();

        if (rndBuf[rndBuf.Length - 1] == 0)
        {
            rndBuf = new byte[rndBuf.Length - 1];
        }

        BigInteger nMinusOne = n - BigInteger.One;

        bool cracked = false;
        BigInteger y = BigInteger.Zero;

        for (int i = 0; i < 100 && !cracked; i++)
        {
            BigInteger g;

            do
            {
                rng.GetBytes(rndBuf);
                g = GetBigInteger(rndBuf);
            }
            while (g >= n);

            y = BigInteger.ModPow(g, r, n);

            if (y.IsOne || y == nMinusOne)
            {
                i--;
                continue;
            }

            for (BigInteger j = BigInteger.One; j < t; j++)
            {
                BigInteger x = BigInteger.ModPow(y, two, n);

                if (x.IsOne)
                {
                    cracked = true;
                    break;
                }

                if (x == nMinusOne)
                {
                    break;
                }

                y = x;
            }
        }

        if (!cracked)
        {
            throw new InvalidOperationException("Prime factors not found");
        }

        BigInteger p = BigInteger.GreatestCommonDivisor(y - BigInteger.One, n);
        BigInteger q = n / p;
        BigInteger dp = d % (p - BigInteger.One);
        BigInteger dq = d % (q - BigInteger.One);
        BigInteger inverseQ = ModInverse(q, p);

        int modLen = rndBuf.Length;
        int halfModLen = (modLen + 1) / 2;

        return new RSAParameters
        {
            Modulus = GetBytes(n, modLen),
            Exponent = GetBytes(e, -1),
            D = GetBytes(d, modLen),
            P = GetBytes(p, halfModLen),
            Q = GetBytes(q, halfModLen),
            DP = GetBytes(dp, halfModLen),
            DQ = GetBytes(dq, halfModLen),
            InverseQ = GetBytes(inverseQ, halfModLen),
        };
    }
}

With the "tricky" BigInteger-to-suitable-for-RSAParameters-byte[] method:

private static byte[] GetBytes(BigInteger value, int size)
{
    byte[] bytes = value.ToByteArray();

    if (size == -1)
    {
        size = bytes.Length;
    }

    if (bytes.Length > size + 1)
    {
        throw new InvalidOperationException($"Cannot squeeze value {value} to {size} bytes from {bytes.Length}.");
    }

    if (bytes.Length == size + 1 && bytes[bytes.Length - 1] != 0)
    {
        throw new InvalidOperationException($"Cannot squeeze value {value} to {size} bytes from {bytes.Length}.");
    }

    Array.Resize(ref bytes, size);
    Array.Reverse(bytes);
    return bytes;
}

And for computing InverseQ you need ModInverse:

private static BigInteger ModInverse(BigInteger e, BigInteger n)
{
    BigInteger r = n;
    BigInteger newR = e;
    BigInteger t = 0;
    BigInteger newT = 1;

    while (newR != 0)
    {
        BigInteger quotient = r / newR;
        BigInteger temp;

        temp = t;
        t = newT;
        newT = temp - quotient * newT;

        temp = r;
        r = newR;
        newR = temp - quotient * newR;
    }

    if (t < 0)
    {
        t = t + n;
    }

    return t;
}

On my computer I'm recovering P and Q from (n, e, d) in ~50ms for a 1024-bit key.  ~2-4 seconds for a 4096-bit key.

Note to implementers who like unit tests: There's not really a defined order for P and Q (like a convention that P always be the larger), so your P and Q values may be backwards from an RSAParameters structure that you started with. DP and DQ will thus also be reversed.


问:
Thymeleaf automatic form generation
I'd like to create form in specific way. The form should be able to render itself based on received data, should be used like that:

```<code> <form action="#" th:action="@{/blahblah}" th:formDefinition="${formDef}" th:object="${formData}"method="post">
</code>```

This should render the necessary input elements in some way, fill in the data etc. Is there a way how to achieve this in Thymeleaf?

答:
Use Apache Freemaker to create templates in Netbeans IDE. Using this templates, auto-generate your forms from your Entities. This allows you to apply the principle of DRY.....Dont Repeat Yourself in your SDLC.

For more infor, watch the below clip on how they have applied the principle:

https://nofluffjuststuff.com/blog/reza_rahman/2015/01/vaadin_cdi_and_java_ee

Title: Thymeleaf automatic form generation

Body:
I'd like to create form in specific way. The form should be able to render itself based on received data, should be used like that:

 <form action="#" th:action="@{/blahblah}" th:formDefinition="${formDef}" th:object="${formData}"method="post">

This should render the necessary input elements in some way, fill in the data etc. Is there a way how to achieve this in Thymeleaf?


问:
Update a development team with rewritten Git repo history, removing big files
I have a git repo with some very large binaries in it. I no longer need them, and I don't care about being able to checkout the files from earlier commits. So, to reduce the repo size, I want to delete the binaries from the history altogether.

After a web search, I concluded that my best (only?) option is to use git-filter-branch:

```<code>git filter-branch --index-filter 'git rm --cached --ignore-unmatch big_1.zip big_2.zip etc.zip' HEAD
</code>```

Does this seem like a good approach so far?

Assuming the answer is yes, I have another problem to contend with. The git manual has this warning:

WARNING! The rewritten history will have different object names for all the objects and will not converge with the original branch. You will not be able to easily push and distribute the rewritten branch on top of the original branch. Please do not use this command if you do not know the full implications, and avoid using it anyway, if a simple single commit would suffice to fix your problem. (See the "RECOVERING FROM UPSTREAM REBASE" section in git-rebase(1) for further information about rewriting published history.)

We have a remote repo on our server. Each developer pushes to and pulls from it. Based on the warning above (and my understanding of how git-filter-branch works), I don't think I'll be able to run git-filter-branch on my local copy and then push the changes.

So, I'm tentatively planning to go through the following steps:

Tell all my developers to commit, push, and stop working for a bit.

Log into the server and run the filter on the central repo.

Have everyone delete their old copies and clone again from the server.

Does this sound right? Is this the best solution?

答: If you don't make your developers re-clone it's likely that they will manage to drag the large files back in.  For example, if they carefully splice onto the new history you will create and then happen to git merge from a local project branch that was not rebased, the parents of the merge commit will include the project branch which ultimately points at the entire history you erased with git filter-branch.

Body:
I have a git repo with some very large binaries in it. I no longer need them, and I don't care about being able to checkout the files from earlier commits. So, to reduce the repo size, I want to delete the binaries from the history altogether.

After a web search, I concluded that my best (only?) option is to use git-filter-branch:

git filter-branch --index-filter 'git rm --cached --ignore-unmatch big_1.zip big_2.zip etc.zip' HEAD

Does this seem like a good approach so far?

Assuming the answer is yes, I have another problem to contend with. The git manual has this warning:

WARNING! The rewritten history will have different object names for all the objects and will not converge with the original branch. You will not be able to easily push and distribute the rewritten branch on top of the original branch. Please do not use this command if you do not know the full implications, and avoid using it anyway, if a simple single commit would suffice to fix your problem. (See the "RECOVERING FROM UPSTREAM REBASE" section in git-rebase(1) for further information about rewriting published history.)

We have a remote repo on our server. Each developer pushes to and pulls from it. Based on the warning above (and my understanding of how git-filter-branch works), I don't think I'll be able to run git-filter-branch on my local copy and then push the changes.

So, I'm tentatively planning to go through the following steps:

Tell all my developers to commit, push, and stop working for a bit.

Log into the server and run the filter on the central repo.

Have everyone delete their old copies and clone again from the server.

Does this sound right? Is this the best solution?


问:
PHP Variables are being 'lost' upon HTML Form submission
I'm relatively new to the web development scene and have been assigned with creating a website capable of logging calls.
I have used a HTML form to achieve this - I have made many of these in the past, but have never encountered this issue before.

My page contains 3 buttons: one to log a call, one to forward a call, and one to view all call logs. I achieve this by using an onclick method in the buttons:

```<code><button type=submit value=log onclick="window.location.href='reception.php?log=1';">Log a call.</button>
</code>```

And then using PHP GET to display the appropriate content on the rest of the page.

```<code>                try {
                    $log = $_GET["log"];
                }
                catch(Exception $ex) {
                    die();
                }

                if($log) {
                    ?>
                    // create form
</code>```

This works perfectly, and I have created my form as below.

```<code><form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" name="log">
<p>
    <label>Call date: </label>
    <input type="date" name="date" value=<?php echo date("Y-m-d"); ?>>
    <span class="error"><sup> <?php echo $dateErr; ?></sup></span>
</p>
<br>
<p>
    <label>Does the client have a contract?</label>
    <select name="contract">
        <option value="default" selected disabled>Please select...</option>
        <option value="true">Yes</option>
        <option value="false">No</option>
    </select>
    <span class="error"><sup> <?php echo $contractErr; ?></sup></span>
</p>
<br>
<p>
    <label>Client forename:</label>
    <input type=text name="fname" <?php if(isset($fname)) echo "value='".$fname."'";?>>
    <span class="error"><sup> <?php echo $fnameErr; ?></sup></span>
</p>
<br>
<p>
    <label>Client surname:</label>
    <input type=text name="sname">
    <span class="error"><sup> <?php echo $snameErr; ?></sup></span>
</p>
<br>
<p>
    <label style="position: relative; top: -135px;">Client enquiry:</label>
    <textarea name=enq style="font-size: 14px; height: 150px; width: 300px;"></textarea>
    <span class="error"><sup> <?php echo $enqErr; ?></sup></span>
</p>
<br>
<p>
    <button type=submit name=submit value=submit style="position:relative; right: -115px; height:40px; width: 100px;">Submit</button>
</p>
</code>```

It works just fine. However, the issue comes when submitting the form: for some  reason, all PHP variables that I define come up empty when submit is clicked, meaning that any auto-completion / error messages do not show up. As you can see in my form code, as a test I made it autofill the "fname" field if the user has already set it, but it does not work.

Here is my PHP for validation (it is not complete yet, I just wanted to do all of the 'isset' checks first):

```<code>if ($_SERVER["REQUEST_METHOD"] == "POST") {
            if(isset($_POST["submit"])) {
                $go = true;
                $query = "INSERT INTO callLog VALUES(NULL, '";
                if(empty($_POST["date"])) {
                    $dateErr = "* Please enter a date.";
                    $go = false;
                }
                else {
                    $query .= date('Y-m-d', strtotime($_POST["date"]))."', ";
                }

                if(empty($_POST["contract"])) {
                    $contractErr = "* Please select 'Yes' or 'No'.";
                    $go = false;
                }
                else {
                    $contract = test_input($_POST["contract"]);
                    if($contract == "Yes") {
                        $contract = "TRUE";
                    }
                    else {
                        $contract = "FALSE";
                    }
                    $query .= $contract.", '";
                }

                if(empty($_POST["fname"])) {
                    $fnameErr = "* Please enter a forename.";
                    $go = false;
                }
                else {
                    $fname = test_input($_POST["fname"]);
                    $query .= $fname."', '";
                }

                if(empty($_POST["sname"])) {
                    $snameErr = "* Please enter a surname.";
                    $go = false;
                }
                else {
                    $sname = test_input($_POST["sname"]);
                    $query .= $fname."', '";
                }

                if(empty($_POST["enq"])) {
                    $enqErr = "* Please enter an enquiry.";
                    $go = false;
                }
                else {
                    $query .= $enq."');";
                }

                if($go) {
                    $conn->query($query);
                    header('Location: reception.php');
                }

                ?><script>
                    $(document).ready(function() {
                        window.location.href='reception.php?log=1';
                    });
                </script><?php
            }
        }
</code>```

The JS at the end is simply so that the page redirects to the call log form page once the data has been submitted, rather than having to click the 'call log' button again.

I'm completely at a loss as to why this doesn't work. Aside from the 'GET' method to display the page, I've done everything as I have in the past which has worked fine. Is it the 'GET' method interfering, or am I missing something?

I have seen that potentially trying something such as Ajax to handle the submission to see if it will work is a possibility, but I am not too familiar with JQuery (knowing only the basics) and do not know how to work with Ajax.

Thanks!

答: You're highjacking the form submission. You're onclick="window.location.href='reception.php?log=1';" just makes a GET request to that page, not a POST to your form action.

Body:
I'm relatively new to the web development scene and have been assigned with creating a website capable of logging calls.
I have used a HTML form to achieve this - I have made many of these in the past, but have never encountered this issue before.

My page contains 3 buttons: one to log a call, one to forward a call, and one to view all call logs. I achieve this by using an onclick method in the buttons:

<button type=submit value=log onclick="window.location.href='reception.php?log=1';">Log a call.</button>

And then using PHP GET to display the appropriate content on the rest of the page.

                try {
                    $log = $_GET["log"];
                }
                catch(Exception $ex) {
                    die();
                }

                if($log) {
                    ?>
                    // create form

This works perfectly, and I have created my form as below.

<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post" name="log">

    Call date:
    <input type="date" name="date" value=<?php echo date("Y-m-d"); ?>>
     <?php echo $dateErr; ?>

    Does the client have a contract?
    <select name="contract">
        <option value="default" selected disabled>Please select...</option>
        <option value="true">Yes</option>
        <option value="false">No</option>
    </select>
     <?php echo $contractErr; ?>

    Client forename:
    <input type=text name="fname" <?php if(isset($fname)) echo "value='".$fname."'";?>>
     <?php echo $fnameErr; ?>

    Client surname:
    <input type=text name="sname">
     <?php echo $snameErr; ?>

    Client enquiry:
    <textarea name=enq style="font-size: 14px; height: 150px; width: 300px;"></textarea>
     <?php echo $enqErr; ?>

    <button type=submit name=submit value=submit style="position:relative; right: -115px; height:40px; width: 100px;">Submit</button>

It works just fine. However, the issue comes when submitting the form: for some  reason, all PHP variables that I define come up empty when submit is clicked, meaning that any auto-completion / error messages do not show up. As you can see in my form code, as a test I made it autofill the "fname" field if the user has already set it, but it does not work.

Here is my PHP for validation (it is not complete yet, I just wanted to do all of the 'isset' checks first):

if ($_SERVER["REQUEST_METHOD"] == "POST") {
            if(isset($_POST["submit"])) {
                $go = true;
                $query = "INSERT INTO callLog VALUES(NULL, '";
                if(empty($_POST["date"])) {
                    $dateErr = "* Please enter a date.";
                    $go = false;
                }
                else {
                    $query .= date('Y-m-d', strtotime($_POST["date"]))."', ";
                }

                if(empty($_POST["contract"])) {
                    $contractErr = "* Please select 'Yes' or 'No'.";
                    $go = false;
                }
                else {
                    $contract = test_input($_POST["contract"]);
                    if($contract == "Yes") {
                        $contract = "TRUE";
                    }
                    else {
                        $contract = "FALSE";
                    }
                    $query .= $contract.", '";
                }

                if(empty($_POST["fname"])) {
                    $fnameErr = "* Please enter a forename.";
                    $go = false;
                }
                else {
                    $fname = test_input($_POST["fname"]);
                    $query .= $fname."', '";
                }

                if(empty($_POST["sname"])) {
                    $snameErr = "* Please enter a surname.";
                    $go = false;
                }
                else {
                    $sname = test_input($_POST["sname"]);
                    $query .= $fname."', '";
                }

                if(empty($_POST["enq"])) {
                    $enqErr = "* Please enter an enquiry.";
                    $go = false;
                }
                else {
                    $query .= $enq."');";
                }

                if($go) {
                    $conn->query($query);
                    header('Location: reception.php');
                }

                ?><?php
            }
        }

The JS at the end is simply so that the page redirects to the call log form page once the data has been submitted, rather than having to click the 'call log' button again.

I'm completely at a loss as to why this doesn't work. Aside from the 'GET' method to display the page, I've done everything as I have in the past which has worked fine. Is it the 'GET' method interfering, or am I missing something?

I have seen that potentially trying something such as Ajax to handle the submission to see if it will work is a possibility, but I am not too familiar with JQuery (knowing only the basics) and do not know how to work with Ajax.

Thanks!


问:
R - Subset a dataframe based on condition from another dataframe
I have a question which is somewhat similar to this post but it is not working for me because of a slight change in the condition.

I have 2 dataframes which looks like:

```<code>> effect
  V1        V2 V3
1 G1 activates G2
2 G3     stops G4
3 G5 activates G6
4 G6     stops G7

> expression
  V1 V2
1 G1  1
2 G2  0
3 G3  1
4 G4  0
5 G5  1
6 G6  1
7 G7  1
</code>```

I want to keep only those rows in effect dataframe which fulfills following condition:

if effect$V2 == activates then expression$V2 should be 1 where
effect$V3 and expression$V1 are the same

if effect$V2 == stops then expression$V2 should be 0 where
effect$V3 and expression$V1 are the same

According to this criteria I will get on this results:

```<code>> results
  V1        V2 V3
1 G3     stops G4
2 G5 activates G6
</code>```

Because this is consistent with the given conditions such that for the first row the V2=stops and expression$V2 for the G4 is 0.

Similarly, for row2 V2=activatesand expression$V2 for the G6 is 1

The structure of the dataframes are given below. Any help will be much appreciated.

df1:

```<code>structure(list(V1 = structure(1:4, .Label = c("G1", "G3", "G5",
"G6"), class = "factor"), V2 = structure(c(1L, 2L, 1L, 2L), .Label = c("activates",
"stops"), class = "factor"), V3 = structure(1:4, .Label = c("G2",
"G4", "G6", "G7"), class = "factor")), .Names = c("V1", "V2",
"V3"), class = "data.frame", row.names = c(NA, -4L))
</code>```

df2:

```<code>structure(list(V1 = structure(1:7, .Label = c("G1", "G2", "G3",
"G4", "G5", "G6", "G7"), class = "factor"), V2 = c(1L, 0L, 1L,
0L, 1L, 1L, 1L)), .Names = c("V1", "V2"), class = "data.frame", row.names = c(NA,
-7L))
</code>```

答:
I have figured out the answer for this. It is:</p>

```<code>ab <- merge(effect, expression, by.x = "V3", by.y = "V1")
cd <- subset(ab, V2.x == "activates" & V2.y == 1 | V2.x == "stops" & V2.y == 0)
results <- cd[,c(2,3,1)]
> results
  V1      V2.x V3
2 G3     stops G4
3 G5 activates G6
</code>```

Body:
I have a question which is somewhat similar to this post but it is not working for me because of a slight change in the condition.

I have 2 dataframes which looks like:

> effect
  V1        V2 V3
1 G1 activates G2
2 G3     stops G4
3 G5 activates G6
4 G6     stops G7

> expression
  V1 V2
1 G1  1
2 G2  0
3 G3  1
4 G4  0
5 G5  1
6 G6  1
7 G7  1

I want to keep only those rows in effect dataframe which fulfills following condition:

if effect$V2 == activates then expression$V2 should be 1 where
effect$V3 and expression$V1 are the same

if effect$V2 == stops then expression$V2 should be 0 where
effect$V3 and expression$V1 are the same

According to this criteria I will get on this results:

> results
  V1        V2 V3
1 G3     stops G4
2 G5 activates G6

Because this is consistent with the given conditions such that for the first row the V2=stops and expression$V2 for the G4 is 0.

Similarly, for row2 V2=activatesand expression$V2 for the G6 is 1

The structure of the dataframes are given below. Any help will be much appreciated.

df1:

structure(list(V1 = structure(1:4, .Label = c("G1", "G3", "G5",
"G6"), class = "factor"), V2 = structure(c(1L, 2L, 1L, 2L), .Label = c("activates",
"stops"), class = "factor"), V3 = structure(1:4, .Label = c("G2",
"G4", "G6", "G7"), class = "factor")), .Names = c("V1", "V2",
"V3"), class = "data.frame", row.names = c(NA, -4L))

df2:

structure(list(V1 = structure(1:7, .Label = c("G1", "G2", "G3",
"G4", "G5", "G6", "G7"), class = "factor"), V2 = c(1L, 0L, 1L,
0L, 1L, 1L, 1L)), .Names = c("V1", "V2"), class = "data.frame", row.names = c(NA,
-7L))

Body:
I have figured out the answer for this. It is:

ab <- merge(effect, expression, by.x = "V3", by.y = "V1")
cd <- subset(ab, V2.x == "activates" & V2.y == 1 | V2.x == "stops" & V2.y == 0)
results <- cd[,c(2,3,1)]
> results
  V1      V2.x V3
2 G3     stops G4
3 G5 activates G6


问:
Is there any way in SASS to nest a tag inside its selector?
Below is a code I have:

```<code>.page-header {
    font-family: 'Roboto', sans-serif;
    color: #333;
}
</code>```

Now I want to set the font size of the header depending on the tag (h1, h2, h3, etc.). Below is what I currently do it like:

```<code>h1.page-header {
    font-size: 56px;
}
h2.page-header {
   font-size: 38px;
}
</code>```

Is there any way to nest it something like:

```<code>.page-header {
    color: #333;

    h1 {
        font-size: 56px;
    }
}
</code>```

(I know this won't work as I expect it, just to give you an idea of what I want).

答:
Use @at-root with interpolation #{} using ampersand & to reference the current selector.

```<code>.page-header {
  @at-root h1#{&} {
    font-size: 56px;
  }
  @at-root h2#{&} {
    font-size: 38px;
  }
}
</code>```

Will produce:

```<code>h1.page-header {
  font-size: 56px;
}
h2.page-header {
  font-size: 38px;
}
</code>```

Body:
Below is a code I have:

.page-header {
    font-family: 'Roboto', sans-serif;
    color: #333;
}

Now I want to set the font size of the header depending on the tag (h1, h2, h3, etc.). Below is what I currently do it like:

h1.page-header {
    font-size: 56px;
}
h2.page-header {
   font-size: 38px;
}

Is there any way to nest it something like:

.page-header {
    color: #333;

    h1 {
        font-size: 56px;
    }
}

(I know this won't work as I expect it, just to give you an idea of what I want).

Body:
Use @at-root with interpolation #{} using ampersand & to reference the current selector.

.page-header {
  @at-root h1#{&} {
    font-size: 56px;
  }
  @at-root h2#{&} {
    font-size: 38px;
  }
}

Will produce:

h1.page-header {
  font-size: 56px;
}
h2.page-header {
  font-size: 38px;
}


问:
Fossil JSON API: How to create a wiki page?
I've been trying to create a wiki page, ufollowing the documentation of the Fossil JSON API. When I put the URL http://myrepo.top/json/wiki/create?name=test I get and answer similar to:

{"fossil":"81d7d3f43ebd4e77095cfbacee7ebc9ae043a014760cde56d437dbd8b6a37c92","timestamp":1496771043,"resultCode":"FOSSIL-3002","resultText":"'name' parameter is missing.","command":"wiki/create","procTimeUs":4000,"procTimeMs":4}

I don't know how the page name is supposed to be given in the URL. I was imagining that was similar to the way you query wiki pages, but seems that the API is expecting something different. Could someone show me the proper way of adding the page name to the Fossil JSON API URL?

Thanks,

答:
In the Fossil mailing list Warren gave me an answer on how to proceed:

curl -H "Content-Type: application/json"                  \
           -d '{"authToken": "nunyabinness",                    \
                "payload": {"name": "foo", "content": "bar"} }' \
           http://localhost:8080/json/wiki/create

and that gives me the proper wiki page.


问:
Java untyped generic classes, removing their functions generics types
Ok Question about javas generics, iterable, and for-each loop.  The problem being that, if I declare my 'Test' class untyped,  I lose all generic information on all my functions and for-each is not likeing that at all.

Example

```<code>public class Test<T> implements Iterable<Integer>{

    public Test() {}

    public Iterator<Integer> iterator() {return null;}

    public static void main(String[] args) {
        Test t = new Test();

        //Good,
        //its returning an Iterator<object> but it automatically changes to  Iterator<Integer>
        Iterator<Integer> it = t.iterator();

        //Bad
        //incompatable types, required Integer, found Object
        for(Integer i : t){
        }
    }Untyped generic classes losing
}
</code>```

When 'Test t' is untyped, the 'iterator()' function returns 'iterator' instead of a 'iterator < Integer >'.

I'm not exactly sure for the reason behind it, I know a fix for that is just use a wild card on 'Test < ? > t = new test()'.  However this is a less than ideal solution.

Is their any way to only edit the class declaration and its functions and have the for each loop work untyped?

答:
You should either write this:

```<code>public class Test implements Iterable<Integer>{
  ...
</code>```

or actually generify your class:

```<code>public class Test<T> implements Iterable<T> {

    public Iterator<T> iterator() {return null;}

    public static void main(String[] args) {
        Test<Integer> t = new Test<Integer>();

        Iterator<Integer> it = t.iterator();

        for(Integer i : t){
        }
    }
}
</code>```

Body:
Ok Question about javas generics, iterable, and for-each loop.  The problem being that, if I declare my 'Test' class untyped,  I lose all generic information on all my functions and for-each is not likeing that at all.

Example

public class Test<T> implements Iterable<Integer>{

    public Test() {}

    public Iterator<Integer> iterator() {return null;}

    public static void main(String[] args) {
        Test t = new Test();

        //Good,
        //its returning an Iterator<object> but it automatically changes to  Iterator<Integer>
        Iterator<Integer> it = t.iterator();

        //Bad
        //incompatable types, required Integer, found Object
        for(Integer i : t){
        }
    }Untyped generic classes losing
}

When 'Test t' is untyped, the 'iterator()' function returns 'iterator' instead of a 'iterator < Integer >'.

I'm not exactly sure for the reason behind it, I know a fix for that is just use a wild card on 'Test < ? > t = new test()'.  However this is a less than ideal solution.

Is their any way to only edit the class declaration and its functions and have the for each loop work untyped?

Body:
You should either write this:

public class Test implements Iterable<Integer>{
  ...

or actually generify your class:

public class Test<T> implements Iterable<T> {

    public Iterator<T> iterator() {return null;}

    public static void main(String[] args) {
        Test<Integer> t = new Test<Integer>();

        Iterator<Integer> it = t.iterator();

        for(Integer i : t){
        }
    }
}


问:
Appending to a private TextArea from a different class in Java

class Backend extends UI {
    // some code
    void start() {
        txtRespond.append(Bot + ": hello, " + Name + "\n"); /* have a problem accessing txtRespond */

public class UI extends javax.swing.JFrame {
    // some code
    private javax.swing.JTextArea txtRespond;
```

I'm trying to add sentences to my JTextArea from a different class.

答:
As I mentioned in my comment very initially when you posted the question, You need to have the private field marked as protected so that the sub class can access it or provide methods for mutation.

Second approach is better as it protects the encapsulation.

```<code>public class UI extends javax.swing.JFrame {
    // some code
    private javax.swing.JTextArea txtRespond;

    protected void appendResponse(String response){
        txtRespond.append(response);
    }

    // your other methods and code if you have.
}

class Backend extends UI {
    // some code
    void start() {
        appendResponse(Bot + ": hello, " + Name + "\n");
    }
}
</code>```

Having a class handle the responsibility of modifying its state is a good practice. We should avoid making them non private.

*P.S. if bot, Name are defined in parent class then you can just pass the variant part of the string and pass it to parent method as parameters(of course you need to modify the signature of method to accept more than one string) and in the method defination you can handle the merging of the strings as per requirements.

Body:
class Backend extends UI {
    // some code
    void start() {
        txtRespond.append(Bot + ": hello, " + Name + "\n"); /* have a problem accessing txtRespond */

public class UI extends javax.swing.JFrame {
    // some code
    private javax.swing.JTextArea txtRespond;

I'm trying to add sentences to my JTextArea from a different class.

Body:
As I mentioned in my comment very initially when you posted the question, You need to have the private field marked as protected so that the sub class can access it or provide methods for mutation.

Second approach is better as it protects the encapsulation.

public class UI extends javax.swing.JFrame {
    // some code
    private javax.swing.JTextArea txtRespond;

    protected void appendResponse(String response){
        txtRespond.append(response);
    }

    // your other methods and code if you have.
}

class Backend extends UI {
    // some code
    void start() {
        appendResponse(Bot + ": hello, " + Name + "\n");
    }
}

Having a class handle the responsibility of modifying its state is a good practice. We should avoid making them non private.

*P.S. if bot, Name are defined in parent class then you can just pass the variant part of the string and pass it to parent method as parameters(of course you need to modify the signature of method to accept more than one string) and in the method defination you can handle the merging of the strings as per requirements.


问:
How to set and unset password on a MIFARE Ultralight EV1 tag?
I would like to be able to set and unset password protection on a MIFARE Ultralight EV1 (MFOUL21) tag using the NfcA? tag technology on Android.

I understand I would use the nfcA.transceive() method for this, but I'm not sure what the arguments to that method would be, so could anyone provide code snippets to set and unset the password?

Update:

With respect to the TapLinx library, I would basically like the nfcA.transceive(...) code snippets equvalent to:

ultralightEV1.programPwd(passwordBytes);

ultralightEV1.programPack(packBytes);

ultralightEV1.enablePasswordProtection(enabled, fromPageNum);

ultralightEV1.authenticatePwd(passwordBytes);

答:
You can use the TapLinx Library from NXP (available at https://www.mifare.net/en/products/tools/taplinx/) to communicate with MIFARE Ultralight EV1 in an abstracted manner.

To use "transceive", according to the datasheet available at http://www.advanide.com/wp-content/uploads/products/rfid/UltraLight%20EV1_MF0ULX1.pdf the WRITE Command (A2) needs to be used, with addresses 25-28h.

UPDATE:
The commands to be sent should be (for MFOUL21):

ultralightEV1.programPwd(passwordBytes);
A227AABBCCDD (for Password AABBCCDD)

ultralightEV1.programPack(packBytes);
A228EEFF0000 (for PACK 0000)

ultralightEV1.enablePasswordProtection(enabled, fromPageNum);
A225xx0000yy (where xx is the modulation mode; 00..strong mod. disabled; 01..strong mod enabled; yy = page where password protection starts)

ultralightEV1.authenticatePwd(passwordBytes);
1BAABBCCDD


问:
How can i select random elements from dropdown lists which has tagname as
?
I tried this thing and it works perfectly when the tag name is selected, but when I use Select select = new Select(); in the tag name div, or something, it fails to work and prompts me with the following error:  org.openqa.selenium.support.ui.UnexpectedTagNameException: Element should have been "select" but was "div".

```<code><div stop-propagation="click" class="custom-select-search">
    <input class="undefined ng-pristine ng-valid ng-touched" type="text" autocomplete="off" ng-model="searchTerm">
</div>
<ul role="menu">
    <li role="presentation" class="ng-scope">
        <a role="menuitem" tabindex="-1" href=""ng-click="select(s)" class="ng-binding">166</a>
    </li>
    <li role="presentation" class="ng-scope">
        <a role="menuitem" tabindex="-1" href=""ng-click="select(s)" class="ng-binding">164</a>
    </li>
    <li role="presentation" class="ng-scope">
        <a role="menuitem" tabindex="-1" href=""ng-click="select(s)" class="ng-binding">165</a>
    </li>
    <li role="presentation" class="ng-scope">
        <a role="menuitem" tabindex="-1" href=""ng-click="select(s)" class="ng-binding">166</a>
    </li>
</ul>
</code>```

This is my code:

```<code>        WebElement elements = driver.findElement(serial);
        Select ComboBoxValues = new Select(elements);
        List <WebElement> weblist = ComboBoxValues.getOptions();
        int iCnt = weblist.size();
        Random num = new Random();
        int iSelect = num.nextInt(iCnt);
        ComboBoxValues.selectByIndex(iSelect);
        System.out.println("Element Name 1 : " +elements.getAttribute("value"));
</code>```

Can anyone tell me to do this.

答: Looks like the site has some custom UI that emulates a dropdown.  Which means you'll have to implement your own code to interact with it.  I would recommend creating a class, let's call it MySiteSelector, that will have a select() method which knows where to click to open the menu list (it doesn't look like that's here), then will search through your list items (a css selector would be "ul[role='menu] li") to find the one that matches your desired target.</p>

Title: How can i select random elements from dropdown lists which has tagname as <div>?

Body:
I tried this thing and it works perfectly when the tag name is selected, but when I use Select select = new Select(); in the tag name div, or something, it fails to work and prompts me with the following error:  org.openqa.selenium.support.ui.UnexpectedTagNameException: Element should have been "select" but was "div".

    <input class="undefined ng-pristine ng-valid ng-touched" type="text" autocomplete="off" ng-model="searchTerm">

        166

        164

        165

        166

This is my code:

        WebElement elements = driver.findElement(serial);
        Select ComboBoxValues = new Select(elements);
        List <WebElement> weblist = ComboBoxValues.getOptions();
        int iCnt = weblist.size();
        Random num = new Random();
        int iSelect = num.nextInt(iCnt);
        ComboBoxValues.selectByIndex(iSelect);
        System.out.println("Element Name 1 : " +elements.getAttribute("value"));

Can anyone tell me to do this.


问:
How can I query YouTube API to get videos from auto-generated 'Topic' channels?
How can I input search parameters using the YouTube API so that I only get video ID's from topic channels? For instance, if I go to youtube.com and manually search "Hello Adele - Topic" I correctly get the song, 'Hello' from the 'Adele - Topic' channel as my first search result, https://www.youtube.com/watch?v=_WS9w10ygpU.
However, if I perform the same query using the YouTube Data API, with the parameters:

```<code>part='snippet'
q='Hello Adele - Topic'
</code>```

I won't get back the ID for the correct video. Is there any way to get this programmatically?

答:
As stated in this thread, auto generated channels have no videos. They have only playlists with videos from other channels. So you have to look for playlists. You may check the sample request in this link.

Here's the URL sample of auto-generated Topic-based Id which grabs its playlist id:

```<code>GET https://www.googleapis.com/youtube/v3/playlists?part=snippet&channelId=HC9m3exs6zk1U&fields=items%2Fid&key={YOUR_API_KEY}
//Outputs sample playlist Id: LP9m3exs6zk1U
</code>```

Now here's the URL sample using that playlist Id to get the videos from the auto-generated Topic-based channel Id:

```<code>GET https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=5&playlistId=LP9m3exs6zk1U&key={YOUR_API_KEY}
//Outputs video data you want.
</code>```

Hope this helps.

Body:
How can I input search parameters using the YouTube API so that I only get video ID's from topic channels? For instance, if I go to youtube.com and manually search "Hello Adele - Topic" I correctly get the song, 'Hello' from the 'Adele - Topic' channel as my first search result, https://www.youtube.com/watch?v=_WS9w10ygpU.
However, if I perform the same query using the YouTube Data API, with the parameters:

part='snippet'
q='Hello Adele - Topic'

I won't get back the ID for the correct video. Is there any way to get this programmatically?

Body:
As stated in this thread, auto generated channels have no videos. They have only playlists with videos from other channels. So you have to look for playlists. You may check the sample request in this link.

Here's the URL sample of auto-generated Topic-based Id which grabs its playlist id:

GET https://www.googleapis.com/youtube/v3/playlists?part=snippet&channelId=HC9m3exs6zk1U&fields=items%2Fid&key={YOUR_API_KEY}
//Outputs sample playlist Id: LP9m3exs6zk1U

Now here's the URL sample using that playlist Id to get the videos from the auto-generated Topic-based channel Id:

GET https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=5&playlistId=LP9m3exs6zk1U&key={YOUR_API_KEY}
//Outputs video data you want.

Hope this helps.


问:
call multiple functions nodejs
I just started with nodejs and I basically have two functions I want to execute and based on the success of each of those functions, or error of those functions, I want the wrapper function to generate an overall status code.  I looked at the async package and I got it working in the happy path where everything succeeds and my last callback gets a success.  But what if one fails?  I see that the error gets sent to the last callback of async.waterfall, but the second function never gets run since there was an error and I do want to know the results of both functions.  I've tried, series, parallel, and waterfall, and from what I can tell, they all call the final callback once an error is hit.  Is there an idiomatic way to do this in Node? </p>

答:
The other answers will work fine, though I think they're not the way I'd do it.

Given that you're already interested in AsyncJS, I would consider using it still, but simply not propagating the error directly.  Swallow the error and have the data part of the callback represent whatever status you want to convey, as your callback is effectively handling it.

For example, let's say you have a function that's part of your async series or parallel call:

```<code>...
function getModel((cb) => {
   model.find({_id: 1}, (err, data) => {
     if (err) return cb(null, { status: 500, message: 'Database connection error' });
     if (!data) return cb(null, { status: 404, message: 'model 1 not found' });
     return cb(null, { status: 200, model: data });
   });
}),
...
</code>```

Title: call multiple functions nodejs

Body:
The other answers will work fine, though I think they're not the way I'd do it.

Given that you're already interested in AsyncJS, I would consider using it still, but simply not propagating the error directly.  Swallow the error and have the data part of the callback represent whatever status you want to convey, as your callback is effectively handling it.

For example, let's say you have a function that's part of your async series or parallel call:

...
function getModel((cb) => {
   model.find({_id: 1}, (err, data) => {
     if (err) return cb(null, { status: 500, message: 'Database connection error' });
     if (!data) return cb(null, { status: 404, message: 'model 1 not found' });
     return cb(null, { status: 200, model: data });
   });
}),
...


问:
Javascript sort array on property array
So I have this array of users that looks something like this:

```<code>[{
    userName: 'Jim',
    roles: ['Member']
}, {
    userName: 'Adam',
    roles: ['Administrator']
}, {
    userName: 'Suzy',
    roles: ['SuperUser']
}, {
    userName: 'Greg',
    roles: ['SuperUser']
}, {
    userName: 'Ady',
    roles: ['Administrator']
}, {
    userName: 'Jeremy',
    roles: ['Administrator']
}]
</code>```

I would like to sort this array by it's roles.
I tried doing this:

```<code>items.sort(function (a, b) {
    var aValue = a.roles[0];
    var bValue = b.roles[0];

    if (aValue < bValue) return -1;
    if (aValue > bValue) return -1;
    return 0;
});
</code>```

But it doesn't do what I expect. Does anyone know how to solve this issue?

答:
give this a shot</p>

```<code>function SortByRole(a, b){
  var aRole = a.roles[0];
  var bRole = b.roles[0];
  return ((aRole < bRole) ? -1 : ((aRole > bRole) ? 1 : 0));
}

array.sort(SortByRole);
</code>```

Title: Javascript sort array on property array

Body:
So I have this array of users that looks something like this:

[{
    userName: 'Jim',
    roles: ['Member']
}, {
    userName: 'Adam',
    roles: ['Administrator']
}, {
    userName: 'Suzy',
    roles: ['SuperUser']
}, {
    userName: 'Greg',
    roles: ['SuperUser']
}, {
    userName: 'Ady',
    roles: ['Administrator']
}, {
    userName: 'Jeremy',
    roles: ['Administrator']
}]

I would like to sort this array by it's roles.
I tried doing this:

items.sort(function (a, b) {
    var aValue = a.roles[0];
    var bValue = b.roles[0];

    if (aValue < bValue) return -1;
    if (aValue > bValue) return -1;
    return 0;
});

But it doesn't do what I expect. Does anyone know how to solve this issue?

Body:
give this a shot

function SortByRole(a, b){
  var aRole = a.roles[0];
  var bRole = b.roles[0];
  return ((aRole < bRole) ? -1 : ((aRole > bRole) ? 1 : 0));
}

array.sort(SortByRole);


问:
When and Why would a Child class declare a static instance member of the parent class?
This is another design pattern in some legacy code that I couldn't find much about on google. In this case a child class extends its abstract parent, but then turns right around and declares a static instance of the parent:

```<code>public abstract class MessageBase {
    protected DAOFactory factory;
    // method declarations
}

public class EDWMessage extends MessageBase {
    private static MessageBase instance;

    public static MessageBase getInstance(Properties properties) {
        if (instance == null) {
            instance = new EDWMessageTransaction(properties, null);
        }
        return instance;
    }
//more code
}
</code>```

I'm not sure I understand what would drive this design pattern (if it is a known pattern). Is this a sort of convenience pattern to avoid declaring each member variable of the parent as static? Or is it meant to allow multiple children classes to each have one instance of the parent. But if that's the case, why the excessive use of inheritance over just plain composition?

The rest of the code gives no indication as to why it would be done this way. Any thoughts or ideas would be much appreciated. Thanks!

P.S. I seem to be running in to a lot of interesting design patterns in this legacy code that I don't know how to handle. Thanks to everyone who has helped me out already.

Edit: Expanding the code sample. Will edit again as I discover someplace that actually uses this code. Yay for no documentation.

答:
This is a common idiom for thread-safe lazy singleton initialization.  If you can have a singleton class, you delegate to a private static instantiating class.

```<code>public class MySingleton{

   private MySingleton(){

   }

   public static MySingleton getInstance(){
       return SingletonCreator.INSTANCE;
   }

   private static class SingletonCreator{
     private static final MySingleton INSTNACE = new MySingleton();
   }
}
</code>```

Not sure if this is how your child class is being used, but this would be a use case for a child class holding a static instance of its parent

Body:
This is another design pattern in some legacy code that I couldn't find much about on google. In this case a child class extends its abstract parent, but then turns right around and declares a static instance of the parent:

public abstract class MessageBase {
    protected DAOFactory factory;
    // method declarations
}

public class EDWMessage extends MessageBase {
    private static MessageBase instance;

    public static MessageBase getInstance(Properties properties) {
        if (instance == null) {
            instance = new EDWMessageTransaction(properties, null);
        }
        return instance;
    }
//more code
}

I'm not sure I understand what would drive this design pattern (if it is a known pattern). Is this a sort of convenience pattern to avoid declaring each member variable of the parent as static? Or is it meant to allow multiple children classes to each have one instance of the parent. But if that's the case, why the excessive use of inheritance over just plain composition?

The rest of the code gives no indication as to why it would be done this way. Any thoughts or ideas would be much appreciated. Thanks!

P.S. I seem to be running in to a lot of interesting design patterns in this legacy code that I don't know how to handle. Thanks to everyone who has helped me out already.

Edit: Expanding the code sample. Will edit again as I discover someplace that actually uses this code. Yay for no documentation.

Body:
This is a common idiom for thread-safe lazy singleton initialization.  If you can have a singleton class, you delegate to a private static instantiating class.

public class MySingleton{

   private MySingleton(){

   }

   public static MySingleton getInstance(){
       return SingletonCreator.INSTANCE;
   }

   private static class SingletonCreator{
     private static final MySingleton INSTNACE = new MySingleton();
   }
}

Not sure if this is how your child class is being used, but this would be a use case for a child class holding a static instance of its parent


答:
The third parameter you are passing into the get function is a callback. If you add value to an array inside the callback and try to access it before the callback is invoked, that array will be empty/undefined.

The way I see it, you have two options:

Look into doing the work you need inside your callback. Either directly, or by passing a callback into the function. Edit: Check out @JohnnyCoder's answer above for the latter.

Consider using a Promise. If the Twitter API doesn't support it, you can consider turning the callback into a promise (by wrapping around the result). For a fairly simple tutorial on how to convert a callback into a Promise using the native JavaScript API, check out this blog post.

Title: Store data from twitter api javascript (nodejs)

Body:
I seem to be having an issue. I'm trying to export data from the twitter api but I can't. Here's what my code looks like :

/// Twitter.js
module.exports = Twitter

function Twitter(twitter) {
    this.twitter = twitter
}

Twitter.prototype.friends = function(params) {
    this.twitter.get('friends/list', params, (err, data) => {
        if (err)
            console.log(err)

        console.log(data) // this prints data to the console but
                          // I want to export and save in a data structure
                          // array or object
    }
}

///bot.js
var Twit = require('twit')
var config = require('/path_to_config.js')
var init = Twit(config)
var Twitter = require('/path_to_Twitter.js')

var bot = new Twitter(config)
bot.friends({ screen_name: 'myscreenname'})

If I try returning the data parameter it returns undefined and if I push data.users to an array it returns an empty array. Any help is and will be appreciated.


问:
Data frame: loop over participants/observations and write column to text file
I'm trying to loop over the participants in a data frame and then write a different column (text) to individual .txt files, so that I ultimately end up with one .txt file per participant containing all the text they produced (a participant can have several observations rows!)

Searching stackoverflow, this is what I have so far:

```<code>dataframe <- data.frame(part_id = rep(seq(1:3), 2), text = c("test1",
"test2", "test3", "test4", "test5", "test6"))
dataframe <- dataframe %>% arrange(part_id)

for(i in dataframe$part_id) {
    subset[i] <- dataframe[dataframe$part_id == i,]$text
    write.table(i, paste(i, ".txt", sep=""),
                col.names = FALSE, row.names = FALSE,  sep = "\t")
}
</code>```

It works insofar as the loop produces individual text files (.txt), but instead of the text, they contain the part_id.

Any help is welcome and much appreciated!

答: Because in write.table(i, file_path) you're writing i (which is the part_id) into the file, change it to write.table(subset[i], file_path) will do the work.

Body:
I'm trying to loop over the participants in a data frame and then write a different column (text) to individual .txt files, so that I ultimately end up with one .txt file per participant containing all the text they produced (a participant can have several observations rows!)

Searching stackoverflow, this is what I have so far:

dataframe <- data.frame(part_id = rep(seq(1:3), 2), text = c("test1",
"test2", "test3", "test4", "test5", "test6"))
dataframe <- dataframe %>% arrange(part_id)

for(i in dataframe$part_id) {
    subset[i] <- dataframe[dataframe$part_id == i,]$text
    write.table(i, paste(i, ".txt", sep=""),
                col.names = FALSE, row.names = FALSE,  sep = "\t")
}

It works insofar as the loop produces individual text files (.txt), but instead of the text, they contain the part_id.

Any help is welcome and much appreciated!


答:
You can use localeCompare method for string comparison inside sort().

var data = [{"userName":"Jim","roles":["Member"]},{"userName":"Adam","roles":["Administrator"]},{"userName":"Suzy","roles":["SuperUser"]},{"userName":"Greg","roles":["SuperUser"]},{"userName":"Ady","roles":["Administrator"]},{"userName":"Jeremy","roles":["Administrator"]}]

data.sort(function(a, b) {
  return a.roles[0].localeCompare(b.roles[0])
})

console.log(data)```

Title: Javascript sort array on property array


问:
Effect of assigning an empty initializer list to an existing vector or map?
I have 2 containers, a std::vector and a std::map:

```<code>vector<int> my_vector;
map<string,int> my_map;
my_vector.push_back(3);

// elaboration of my_vector;
...

my_map["Hello"] = 1;

// elaboration of my_map
...
</code>```

Later I do:

```<code>my_map = {};
my_vector = {};
</code>```

This should make the 2 containers 2 empty containers, right? Furthermore, what happens to the memory previously pointed to from my_map and my_vector?

(I'm on C++11)

答:
Yes both assignments cause the vector and the map to be emptied.  Both the assignments are linear in the size of the vector and the map because both require every single element in the container to be destroyed before assignment, and that requires an O(n) traversal.  The vector reuses memory (https://wandbox.org/permlink/eIJEcEqERC2ybAjU) I think whether or not the map reuses memory is implementation defined (or at least I was not able to make out from the documentation)

As for the tricky part (in my opinion), which assignment operator is called here?  Is it the assignment operator from an initializer list or the move assignment operator for the vector and the map (since {} is implicitly convertible to an instance of either).  I found this quote from cppreference here http://en.cppreference.com/w/cpp/language/operator_assignment#Builtin_direct_assignment

Note that, if a non-template assignment operator from some non-class type is available, it is preferred over the copy/move assignment in E1 = {} because {} to non-class is an identity conversion, which outranks the user-defined conversion from {} to a class type.

So if there is a non template assignment operator, which std::vector does have. That is preferred over the assignment operator from a templated std::intializer_list assignment operator.  You just have to inspect the interface to see what is going on.  You can see the same here

```<code>#include <initializer_list>
#include <iostream>
#include <string>
#include <vector>
#include <map>

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

class Something {
public:
    Something() {
        cout << __PRETTY_FUNCTION__ << endl;
    }
    template <typename U>
    Something(std::initializer_list<U>) {
        cout << __PRETTY_FUNCTION__ << endl;
    }
    Something& operator=(const Something&) {
        cout << __PRETTY_FUNCTION__ << endl;
        return *this;
    }
    Something& operator=(Something&&) {
        cout << __PRETTY_FUNCTION__ << endl;
        return *this;
    }
    Something(const Something&) {
        cout << __PRETTY_FUNCTION__ << endl;
    }
    Something(Something&&) {
        cout << __PRETTY_FUNCTION__ << endl;
    }
    template <typename U>
    Something& operator=(std::initializer_list<U>) {
        cout << __PRETTY_FUNCTION__ << endl;
        return *this;
    }

    // to silence unused variable warning
    int get_something() {
        return this->something;
    }
private:
    int something{1};
};

int main() {
    auto something = Something{};
    something = {};
    something = {1, 2, 3};
}
</code>```

The output for this is

```<code>Something::Something()
Something::Something()
Something &Something::operator=(Something &&)
Something &Something::operator=(std::initializer_list<U>) [U = int]
</code>```

Note that the above situation is not what happens for std::vector because its initializer_list assignment operator is not a template, so that is called.

Body:
I have 2 containers, a std::vector and a std::map:

vector<int> my_vector;
map<string,int> my_map;
my_vector.push_back(3);

// elaboration of my_vector;
...

my_map["Hello"] = 1;

// elaboration of my_map
...

Later I do:

my_map = {};
my_vector = {};

This should make the 2 containers 2 empty containers, right? Furthermore, what happens to the memory previously pointed to from my_map and my_vector?

(I'm on C++11)

Body:
Yes both assignments cause the vector and the map to be emptied.  Both the assignments are linear in the size of the vector and the map because both require every single element in the container to be destroyed before assignment, and that requires an O(n) traversal.  The vector reuses memory (https://wandbox.org/permlink/eIJEcEqERC2ybAjU) I think whether or not the map reuses memory is implementation defined (or at least I was not able to make out from the documentation)

As for the tricky part (in my opinion), which assignment operator is called here?  Is it the assignment operator from an initializer list or the move assignment operator for the vector and the map (since {} is implicitly convertible to an instance of either).  I found this quote from cppreference here http://en.cppreference.com/w/cpp/language/operator_assignment#Builtin_direct_assignment

Note that, if a non-template assignment operator from some non-class type is available, it is preferred over the copy/move assignment in E1 = {} because {} to non-class is an identity conversion, which outranks the user-defined conversion from {} to a class type.

So if there is a non template assignment operator, which std::vector does have. That is preferred over the assignment operator from a templated std::intializer_list assignment operator.  You just have to inspect the interface to see what is going on.  You can see the same here

#include <initializer_list>
#include <iostream>
#include <string>
#include <vector>
#include <map>

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

class Something {
public:
    Something() {
        cout << __PRETTY_FUNCTION__ << endl;
    }
    template <typename U>
    Something(std::initializer_list<U>) {
        cout << __PRETTY_FUNCTION__ << endl;
    }
    Something& operator=(const Something&) {
        cout << __PRETTY_FUNCTION__ << endl;
        return *this;
    }
    Something& operator=(Something&&) {
        cout << __PRETTY_FUNCTION__ << endl;
        return *this;
    }
    Something(const Something&) {
        cout << __PRETTY_FUNCTION__ << endl;
    }
    Something(Something&&) {
        cout << __PRETTY_FUNCTION__ << endl;
    }
    template <typename U>
    Something& operator=(std::initializer_list<U>) {
        cout << __PRETTY_FUNCTION__ << endl;
        return *this;
    }

    // to silence unused variable warning
    int get_something() {
        return this->something;
    }
private:
    int something{1};
};

int main() {
    auto something = Something{};
    something = {};
    something = {1, 2, 3};
}

The output for this is

Something::Something()
Something::Something()
Something &Something::operator=(Something &&)
Something &Something::operator=(std::initializer_list<U>) [U = int]

Note that the above situation is not what happens for std::vector because its initializer_list assignment operator is not a template, so that is called.


问:
How to place elements of legend next to each other?
I plot my plots using matplotlib.pyplot and I would like to plot some of the legend items next to each other instead of among each other. As you can see here, this would save space in my plots:

I tried plt.legend(ncol=2)to split the legend into two columns. This is working as expected but I cant define where to start the new column:

So what I want is to split the dot-items side by side and underneath the line items. Is there any smart way to do this?

答:
My first suggestion would be to use two legends. This would allow each of them to be placed at a suitable position.

You can then also remove the border (frameon=False) around the legend and place them on top of each other.


问:
How multi processes bind to one udp port
I have two applications, one is C-Based, one is NodeJs-Based.
Two apps need process UDP message from same port in one Centos machine.
Is it possible to have 2 programs that bind to same UDP port and take message simultaneously?

In NodeJs, I used dgram:

```<code>dgram.createSocket({type: "udp4", reuseAddr: true})
</code>```

And in C, I use SO_REUSEADDR, SO_REUSEPORT parameter for the setting socket.

The problem is: I can not receive any UDP message in application started later. That means only one application can receive UDP message.
Any help is really appreciated. Thanks

答:
Using SO_REUSEADDR or SO_REUSEPORT on a UDP socket only work for incoming  multicast or broadcast packets.

If a unicast packet comes in, whether it is delivered to all sockets or just one (and which one) is implementation defined.

Body:
I have two applications, one is C-Based, one is NodeJs-Based.
Two apps need process UDP message from same port in one Centos machine.
Is it possible to have 2 programs that bind to same UDP port and take message simultaneously?

In NodeJs, I used dgram:

dgram.createSocket({type: "udp4", reuseAddr: true})

And in C, I use SO_REUSEADDR, SO_REUSEPORT parameter for the setting socket.

The problem is: I can not receive any UDP message in application started later. That means only one application can receive UDP message.
Any help is really appreciated. Thanks


问:
How to adapt Makefile for make tests target?
My folder structure looks like this:

```<code>src
--main.cpp
tests
--src
----main_test.cpp
Makefile
</code>```

I want to make a target like make main_test, in order to be able to run test program as ./main_test.

Initially I had a Makefile, which I haven't modified for a long time. So I started modify its content, in order to create new main_test target.

Makefile

```<code>CXX = g++
CXXFLAGS = -O2 -Wall -std=c++11 -Iinclude
LDFLAGS =

EXE = main
SRCDIR = src
BINDIR = bin
OBJDIR = tests/bin

OBJECTS = $(patsubst $(SRCDIR)/%.cpp,$(BINDIR)/%.o,$(wildcard
$(SRCDIR)/*.cpp))

all: $(EXE)

$(EXE): $(BINDIR) $(OBJECTS)
    $(CXX) $(OBJECTS) -o $(EXE) $(LDFLAGS)

$(BINDIR)/%.o: $(SRCDIR)/%.cpp
    $(CXX) $(CXXFLAGS) -c -MMD -o $@ $<

include $(wildcard $(BINDIR)/*.d)

$(OBJDIR):
    mkdir -p $(OBJDIR)

main_test: $(OBJDIR) tests/bin/main_test.o
    g++ -O2 -Wall -std=c++11 tests/bin/main_test.o -o tests/main_test

tests/bin/main_test.o: $(OBJDIR) tests/src/main_test.cpp
    g++ -O2 -Wall -std=c++11 tests/src/main_test.cpp -o tests/bin/main_test.o

clean_tests:
    rm -rf $(OBJDIR)

$(BINDIR):
    mkdir -p $(BINDIR)

clean:
    rm -rf $(BINDIR) $(EXE)

.PHONY: clean all
</code>```

Unfortunately, something went wrong:

```<code>make main_test
mkdir -p tests/bin
g++ -O2 -Wall -std=c++11 tests/src/main_test.cpp -o tests/bin/main_test.o
g++ -O2 -Wall -std=c++11 tests/bin/main_test.o -o tests/main_test
tests/bin/main_test.o: In function `_start':
(.text+0x1f0): multiple definition of `_start'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crt1.o:(.text+0x0): first defined here
tests/bin/main_test.o: In function `_fini':
(.fini+0x0): multiple definition of `_fini'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crti.o:(.fini+0x0): first defined here
tests/bin/main_test.o:(.rodata+0x0): multiple definition of `_IO_stdin_used'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crt1.o:(.rodata.cst4+0x0): first defined here
tests/bin/main_test.o: In function `data_start':
(.data+0x0): multiple definition of `__data_start'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crt1.o:(.data+0x0): first defined here
tests/bin/main_test.o: In function `data_start':
(.data+0x8): multiple definition of `__dso_handle'
/usr/lib/gcc/x86_64-linux-gnu/5/crtbegin.o:(.data+0x0): first defined here
tests/bin/main_test.o: In function `_init':
(.init+0x0): multiple definition of `_init'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crti.o:(.init+0x0): first defined here
/usr/lib/gcc/x86_64-linux-gnu/5/crtend.o:(.tm_clone_table+0x0): multiple definition of `__TMC_END__'
tests/bin/main_test.o:(.data+0x10): first defined here
/usr/bin/ld: error in tests/bin/main_test.o(.eh_frame); no .eh_frame_hdr table will be created.
collect2: error: ld returned 1 exit status
Makefile:26: recipe for target 'main_test' failed
make: *** [main_test] Error 1
</code>```

How should I fix this problem?

答:
In the compile rule for tests/bin/main_test.o you missed -c command line option.

Use an order-only dependency for output directories, e.g.:

```<code>main_test: tests/bin/main_test.o | $(OBJDIR)
</code>```

Body:
My folder structure looks like this:

src
--main.cpp
tests
--src
----main_test.cpp
Makefile

I want to make a target like make main_test, in order to be able to run test program as ./main_test.

Initially I had a Makefile, which I haven't modified for a long time. So I started modify its content, in order to create new main_test target.

Makefile

CXX = g++
CXXFLAGS = -O2 -Wall -std=c++11 -Iinclude
LDFLAGS =

EXE = main
SRCDIR = src
BINDIR = bin
OBJDIR = tests/bin

OBJECTS = $(patsubst $(SRCDIR)/%.cpp,$(BINDIR)/%.o,$(wildcard
$(SRCDIR)/*.cpp))

all: $(EXE)

$(EXE): $(BINDIR) $(OBJECTS)
    $(CXX) $(OBJECTS) -o $(EXE) $(LDFLAGS)

$(BINDIR)/%.o: $(SRCDIR)/%.cpp
    $(CXX) $(CXXFLAGS) -c -MMD -o $@ $<

include $(wildcard $(BINDIR)/*.d)

$(OBJDIR):
    mkdir -p $(OBJDIR)

main_test: $(OBJDIR) tests/bin/main_test.o
    g++ -O2 -Wall -std=c++11 tests/bin/main_test.o -o tests/main_test

tests/bin/main_test.o: $(OBJDIR) tests/src/main_test.cpp
    g++ -O2 -Wall -std=c++11 tests/src/main_test.cpp -o tests/bin/main_test.o

clean_tests:
    rm -rf $(OBJDIR)

$(BINDIR):
    mkdir -p $(BINDIR)

clean:
    rm -rf $(BINDIR) $(EXE)

.PHONY: clean all

Unfortunately, something went wrong:

make main_test
mkdir -p tests/bin
g++ -O2 -Wall -std=c++11 tests/src/main_test.cpp -o tests/bin/main_test.o
g++ -O2 -Wall -std=c++11 tests/bin/main_test.o -o tests/main_test
tests/bin/main_test.o: In function `_start':
(.text+0x1f0): multiple definition of `_start'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crt1.o:(.text+0x0): first defined here
tests/bin/main_test.o: In function `_fini':
(.fini+0x0): multiple definition of `_fini'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crti.o:(.fini+0x0): first defined here
tests/bin/main_test.o:(.rodata+0x0): multiple definition of `_IO_stdin_used'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crt1.o:(.rodata.cst4+0x0): first defined here
tests/bin/main_test.o: In function `data_start':
(.data+0x0): multiple definition of `__data_start'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crt1.o:(.data+0x0): first defined here
tests/bin/main_test.o: In function `data_start':
(.data+0x8): multiple definition of `__dso_handle'
/usr/lib/gcc/x86_64-linux-gnu/5/crtbegin.o:(.data+0x0): first defined here
tests/bin/main_test.o: In function `_init':
(.init+0x0): multiple definition of `_init'
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crti.o:(.init+0x0): first defined here
/usr/lib/gcc/x86_64-linux-gnu/5/crtend.o:(.tm_clone_table+0x0): multiple definition of `__TMC_END__'
tests/bin/main_test.o:(.data+0x10): first defined here
/usr/bin/ld: error in tests/bin/main_test.o(.eh_frame); no .eh_frame_hdr table will be created.
collect2: error: ld returned 1 exit status
Makefile:26: recipe for target 'main_test' failed
make: *** [main_test] Error 1

How should I fix this problem?

Body:
In the compile rule for tests/bin/main_test.o you missed -c command line option.

Use an order-only dependency for output directories, e.g.:

main_test: tests/bin/main_test.o | $(OBJDIR)