问:
scipy minimize 'trust-krylov' doesn't seem to stop when the change reaches 'tol'
I'm using the trust-krylov method of scipy.optimize.minimize on a very complex minimization problem (it is far too long to post the actual code here). What I've found is that the routine runs many iterations far past when the differential change of the objective function between iterations drops below the 'tol' keyword I set. Let's call the objective function J and the change from iteration i to i+1 is dJ.

I understand 'tol' to mean the minimum acceptable change in objective value dJ between iterations. So if I set 'tol' to 1.e-4 as in

```<code>res=minimize(J,X0,method='trust-krylov', tol=1.e-4, jac=Jacobian,hessp=Hessian)
</code>```

then I would expect the code to stop running a few iterations after dJ dips and stays below this value. However I'm running a code right now and dJ is below 1.e-8 and it is still running that way after 16 iterations and counting. Possible bug?

答:
You are misunderstanding the tol argument.

It's not about: |obj_i - obj_i-1| (calculation on scalar), but about: ||grad_i||_p (calculation on vector).

The latter condition is often used and part of most nonlinear-optimizers (especially when no KKT-condition or second-order information is available). It also follows directly the theory: first order necessary optimality condition for local optimal points.

You can look at the sources:

here: tol becomes gtol:

```<code>if meth in ('bfgs', 'cg', 'l-bfgs-b', 'tnc', 'dogleg',
            'trust-ncg', 'trust-exact', 'trust-krylov'):
   options.setdefault('gtol', tol)
</code>```

here: _minimize_trust_krylov is called:

```<code>elif meth == 'trust-krylov':
    return _minimize_trust_krylov(fun, x0, args, jac, hess, hessp,
                                  callback=callback, **options)
</code>```

_trustregion_krylov talks about the oder conditions and depending on exact / inexact the final optimizer is called:

```<code>if inexact:
    return _minimize_trust_region(fun, x0, args=args, jac=jac,
                                  hess=hess, hessp=hessp,
                                  subproblem=get_trlib_quadratic_subproblem(
                                      tol_rel_i=-2.0, tol_rel_b=-3.0,
                                      disp=trust_region_options.get('disp', False)
                                      ),
                                  **trust_region_options)
else:
    return _minimize_trust_region(fun, x0, args=args, jac=jac,
                                  hess=hess, hessp=hessp,
                                  subproblem=get_trlib_quadratic_subproblem(
                                      tol_rel_i=1e-8, tol_rel_b=1e-6,
                                      disp=trust_region_options.get('disp', False)
                                      ),
                                  **trust_region_options)
</code>```

the optimizer used containing the following lines:

```<code>gtol : float
    Gradient norm must be less than `gtol`
    before successful termination.

# check if the gradient is small enough to stop
if m.jac_mag < gtol:
    warnflag = 0
    break

# check if we have looked at enough iterations
if k >= maxiter:
    warnflag = 1
    break
</code>```

here jac_mag is found:

```<code>@property
def jac_mag(self):
    """Magniture of jacobian of objective function at current iteration."""
    if self._g_mag is None:
        self._g_mag = scipy.linalg.norm(self.jac)
    return self._g_mag
</code>```

which follows the beginning of this answer and euclidean-norm (p=2) is used!

Body:
I'm using the trust-krylov method of scipy.optimize.minimize on a very complex minimization problem (it is far too long to post the actual code here). What I've found is that the routine runs many iterations far past when the differential change of the objective function between iterations drops below the 'tol' keyword I set. Let's call the objective function J and the change from iteration i to i+1 is dJ.

I understand 'tol' to mean the minimum acceptable change in objective value dJ between iterations. So if I set 'tol' to 1.e-4 as in

res=minimize(J,X0,method='trust-krylov', tol=1.e-4, jac=Jacobian,hessp=Hessian)

then I would expect the code to stop running a few iterations after dJ dips and stays below this value. However I'm running a code right now and dJ is below 1.e-8 and it is still running that way after 16 iterations and counting. Possible bug?

Body:
You are misunderstanding the tol argument.

It's not about: |obj_i - obj_i-1| (calculation on scalar), but about: ||grad_i||_p (calculation on vector).

The latter condition is often used and part of most nonlinear-optimizers (especially when no KKT-condition or second-order information is available). It also follows directly the theory: first order necessary optimality condition for local optimal points.

You can look at the sources:

here: tol becomes gtol:

if meth in ('bfgs', 'cg', 'l-bfgs-b', 'tnc', 'dogleg',
            'trust-ncg', 'trust-exact', 'trust-krylov'):
   options.setdefault('gtol', tol)

here: _minimize_trust_krylov is called:

elif meth == 'trust-krylov':
    return _minimize_trust_krylov(fun, x0, args, jac, hess, hessp,
                                  callback=callback, **options)

_trustregion_krylov talks about the oder conditions and depending on exact / inexact the final optimizer is called:

if inexact:
    return _minimize_trust_region(fun, x0, args=args, jac=jac,
                                  hess=hess, hessp=hessp,
                                  subproblem=get_trlib_quadratic_subproblem(
                                      tol_rel_i=-2.0, tol_rel_b=-3.0,
                                      disp=trust_region_options.get('disp', False)
                                      ),
                                  **trust_region_options)
else:
    return _minimize_trust_region(fun, x0, args=args, jac=jac,
                                  hess=hess, hessp=hessp,
                                  subproblem=get_trlib_quadratic_subproblem(
                                      tol_rel_i=1e-8, tol_rel_b=1e-6,
                                      disp=trust_region_options.get('disp', False)
                                      ),
                                  **trust_region_options)

the optimizer used containing the following lines:

gtol : float
    Gradient norm must be less than `gtol`
    before successful termination.

# check if the gradient is small enough to stop
if m.jac_mag < gtol:
    warnflag = 0
    break

# check if we have looked at enough iterations
if k >= maxiter:
    warnflag = 1
    break

here jac_mag is found:

@property
def jac_mag(self):
    """Magniture of jacobian of objective function at current iteration."""
    if self._g_mag is None:
        self._g_mag = scipy.linalg.norm(self.jac)
    return self._g_mag

which follows the beginning of this answer and euclidean-norm (p=2) is used!


来源: stackexchange

问:
Fullscreen background video and keep it centered
I'm trying to create a site where I have a background video playing with some HTML5.
This is all working perfectly, it works just the way I want it.
But I also want to keep the image centered on the screen, even when a user resizes the browser.

```<code><video id="video" src="video/video.mov" type="video/mov" autoplay loop></video>
</code>```

I got this to work with some jQuery, but was wondering if there is a CSS solution for this.

```<code>function resizeHandler() {
        // scale the video
        var documentHeight = $(document).height();
        var documentWidth = $(document).width();
        var ratio = $('#video').width() / $('#video').height();

        if((documentWidth / documentHeight) < ratio) {
            $('#video').css({
                'width': 'auto',
                'height': '100%',
                'left': '0px',
                'right': '0px',
                'top': '0px',
                'bottom': '0px'
            })

            var marginRight = $('#video').width() - $(document).width();
            $('#video').css('left', -marginRight);
        } else {
            $('#video').css({
                'width': '100%',
                'height': 'auto',
                'left': '0px',
                'right': '0px',
                'top': '0px',
                'bottom': '0px'
            })

            var marginTop = $('#video').height() - $(document).height();
            $('#video').css('top', -marginTop);
        }
    }
</code>```

This is the jQuery I wrote to stretch the image to fit the screen, and to keep the image sort of centered.
Not sure if this is possible in CSS, but if somebody knows how to, this might be nice.

答:
Use Css Property. object-fit: cover;

body, html {
  padding: 0;
  margin: 0;
  height: 100%;
  width: 100%;
}

video {
  height: 100%;
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><video controls>
  <source src=http://techslides.com/demos/sample-videos/small.webm type=video/webm>
  <source src=http://techslides.com/demos/sample-videos/small.ogv type=video/ogg>
  <source src=http://techslides.com/demos/sample-videos/small.mp4 type=video/mp4>
  <source src=http://techslides.com/demos/sample-videos/small.3gp type=video/3gp>
</video></code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to create a site where I have a background video playing with some HTML5.
This is all working perfectly, it works just the way I want it.
But I also want to keep the image centered on the screen, even when a user resizes the browser.

<video id="video" src="video/video.mov" type="video/mov" autoplay loop></video>

I got this to work with some jQuery, but was wondering if there is a CSS solution for this.

function resizeHandler() {
        // scale the video
        var documentHeight = $(document).height();
        var documentWidth = $(document).width();
        var ratio = $('#video').width() / $('#video').height();

        if((documentWidth / documentHeight) < ratio) {
            $('#video').css({
                'width': 'auto',
                'height': '100%',
                'left': '0px',
                'right': '0px',
                'top': '0px',
                'bottom': '0px'
            })

            var marginRight = $('#video').width() - $(document).width();
            $('#video').css('left', -marginRight);
        } else {
            $('#video').css({
                'width': '100%',
                'height': 'auto',
                'left': '0px',
                'right': '0px',
                'top': '0px',
                'bottom': '0px'
            })

            var marginTop = $('#video').height() - $(document).height();
            $('#video').css('top', -marginTop);
        }
    }

This is the jQuery I wrote to stretch the image to fit the screen, and to keep the image sort of centered.
Not sure if this is possible in CSS, but if somebody knows how to, this might be nice.

Body:
Use Css Property. object-fit: cover;

body, html {
  padding: 0;
  margin: 0;
  height: 100%;
  width: 100%;
}

video {
  height: 100%;
  width: 100%;
}

<video controls>
  <source src=http://techslides.com/demos/sample-videos/small.webm type=video/webm>
  <source src=http://techslides.com/demos/sample-videos/small.ogv type=video/ogg>
  <source src=http://techslides.com/demos/sample-videos/small.mp4 type=video/mp4>
  <source src=http://techslides.com/demos/sample-videos/small.3gp type=video/3gp>
</video>


问:
UpdatePanel not working in IE or Chrome
I have an updatepanel on my masterpage. Within the contentplace holder I have my update progress control. When a user clicks on the button I load some data into a gridview. This works perfectly in FireFox. User clicks the button, the loading image in my updateprogress fires and loads the gridview. When I test this in IE 6 or 7 or in Chrome. It does a full postback and the updateprogress is never shown. So the updatepanel doesnt seem to be working in these two browsers. Code is below. Again...it works perfect in FireFox.</p>

```<code>***From Masterpage ***

<asp:UpdatePanel ID="UpdatePanel" runat="server">
 <contenttemplate>
  <asp:contentplaceholder id="holder" runat="server" />
  </contenttemplate>
</asp:UpdatePanel>

**From aspx page ****

 <asp:UpdateProgress ID="UpdateProgress1" runat="server">
    <ProgressTemplate>
       <img src="ajax-loader.gif" />
    </ProgressTemplate>
 </asp:UpdateProgress>
</code>```

答: We had some namespace and dll issues with this. </p>

ContentLicense: CC BY-SA 2.5

Title: UpdatePanel not working in IE or Chrome

Body:
I have an updatepanel on my masterpage. Within the contentplace holder I have my update progress control. When a user clicks on the button I load some data into a gridview. This works perfectly in FireFox. User clicks the button, the loading image in my updateprogress fires and loads the gridview. When I test this in IE 6 or 7 or in Chrome. It does a full postback and the updateprogress is never shown. So the updatepanel doesnt seem to be working in these two browsers. Code is below. Again...it works perfect in FireFox.

***From Masterpage ***

<asp:UpdatePanel ID="UpdatePanel" runat="server">
 <contenttemplate>
  <asp:contentplaceholder id="holder" runat="server" />
  </contenttemplate>
</asp:UpdatePanel>

**From aspx page ****

 <asp:UpdateProgress ID="UpdateProgress1" runat="server">
    <ProgressTemplate>

    </ProgressTemplate>
 </asp:UpdateProgress>


问:
Range.Value not working for assigning cell contents to variable in VBA
I am writing my first script with VBA and I am having a hard time assigning the value entered into a cell to a String variable, I used Message Boxes to test where the issue is and it showed me I'm in the right workbook and the right sheet but then shows a blank for the value in "A1" even though I have a text value there and made sure I saved the workbook, what I have is below:

```<code>Sub copyworksheet()

Dim sourceWorkbook As String
Dim destinationWorkbook As String

Dim folderName As String

destinationWorkbook = ActiveWorkbook.Name
Sheets(1).Activate

MsgBox Range("A1").Value        ' Shows blank when debugging
folderName = Range("A1").Value
MsgBox "Here is " & folderName  ' Shows "Here is " when debugging

End Sub
</code>```

** As an additional note, the A1 cell contains 02Nov, and I have tried changing the format of this cell and it hasn't fixed the issue, currently the cell format is Text

答:
Alternate way is using Cells.

```<code>MsgBox Cells(1, 1).Value
folderName = Cells(1, 1).Value
</code>```

Body:
I am writing my first script with VBA and I am having a hard time assigning the value entered into a cell to a String variable, I used Message Boxes to test where the issue is and it showed me I'm in the right workbook and the right sheet but then shows a blank for the value in "A1" even though I have a text value there and made sure I saved the workbook, what I have is below:

Sub copyworksheet()

Dim sourceWorkbook As String
Dim destinationWorkbook As String

Dim folderName As String

destinationWorkbook = ActiveWorkbook.Name
Sheets(1).Activate

MsgBox Range("A1").Value        ' Shows blank when debugging
folderName = Range("A1").Value
MsgBox "Here is " & folderName  ' Shows "Here is " when debugging

End Sub

** As an additional note, the A1 cell contains 02Nov, and I have tried changing the format of this cell and it hasn't fixed the issue, currently the cell format is Text

Body:
Alternate way is using Cells.

MsgBox Cells(1, 1).Value
folderName = Cells(1, 1).Value


问:
Byte conversion from hash string, java vs python
I have issue with converting a pure java Curve25519 function to Python equivalent, the specific problem is related to digest function that convert hash string to byte equivalent, the java implementation :

Data example :

sP = "this is a sample of secret pass phrase for test purpose"

```<code>/**
 * Calculate the SHA-256 hash of a string
 *
 * @param       input           Data to be hashed
 * @return                      The hash digest
 */
public static byte[] singleDigest(String input) {
    byte[] bytes;
    try {
        bytes = singleDigest(input.getBytes("UTF-8"));
        System.out.println("bytes"+bytes);
        System.out.println("before singleDigest"+input);
    } catch (UnsupportedEncodingException exc) {
        bytes = null;
    }
    return bytes;
}

/**
 * Calculate the SHA-256 hash of a byte array
 *
 * @param       input           Data to be hashed
 * @return                      The hash digest
 */
public static byte[] singleDigest(byte[] input) {
    byte[] bytes;
    synchronized (digest) {
        digest.reset();
        bytes = digest.digest(input);

        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < bytes.length; i++) {
            System.out.println(bytes[i]);
            sb.append(String.format("%02x", bytes[i] & 0xFF));
        }
        System.out.println(sb.toString());
    }
    return bytes;
}
</code>```

Generate this byte output :

byteOutput :82, -57, 124, 58, -105, 76, 123, 3, 119, -21, 121, 71, -54, 73, -75, 54, 31, -33, -49, -68, -16, -19, 125, -61, -116, -82, 96, 50, -35, -119, -28, 25

with positive and negative numbers, on python side, I use this function to convert a hashed string to byte :

```<code>secret = sha256(sP.encode('utf-8')).hexdigest()
sct = ParseHexString(secret).getData()

class ParseHexString(object):

    def __init__(self, hex):
        """

        """
        if not isinstance(hex, str):
            return None
        else:

            self.hex = hex
            self.listOfByte = None

        self.run()

    def run(self):

        if len(self.hex)&0x01 == 1:
            return None

        lbytes = []
        for i in range(0, len(self.hex), 2):
            op1, op2 = self.hex[i:i + 2]
            oop1 = ord(op1)
            oop2 = ord(op2)

            char1 = oop1 - 0x57 if oop1 > 0x60 else oop1 - 0x30
            char2 = oop2 - 0x57 if oop2 > 0x60 else oop2 - 0x30

            if (char1 < 0 or char2 < 0 or char1 > 15 or char2 > 15):
                print("Invalid hex number ",op1,op2)

            lbytes.append(((char1 << 4) + char2))

        self.listOfByte = lbytes

    def getData(self):
        return self.listOfByte
</code>```

I used lists here instead of mutable bytearray because of internal representation of bytearray (0 - 256), and the output for some hashed string
is different and is only positive integers :

82, 199, 124, 58, 151, 76, 123, 3, 119, 235, 121, 71, 202, 73, 181, 54, 31, 217, 207, 188, 240, 237, 125, 196, 140, 174, 96, 50, 221, 137, 228, 25

I noticed that (256 - JavaByteOutput[x] == PythonByteOtput[x]) when JavaByteOutput is a negative number, the question is, how I can modify my ParseHexString class to have equivalent positive/negative output, and I want pure python code and no libraries.

Thanks for any kind answer.
Regards
Alex

Body:
I have issue with converting a pure java Curve25519 function to Python equivalent, the specific problem is related to digest function that convert hash string to byte equivalent, the java implementation :

Data example :

sP = "this is a sample of secret pass phrase for test purpose"

/**
 * Calculate the SHA-256 hash of a string
 *
 * @param       input           Data to be hashed
 * @return                      The hash digest
 */
public static byte[] singleDigest(String input) {
    byte[] bytes;
    try {
        bytes = singleDigest(input.getBytes("UTF-8"));
        System.out.println("bytes"+bytes);
        System.out.println("before singleDigest"+input);
    } catch (UnsupportedEncodingException exc) {
        bytes = null;
    }
    return bytes;
}

/**
 * Calculate the SHA-256 hash of a byte array
 *
 * @param       input           Data to be hashed
 * @return                      The hash digest
 */
public static byte[] singleDigest(byte[] input) {
    byte[] bytes;
    synchronized (digest) {
        digest.reset();
        bytes = digest.digest(input);

        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < bytes.length; i++) {
            System.out.println(bytes[i]);
            sb.append(String.format("%02x", bytes[i] & 0xFF));
        }
        System.out.println(sb.toString());
    }
    return bytes;
}

Generate this byte output :

byteOutput :82, -57, 124, 58, -105, 76, 123, 3, 119, -21, 121, 71, -54, 73, -75, 54, 31, -33, -49, -68, -16, -19, 125, -61, -116, -82, 96, 50, -35, -119, -28, 25

with positive and negative numbers, on python side, I use this function to convert a hashed string to byte :

secret = sha256(sP.encode('utf-8')).hexdigest()
sct = ParseHexString(secret).getData()

class ParseHexString(object):

    def __init__(self, hex):
        """

        """
        if not isinstance(hex, str):
            return None
        else:

            self.hex = hex
            self.listOfByte = None

        self.run()

    def run(self):

        if len(self.hex)&0x01 == 1:
            return None

        lbytes = []
        for i in range(0, len(self.hex), 2):
            op1, op2 = self.hex[i:i + 2]
            oop1 = ord(op1)
            oop2 = ord(op2)

            char1 = oop1 - 0x57 if oop1 > 0x60 else oop1 - 0x30
            char2 = oop2 - 0x57 if oop2 > 0x60 else oop2 - 0x30

            if (char1 < 0 or char2 < 0 or char1 > 15 or char2 > 15):
                print("Invalid hex number ",op1,op2)

            lbytes.append(((char1 << 4) + char2))

        self.listOfByte = lbytes

    def getData(self):
        return self.listOfByte

I used lists here instead of mutable bytearray because of internal representation of bytearray (0 - 256), and the output for some hashed string
is different and is only positive integers :

82, 199, 124, 58, 151, 76, 123, 3, 119, 235, 121, 71, 202, 73, 181, 54, 31, 217, 207, 188, 240, 237, 125, 196, 140, 174, 96, 50, 221, 137, 228, 25

I noticed that (256 - JavaByteOutput[x] == PythonByteOtput[x]) when JavaByteOutput is a negative number, the question is, how I can modify my ParseHexString class to have equivalent positive/negative output, and I want pure python code and no libraries.

Thanks for any kind answer.
Regards
Alex

Body:
In Python, a % b always returns a value with the same sign as b between 0 (inclusive) and b (exclusive). In this case b is 256.

So to shift the values to the range [-128, 128), add 128 to each value, take the modulus base 256 then subtract 128:

x = [82, 199, 124, 58, 151, 76, 123, 3, 119, 235, 121, 71, 202, 73, 181, 54, 31, 217, 207, 188, 240, 237, 125, 196, 140, 174, 96, 50, 221, 137, 228, 25]

y = [(xi + 128) % 256 - 128 for xi in x]
# [82, -57, 124, 58, -105, 76, 123, 3, 119, -21, 121, 71, -54, 73, -75, 54, 31, -39, -49, -68, -16, -19, 125, -60, -116, -82, 96, 50, -35, -119, -28, 25]

Therefore, in ParseHexString.run define:

self.listOfByte = [(xi + 128) % 256 - 128 for xi in lbytes]

If NumPy were an option, you could instead simply view the unsigned 1-byte ints as signed 1-byte ints:

import numpy as np
x = np.array([82, 199, 124, 58, 151, 76, 123, 3, 119, 235, 121, 71, 202, 73, 181, 54, 31, 217, 207, 188, 240, 237, 125, 196, 140, 174, 96, 50, 221, 137, 228, 25], dtype='uint8')

x.view('i1')
# array([  82,  -57,  124,   58, -105,   76,  123,    3,  119,  -21,  121,
#          71,  -54,   73,  -75,   54,   31,  -39,  -49,  -68,  -16,  -19,
#         125,  -60, -116,  -82,   96,   50,  -35, -119,  -28,   25], dtype=int8)


问:
How to convert a byte array to two long values?
I'm reading a 16 byte array (byte[16]) from a JDBC ResultSet with rs.getBytes("id") and now I need to convert it to two long values. How can I do that?

This is the code I have tried, but I probably didn't use ByteBuffer correctly.

```<code>byte[] bytes = rs.getBytes("id");
System.out.println("bytes: "+bytes.length); // prints "bytes: 16"

ByteBuffer buffer = ByteBuffer.allocate(16);
buffer = buffer.put(bytes);

// throws an java.nio.BufferUnderflowException
long leastSignificant = buffer.getLong();
long mostSignificant = buffer.getLong();
</code>```

I stored the byte array to the database using:

```<code>byte[] bytes = ByteBuffer.allocate(16)
    .putLong(leastSignificant)
    .putLong(mostSignificant).array();
</code>```

答:
You can do</p>

```<code>ByteBuffer buffer = ByteBuffer.wrap(bytes);
long leastSignificant = buffer.getLong();
long mostSignificant = buffer.getLong();
</code>```

Body:
I'm reading a 16 byte array (byte[16]) from a JDBC ResultSet with rs.getBytes("id") and now I need to convert it to two long values. How can I do that?

This is the code I have tried, but I probably didn't use ByteBuffer correctly.

byte[] bytes = rs.getBytes("id");
System.out.println("bytes: "+bytes.length); // prints "bytes: 16"

ByteBuffer buffer = ByteBuffer.allocate(16);
buffer = buffer.put(bytes);

// throws an java.nio.BufferUnderflowException
long leastSignificant = buffer.getLong();
long mostSignificant = buffer.getLong();

I stored the byte array to the database using:

byte[] bytes = ByteBuffer.allocate(16)
    .putLong(leastSignificant)
    .putLong(mostSignificant).array();

Body:
You can do

ByteBuffer buffer = ByteBuffer.wrap(bytes);
long leastSignificant = buffer.getLong();
long mostSignificant = buffer.getLong();


问:
Possibility to auto refresh launch in reportportal.io
is there any way to auto refresh my launch screen on reportportal.io?

Currently, in order to actually see my results in real time I have to manually click refresh.

答:
Not now. We avoid it to keep server safe, limiting number of requests.

but
we started already migration of UI on ReactJS.
and with it, we will add WebSocket connections.
This will look like push-updates.

will be available with 4.1 or so.

please check our roadmap here
https://github.com/reportportal/reportportal/wiki/Roadmap-4.0


问:
PHP binary data into pdf
I've written an api to an external service which is giving me a response with binary data. Now I would like to create an PDF to view the data correctly.

The Response headers of the API:

```<code>0 => string 'HTTP/1.1 200 OK' (length=15)
1 => string 'Cache-Control: private' (length=22)
2 => string 'Content-Length: 275454' (length=22)
3 => string 'Content-Type: application/pdf' (length=29)
4 => string 'Server: Microsoft-IIS/8.0' (length=25)
5 => string 'model: Invariant' (length=16)
6 => string 'Content-Disposition: attachment; filename=response_3a293a37-7a00-49ca-b557-fa218f834eb4.pdf' (length=91)
7 => string 'X-AspNet-Version: 4.0.30319' (length=27)
8 => string 'X-Powered-By: ASP.NET' (length=21)
9 => string 'Set-Cookie: ARRAffinity=3d8fa41aef05715eddd28bd82d74a76f49904e3d3e55e9dbdf656e2598101182;Path=/;HttpOnly;Domain=x2c-test.sprengnetter.at' (length=136)
10 => string 'Date: Wed, 06 Dec 2017 12:12:56 GMT' (length=35)
11 => string 'Connection: close' (length=17)
</code>```

The name of the PDF is a random name.

Now Im trying to get a pdf out of my response:

```<code>$response_pdf = file_get_contents($remote_print, true, $context);
    if($response_pdf === FALSE){
        var_dump($http_response_header);
        echo "error pdf";
    }else{
        var_dump($http_response_header);

        $base64 = "/$response_pdf/";
        $binary = base64_decode($base64);
        file_put_contents('my.pdf',$binary);
        header('Content-type: application/pdf');
        header('Content-Disposition: attachment; filename="my.pdf"');
        return $binary;
</code>```

In the Response is data like this:

```<code>%PDF-1.5 4 0 obj <>/XObject<>>>/Group <>>> endobj 5 0 obj <>stream x��Y[O#7�+~�Uc|�<���UUU[�ݪo�IJ�I�H�ԟ�
</code>```

I dont have much experience with binary data and how to create a pdf out of binary data. So I would be happy for some help.

答:
I could answer my question myself.

First I created a tempfile with tempnam() and renamed it with rename() and give it the correct path .. then I just did file_put_contents() on the new generated file.

Title: PHP binary data into pdf

Body:
I've written an api to an external service which is giving me a response with binary data. Now I would like to create an PDF to view the data correctly.

The Response headers of the API:

0 => string 'HTTP/1.1 200 OK' (length=15)
1 => string 'Cache-Control: private' (length=22)
2 => string 'Content-Length: 275454' (length=22)
3 => string 'Content-Type: application/pdf' (length=29)
4 => string 'Server: Microsoft-IIS/8.0' (length=25)
5 => string 'model: Invariant' (length=16)
6 => string 'Content-Disposition: attachment; filename=response_3a293a37-7a00-49ca-b557-fa218f834eb4.pdf' (length=91)
7 => string 'X-AspNet-Version: 4.0.30319' (length=27)
8 => string 'X-Powered-By: ASP.NET' (length=21)
9 => string 'Set-Cookie: ARRAffinity=3d8fa41aef05715eddd28bd82d74a76f49904e3d3e55e9dbdf656e2598101182;Path=/;HttpOnly;Domain=x2c-test.sprengnetter.at' (length=136)
10 => string 'Date: Wed, 06 Dec 2017 12:12:56 GMT' (length=35)
11 => string 'Connection: close' (length=17)

The name of the PDF is a random name.

Now Im trying to get a pdf out of my response:

$response_pdf = file_get_contents($remote_print, true, $context);
    if($response_pdf === FALSE){
        var_dump($http_response_header);
        echo "error pdf";
    }else{
        var_dump($http_response_header);

        $base64 = "/$response_pdf/";
        $binary = base64_decode($base64);
        file_put_contents('my.pdf',$binary);
        header('Content-type: application/pdf');
        header('Content-Disposition: attachment; filename="my.pdf"');
        return $binary;

In the Response is data like this:

%PDF-1.5 4 0 obj <>/XObject<>>>/Group <>>> endobj 5 0 obj <>stream x��Y[O#7�+~�Uc|�<���UUU[�ݪo�IJ�I�H�ԟ�

I dont have much experience with binary data and how to create a pdf out of binary data. So I would be happy for some help.


问:
convert HTML to json in python using BeautifulSoup
I am trying to convert HTML table to json using beautifulsoup() function python, i was able to convert some other tables to json but this is of different kind.

I am trying to achieve something like this:

```<code>[{
    "name": "abc",
    "age": "21",
    "sex": "m",
    "loction": "us",
    "language": "en"
}, {
    "name": "xyz",
    "age": "25",
    "sex": "f",
    "loction": "us",
    "language": "en"
}]
</code>```

Table is :

```<code><table><colgroup><col /><col /><col /><col /><col /></colgroup>
<tbody>
<tr>
<th><span>name</span></th>
<th><span>age</span></th>
<th><span>sex</span></th>
<th><span>location</span></th>
<th><span>language</span></th>
</tr>
<tr>
<td colspan="1">
<p><span>abc</span></p>
</td>
<td colspan="1"><span>21</span></td>
<td colspan="1"><span>m</span></td>
<td colspan="1">us</td>
<td colspan="1">en</td>
</tr>
<tr>
<td colspan="1">
<p><span>xyz</span></p>
</td>
<td colspan="1"><span>25</span></td>
<td colspan="1">f</td>
<td colspan="1">us</td>
<td colspan="1">en</td>
</tr>
</tbody>
</table>
</code>```

Some help is appreciated

答:
You can, of course, make a list of dictionaries manually, but we can also do it without doing 0 explicit HTML parsing at all by transitioning through a pandas.DataFrame using pandas.read_html():

```<code>from pprint import pprint
import pandas as pd

data = """your HTML"""

df = pd.read_html(data, flavor="lxml")[0]

new_header = df.iloc[0]
df = df[1:]
df.columns = new_header

pprint(df.to_dict('records'))
</code>```

Prints:

```<code>[{'age': '21', 'language': 'en', 'location': 'us', 'name': 'abc', 'sex': 'm'},
 {'age': '25', 'language': 'en', 'location': 'us', 'name': 'xyz', 'sex': 'f'}]
</code>```

Body:
I am trying to convert HTML table to json using beautifulsoup() function python, i was able to convert some other tables to json but this is of different kind.

I am trying to achieve something like this:

[{
    "name": "abc",
    "age": "21",
    "sex": "m",
    "loction": "us",
    "language": "en"
}, {
    "name": "xyz",
    "age": "25",
    "sex": "f",
    "loction": "us",
    "language": "en"
}]

Table is :

<colgroup><col /><col /><col /><col /><col /></colgroup>

name
age
sex
location
language

abc

21
m
us
en

xyz

25
f
us
en

Some help is appreciated

Body:
You can, of course, make a list of dictionaries manually, but we can also do it without doing 0 explicit HTML parsing at all by transitioning through a pandas.DataFrame using pandas.read_html():

from pprint import pprint
import pandas as pd

data = """your HTML"""

df = pd.read_html(data, flavor="lxml")[0]

new_header = df.iloc[0]
df = df[1:]
df.columns = new_header

pprint(df.to_dict('records'))

Prints:

[{'age': '21', 'language': 'en', 'location': 'us', 'name': 'abc', 'sex': 'm'},
 {'age': '25', 'language': 'en', 'location': 'us', 'name': 'xyz', 'sex': 'f'}]


问:
Java product of two arrays

I would like to resolve a problem for my homework. I have to multiply an array by itself using a method in Java that I created. However, my method doesn't work and I don't know why.

```<code>public static void initialiser(int mat[][]) {
    int i,j;
    for (i = 0; i < mat.length; i++) {
        for(j = 0; j < mat[0].length; j++) {
            mat[i][j] = 0;
        }
    }
}

public static int[][] produit(int mat1[][], int mat2[][]) {
    int i,j,k;
    int [][] matProduit = new int[mat1.length][mat2[0].length];

    for (i = 0; i < mat1.length; i++) {
        for(j = 0; j < mat2[0].length; j++) {
            initialiser(matProduit);
            for (k = 0; k < mat2.length; k++) {
                matProduit[i][j] =  mat1[i][k] * mat2[k][j];
            }
        }
    }
    return matProduit;
}
</code>```

This is the result I should get:

```<code>0   1   0   0   0   0
0   0   1   0   0   1
0   0   0   0   1   1
0   0   1   0   1   0
0   0   0   0   0   0
0   0   0   0   0   0
</code>```

This is the result I get:

```<code>0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
</code>```

答:
As pointed by Assylias in the comments, you are calling    initialiser(matProduit) at each iteration, thus resetting your matrix to zero.

I would advise you to try the debug mode for those kind of problems. It is your top tool for your daily coding.

Please find my own answer on another question, adressing the debug, how to do it, activating it and using it at least correctly.

Title: Java product of two arrays

Body:
I would like to resolve a problem for my homework. I have to multiply an array by itself using a method in Java that I created. However, my method doesn't work and I don't know why.

public static void initialiser(int mat[][]) {
    int i,j;
    for (i = 0; i < mat.length; i++) {
        for(j = 0; j < mat[0].length; j++) {
            mat[i][j] = 0;
        }
    }
}

public static int[][] produit(int mat1[][], int mat2[][]) {
    int i,j,k;
    int [][] matProduit = new int[mat1.length][mat2[0].length];

    for (i = 0; i < mat1.length; i++) {
        for(j = 0; j < mat2[0].length; j++) {
            initialiser(matProduit);
            for (k = 0; k < mat2.length; k++) {
                matProduit[i][j] =  mat1[i][k] * mat2[k][j];
            }
        }
    }
    return matProduit;
}

This is the result I should get:

0   1   0   0   0   0
0   0   1   0   0   1
0   0   0   0   1   1
0   0   1   0   1   0
0   0   0   0   0   0
0   0   0   0   0   0

This is the result I get:

0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0


问:
How to iterate over folders stored in a MAPIFolder object?
I'm working on a Outlook Add-in developed in COM/ATL/C++ and I want to iterate over all subfolders of a particular Outlook folder, which is passed off as a MAPIFolder object.

According to Microsoft's docs, a MAPIFolder object includes a Folders property whjich consists of a Folders collection which represent all the available Outlook folders in a specific subset at one level of the folder tree.  Yet, I haven't found any reference on how to iterate over these collections.  Microsoft's docs are virtually nonexistent, and although there are examples covering similar features in C#, such as MS DevCenter How to: Get a Default Folder and Enumerate Its Subfolders, Microsoft does not offer any info on how to accomplish the same goal with C++.

Does anyone know how to iterate over all folders with calls to MAPIFolder and/or Folders objects?

答: Use a for loop (from 1 to Count). Or call Folders.GetFirst and use while loop calling Folders.GetNext on each iteration.


问:
How to store raw jpeg image into the internal flash of STM32F2 series microcontroller using Embedded C?
I have a .JPEG file which I need to store into internal memory of the STM32F2 series controller. Is this possible to do without any conversion/encoding the JPEG file? If so can anyone please provide some sample code for my understanding.</p>

答:
Generally, one method is to define a constant array which is initialized with the data from the JPEG (or any binary) file.  Then that array definition gets linked with your code and becomes a part of the firmware programmed to flash.  If desired, you can use linker directives to locate the array (i.e., the file data) at a specific address in flash.

You can accomplish this general idea in many different ways.  Below is just one specific example implementation of this technique.

First, create a desktop program that reads the JPEG file as a stream of bytes and writes those bytes into a new comma separated text file.  Here are the first two lines of an example file, I'll call my_jpeg.h:

```<code>0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46, 0x49, 0x46, 0x00, 0x01, 0x01, 0x01, 0x00, 0x48,
0x00, 0x48, 0x00, 0x00, 0xFF, 0xE1, 0x03, 0xA0, 0x00, 0x01, 0x69, 0x48, 0x00, 0x4D, 0x4D, 0x46,
</code>```

Then define an array in your C code and initialize it with the data from the file you created.

```<code>const uint8_t my_jpeg[] = {
    #include "my_jpeg.h"
};
</code>```

Now all that JPEG file data will be included in your firmware and be programmed to flash when you program the firmware.

You could use a makefile recipe or your IDE's pre-build batch script feature to run your JPEG conversion program automatically and produce my_jpeg.h during the build.

Body:
Generally, one method is to define a constant array which is initialized with the data from the JPEG (or any binary) file.  Then that array definition gets linked with your code and becomes a part of the firmware programmed to flash.  If desired, you can use linker directives to locate the array (i.e., the file data) at a specific address in flash.

You can accomplish this general idea in many different ways.  Below is just one specific example implementation of this technique.

First, create a desktop program that reads the JPEG file as a stream of bytes and writes those bytes into a new comma separated text file.  Here are the first two lines of an example file, I'll call my_jpeg.h:

0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46, 0x49, 0x46, 0x00, 0x01, 0x01, 0x01, 0x00, 0x48,
0x00, 0x48, 0x00, 0x00, 0xFF, 0xE1, 0x03, 0xA0, 0x00, 0x01, 0x69, 0x48, 0x00, 0x4D, 0x4D, 0x46,

Then define an array in your C code and initialize it with the data from the file you created.

const uint8_t my_jpeg[] = {
    #include "my_jpeg.h"
};

Now all that JPEG file data will be included in your firmware and be programmed to flash when you program the firmware.

You could use a makefile recipe or your IDE's pre-build batch script feature to run your JPEG conversion program automatically and produce my_jpeg.h during the build.


问:
SQL create linked fuzzy records
If I have a set of records:

```<code>ID  DESCRIPTION     VALUE
1    HORSE JOCKEY     200
2    HORSE JOCK       300
3    SOCKS            50
4    HORSE JOCKE      200
</code>```

Which I have already run a string distance function over to include with only pairs of high probability matches

```<code>ID1  DESCRIPTION1    VALUE1  ID2  DESCRIPTION2     VALUE2  STRING_DISTANCE
 1    HORSE JOCKEY     200    2    HORSE JOCK        300        95
 1    HORSE JOCKEY     200    4    HORSE JOCKE       200        97
 2    HORSE JOCK       300    4    HORSE JOCKE       200        98
</code>```

How do I then link these records to create one unique ID (say 10 for Horse Jockey) for assuming all the above are supposed to be HORSE JOCKEY but have typos? Similair to below:

```<code>ID1  DESCRIPTION1    VALUE1  ID2  DESCRIPTION2     VALUE2  STRING_DISTANCE UNIQUE_ID
 1    HORSE JOCKEY     200    2    HORSE JOCK        300        95             10
 1    HORSE JOCKEY     200    4    HORSE JOCKE       200        97             10
 2    HORSE JOCK       300    4    HORSE JOCKE       200        98             10
</code>```

Ultimately looking for

```<code>ID  DESCRIPTION     VALUE   UNIQUE_ID
1    HORSE JOCKEY     200      10
2    HORSE JOCK       300      10
3    SOCKS            50       11
4    HORSE JOCKE      200      10
</code>```

答:
The unique ID returned will be the ID of the item in the group that has the longest string length for the description (since the other strings appear to be sub-strings of that string) and if there are multiple longest length descriptions then the minimum of those IDs is used:

SQL Fiddle

Oracle 11g R2 Schema Setup:

```<code>CREATE TABLE your_table ( ID, DESCRIPTION, VALUE ) AS
SELECT 1, 'HORSE JOCK', 300 FROM DUAL UNION ALL
SELECT 2, 'HORSE JOCKEY', 200 FROM DUAL UNION ALL
SELECT 3, 'SOCKS', 50 FROM DUAL UNION ALL
SELECT 4, 'HORSE JOCKE', 200 FROM DUAL;
</code>```

Query 1:

```<code>SELECT id,
       description,
       value,
       MIN( CONNECT_BY_ROOT( id ) )
         KEEP ( DENSE_RANK LAST ORDER BY LENGTH( CONNECT_BY_ROOT( description ) ) )
         AS unique_id
FROM   your_table t
CONNECT BY NOCYCLE
       UTL_MATCH.JARO_WINKLER ( PRIOR description,  description ) >= 0.95
GROUP BY
       id,
       description,
       value
</code>```

Results:

```<code>| ID |  DESCRIPTION | VALUE | UNIQUE_ID |
|----|--------------|-------|-----------|
|  1 |   HORSE JOCK |   300 |         2 |
|  2 | HORSE JOCKEY |   200 |         2 |
|  3 |        SOCKS |    50 |         3 |
|  4 |  HORSE JOCKE |   200 |         2 |
</code>```

Title: SQL create linked fuzzy records

Body:
If I have a set of records:

ID  DESCRIPTION     VALUE
1    HORSE JOCKEY     200
2    HORSE JOCK       300
3    SOCKS            50
4    HORSE JOCKE      200

Which I have already run a string distance function over to include with only pairs of high probability matches

ID1  DESCRIPTION1    VALUE1  ID2  DESCRIPTION2     VALUE2  STRING_DISTANCE
 1    HORSE JOCKEY     200    2    HORSE JOCK        300        95
 1    HORSE JOCKEY     200    4    HORSE JOCKE       200        97
 2    HORSE JOCK       300    4    HORSE JOCKE       200        98

How do I then link these records to create one unique ID (say 10 for Horse Jockey) for assuming all the above are supposed to be HORSE JOCKEY but have typos? Similair to below:

ID1  DESCRIPTION1    VALUE1  ID2  DESCRIPTION2     VALUE2  STRING_DISTANCE UNIQUE_ID
 1    HORSE JOCKEY     200    2    HORSE JOCK        300        95             10
 1    HORSE JOCKEY     200    4    HORSE JOCKE       200        97             10
 2    HORSE JOCK       300    4    HORSE JOCKE       200        98             10

Ultimately looking for

ID  DESCRIPTION     VALUE   UNIQUE_ID
1    HORSE JOCKEY     200      10
2    HORSE JOCK       300      10
3    SOCKS            50       11
4    HORSE JOCKE      200      10

Body:
The unique ID returned will be the ID of the item in the group that has the longest string length for the description (since the other strings appear to be sub-strings of that string) and if there are multiple longest length descriptions then the minimum of those IDs is used:

SQL Fiddle

Oracle 11g R2 Schema Setup:

CREATE TABLE your_table ( ID, DESCRIPTION, VALUE ) AS
SELECT 1, 'HORSE JOCK', 300 FROM DUAL UNION ALL
SELECT 2, 'HORSE JOCKEY', 200 FROM DUAL UNION ALL
SELECT 3, 'SOCKS', 50 FROM DUAL UNION ALL
SELECT 4, 'HORSE JOCKE', 200 FROM DUAL;

Query 1:

SELECT id,
       description,
       value,
       MIN( CONNECT_BY_ROOT( id ) )
         KEEP ( DENSE_RANK LAST ORDER BY LENGTH( CONNECT_BY_ROOT( description ) ) )
         AS unique_id
FROM   your_table t
CONNECT BY NOCYCLE
       UTL_MATCH.JARO_WINKLER ( PRIOR description,  description ) >= 0.95
GROUP BY
       id,
       description,
       value

Results:

| ID |  DESCRIPTION | VALUE | UNIQUE_ID |
|----|--------------|-------|-----------|
|  1 |   HORSE JOCK |   300 |         2 |
|  2 | HORSE JOCKEY |   200 |         2 |
|  3 |        SOCKS |    50 |         3 |
|  4 |  HORSE JOCKE |   200 |         2 |


问:
ASP.NET Core - Razor not checking for view embeded in assembly
I am trying to set up a pair of .NET Core project where one is a class library including a ViewComponent and the other is an ASP.NET Core MVC application which makes use of that component.

I followed the guide here: http://www.strathweb.com/2016/01/re-using-external-view-components-in-asp-net-5-asp-net-mvc-6/

However, I can't seem to get this working. I keep getting:

InvalidOperationException: The view 'Components/Test/Default' was not
  found. The following locations were searched:
  /Views/Home/Components/Test/Default.cshtml
  /Views/Shared/Components/Test/Default.cshtml

The component itself:

```<code>public class TestViewComponent : ViewComponent
{
    public TestViewComponent()
    {
    }

    public IViewComponentResult Invoke()
    {
        return View();
    }
}
</code>```

The corresponding view (file path is Views/Shared/Components/Test/Default.cshtml):

```<code><p>Hello from test component</p>
</code>```

Relevant bit from ConfigureServices to tell Razor to look for views in the assembly:

```<code>services.Configure<RazorViewEngineOptions>(o =>
{
    o.FileProviders.Add(new EmbeddedFileProvider(
        typeof(TestViewComponent).GetTypeInfo().Assembly, "Test.Components"));
});
</code>```

project.json from the class library project:

```<code>"buildOptions": {
  "embed": {
    "include": [ "Views" ]
  }
},
</code>```

and finally, at the bottom of _Layout.cshtml in the MVC project:

    @await Component.InvokeAsync("Test")

```

Things I've tried:

Moving Default.cshtml for the component into the correct location in the MVC project. This gets things working fine so I'm pretty sure it's just a problem with Razor finding the view.

Checking the view has been embedded into the assembly properly. I used GetManifestResourceNames() and it was listed as MiddlewareTest.Views.Shared.Components.Test.Default.cshtml so that looks fine.

答:
I had this problem and it was resolved by changing Build Action property on the View from None to Embedded Resource.

Right click view in Solution Explorer.

Select Properties.

Change Build Action to Embedded Resource.

Alternatively, if you want to automatically add all Views as Embedded Resources, you can add this ItemGroup to your .csproj file:

<ItemGroup>
    <EmbeddedResource Include="Views\**\*.cshtml" />
  </ItemGroup>

Body:
I am trying to set up a pair of .NET Core project where one is a class library including a ViewComponent and the other is an ASP.NET Core MVC application which makes use of that component.

I followed the guide here: http://www.strathweb.com/2016/01/re-using-external-view-components-in-asp-net-5-asp-net-mvc-6/

However, I can't seem to get this working. I keep getting:

InvalidOperationException: The view 'Components/Test/Default' was not
  found. The following locations were searched:
  /Views/Home/Components/Test/Default.cshtml
  /Views/Shared/Components/Test/Default.cshtml

The component itself:

public class TestViewComponent : ViewComponent
{
    public TestViewComponent()
    {
    }

    public IViewComponentResult Invoke()
    {
        return View();
    }
}

The corresponding view (file path is Views/Shared/Components/Test/Default.cshtml):

Hello from test component

Relevant bit from ConfigureServices to tell Razor to look for views in the assembly:

services.Configure<RazorViewEngineOptions>(o =>
{
    o.FileProviders.Add(new EmbeddedFileProvider(
        typeof(TestViewComponent).GetTypeInfo().Assembly, "Test.Components"));
});

project.json from the class library project:

"buildOptions": {
  "embed": {
    "include": [ "Views" ]
  }
},

and finally, at the bottom of _Layout.cshtml in the MVC project:

    @await Component.InvokeAsync("Test")

Things I've tried:

Moving Default.cshtml for the component into the correct location in the MVC project. This gets things working fine so I'm pretty sure it's just a problem with Razor finding the view.

Checking the view has been embedded into the assembly properly. I used GetManifestResourceNames() and it was listed as MiddlewareTest.Views.Shared.Components.Test.Default.cshtml so that looks fine.


问:
Applying multiple functions (Mean., STD etc ) across columns in Python
I have this data of 4 columns and 8 rows...

```<code>df = pd.DataFrame([[1, 2, 3,7], [2, 8, 6,8],[3, 2, 3,7], [4, 4, 6,8],[5, 2, 3,7], [6, 1, 6,8],[7, 8, 3,7], [8, 9, 6,8]], columns=['time','A', 'B', 'C'])

       time  A  B  C
    0     1  2  3  7
    1     2  8  6  8
    2     3  2  3  7
    3     4  4  6  8
    4     5  2  3  7
    5     6  1  6  8
    6     7  8  3  7
    7     8  9  6  8
</code>```

I want to take mean and STD of column A and C, across columns not rows. e.g Mean and STD of 2 and 7 is "" (mean) and "3.535533906" (STD) respectively as following.

I want my result to look like this...

```<code>      Mean  STD
    0 4.7   3.535533906
    1 8     0
    2 .     .
    3 .     .
    . .     .
    . .     .
</code>```

However, when I try to do

df= df.loc[(df.time>=2) & (df.time<=7),['A','C']],(['mean','std'])

I get the following error...

AttributeError: 'DataFrame' object has no attribute 'time'

I've tried to find solutions by doing this as well but in vain :

```<code>df= df.loc[(df.time>=2) & (df.time<=7),['A','C']].agg(['mean','std'])
</code>```

but it gives me result of all rows mean and STD.

```<code>                 A         C
    mean  4.166667  7.500000
    std   3.125167  0.547723
</code>```

How do I fix it?

Body:
I have this data of 4 columns and 8 rows...

df = pd.DataFrame([[1, 2, 3,7], [2, 8, 6,8],[3, 2, 3,7], [4, 4, 6,8],[5, 2, 3,7], [6, 1, 6,8],[7, 8, 3,7], [8, 9, 6,8]], columns=['time','A', 'B', 'C'])

       time  A  B  C
    0     1  2  3  7
    1     2  8  6  8
    2     3  2  3  7
    3     4  4  6  8
    4     5  2  3  7
    5     6  1  6  8
    6     7  8  3  7
    7     8  9  6  8

I want to take mean and STD of column A and C, across columns not rows. e.g Mean and STD of 2 and 7 is "" (mean) and "3.535533906" (STD) respectively as following.

I want my result to look like this...

      Mean  STD
    0 4.7   3.535533906
    1 8     0
    2 .     .
    3 .     .
    . .     .
    . .     .

However, when I try to do

df= df.loc[(df.time>=2) & (df.time<=7),['A','C']],(['mean','std'])

I get the following error...

AttributeError: 'DataFrame' object has no attribute 'time'

I've tried to find solutions by doing this as well but in vain :

df= df.loc[(df.time>=2) & (df.time<=7),['A','C']].agg(['mean','std'])

but it gives me result of all rows mean and STD.

                 A         C
    mean  4.166667  7.500000
    std   3.125167  0.547723

How do I fix it?

Body:
Another way:

In [346]: df[['A','C']].T.agg(['mean','std']).T
Out[346]:
   mean       std
0   4.5  3.535534
1   8.0  0.000000
2   4.5  3.535534
3   6.0  2.828427
4   4.5  3.535534
5   4.5  4.949747
6   7.5  0.707107
7   8.5  0.707107

or as a new columns in the original DF:

In [347]: df[['Mean','STD']] = df[['A','C']].T.agg(['mean','std']).T

In [348]: df
Out[348]:
   time  A  B  C  Mean       STD
0     1  2  3  7   4.5  3.535534
1     2  8  6  8   8.0  0.000000
2     3  2  3  7   4.5  3.535534
3     4  4  6  8   6.0  2.828427
4     5  2  3  7   4.5  3.535534
5     6  1  6  8   4.5  4.949747
6     7  8  3  7   7.5  0.707107
7     8  9  6  8   8.5  0.707107


问:
How to implement Google Analytics event tracking inside a React VR project?
This is loosely written to give a basic idea of what I'm trying achieve.

    < VrButton onClick={props.userClick}>< /VrButton>

```<code>userClick={() => this.triggerTracking}

triggerTracking() {
    ga('send', 'event', 'myEventCategory', 'myEventAction', 'myEventLabel');
}
</code>```

I expect the code to trigger Google Analytics event tracking in the GA system when the user clicks on a button, but I get an error message - "ga is not a function".

I have GA set up in my index.html file, with the proper ID, and pulling in the latest analytics.js API.

答:
Do next stps:

open the network debug tool of your browser.

reload your page

review loaded url list and check that www.google-analytics.com/analytics.js is loaded

If you does not see such url loaded - read google analitycks manual about how to setup google analytics on your page.

If you see such url replace url www.google-analytics.com/analytics.js with www.google-analytics.com/analytics_debug.js in your page, than reload and than go to console tab of your browser debugger and check the errors.

Body:
This is loosely written to give a basic idea of what I'm trying achieve.

    < VrButton onClick={props.userClick}>< /VrButton>

userClick={() => this.triggerTracking}

triggerTracking() {
    ga('send', 'event', 'myEventCategory', 'myEventAction', 'myEventLabel');
}

I expect the code to trigger Google Analytics event tracking in the GA system when the user clicks on a button, but I get an error message - "ga is not a function".

I have GA set up in my index.html file, with the proper ID, and pulling in the latest analytics.js API.


问:
Connect to SFTP using PHP and private key
I have read article after article and just cannot find "the solution" that works for what I have.

I am trying to upload files via SFTP using php scripting. I have connected using CyberDuck successfully, but I need to do this programatically.

I have a .PPK file from the vendor that I used in CyberDuck. I have a username. I have the hostname. If I open the PPK file I see some Public Lines, Private Lines and Private-MAC.

Is there anyway I can access the server to do what I need to do using the information I have?

Here is the code I was playing with:

```<code><?php if (!function_exists("ssh2_connect")) die("function ssh2_connect doesn't exist");
?>
<?php
$conn = ssh2_connect('hostname.com', 22);
echo $conn;
ssh2_auth_pubkey_file($conn,'USERNAME','/var/www/html/FILENAME.PPK');

// send a file
ssh2_scp_send($conn, '/var/www/html/FILETOSEND.TXT', 'FILETOSEND.TXT', 0644);
?>
</code>```

I don't receive any errors but the file doesn't show up on the server.
I can confirm that SSH2 is installed on my webhost.

Thanks for any help you can provide.

答:
The question is quite old, but as I was looking for exactly the same answer, here is what I managed to gather.

First: Change key format from .ppk to .pem

.pkk keys are PuTTY format private key.

If you want to change that to .pem format, you need to install putty-tools with:

sudo apt install putty-tools
```

<p>(On a Mac, install putty package with homebrew. For Windows, I have no clue.)</p>

<p>Then you can change the format of the key:</p>

<pre class="lang-none prettyprint-override"><code>puttygen privatekey.ppk -O private-openssh -o privatekey.pem
</code>```

Just in case you want to extract the public key from that private key, (you won't need for the rest of that answer, but just in case) it is quite easy:

openssl rsa -in privatekey.pem -pubout > publickey.pub
```

<h1>Second: Login with sFTP</h1>

<p>Now that you have the <code>privatekey.pem</code>, you can use phpseclib to connect via SFTP. First, install phpseclib with Composer:</p>

<pre class="lang-none prettyprint-override"><code>composer require phpseclib/phpseclib
</code>```

Then in PHP:

require "vendor/autoload.php";

use phpseclib\Crypt\RSA;
use phpseclib\Net\SFTP;

$sftp = new SFTP('sftp.server.com');

// create new RSA key
$privateKey = new RSA();

// in case that key has a password
$privateKey->setPassword('private key password');

// load the private key
$privateKey->loadKey(file_get_contents('/path/to/privatekey.pem'));

// login via sftp
if (!$sftp->login('username', $privateKey)) {
    throw new Exception('sFTP login failed');
}

// now you can list what's in here
$filesAndFolders = $sftp->nlist();

// you can change directory
$sftp->chdir('coolstuffdir');

// get a file
$sftp->get('remoteFile', 'localFile');

// create a remote new file with defined content
$sftp->put('newfile.txt', 'new file content');

// put a local file
$sftp->put('remote.txt', 'local.txt', NET_SFTP_LOCAL_FILE);
```

If you want more info, go to the phpseclib sFTP feature list.

Body:
I have read article after article and just cannot find "the solution" that works for what I have.

I am trying to upload files via SFTP using php scripting. I have connected using CyberDuck successfully, but I need to do this programatically.

I have a .PPK file from the vendor that I used in CyberDuck. I have a username. I have the hostname. If I open the PPK file I see some Public Lines, Private Lines and Private-MAC.

Is there anyway I can access the server to do what I need to do using the information I have?

Here is the code I was playing with:

<?php if (!function_exists("ssh2_connect")) die("function ssh2_connect doesn't exist");
?>
<?php
$conn = ssh2_connect('hostname.com', 22);
echo $conn;
ssh2_auth_pubkey_file($conn,'USERNAME','/var/www/html/FILENAME.PPK');

// send a file
ssh2_scp_send($conn, '/var/www/html/FILETOSEND.TXT', 'FILETOSEND.TXT', 0644);
?>

I don't receive any errors but the file doesn't show up on the server.
I can confirm that SSH2 is installed on my webhost.

Thanks for any help you can provide.

Body:
The question is quite old, but as I was looking for exactly the same answer, here is what I managed to gather.

First: Change key format from .ppk to .pem

.pkk keys are PuTTY format private key.

If you want to change that to .pem format, you need to install putty-tools with:

sudo apt install putty-tools

(On a Mac, install putty package with homebrew. For Windows, I have no clue.)

Then you can change the format of the key:

puttygen privatekey.ppk -O private-openssh -o privatekey.pem

Just in case you want to extract the public key from that private key, (you won't need for the rest of that answer, but just in case) it is quite easy:

openssl rsa -in privatekey.pem -pubout > publickey.pub

Second: Login with sFTP

Now that you have the privatekey.pem, you can use phpseclib to connect via SFTP. First, install phpseclib with Composer:

composer require phpseclib/phpseclib

Then in PHP:

require "vendor/autoload.php";

use phpseclib\Crypt\RSA;
use phpseclib\Net\SFTP;

$sftp = new SFTP('sftp.server.com');

// create new RSA key
$privateKey = new RSA();

// in case that key has a password
$privateKey->setPassword('private key password');

// load the private key
$privateKey->loadKey(file_get_contents('/path/to/privatekey.pem'));

// login via sftp
if (!$sftp->login('username', $privateKey)) {
    throw new Exception('sFTP login failed');
}

// now you can list what's in here
$filesAndFolders = $sftp->nlist();

// you can change directory
$sftp->chdir('coolstuffdir');

// get a file
$sftp->get('remoteFile', 'localFile');

// create a remote new file with defined content
$sftp->put('newfile.txt', 'new file content');

// put a local file
$sftp->put('remote.txt', 'local.txt', NET_SFTP_LOCAL_FILE);

If you want more info, go to the phpseclib sFTP feature list.

ContentLicense: CC BY-SA 4.0


问:
Output UUID in Go as a short string
Is there a built in way, or reasonably standard package that allows you to convert a standard UUID into a short string that would enable shorter URL's?

I.e. taking advantage of using a larger range of characters such as [A-Za-z0-9] to output a shorter string.

I know we can use base64 to encode the bytes, as follows, but I'm after something that creates a string that looks like a "word", i.e. no + and /:

```<code>id = base64.StdEncoding.EncodeToString(myUuid.Bytes())
</code>```

答:
As suggested here, If you want just a fairly random string to use as slug, better to not bother with UUID at all.

You can simply use go's native math/rand library to make random strings of desired length:

```<code>import (
"math/rand"
"encoding/hex"
)

b := make([]byte, 4) //equals 8 characters
rand.Read(b)
s := hex.EncodeToString(b)
</code>```

Title: Output UUID in Go as a short string

Body:
Is there a built in way, or reasonably standard package that allows you to convert a standard UUID into a short string that would enable shorter URL's?

I.e. taking advantage of using a larger range of characters such as [A-Za-z0-9] to output a shorter string.

I know we can use base64 to encode the bytes, as follows, but I'm after something that creates a string that looks like a "word", i.e. no + and /:

id = base64.StdEncoding.EncodeToString(myUuid.Bytes())

Body:
As suggested here, If you want just a fairly random string to use as slug, better to not bother with UUID at all.

You can simply use go's native math/rand library to make random strings of desired length:

import (
"math/rand"
"encoding/hex"
)

b := make([]byte, 4) //equals 8 characters
rand.Read(b)
s := hex.EncodeToString(b)


问:
OpenSSL: Get the name of a hash algorithm by EVP_MD*
For logging I'm trying to find a way of getting the name of a hash algorithm by the EVP_MD* object.
But I could not find a suitable answer anywhere.
Thanks!

答:
I found the answer on my own:</p>

```<code>EVP_MD* pMD = EVP_sha256();

const char *mdalgSn = OBJ_nid2sn(pMD->pkey_type);
const char *mdalgLn = OBJ_nid2ln(pMD->pkey_type);

printf("ShortName: %s\n", mdalgSn);
printf("LongName: %s\n", mdalgLn);

//ShortName: RSA-SHA256
//LongName: sha256WithRSAEncryption
</code>```

Body:
I found the answer on my own:

EVP_MD* pMD = EVP_sha256();

const char *mdalgSn = OBJ_nid2sn(pMD->pkey_type);
const char *mdalgLn = OBJ_nid2ln(pMD->pkey_type);

printf("ShortName: %s\n", mdalgSn);
printf("LongName: %s\n", mdalgLn);

//ShortName: RSA-SHA256
//LongName: sha256WithRSAEncryption


问:
Retry a call with Retrofit 2 and RxJava2 after displaying a dialog
I'm calling an API using Retrofit 2 and RxJava2.
If a call fails, in some cases (e.g. no Internet connection), I want to display an error dialog to the user and let him retry.

As I'm using RxJava, I was thinking of using .retryWhen(...) but I don't know how to do that as it needs to wait for the user to press the button on the dialog.

At the moment I display the dialog but it retries before the user presses any button. Plus I would like the call to not be retried when the user presses 'cancel'.

Here is the code I have at the moment:

```<code>private void displayDialog(DialogInterface.OnClickListener positive, DialogInterface.OnClickListener negative) {
    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
    builder.setMessage("Unexpected error, do you want to retry?")
            .setPositiveButton("Retry", positive)
            .setNegativeButton("Cancel", negative)
            .show();
}

private Observable<Boolean> notifyUser() {
    final PublishSubject<Boolean> subject = PublishSubject.create();
    displayDialog(
            (dialogInterface, i) -> subject.onNext(true),
            (dialogInterface, i) -> subject.onNext(false)
    );

    return subject;
}

private void onClick() {
    Log.d(TAG, "onClick");
    getData()
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(Schedulers.io())
            .retryWhen(attempts -> {
                return attempts.zipWith(
                        notifyUser(),
                        (throwable, res) -> res);
            })
            .subscribe(
                    s -> {
                        Log.d(TAG, "success");
                    });
}
</code>```

答:
```<code>final PublishSubject<Object> retrySubject = PublishSubject.create();

disposable.add(getData()
    .doOnError(throwable -> enableButton())
    .retryWhen(observable -> observable.zipWith(retrySubject, (o, o2) -> o))
    .subscribeWith(/* do what you want with the result*/)
}));
</code>```

When button is clicked you trigger this event:

```<code>retrySubject.onNext(new Object());
</code>```

As you can see in this Marble diagram:

the error is not propagated. The retryWhen operator will indeed handle it and do a proper action. This is the reason why you have to enable (or for example show a Dialog) in doOnError, before retryWhen operator.

When you don't want to listen anymore for successive retry attempts, you just need to unsubscribe:

```<code>disposable.dispose();
</code>```

As per your question:

What should I do if I want to retry only on a specific Exception but
  not on the other ones?

You can modify your retryWhen in this way:

```<code>.retryWhen(throwableObservable -> throwableObservable.flatMap(throwable -> {
      if (throwable instanceof TargetException) {
          return Observable.just(throwable).zipWith(retrySubject, (o, o2) -> o);
      } else {
          throw Throwables.propagate(throwable);
      }
}))
</code>```

Where Throwables.propagate(throwable) is a Guava util that can be replaced with throw new RuntimeException(throwable);

Body:
I'm calling an API using Retrofit 2 and RxJava2.
If a call fails, in some cases (e.g. no Internet connection), I want to display an error dialog to the user and let him retry.

As I'm using RxJava, I was thinking of using .retryWhen(...) but I don't know how to do that as it needs to wait for the user to press the button on the dialog.

At the moment I display the dialog but it retries before the user presses any button. Plus I would like the call to not be retried when the user presses 'cancel'.

Here is the code I have at the moment:

private void displayDialog(DialogInterface.OnClickListener positive, DialogInterface.OnClickListener negative) {
    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
    builder.setMessage("Unexpected error, do you want to retry?")
            .setPositiveButton("Retry", positive)
            .setNegativeButton("Cancel", negative)
            .show();
}

private Observable<Boolean> notifyUser() {
    final PublishSubject<Boolean> subject = PublishSubject.create();
    displayDialog(
            (dialogInterface, i) -> subject.onNext(true),
            (dialogInterface, i) -> subject.onNext(false)
    );

    return subject;
}

private void onClick() {
    Log.d(TAG, "onClick");
    getData()
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(Schedulers.io())
            .retryWhen(attempts -> {
                return attempts.zipWith(
                        notifyUser(),
                        (throwable, res) -> res);
            })
            .subscribe(
                    s -> {
                        Log.d(TAG, "success");
                    });
}

Body:
final PublishSubject<Object> retrySubject = PublishSubject.create();

disposable.add(getData()
    .doOnError(throwable -> enableButton())
    .retryWhen(observable -> observable.zipWith(retrySubject, (o, o2) -> o))
    .subscribeWith(/* do what you want with the result*/)
}));

When button is clicked you trigger this event:

retrySubject.onNext(new Object());

As you can see in this Marble diagram:

the error is not propagated. The retryWhen operator will indeed handle it and do a proper action. This is the reason why you have to enable (or for example show a Dialog) in doOnError, before retryWhen operator.

When you don't want to listen anymore for successive retry attempts, you just need to unsubscribe:

disposable.dispose();

As per your question:

What should I do if I want to retry only on a specific Exception but
  not on the other ones?

You can modify your retryWhen in this way:

.retryWhen(throwableObservable -> throwableObservable.flatMap(throwable -> {
      if (throwable instanceof TargetException) {
          return Observable.just(throwable).zipWith(retrySubject, (o, o2) -> o);
      } else {
          throw Throwables.propagate(throwable);
      }
}))

Where Throwables.propagate(throwable) is a Guava util that can be replaced with throw new RuntimeException(throwable);


问:
removing tags for a string with recursion
I have the following function which should remove tags from an input string.

example in:

```<code>'<strong>hello <em>my name <strong>is</strong> </em></strong>'
</code>```

result:

```<code>'hello my name is'
</code>```

Currently I have this code, but not sure how to make it work with recursion.

```<code>const clean= (str) => {
    const tags = ['<strong>', '</strong>', '<em>', '</em>', '<del>', '</del>']
    let strSanited = ''
    tags.forEach(tag => {
        if (str.includes(tag)) {
            strSanited = str.replace(tag, '')
        }else{
            // recursion here??
        }
    })
}

clean('<strong>hello <em>my name <strong>is</strong> </em></strong>')
</code>```

答:
Also You can use regular expression to do so.

EX.

```<code> yourstring.replace(/<(?:.|\n)*?>/gm, '');
</code>```

Reference:Strip HTML from Text JavaScript

This way you need not to worry about other html tags, it will take care of all the html tags. Let know if it helps

Body:
I have the following function which should remove tags from an input string.

example in:

'hello my name is '

result:

'hello my name is'

Currently I have this code, but not sure how to make it work with recursion.

const clean= (str) => {
    const tags = ['', '', '', '', '', '']
    let strSanited = ''
    tags.forEach(tag => {
        if (str.includes(tag)) {
            strSanited = str.replace(tag, '')
        }else{
            // recursion here??
        }
    })
}

clean('hello my name is ')

Body:
Also You can use regular expression to do so.

EX.

 yourstring.replace(/<(?:.|\n)*?>/gm, '');

Reference:Strip HTML from Text JavaScript

This way you need not to worry about other html tags, it will take care of all the html tags. Let know if it helps


问:
Checking if object is a DOM-element
Passing DOM elements to WebWorkers gets tricky since all references to the DOM are 'lost'. I need to check objects that are passed before the WebWorker's message is sent.

What is the fastest way to check if an instance of an object is a DOM-element OR/AND part of the DOM tree, OR has 'children' that contain any references to the DOM tree?

piece of the usage:

```<code>var a = new SharedWorker("bigdatahandler.js");
a.postMessage(s);

s //<--should not be a DOM object
</code>```

答:
To check if it's an element I think obj.nodeName is your best bet.

```<code>var a = new SharedWorker("bigdatahandler.js");
if (!s.nodeName) {
    a.postMessage(s);
}
</code>```

You can also check s instanceof Element, because you don't need to support IE I guess :)

To check if it's part of the DOM:

```<code>function inDOM(elem) {
  do {
      if (elem == document.documentElement) {
         return true;
      }
  } while (elem = elem.parentNode)
  return false;
}
</code>```

Title: Checking if object is a DOM-element

Body:
Passing DOM elements to WebWorkers gets tricky since all references to the DOM are 'lost'. I need to check objects that are passed before the WebWorker's message is sent.

What is the fastest way to check if an instance of an object is a DOM-element OR/AND part of the DOM tree, OR has 'children' that contain any references to the DOM tree?

piece of the usage:

var a = new SharedWorker("bigdatahandler.js");
a.postMessage(s);

s //<--should not be a DOM object

Body:
To check if it's an element I think obj.nodeName is your best bet.

var a = new SharedWorker("bigdatahandler.js");
if (!s.nodeName) {
    a.postMessage(s);
}

You can also check s instanceof Element, because you don't need to support IE I guess :)

To check if it's part of the DOM:

function inDOM(elem) {
  do {
      if (elem == document.documentElement) {
         return true;
      }
  } while (elem = elem.parentNode)
  return false;
}


问:
How to change timeout in JDI Test Automation Framework
I need to change timeout for waiting particular webElements. For all of others default is pretty fine. Default timeout could be changed in settings:

```<code>timeout.wait.element=10
</code>```

How to change timeout only for given elements?

答:
For setting specific timeout on element you can use

textField.setWaitTimeout(10);

textField.input("TEXT");

But if you also has some waiting criteria and want to do something after it becomes true you can use

String text = textField.wait(w -> w.getText(), t -> t.equals("test"), 10);

or textField.wait(w -> w.getText().equals("test"), 10); if you just want to wait something

Body:
I need to change timeout for waiting particular webElements. For all of others default is pretty fine. Default timeout could be changed in settings:

timeout.wait.element=10

How to change timeout only for given elements?


问:
how indexing works internally in hive?
An Index is nothing but a pointer on a particular column of a table. Creating an index means creating a pointer on a particular column of a table. If a column is indexed in a table, and how the data of that particular column is pointed,when that specific column is queried? </p>

答:
From the documentation

The goal of Hive indexing is to improve the speed of query lookup on
  certain columns of a table. Without an index, queries with predicates
  like 'WHERE tab1.col1 = 10' load the entire table or partition and
  process all the rows. But if an index exists for col1, then only a
  portion of the file needs to be loaded and processed. The improvement
  in query speed that an index can provide comes at the cost of
  additional processing to create the index and disk space to store the
  index.

Behind the scene, Hive creates essentially a  Map with the values of the column that it is indexing and the offset + files where the data is located in the HDFS, in that way, Hive does not need to scan all the data to search for a certain value.  Here is a good article explaining basic concepts

https://acadgild.com/blog/indexing-in-hive/

Title: how indexing works internally in hive?


问:
Objective-C: What does this code mean?
In the MyViewController.h file:

```<code>@property (nonatomic, copy, nullable, class) void (^saveMetadataSuccess)(MyViewController*const _Nullable myViewController);
</code>```

In the MyViewController.m file:

```<code>void (^saveMetadataSuccess)(MyViewControllerr* const myViewController) = nil;

+ (void)setSaveMetadataSuccess:(void (^)(MyViewController* const))newMetadataSaveSuccess {
    saveMetadataSuccess = [newMetadataSaveSuccess copy];
}

+ (void (^)(MyViewController* const))saveMetadataSuccess {
    return saveMetadataSuccess;
}
</code>```

And finally the method which I don't understand:

```<code>- (void)success {
dispatch_async(dispatch_get_main_queue(), ^{
        MyViewController.saveMetadataSuccess(self);
    });
}
</code>```

From my understanding, saveMetadataSuccess is a getter, but MyViewController.saveMetadataSuccess(self);seems to set something.

Can somebody enlighten me?

Thanks

答:
MyViewController.saveMetadataSuccess is a getter and it returns a block that then being called with a param (self).

So it's like a function that returns other function.

Also you must not just call MyViewController.saveMetadataSuccess(self); because MyViewController.saveMetadataSuccess is nullable and it will crash if MyViewController.saveMetadataSuccess is null.

You have to check MyViewController.saveMetadataSuccess first:

```<code>- (void)success {
dispatch_async(dispatch_get_main_queue(), ^{
        if (MyViewController.saveMetadataSuccess) {
            MyViewController.saveMetadataSuccess(self);
        }
    });
</code>```

}

Title: Objective-C: What does this code mean?

Body:
In the MyViewController.h file:

@property (nonatomic, copy, nullable, class) void (^saveMetadataSuccess)(MyViewController*const _Nullable myViewController);

In the MyViewController.m file:

void (^saveMetadataSuccess)(MyViewControllerr* const myViewController) = nil;

+ (void)setSaveMetadataSuccess:(void (^)(MyViewController* const))newMetadataSaveSuccess {
    saveMetadataSuccess = [newMetadataSaveSuccess copy];
}

+ (void (^)(MyViewController* const))saveMetadataSuccess {
    return saveMetadataSuccess;
}

And finally the method which I don't understand:

- (void)success {
dispatch_async(dispatch_get_main_queue(), ^{
        MyViewController.saveMetadataSuccess(self);
    });
}

From my understanding, saveMetadataSuccess is a getter, but MyViewController.saveMetadataSuccess(self);seems to set something.

Can somebody enlighten me?

Thanks

Body:
MyViewController.saveMetadataSuccess is a getter and it returns a block that then being called with a param (self).

So it's like a function that returns other function.

Also you must not just call MyViewController.saveMetadataSuccess(self); because MyViewController.saveMetadataSuccess is nullable and it will crash if MyViewController.saveMetadataSuccess is null.

You have to check MyViewController.saveMetadataSuccess first:

- (void)success {
dispatch_async(dispatch_get_main_queue(), ^{
        if (MyViewController.saveMetadataSuccess) {
            MyViewController.saveMetadataSuccess(self);
        }
    });

}


问:
Recommended way to initialize srand?
I need a 'good' way to initialize the pseudo-random number generator in C++. I've found an article that states:

In order to generate random-like
  numbers, srand is usually initialized
  to some distinctive value, like those
  related with the execution time. For
  example, the value returned by the
  function time (declared in header
  ctime) is different each second, which
  is distinctive enough for most
  randoming needs.

Unixtime isn't distinctive enough for my application. What's a better way to initialize this? Bonus points if it's portable, but the code will primarily be running on Linux hosts.

I was thinking of doing some pid/unixtime math to get an int, or possibly reading data from /dev/urandom.

Thanks!

EDIT

Yes, I am actually starting my application multiple times a second and I've run into collisions.

答:
As long as your program is only running on Linux (and your program is an ELF executable), you are guaranteed that the kernel provides your process with a unique random seed in the ELF aux vector. The kernel gives you 16 random bytes, different for each process, which you can get with getauxval(AT_RANDOM). To use these for srand, use just an int of them, as such:

```<code>#include <sys/auxv.h>

void initrand(void)
{
    unsigned int *seed;

    seed = (unsigned int *)getauxval(AT_RANDOM);
    srand(*seed);
}
</code>```

It may be possible that this also translates to other ELF-based systems. I'm not sure what aux values are implemented on systems other than Linux.

OwnerDisplayName: Gary Richardson

Title: Recommended way to initialize srand?

LastEditorDisplayName: Gary Richardson

Body:
As long as your program is only running on Linux (and your program is an ELF executable), you are guaranteed that the kernel provides your process with a unique random seed in the ELF aux vector. The kernel gives you 16 random bytes, different for each process, which you can get with getauxval(AT_RANDOM). To use these for srand, use just an int of them, as such:

#include <sys/auxv.h>

void initrand(void)
{
    unsigned int *seed;

    seed = (unsigned int *)getauxval(AT_RANDOM);
    srand(*seed);
}

It may be possible that this also translates to other ELF-based systems. I'm not sure what aux values are implemented on systems other than Linux.


问:
R dplyr - select values from one column based on position of a specific value in another column
I am working with gait-cycle data. I have 8 events marked for each id and gait trial. The values "LFCH" and "RFCH" occurs twice in each trial, as these represent the beginning and the end of the gait cycles from left and right leg.

Sample Data Frame:

```<code>df <- data.frame(ID = rep(1:5, each = 16),
                 Gait_nr = rep(1:2, each = 8, times=5),
                 Frame = rep(c(1,5,7,9,10,15,22,25), times = 10),
                 Marks = rep(c("LFCH", "LHL", "RFCH", "LTO", "RHL", "LFCH", "RTO", "RFCH"), times =10)

head(df,8)
  ID Gait_nr Frame Marks
1  1       1     1  LFCH
2  1       1     5   LHL
3  1       1     7  RFCH
4  1       1     9   LTO
5  1       1    10   RHL
6  1       1    15  LFCH
7  1       1    22   RTO
8  1       1    25  RFCH
</code>```

I wold like to create something like

```<code>Total_gait_left = Frame[The last time Marks == "LFCH"] - Frame[The first time Marks == "LFCH"]
</code>```

My current code solves the problem, but depends on the position of the Frame values rather than actual values in Marks. Any individual not following the normal gait pattern will have wrong values produced by the code.

```<code>library(tidyverse)
l <- df %>% group_by(ID, Gait_nr) %>% filter(grepl("L.+", Marks)) %>%
  summarize(Total_gait = Frame[4] - Frame[1],
            Side = "left")

r <- df %>% group_by(ID, Gait_nr) %>% filter(grepl("R.+", Marks)) %>%
  summarize(Total_gait = Frame[4] - Frame[1],
            Side = "right")

val <- union(l,r, by=c("ID", "Gait_nr", "Side")) %>% arrange(ID, Gait_nr, Side)
</code>```

Can you help me make my code more stable by helping me change e.g. Frame[4] to something like Frame[Marks=="LFCH" the last time ]?

答:
We can use first and last from the dplyr package.

```<code>library(dplyr)

df2 <- df %>%
  filter(Marks %in% "LFCH") %>%
  group_by(ID, Gait_nr) %>%
  summarise(Total_gait = last(Frame) - first(Frame)) %>%
  ungroup()
df2
# # A tibble: 10 x 3
#       ID Gait_nr Total_gait
#    <int>   <int>      <dbl>
#  1     1       1         14
#  2     1       2         14
#  3     2       1         14
#  4     2       2         14
#  5     3       1         14
#  6     3       2         14
#  7     4       1         14
#  8     4       2         14
#  9     5       1         14
# 10     5       2         14
</code>```

Body:
I am working with gait-cycle data. I have 8 events marked for each id and gait trial. The values "LFCH" and "RFCH" occurs twice in each trial, as these represent the beginning and the end of the gait cycles from left and right leg.

Sample Data Frame:

df <- data.frame(ID = rep(1:5, each = 16),
                 Gait_nr = rep(1:2, each = 8, times=5),
                 Frame = rep(c(1,5,7,9,10,15,22,25), times = 10),
                 Marks = rep(c("LFCH", "LHL", "RFCH", "LTO", "RHL", "LFCH", "RTO", "RFCH"), times =10)

head(df,8)
  ID Gait_nr Frame Marks
1  1       1     1  LFCH
2  1       1     5   LHL
3  1       1     7  RFCH
4  1       1     9   LTO
5  1       1    10   RHL
6  1       1    15  LFCH
7  1       1    22   RTO
8  1       1    25  RFCH

I wold like to create something like

Total_gait_left = Frame[The last time Marks == "LFCH"] - Frame[The first time Marks == "LFCH"]

My current code solves the problem, but depends on the position of the Frame values rather than actual values in Marks. Any individual not following the normal gait pattern will have wrong values produced by the code.

library(tidyverse)
l <- df %>% group_by(ID, Gait_nr) %>% filter(grepl("L.+", Marks)) %>%
  summarize(Total_gait = Frame[4] - Frame[1],
            Side = "left")

r <- df %>% group_by(ID, Gait_nr) %>% filter(grepl("R.+", Marks)) %>%
  summarize(Total_gait = Frame[4] - Frame[1],
            Side = "right")

val <- union(l,r, by=c("ID", "Gait_nr", "Side")) %>% arrange(ID, Gait_nr, Side)

Can you help me make my code more stable by helping me change e.g. Frame[4] to something like Frame[Marks=="LFCH" the last time ]?

Body:
We can use first and last from the dplyr package.

library(dplyr)

df2 <- df %>%
  filter(Marks %in% "LFCH") %>%
  group_by(ID, Gait_nr) %>%
  summarise(Total_gait = last(Frame) - first(Frame)) %>%
  ungroup()
df2
# # A tibble: 10 x 3
#       ID Gait_nr Total_gait
#    <int>   <int>      <dbl>
#  1     1       1         14
#  2     1       2         14
#  3     2       1         14
#  4     2       2         14
#  5     3       1         14
#  6     3       2         14
#  7     4       1         14
#  8     4       2         14
#  9     5       1         14
# 10     5       2         14


问:
Ruby equivalent operators at "OrElse" and "AndAlso" of Vb.net
There are operators in Ruby similar to "OrElse"and "AndAlso" in VB.NET?

For example in Ruby NoMethodError exception is raised when active_record is nil:

```<code>if active_record.nil? || active_record.errors.count == 0
     ...
end
</code>```

In VB.net i can do:

```<code> If active_record Is Nothing OrElse active_record.errors.count = 0
    ...
 End
</code>```

That does not generate an exception because it is only checked the first expression

答:
in ruby, there is a big difference between something that is nil and something that is undefined. Considering the following, from IRB:

```<code>ruby-1.9.2-p0 :002 > active_record
NameError: undefined local variable or method `active_record' for main:Object
    from (irb):2
    from /Users/jed/.rvm/rubies/ruby-1.9.2-p0/bin/irb:16:in `<main>'
ruby-1.9.2-p0 :003 > active_record = nil
 => nil
ruby-1.9.2-p0 :004 > active_record.class
 => NilClass
ruby-1.9.2-p0 :006 > active_record.nil?
 => true
</code>```

So, an object that is nil is an instance of NilClass and therefore responds to the message nil? will return true, but without declaring the variable (as in your code) Ruby doesn't know what you are calling.

A couple of options here:

Ruby's || operator is a strict operator, whereas the or keyword is less strict, so I don't know where the vb operation compares to these two or flow options.

you could use a neat little gem callled 'andand'

```<code>require 'andand'
active_record.andand.errors.count == 0
</code>```

but, generally when you are dealing with this situation in rails, you would use another means to determine the situation above, consider:

```<code>@post = Post.new(:my_key => "my value") #=> an ActiveRecord object
if @post.valid?
  # do something meaningful
else
  puts @post.errors.full_messages.to_sentence
end
</code>```

and if you mean to assign something based on if it possibly undefined, you would want to use memoization:

```<code>@post ||= Post.new
</code>```

which will declare the object if undefined or use the existing object

Body:
There are operators in Ruby similar to "OrElse"and "AndAlso" in VB.NET?

For example in Ruby NoMethodError exception is raised when active_record is nil:

if active_record.nil? || active_record.errors.count == 0
     ...
end

In VB.net i can do:

 If active_record Is Nothing OrElse active_record.errors.count = 0
    ...
 End

That does not generate an exception because it is only checked the first expression

Body:
in ruby, there is a big difference between something that is nil and something that is undefined. Considering the following, from IRB:

ruby-1.9.2-p0 :002 > active_record
NameError: undefined local variable or method `active_record' for main:Object
    from (irb):2
    from /Users/jed/.rvm/rubies/ruby-1.9.2-p0/bin/irb:16:in `<main>'
ruby-1.9.2-p0 :003 > active_record = nil
 => nil
ruby-1.9.2-p0 :004 > active_record.class
 => NilClass
ruby-1.9.2-p0 :006 > active_record.nil?
 => true

So, an object that is nil is an instance of NilClass and therefore responds to the message nil? will return true, but without declaring the variable (as in your code) Ruby doesn't know what you are calling.

A couple of options here:

Ruby's || operator is a strict operator, whereas the or keyword is less strict, so I don't know where the vb operation compares to these two or flow options.

you could use a neat little gem callled 'andand'

require 'andand'
active_record.andand.errors.count == 0

but, generally when you are dealing with this situation in rails, you would use another means to determine the situation above, consider:

@post = Post.new(:my_key => "my value") #=> an ActiveRecord object
if @post.valid?
  # do something meaningful
else
  puts @post.errors.full_messages.to_sentence
end

and if you mean to assign something based on if it possibly undefined, you would want to use memoization:

@post ||= Post.new

which will declare the object if undefined or use the existing object


问:
Reading data from a file and storing it in a variable
I'd like to show the employee number (without declaring in the class), name, occupation, and department of employees from a text file called organisation.txt, and save them in the variables declared in the class OrganisationRecord.

How can I pull the data in the text file and save them into the corresponding variables?

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

#define ORGANISATIONALRECORDSFILE "organisation.txt"
#define HRRECORDSFILE "HR_records.txt"
#define PAYROLLRECORDSFILE "payroll_records.txt"

using namespace std;

class OrganisationRecord
{
private:
public:
    string name;
    string occupation;
    string department;
};

class HRRecord
{
private:
public:
    string address;
    string phonenumber;
    string ninumber;
};

class PayrollRecord
{
private:
public:
    string ninumber;
    double salary;
};

class PayrollProcessing
{
private:
    ifstream inputfile;
    ofstream outputfile;
    vector<OrganisationRecord> OrganisationRecords;
    vector<HRRecord> HRRecords;
    vector<PayrollRecord> PayrollRecords;
public:
    void loadOrganisationRecords(string filename);
    void loadHRRecords(string filename);
    void loadPayrollRecords(string filename);
    void displayEmployeeOfSalaryGTE(double salary);
    //GTE = greater than or equal to
};

void PayrollProcessing::loadOrganisationRecords(string filename)
{
    inputfile.open(ORGANISATIONALRECORDSFILE);

    if (!inputfile)
    {
        cout << "the organisation records file does not exist" << endl;
        return;
    }

        OrganisationRecord _organisationrecord;
        int employeenumber;

        while (inputfile >> employeenumber)
        {
            while (inputfile >> _organisationrecord.name)
            {
                cout << _organisationrecord.name;
                cout << _organisationrecord.occupation;
                cout << _organisationrecord.department <<endl;
            }

            OrganisationRecords.push_back(_organisationrecord);
        }

}

int main(void)
{
    PayrollProcessing database1;
    database1.loadOrganisationRecords(ORGANISATIONALRECORDSFILE);

    return 0;
}
</code>```

organisation.txt

0001
Stephen Jones
Sales Clerk
Sales
0002
John Smith
Programmer
OS Development
0003
Fred Blogs
Project Manager
Outsourcing
```

答:
Here is an approach that will work without any error checking on the input.  Like others have said, you need to read in the file line by line using std::getline() because just feeding directly into your variables will cause the input parsing to be delimited by spaces in the text, as opposed to the whole line.

```<code>OrganisationRecord _organisationrecord;
std::string employeeNumberStr;
int employeenumber;

// without any robust error checking...
while (std::getline(inputfile, employeeNumberStr))
{
    // store employee number string as an integer
    std::stringstream ss;
    ss << employeeNumberStr;
    ss >> employeenumber;

    std::getline(inputfile, _organisationrecord.name);
    std::getline(inputfile, _organisationrecord.occupation);
    std::getline(inputfile, _organisationrecord.department);

    // debug print results
    std::cout << "id number: " << employeenumber << std::endl;
    std::cout << "name: " << _organisationrecord.name << std::endl;
    std::cout << "occupation: " << _organisationrecord.occupation << std::endl;
    std::cout << "department: " << _organisationrecord.department << std::endl;

    OrganisationRecords.push_back(_organisationrecord);
}
</code>```

Body:
I'd like to show the employee number (without declaring in the class), name, occupation, and department of employees from a text file called organisation.txt, and save them in the variables declared in the class OrganisationRecord.

How can I pull the data in the text file and save them into the corresponding variables?

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

#define ORGANISATIONALRECORDSFILE "organisation.txt"
#define HRRECORDSFILE "HR_records.txt"
#define PAYROLLRECORDSFILE "payroll_records.txt"

using namespace std;

class OrganisationRecord
{
private:
public:
    string name;
    string occupation;
    string department;
};

class HRRecord
{
private:
public:
    string address;
    string phonenumber;
    string ninumber;
};

class PayrollRecord
{
private:
public:
    string ninumber;
    double salary;
};

class PayrollProcessing
{
private:
    ifstream inputfile;
    ofstream outputfile;
    vector<OrganisationRecord> OrganisationRecords;
    vector<HRRecord> HRRecords;
    vector<PayrollRecord> PayrollRecords;
public:
    void loadOrganisationRecords(string filename);
    void loadHRRecords(string filename);
    void loadPayrollRecords(string filename);
    void displayEmployeeOfSalaryGTE(double salary);
    //GTE = greater than or equal to
};

void PayrollProcessing::loadOrganisationRecords(string filename)
{
    inputfile.open(ORGANISATIONALRECORDSFILE);

    if (!inputfile)
    {
        cout << "the organisation records file does not exist" << endl;
        return;
    }

        OrganisationRecord _organisationrecord;
        int employeenumber;

        while (inputfile >> employeenumber)
        {
            while (inputfile >> _organisationrecord.name)
            {
                cout << _organisationrecord.name;
                cout << _organisationrecord.occupation;
                cout << _organisationrecord.department <<endl;
            }

            OrganisationRecords.push_back(_organisationrecord);
        }

}

int main(void)
{
    PayrollProcessing database1;
    database1.loadOrganisationRecords(ORGANISATIONALRECORDSFILE);

    return 0;
}

organisation.txt

0001
Stephen Jones
Sales Clerk
Sales
0002
John Smith
Programmer
OS Development
0003
Fred Blogs
Project Manager
Outsourcing

Body:
Here is an approach that will work without any error checking on the input.  Like others have said, you need to read in the file line by line using std::getline() because just feeding directly into your variables will cause the input parsing to be delimited by spaces in the text, as opposed to the whole line.

OrganisationRecord _organisationrecord;
std::string employeeNumberStr;
int employeenumber;

// without any robust error checking...
while (std::getline(inputfile, employeeNumberStr))
{
    // store employee number string as an integer
    std::stringstream ss;
    ss << employeeNumberStr;
    ss >> employeenumber;

    std::getline(inputfile, _organisationrecord.name);
    std::getline(inputfile, _organisationrecord.occupation);
    std::getline(inputfile, _organisationrecord.department);

    // debug print results
    std::cout << "id number: " << employeenumber << std::endl;
    std::cout << "name: " << _organisationrecord.name << std::endl;
    std::cout << "occupation: " << _organisationrecord.occupation << std::endl;
    std::cout << "department: " << _organisationrecord.department << std::endl;

    OrganisationRecords.push_back(_organisationrecord);
}


问:
How to get windows explorer full path of opened outlook MSG file?
This question is related to outlook add-in.

I have one MSG file in my file system. lets start with example.

one msg file is located in @"d:\MSG Files\MailItemSubject.msg".

When I open that msg file in the windows explorer, my office plug-in will
be started with outlook application. I register my event handler for
Outlook.Application.Inspectors.NewInspector. And try to get the full path of
the msg file in the handler function.

I want to know where this message file comes.
But I have no idea about how to get the full path.

Does anyone meet the same problem?
Does anyone have any idea about it?
How to get windows explorer full path?

答: That information is not exposed through any API. More than that, Outlook creates a temporary message in the default message store and creates a copy of the MSG file there.</p>