问:
Reshape ndarray in batches for RNN
targets start from 2 . From given array we took input and target is its next element.Due to shape only till 12 input is coming.I need to reshape the input to array of shape(no of batches,2,2,3) where no of batches is len(text)//(2*2*3) so the no of inputs will be input[:no of batches*2*2*3]
    convert this [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] into

```<code>    [
      # First Batch
      [
        # Batch of Input
        [[ 1  2  3], [ 7  8  9]],
        # Batch of targets
        [[ 2  3  4], [ 8  9 10]]
      ],

      # Second Batch
      [
        # Batch of Input
        [[ 4  5  6], [10 11 12]],
        # Batch of targets
        [[ 5  6  7], [11 12 13]]
      ]
    ]
</code>```

targets start from 2 . From given array we took input and target is its next element.Due to shape only till 12 input is coming.I need to reshape the input to array of shape(no of batches,2,2,3) where no of batches is len(text)//(2*2*3) so the no of inputs will be input[:no of batches*2*2*3]

Title: Reshape ndarray in batches for RNN

Body:
targets start from 2 . From given array we took input and target is its next element.Due to shape only till 12 input is coming.I need to reshape the input to array of shape(no of batches,2,2,3) where no of batches is len(text)//(2*2*3) so the no of inputs will be input[:no of batches*2*2*3]
    convert this [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] into

    [
      # First Batch
      [
        # Batch of Input
        [[ 1  2  3], [ 7  8  9]],
        # Batch of targets
        [[ 2  3  4], [ 8  9 10]]
      ],

      # Second Batch
      [
        # Batch of Input
        [[ 4  5  6], [10 11 12]],
        # Batch of targets
        [[ 5  6  7], [11 12 13]]
      ]
    ]

targets start from 2 . From given array we took input and target is its next element.Due to shape only till 12 input is coming.I need to reshape the input to array of shape(no of batches,2,2,3) where no of batches is len(text)//(2*2*3) so the no of inputs will be input[:no of batches*2*2*3]

Body:
you can use strides

link1

link2

from numpy.lib.stride_tricks import as_strided as strided

a = np.arange(1, 16)
a

array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15])

s = a.strides[0]
strided(a, (2, 2, 2, 3), (s * 3, s, s * 6, s))

array([[[[ 1,  2,  3],
         [ 7,  8,  9]],

        [[ 2,  3,  4],
         [ 8,  9, 10]]],

       [[[ 4,  5,  6],
         [10, 11, 12]],

        [[ 5,  6,  7],
         [11, 12, 13]]]])


来源: stackexchange

问:
iPhone Admob UITableView troubles
I am sure this is a simple fix, but I can't seem to find it.  I have a table view that currently works just fine, set up as:

```<code>static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}

NSUInteger row = [indexPath row];
cell.textLabel.text = [creedsList objectAtIndex:row];
cell.imageView.image = [UIImage imageNamed:[creedsImages objectAtIndex:row]];

return cell;
</code>```

The Admob SDK says to add this line:

```<code>[cell.contentView addSubview:[AdMobView requestAdWithDelegate:self]];
</code>```

But then it populates EVERY cell with ads.  Any thoughts?

EDIT:
I am using this code to populate:

```<code>NSUInteger row = [indexPath row];
cell.textLabel.text = [creedsList objectAtIndex:row];
</code>```

答:
You want to do that on only the particular rows you want the ads to show up in.

So if you wanted to show up only on the first row, you could do something like

```<code>static int adTag = 999; // Used for identifying whether cell already contains ad
UIView * adView = [cell.contentView viewWithTag:adTag];

if(row == 0 && !adView)
{
    adView = [AdMobView requestAdWithDelegate:self];
    adView.tag = adTag;
    [cell.contentView addSubview:adView];
}
else if(row != 0 && adView)
{
    // Must remove since cells are reused.
    [adView removeFromSuperview];
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: iPhone Admob UITableView troubles

Body:
I am sure this is a simple fix, but I can't seem to find it.  I have a table view that currently works just fine, set up as:

static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}

NSUInteger row = [indexPath row];
cell.textLabel.text = [creedsList objectAtIndex:row];
cell.imageView.image = [UIImage imageNamed:[creedsImages objectAtIndex:row]];

return cell;

The Admob SDK says to add this line:

[cell.contentView addSubview:[AdMobView requestAdWithDelegate:self]];

But then it populates EVERY cell with ads.  Any thoughts?

EDIT:
I am using this code to populate:

NSUInteger row = [indexPath row];
cell.textLabel.text = [creedsList objectAtIndex:row];

Body:
You want to do that on only the particular rows you want the ads to show up in.

So if you wanted to show up only on the first row, you could do something like

static int adTag = 999; // Used for identifying whether cell already contains ad
UIView * adView = [cell.contentView viewWithTag:adTag];

if(row == 0 && !adView)
{
    adView = [AdMobView requestAdWithDelegate:self];
    adView.tag = adTag;
    [cell.contentView addSubview:adView];
}
else if(row != 0 && adView)
{
    // Must remove since cells are reused.
    [adView removeFromSuperview];
}


问:
VBA - Excel Copy and paste range with criteria
I want to copy a range in Sheet1 range A1:A100 where in the each cells filled with value like "Animal", "Plant", "Rock", and "Sand". Then, I want paste in Sheet2 range B1:B100 with conditions if the value at Range A1:A100 is "Animal" paste with "1", if the value is "Plant" paste with "2", ect.

How I write the VBA code? With simple and reducing memory usage.
My code :

```<code>Sub copyrange()
    Dim i           As Long
    Dim lRw         As Long
    Dim lRw_2       As Long

    Application.ScreenUpdating = False
    lRw = Sheet1.Cells(Rows.Count, "A").End(xlUp).Row
    ThisWorkbook.Sheets("Sheet1").Activate

    For i = 1 To lRw
        Range("A" & i).Copy
        lRw_2 = Sheets("Sheet2").Cells(Rows.Count, "B").End(xlUp).Row + 1
        Sheets("Sheet1").Activate
        'I not sure for this one, the code is too long
            Select Case ThisWorkbook.Sheets("sheet1").Range("A" & i).Value
            Case "Animal"
            With Sheets("Sheet2").Range("B" & lRw_2)
            .Value = 1
            End With
            Case "Plant"
            With Sheets("Sheet2").Range("B" & lRw_2)
            .Value = 2
            End With
            Case "Rock"
            With Sheets("Sheet2").Range("B" & lRw_2)
            .Value = 3
            End With
            Case "Sand"
            With Sheets("Sheet2").Range("B" & lRw_2)
            .Value = 4
            End With
            End Select
        Sheets("Sheet1").Activate
    Next i
    Application.ScreenUpdating = True
End Sub
</code>```

Thanks in advance.

答:
Try this:</p>

```<code>Option Explicit

Public Sub replaceItems()
    Application.ScreenUpdating = False
    With Sheets(2).Range("B1:B100")
        .Value2 = Sheets(1).Range("A1:A100").Value2
        .Replace What:="Animal", Replacement:=1, LookAt:=xlWhole
        .Replace What:="Plant", Replacement:=2, LookAt:=xlWhole
        .Replace What:="Rock", Replacement:=3, LookAt:=xlWhole
        .Replace What:="Sand", Replacement:=4, LookAt:=xlWhole
    End With
    Application.ScreenUpdating = True
End Sub
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to copy a range in Sheet1 range A1:A100 where in the each cells filled with value like "Animal", "Plant", "Rock", and "Sand". Then, I want paste in Sheet2 range B1:B100 with conditions if the value at Range A1:A100 is "Animal" paste with "1", if the value is "Plant" paste with "2", ect.

How I write the VBA code? With simple and reducing memory usage.
My code :

Sub copyrange()
    Dim i           As Long
    Dim lRw         As Long
    Dim lRw_2       As Long

    Application.ScreenUpdating = False
    lRw = Sheet1.Cells(Rows.Count, "A").End(xlUp).Row
    ThisWorkbook.Sheets("Sheet1").Activate

    For i = 1 To lRw
        Range("A" & i).Copy
        lRw_2 = Sheets("Sheet2").Cells(Rows.Count, "B").End(xlUp).Row + 1
        Sheets("Sheet1").Activate
        'I not sure for this one, the code is too long
            Select Case ThisWorkbook.Sheets("sheet1").Range("A" & i).Value
            Case "Animal"
            With Sheets("Sheet2").Range("B" & lRw_2)
            .Value = 1
            End With
            Case "Plant"
            With Sheets("Sheet2").Range("B" & lRw_2)
            .Value = 2
            End With
            Case "Rock"
            With Sheets("Sheet2").Range("B" & lRw_2)
            .Value = 3
            End With
            Case "Sand"
            With Sheets("Sheet2").Range("B" & lRw_2)
            .Value = 4
            End With
            End Select
        Sheets("Sheet1").Activate
    Next i
    Application.ScreenUpdating = True
End Sub

Thanks in advance.

Body:
Try this:

Option Explicit

Public Sub replaceItems()
    Application.ScreenUpdating = False
    With Sheets(2).Range("B1:B100")
        .Value2 = Sheets(1).Range("A1:A100").Value2
        .Replace What:="Animal", Replacement:=1, LookAt:=xlWhole
        .Replace What:="Plant", Replacement:=2, LookAt:=xlWhole
        .Replace What:="Rock", Replacement:=3, LookAt:=xlWhole
        .Replace What:="Sand", Replacement:=4, LookAt:=xlWhole
    End With
    Application.ScreenUpdating = True
End Sub


问:
Replacing character string with another character string
I have a data frame for which I am attempting to replace certain values with others. So, as a small example, I have a dummy data frame of:

```<code>dummy<-c("1","2","3","4")
dummy<-data.frame(dummy)
dummy$dummy<-as.character(dummy$dummy)

odd<-c("1","3")

replace(dummy$dummy, dummy$dummy==odd, "odd")

#> [1] "odd" "2"   "3"   "4"
</code>```

Why would this only replace "1" with "odd" and not "3"?

My actual dataset has more information in it (it is restaurant cuisine types and I need to replace the types of cuisine by a more general category. For example, I have the cuisine types "Italian" and "French" in my dataset that need to be replaced with "European", and cuisine types "Southwestern" and "Pacific Northwestern" that need to be replaced with "American".

Is the above idea the most efficient way to do this?

答:
We can do this in base R

```<code>levels(df$dummy)[levels(df$dummy) %in% c(1, 3)] <- "odd"
df
#  dummy
#1   odd
#2     2
#3   odd
#4     4
</code>```

data

```<code>df <- data.frame(dummy = c("1","2","3","4"))
</code>```

Body:
I have a data frame for which I am attempting to replace certain values with others. So, as a small example, I have a dummy data frame of:

dummy<-c("1","2","3","4")
dummy<-data.frame(dummy)
dummy$dummy<-as.character(dummy$dummy)

odd<-c("1","3")

replace(dummy$dummy, dummy$dummy==odd, "odd")

#> [1] "odd" "2"   "3"   "4"

Why would this only replace "1" with "odd" and not "3"?

My actual dataset has more information in it (it is restaurant cuisine types and I need to replace the types of cuisine by a more general category. For example, I have the cuisine types "Italian" and "French" in my dataset that need to be replaced with "European", and cuisine types "Southwestern" and "Pacific Northwestern" that need to be replaced with "American".

Is the above idea the most efficient way to do this?

Body:
We can do this in base R

levels(df$dummy)[levels(df$dummy) %in% c(1, 3)] <- "odd"
df
#  dummy
#1   odd
#2     2
#3   odd
#4     4

data

df <- data.frame(dummy = c("1","2","3","4"))


问:
Vertically centre variable-height divs within fullscreen wrapper
The wrapper is 1170px wide - variable/full-screen height
Child divs are % width - variable in height (though i've specified px in the jsfiddle)

I've used the table(parent)/table-cell(child) method and that doesn't work.
Margin 0 Auto also doesn't seem to do anything - I'm not sure if it has anything to do with the relative position attribute of the child divs...

https://jsfiddle.net/x3cm32my/

```<code>.wrap {
  background: grey;
  margin-left: auto;
  margin-right: auto;
  width: 1170px;
  min-height: 100vh;
  vertical-align: middle;
  text-align: left;
  display: table;
}

.mod-left {
  background: blue;
  margin:0 auto;
  width: 30%;
  height: 100px;
  float: left;
  vertical-align: middle;
  position: relative;
  display: table-cell;
}

.mod-right {
  background: green;
  margin:0 auto;
  width: 65%;
  float: right;
  display: table-cell;
  vertical-align: middle;
  text-align: center;
  height: 150px;
  position: relative;
}
</code>```

Would appreciate any tips!

答:
What about trying flexbox? To center your content use the following:</p>

```<code>.wrap { background: grey; margin-left: auto; margin-right: auto; width: 1170px; min-height: 100vh; text-align: left; display: flex; justify-content: center; align-items: center;}
</code>```

Body:
The wrapper is 1170px wide - variable/full-screen height
Child divs are % width - variable in height (though i've specified px in the jsfiddle)

I've used the table(parent)/table-cell(child) method and that doesn't work.
Margin 0 Auto also doesn't seem to do anything - I'm not sure if it has anything to do with the relative position attribute of the child divs...

https://jsfiddle.net/x3cm32my/

.wrap {
  background: grey;
  margin-left: auto;
  margin-right: auto;
  width: 1170px;
  min-height: 100vh;
  vertical-align: middle;
  text-align: left;
  display: table;
}

.mod-left {
  background: blue;
  margin:0 auto;
  width: 30%;
  height: 100px;
  float: left;
  vertical-align: middle;
  position: relative;
  display: table-cell;
}

.mod-right {
  background: green;
  margin:0 auto;
  width: 65%;
  float: right;
  display: table-cell;
  vertical-align: middle;
  text-align: center;
  height: 150px;
  position: relative;
}

Would appreciate any tips!

Body:
What about trying flexbox? To center your content use the following:

.wrap { background: grey; margin-left: auto; margin-right: auto; width: 1170px; min-height: 100vh; text-align: left; display: flex; justify-content: center; align-items: center;}


问:
Create and parse multipart HTTP requests in Python
I'm trying to write some python code which can create multipart mime http requests in the client, and then appropriately interpret then on the server.  I have, I think, partially succeeded on the client end with this:

```<code>from email.mime.multipart import MIMEMultipart, MIMEBase
import httplib
h1 = httplib.HTTPConnection('localhost:8080')
msg = MIMEMultipart()
fp = open('myfile.zip', 'rb')
base = MIMEBase("application", "octet-stream")
base.set_payload(fp.read())
msg.attach(base)
h1.request("POST", "http://localhost:8080/server", msg.as_string())
</code>```

The only problem with this is that the email library also includes the Content-Type and MIME-Version headers, and I'm not sure how they're going to be related to the HTTP headers included by httplib:

```<code>Content-Type: multipart/mixed; boundary="===============2050792481=="
MIME-Version: 1.0

--===============2050792481==
Content-Type: application/octet-stream
MIME-Version: 1.0
</code>```

This may be the reason that when this request is received by my web.py application, I just get an error message.  The web.py POST handler:

```<code>class MultipartServer:
    def POST(self, collection):
        print web.input()
</code>```

Throws this error:

```<code>Traceback (most recent call last):
  File "/usr/local/lib/python2.6/dist-packages/web.py-0.34-py2.6.egg/web/application.py", line 242, in process
    return self.handle()
  File "/usr/local/lib/python2.6/dist-packages/web.py-0.34-py2.6.egg/web/application.py", line 233, in handle
    return self._delegate(fn, self.fvars, args)
  File "/usr/local/lib/python2.6/dist-packages/web.py-0.34-py2.6.egg/web/application.py", line 415, in _delegate
    return handle_class(cls)
  File "/usr/local/lib/python2.6/dist-packages/web.py-0.34-py2.6.egg/web/application.py", line 390, in handle_class
    return tocall(*args)
  File "/home/richard/Development/server/webservice.py", line 31, in POST
    print web.input()
  File "/usr/local/lib/python2.6/dist-packages/web.py-0.34-py2.6.egg/web/webapi.py", line 279, in input
    return storify(out, *requireds, **defaults)
  File "/usr/local/lib/python2.6/dist-packages/web.py-0.34-py2.6.egg/web/utils.py", line 150, in storify
    value = getvalue(value)
  File "/usr/local/lib/python2.6/dist-packages/web.py-0.34-py2.6.egg/web/utils.py", line 139, in getvalue
    return unicodify(x)
  File "/usr/local/lib/python2.6/dist-packages/web.py-0.34-py2.6.egg/web/utils.py", line 130, in unicodify
    if _unicode and isinstance(s, str): return safeunicode(s)
  File "/usr/local/lib/python2.6/dist-packages/web.py-0.34-py2.6.egg/web/utils.py", line 326, in safeunicode
    return obj.decode(encoding)
  File "/usr/lib/python2.6/encodings/utf_8.py", line 16, in decode
    return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode bytes in position 137-138: invalid data
</code>```

My line of code is represented by the error line about half way down:

```<code>  File "/home/richard/Development/server/webservice.py", line 31, in POST
    print web.input()
</code>```

It's coming along, but I'm not sure where to go from here.  Is this a problem with my client code, or a limitation of web.py (perhaps it just can't support multipart requests)?  Any hints or suggestions of alternative code libraries would be gratefully received.

EDIT

The error above was caused by the data not being automatically base64 encoded.  Adding

```<code>encoders.encode_base64(base)
</code>```

Gets rid of this error, and now the problem is clear.  HTTP request isn't being interpreted correctly in the server, presumably because the email library is including what should be the HTTP headers in the body instead:

```<code><Storage {'Content-Type: multipart/mixed': u'',
          ' boundary': u'"===============1342637378=="\n'
          'MIME-Version: 1.0\n\n--===============1342637378==\n'
          'Content-Type: application/octet-stream\n'
          'MIME-Version: 1.0\n'
          'Content-Transfer-Encoding: base64\n'
          '\n0fINCs PBk1jAAAAAAAAA.... etc
</code>```

So something is not right there.

Thanks

Richard

答: I used this package by Will Holcomb http://pypi.python.org/pypi/MultipartPostHandler/0.1.0 to make multi-part requests with urllib2, it may help you out.</p>

Body:
I'm trying to write some python code which can create multipart mime http requests in the client, and then appropriately interpret then on the server.  I have, I think, partially succeeded on the client end with this:

from email.mime.multipart import MIMEMultipart, MIMEBase
import httplib
h1 = httplib.HTTPConnection('localhost:8080')
msg = MIMEMultipart()
fp = open('myfile.zip', 'rb')
base = MIMEBase("application", "octet-stream")
base.set_payload(fp.read())
msg.attach(base)
h1.request("POST", "http://localhost:8080/server", msg.as_string())

The only problem with this is that the email library also includes the Content-Type and MIME-Version headers, and I'm not sure how they're going to be related to the HTTP headers included by httplib:

Content-Type: multipart/mixed; boundary="===============2050792481=="
MIME-Version: 1.0

--===============2050792481==
Content-Type: application/octet-stream
MIME-Version: 1.0

This may be the reason that when this request is received by my web.py application, I just get an error message.  The web.py POST handler:

class MultipartServer:
    def POST(self, collection):
        print web.input()

Throws this error:

Traceback (most recent call last):
  File "/usr/local/lib/python2.6/dist-packages/web.py-0.34-py2.6.egg/web/application.py", line 242, in process
    return self.handle()
  File "/usr/local/lib/python2.6/dist-packages/web.py-0.34-py2.6.egg/web/application.py", line 233, in handle
    return self._delegate(fn, self.fvars, args)
  File "/usr/local/lib/python2.6/dist-packages/web.py-0.34-py2.6.egg/web/application.py", line 415, in _delegate
    return handle_class(cls)
  File "/usr/local/lib/python2.6/dist-packages/web.py-0.34-py2.6.egg/web/application.py", line 390, in handle_class
    return tocall(*args)
  File "/home/richard/Development/server/webservice.py", line 31, in POST
    print web.input()
  File "/usr/local/lib/python2.6/dist-packages/web.py-0.34-py2.6.egg/web/webapi.py", line 279, in input
    return storify(out, *requireds, **defaults)
  File "/usr/local/lib/python2.6/dist-packages/web.py-0.34-py2.6.egg/web/utils.py", line 150, in storify
    value = getvalue(value)
  File "/usr/local/lib/python2.6/dist-packages/web.py-0.34-py2.6.egg/web/utils.py", line 139, in getvalue
    return unicodify(x)
  File "/usr/local/lib/python2.6/dist-packages/web.py-0.34-py2.6.egg/web/utils.py", line 130, in unicodify
    if _unicode and isinstance(s, str): return safeunicode(s)
  File "/usr/local/lib/python2.6/dist-packages/web.py-0.34-py2.6.egg/web/utils.py", line 326, in safeunicode
    return obj.decode(encoding)
  File "/usr/lib/python2.6/encodings/utf_8.py", line 16, in decode
    return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode bytes in position 137-138: invalid data

My line of code is represented by the error line about half way down:

  File "/home/richard/Development/server/webservice.py", line 31, in POST
    print web.input()

It's coming along, but I'm not sure where to go from here.  Is this a problem with my client code, or a limitation of web.py (perhaps it just can't support multipart requests)?  Any hints or suggestions of alternative code libraries would be gratefully received.

EDIT

The error above was caused by the data not being automatically base64 encoded.  Adding

encoders.encode_base64(base)

Gets rid of this error, and now the problem is clear.  HTTP request isn't being interpreted correctly in the server, presumably because the email library is including what should be the HTTP headers in the body instead:

<Storage {'Content-Type: multipart/mixed': u'',
          ' boundary': u'"===============1342637378=="\n'
          'MIME-Version: 1.0\n\n--===============1342637378==\n'
          'Content-Type: application/octet-stream\n'
          'MIME-Version: 1.0\n'
          'Content-Transfer-Encoding: base64\n'
          '\n0fINCs PBk1jAAAAAAAAA.... etc

So something is not right there.

Thanks

Richard


问:
Adding Number by javascript
```<code><html>
<head>
<title>JavaScript - using function</title>
<script>
function add(){
var value1=document.getElementById("n1").value;
var value2=document.getElementById("n2").value;
document.getElementById("result").value=parseFloat(value1)+parseFloat(value2);
}
</script>
</head>
<body>
<label>First Number:<input type="number" id="n1"/></label>
<label>Second Number:<input type="number" id="n2"/></label>
<input type="button" value="Add" onClick="add()" />
<p>
Result = <span id="result" ></span>
</p>
</body>
</html>
</code>```

I am new to JavaScript and wanted to create a script that add numbers up. After pressing "Add" button, I cannot get the result to be displayed. How to get the result displayed?

答:
Its better to put the js at the end of the document - also as noted the onclick handler needs to call the function. I also tidied up the code a little.

<title>JavaScript - using function</title>

  First Number:<input type="number" id="n1"/>
  Second Number:<input type="number" id="n2"/>
  <input type="button" value="Add" onclick="add()">

Result =

```

Title: Adding Number by javascript

Body:
<title>JavaScript - using function</title>

First Number:<input type="number" id="n1"/>
Second Number:<input type="number" id="n2"/>
<input type="button" value="Add" onClick="add()" />

Result =

I am new to JavaScript and wanted to create a script that add numbers up. After pressing "Add" button, I cannot get the result to be displayed. How to get the result displayed?

Body:
Its better to put the js at the end of the document - also as noted the onclick handler needs to call the function. I also tidied up the code a little.

<html>
<head>
<title>JavaScript - using function</title>
<style>label{display:block}</style>
</head>
<body>
  <label>First Number:<input type="number" id="n1"/></label>
  <label>Second Number:<input type="number" id="n2"/></label>
  <input type="button" value="Add" onclick="add()">
  <p>Result = <span id="result" ></span></p>

<script>
function add(){
  var value1=parseFloat(document.getElementById("n1").value);
  var value2=parseFloat(document.getElementById("n2").value);
  var total= value1 + value2;
  document.getElementById("result").innerText=total;
}
</script>

</body>
</html>


问:
How do I find HTML elements without IDs, by searching for them by other arbitrary identifiers?
Basically, I'm trying to find this element in a HTML doc. Not sure how to go about doing this, as there's no ID and I'm relatively new to DOM stuff. Anyone got any idea how to find the text of this ? </p>

```<code><strong ng-bind-html="gamePin"
       data-functional-selector="game-pin"
       class="ng-binding">6969696</strong>
</code>```

答:
You can use tag name and attribute selectors, document.querySelector() or document.querySelectorAll()

```<code>let el = document.querySelectorAll("strong[data-functional-selector='game-pin']");
</code>```

```<code>let selector = "strong[ng-bind-html='gamePin'][data-functional-selector='game-pin'][class='ng-binding']";
let el = document.querySelector(selector);
</code>```

Body:
Basically, I'm trying to find this element in a HTML doc. Not sure how to go about doing this, as there's no ID and I'm relatively new to DOM stuff. Anyone got any idea how to find the text of this ?

6969696

Body:
You can use tag name and attribute selectors, document.querySelector() or document.querySelectorAll()

let el = document.querySelectorAll("strong[data-functional-selector='game-pin']");

let selector = "strong[ng-bind-html='gamePin'][data-functional-selector='game-pin'][class='ng-binding']";
let el = document.querySelector(selector);


问:
Apache Zeppelin - How to use Helium framework in Apache Zeppelin
From Zeppelin-0.7, Zeppelin started supporting Helium plugins/packages using Helium Framework. However, I am not able to view any of the plugin on Helium page (localhost:8080/#/helium). As per this JIRA, I placed sample Helium.json (available on s3) under /local-repo/helium-registry-cache. However, after that I got NPE while restarting Apache Zeppelin service.

I have tried Zeppelin 0.7 as well as Zeppelin 0.8.0 snaptshot versions. In particular, I want to use map Helium package - Helium-Map in Zeppelin note.

Can some one point me to any guide or documentation having detailed steps of using Helium package in Zeppelin? Any help would be greatly appreciated!

答:
Zeppelin 0.7.x

Zeppelin 0.7.x doesn't support the online registry. In other words,
 Zeppelin doesn't use helium.json. So you need to install each package by yourself.

clone the helium package what you want to install

modify the artifact value to the absolute path considering your local machine in helium-xxx.json

copy zeppelin-xxx.json into the $ZEPPELIN_HOME/helium directory (create if it doesn't exist yet)

restart Zeppelin and go to the localhost:8080/#/helium page, then install the package.

Zeppelin 0.8.0-SNAPSHOT

Zeppelin 0.8.0-SNAPSHOT supports the online registry. So you can install without any preparation.

But the NPE problem you've faced was fixed after https://github.com/apache/zeppelin/pull/2380.

So please git pull origin master and rebuild it :)

FYI, Now Zeppelin provides proxy functionality for helium. Refer https://github.com/apache/zeppelin/pull/2363


答:
The following code should work.</p>

```<code>$( "div:contains('6969696')" )
</code>```

Title: How do I find HTML elements without IDs, by searching for them by other arbitrary identifiers?

Body:
The following code should work.

$( "div:contains('6969696')" )


问:
How to group documents by hour in elasticsearch?
I have my documents indexed in different times. Now I need to group these documents by per hour of day.That is the buckets after aggregation should show ranges from 00 to 23. is this kind of sorting possible in elasticsearch?</p>

答:
Probably late to the party, but this kind of aggregation is not directly possible using Elasticsearch. There are couple of workarounds though:

You can store the hour field as a separate field at the time of indexing.

You can use the histogram provided by Elasticsearch and merge the results in application code.

You could use the script as suggested by @Heschoon. (One wrinkle is if this is in prod, you might have disabled inline scripts, so you can't directly do this in query. Instead you will need to add a script)


问:
Are disk sector writes atomic?
Clarified Question:

When the OS sends the command to write a sector to disk is it atomic? i.e. Write of new data succeeds fully or old data is left intact should the power fail immediately following the write command. I don't care about what happens in multiple sector writes - torn pages are acceptable.

Old Question:

Say you have old data X on disk, you write new data Y over it, and a tree falls on the power line during that write. With no fancy UPS or battery backed disk controller, you can end up with a torn page, where the data on disk is part X and part Y. Can you ever end up with a situation where the data on disk is part X, part Y, and part garbage?

I've been trying to understand the design of ACID systems like databases, and to my naive thinking, it seems firebird, which does not use a write-ahead log, is relying that a given write will not destroy old data (X) - only fail to fully write new data (Y). That means that if part of X is being overwritten, only the part of X that is being overwritten can be changed, not the part of X we intend to keep.

To clarify, this means if you have a page sized buffer, say 4096 bytes, filled with half Y, half X that we want to keep - and we tell the OS to write that buffer over X, there is no situation short of serious disk failure where the half X that we want to keep is corrupted during the write.

答:
when updating the
disk, the only guarantee drive manufactures make is that a single 512-
byte write is atomic (i.e., it will either complete in its entirety or it won’t
complete at all); thus, if an untimely power loss occurs, only a portion of
a larger write may complete (sometimes called a torn write).</p>

ContentLicense: CC BY-SA 4.0

Title: Are disk sector writes atomic?


问:
Passing specified parameters in route file to the controller in laravel
In laravel routes file I have written this :

```<code>Route::get('/{lang}/{page}', 'PagesController@get' )->where('lang' , $langPattern );
</code>```

and in pages controller I wrote this :

```<code>public function get($lang,$page)
{
     // do something
}
</code>```

But I want only to use page parameter

I created a middleware to select language and there is no need for $lang in controllers

How can I remove it ?

Can I write like this :

```<code>public function get($page)
{
     // do something
}
</code>```

My language middleware :

```<code>public function handle($request, Closure $next )
{
    // URL language
    $urllang = $request->segment(1);

    if ($request->session()->has("lang")){
        $sessionLang = $request->session()->get('lang');

        // if requested url hasn't language
        if ($urllang == NULL) {
            $urllang = $sessionLang;
            return redirect('/' . $sessionLang);
        }

        // if user change the language
        elseif ($urllang != NULL && $urllang != $sessionLang) {
            $request->session()->put('lang' , $urllang);
        }
    }
    else{
        // if there is no session lang and no url lang
        // get app main lang from config file
        // Put session and redirect
        if ($urllang == NULL) {
            $request->session()->put('lang' , config('app.locale'));
            return redirect('/' . config('app.locale'));
        }
        // if there is no session
        // Only put session
        else{
            $request->session()->put('lang' , $urllang);
        }
    }

    // get requested language id from database
    $lang = Lang::select("id" , "short" , "name" , "title" , "keywords" , "description" , "copyrights" , "site_name")->where( ['short' => $urllang , 'active' => 1 ])->first();
    // if requested language is not exist
    if (!$lang) {
        $request->session()->put('lang' , config('app.locale'));
        abort(404);
    }else{
        Lang::set($lang);
        return $next($request);
    }

}
</code>```

Thanks .

答:
You can opt out of using arguments as parameters and get only the necessary ones from the request:</p>

```<code>public function get(Request $request)
{
    $lang = $request->route('lang');
    $page = $request->route('page');
    // ...
}
</code>```

Body:
In laravel routes file I have written this :

Route::get('/{lang}/{page}', 'PagesController@get' )->where('lang' , $langPattern );

and in pages controller I wrote this :

public function get($lang,$page)
{
     // do something
}

But I want only to use page parameter

I created a middleware to select language and there is no need for $lang in controllers

How can I remove it ?

Can I write like this :

public function get($page)
{
     // do something
}

My language middleware :

public function handle($request, Closure $next )
{
    // URL language
    $urllang = $request->segment(1);

    if ($request->session()->has("lang")){
        $sessionLang = $request->session()->get('lang');

        // if requested url hasn't language
        if ($urllang == NULL) {
            $urllang = $sessionLang;
            return redirect('/' . $sessionLang);
        }

        // if user change the language
        elseif ($urllang != NULL && $urllang != $sessionLang) {
            $request->session()->put('lang' , $urllang);
        }
    }
    else{
        // if there is no session lang and no url lang
        // get app main lang from config file
        // Put session and redirect
        if ($urllang == NULL) {
            $request->session()->put('lang' , config('app.locale'));
            return redirect('/' . config('app.locale'));
        }
        // if there is no session
        // Only put session
        else{
            $request->session()->put('lang' , $urllang);
        }
    }

    // get requested language id from database
    $lang = Lang::select("id" , "short" , "name" , "title" , "keywords" , "description" , "copyrights" , "site_name")->where( ['short' => $urllang , 'active' => 1 ])->first();
    // if requested language is not exist
    if (!$lang) {
        $request->session()->put('lang' , config('app.locale'));
        abort(404);
    }else{
        Lang::set($lang);
        return $next($request);
    }

}

Thanks .

Body:
You can opt out of using arguments as parameters and get only the necessary ones from the request:

public function get(Request $request)
{
    $lang = $request->route('lang');
    $page = $request->route('page');
    // ...
}


问:
W2UI: Click and other events of content loaded inside panels are not working
I'm using w2ui 1.5-rc1 layout components.
Attaching an event handler to an element inside a panel won't trigger the action:

Adele

Bella

Carl

```

<p>Clicking on the items <strong>Bella</strong> or <strong>Carl</strong> will never trigger the alert.
If I remove the w2ui layout then everything works.</p>

<pre class="lang-html prettyprint-override"><code><script>
    $(function() {
        $("#mylist li a").click(function() {
           alert( "Handler for .click() called." );
        });
    })
</script>
<div id="list-panel" >
    <ul id="mylist" class="list-group">
        <li><span>Adele</span></li>
        <li><span>Bella</span></li>
        <li><span>Carl</span></li>
    </ul>
</div>
</code>```

I noticed that the same happens when I try to add bootstrap components or any other content inside a panel. The click, change and other events on those components are never triggered.

Any idea why?

答:
As recommended by other users in w2ui github repository, attaching the events to the document element will work.</p>

```<code>$(document).on("click", "#mylist li a", function() {
   alert( "Handler for .click() called" );
});
</code>```

Body:
I'm using w2ui 1.5-rc1 layout components.
Attaching an event handler to an element inside a panel won't trigger the action:

Adele

Bella

Carl

Clicking on the items Bella or Carl will never trigger the alert.
If I remove the w2ui layout then everything works.

Adele

Bella

Carl

I noticed that the same happens when I try to add bootstrap components or any other content inside a panel. The click, change and other events on those components are never triggered.

Any idea why?

Body:
As recommended by other users in w2ui github repository, attaching the events to the document element will work.

$(document).on("click", "#mylist li a", function() {
   alert( "Handler for .click() called" );
});


问:
How to shrink logo size when scrolling down?
if you go to http://www.baycrest.org/b2btest/index2.html
When scrolling down, I want the logo to shrink and fit in to the white bar. Is this done using Javascript? Or just pure CSS? If you know of any templates, that would help greatly too. Thanks</p>

答:
You can use JQuery's on-scroll event to get the location of the scroll from top. Based on that you can apply different CSS classes to the logo and change its size dynamically.

```<code>$(window).on('scroll',function(event){
  console.log(event);
});
</code>```

Read more here.

Another cool library for nicely handling the page header on scroll events is Headroom.js. You should check it out.

Body:
You can use JQuery's on-scroll event to get the location of the scroll from top. Based on that you can apply different CSS classes to the logo and change its size dynamically.

$(window).on('scroll',function(event){
  console.log(event);
});

Read more here.

Another cool library for nicely handling the page header on scroll events is Headroom.js. You should check it out.


答:
You can use css transitions and javascript/jquery to achive the effect.On scroll event add a  new class to the header and add styles for the logo to shrink.A demo snippet for example.

$(document).on("scroll", function(){
  if
      ($(document).scrollTop() > 50){
        $("header").addClass("shrink");
    }
  else
  {
   $("header").removeClass("shrink");
  }
 });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>*{
margin:0px;
padding:0px;
}
.header{
  padding:20px;
  top: 0;
  position: fixed;
  -webkit-transition: all 0.5s ease-in-out;
  -moz-transition: all 0.5s ease-in-out ;
  transition:all 0.5s ease-in-out ;
  z-index:999;
  background:#FFF;
  width:100%;
  border-bottom:1px solid #ddd;
}
.header img{
    -webkit-transition: all 0.5s ease-in-out;
    -moz-transition: all 0.5s ease-in-out ;
     transition:all 0.5s ease-in-out ;
     width:75px;
     height:75px;
}

.shrink{
  padding:10px;
}

.shrink img{
   width:50px;
    height:50px;
}</code>```

Scroll down

   Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

   Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

   Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

   Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

   Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

   Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

```

Title: How to shrink logo size when scrolling down?

Body:
if you go to http://www.baycrest.org/b2btest/index2.html
When scrolling down, I want the logo to shrink and fit in to the white bar. Is this done using Javascript? Or just pure CSS? If you know of any templates, that would help greatly too. Thanks

Body:
You can use css transitions and javascript/jquery to achive the effect.On scroll event add a  new class to the header and add styles for the logo to shrink.A demo snippet for example.

$(document).on("scroll", function(){
  if
      ($(document).scrollTop() > 50){
        $("header").addClass("shrink");
    }
  else
  {
   $("header").removeClass("shrink");
  }
 });

*{
margin:0px;
padding:0px;
}
.header{
  padding:20px;
  top: 0;
  position: fixed;
  -webkit-transition: all 0.5s ease-in-out;
  -moz-transition: all 0.5s ease-in-out ;
  transition:all 0.5s ease-in-out ;
  z-index:999;
  background:#FFF;
  width:100%;
  border-bottom:1px solid #ddd;
}
.header img{
    -webkit-transition: all 0.5s ease-in-out;
    -moz-transition: all 0.5s ease-in-out ;
     transition:all 0.5s ease-in-out ;
     width:75px;
     height:75px;
}

.shrink{
  padding:10px;
}

.shrink img{
   width:50px;
    height:50px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header class="header">
  <img src="http://via.placeholder.com/350x150" title="logo">
</header>

<div class="container">
  <p><strong>Scroll down</strong></p>
  <p>
   Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
  </p>
    <p>
   Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
  </p>
    <p>
   Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
  </p>
    <p>
   Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
  </p>
    <p>
   Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
  </p>
    <p>
   Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
  </p>
</div>


问:
How to reset a form on JSP page?
I want to reset a form which will blank all input field and checkbox.
But here's my code doesn't work.

```<code><form id="rwdPromotionDetailsAdd">
     <input type="button" onclick="resetForm()" value="Reset form">
</form>

    <script>
            function resetForm() {
                        document.getElementById("rwdPromotionDetailsAdd").reset();
                    }
<script>
</code>```

How can i reset a form ? Any better suggestion ?

答:
You just need to insert this within a form

<input type="reset" value="Reset form">

Don't even have to attach a listener to it

Title: How to reset a form on JSP page?

Body:
I want to reset a form which will blank all input field and checkbox.
But here's my code doesn't work.

<form id="rwdPromotionDetailsAdd">
     <input type="button" onclick="resetForm()" value="Reset form">
</form>


问:
How to apply CSS changes in every posts (every posts ID)
I want to hide the side bar and stretch the content box to full width to all posts from my WP blog. To individual posts that's what I'm doing, and it's working fine:

```<code>.postid-72 #main-sidebar {
display: none;
}
.postid-72 #main-content {
width: 100%;
}
</code>```

But I'm looking for some way to apply this changes to all my blog posts, something hypothetical like this:

```<code>.postid-**every id posts** #main-sidebar {
display: none;
}
.postid-**every id posts** #main-content {
width: 100%;
}
</code>```

I know that is possible to do something like this, which isn't usefull for me:

```<code>.postid-72, .postid-53, .postid-115 #main-sidebar {
display: none;
}
</code>```

答:
If you want to just set this two css by using post id then you can set only this two css in your header.php file inside head section with passing dynamic ID something like this:

First of all get current post id with : $id = get_the_ID() then pass it in your css using,

```<code>.postid-<?php echo $id; ?> #main-sidebar {
display: none;
}
.postid-<?php echo $id; ?> #main-content {
width: 100%;
}
</code>```

Hope this will helpful for you.
Thanks.

Body:
I want to hide the side bar and stretch the content box to full width to all posts from my WP blog. To individual posts that's what I'm doing, and it's working fine:

.postid-72 #main-sidebar {
display: none;
}
.postid-72 #main-content {
width: 100%;
}

But I'm looking for some way to apply this changes to all my blog posts, something hypothetical like this:

.postid-**every id posts** #main-sidebar {
display: none;
}
.postid-**every id posts** #main-content {
width: 100%;
}

I know that is possible to do something like this, which isn't usefull for me:

.postid-72, .postid-53, .postid-115 #main-sidebar {
display: none;
}

Body:
If you want to just set this two css by using post id then you can set only this two css in your header.php file inside head section with passing dynamic ID something like this:

First of all get current post id with : $id = get_the_ID() then pass it in your css using,

.postid-<?php echo $id; ?> #main-sidebar {
display: none;
}
.postid-<?php echo $id; ?> #main-content {
width: 100%;
}

Hope this will helpful for you.
Thanks.


问:
Using target="_blank" in a php redirect. Where do i put it?
Good day stackoverflow. Thank you for your time.

I have this php

```<code>$ImageLinks['image.png'] = 'http://www.example.com/r/redirect.php';
</code>```

which redirects to the 'redirect.php' - which is the following

```<code><?php $URL="http://thetargetlinktobeopenedinnewtab.com";
header ("Location: $URL");
exit();
?>
</code>```

How can I make this $URL open in a new tab? I've tried placing the target="_blank" all over the place.

答:
target is an HTML attribute; it has nothing to do with PHP redirects.

What you're attempting to do isn't possible. The header you're returning will redirect the user but it can't open a new tab.

Body:
Good day stackoverflow. Thank you for your time.

I have this php

$ImageLinks['image.png'] = 'http://www.example.com/r/redirect.php';

which redirects to the 'redirect.php' - which is the following

<?php $URL="http://thetargetlinktobeopenedinnewtab.com";
header ("Location: $URL");
exit();
?>

How can I make this $URL open in a new tab? I've tried placing the target="_blank" all over the place.


问:
How do I pass this.props.children to Textarea
I am passing this.props.childred in textarea  using defaultValue but it is giving me Error
Uncaught Error: If you supply defaultValue on a , do not pass children.

what is the other alternative or is there a better way of bassing the values

```<code>import React, {Component} from 'react';

class Update extends Component {

    constructor(props){
        super(props);
        this.state = {
            editing:false
        }

        this.renderEdit = this.renderEdit.bind(this)
    }

    edit(){
        this.setState({
            editing:true
        })

    }
    remove(){
        alert("remove")
    }
    save(){
        this.setState({
            editing:false
        })
    }

    renderNormal(){
        return (
            <div className="container">

        <div className="content"> {this.props.children}</div>
        <button onClick={this.edit.bind(this)} className="edit" >Edit </button>
        <button onClick={this.remove} className="remove" >Remove </button>
        </div>
        );

    }
    renderEdit(){

        console.log( 'this.props ', this.props)

console.log( 'this.props.children ', this.props.children)

        return (
        <div className="container">

        <textarea ref="newText" defaultValue={this.props.children} > </textarea>
        <button onClick={this.save.bind(this)} className="edit" >Save </button>
        </div>
        );

    }

    render(){
        var great = "awesome "

        if(this.state.editing){
             return this.renderEdit();
        }else{
            return this.renderNormal();
        }

    }
}
export default Update;
</code>```

答:
Use self-closing syntax like this:

```<code><textarea ref="newText" defaultValue={this.props.children}/>
</code>```

Or actually, you can just remove the space between <textarea> tags as well.

Body:
I am passing this.props.childred in textarea  using defaultValue but it is giving me Error
Uncaught Error: If you supply defaultValue on a , do not pass children.

what is the other alternative or is there a better way of bassing the values

import React, {Component} from 'react';

class Update extends Component {

    constructor(props){
        super(props);
        this.state = {
            editing:false
        }

        this.renderEdit = this.renderEdit.bind(this)
    }

    edit(){
        this.setState({
            editing:true
        })

    }
    remove(){
        alert("remove")
    }
    save(){
        this.setState({
            editing:false
        })
    }

    renderNormal(){
        return (

 {this.props.children}

        <button onClick={this.edit.bind(this)} className="edit" >Edit </button>
        <button onClick={this.remove} className="remove" >Remove </button>

        );

    }
    renderEdit(){

        console.log( 'this.props ', this.props)

console.log( 'this.props.children ', this.props.children)

        return (

        <textarea ref="newText" defaultValue={this.props.children} > </textarea>
        <button onClick={this.save.bind(this)} className="edit" >Save </button>

        );

    }

    render(){
        var great = "awesome "

        if(this.state.editing){
             return this.renderEdit();
        }else{
            return this.renderNormal();
        }

    }
}
export default Update;

Body:
Use self-closing syntax like this:

<textarea ref="newText" defaultValue={this.props.children}/>

Or actually, you can just remove the space between <textarea> tags as well.


问:
Search activity not being launched when pressing enter
Search activity not being launched when pressing enter.The search view is shown nicely on the action bar. But when i type the search query and press enter

AndroidManifest.xml

```<code><?xml version="1.0" encoding="utf-8"?>
   <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.punit.rateit"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="11"
    android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET"/>

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme"

    >
    <activity
        android:name="com.punit.rateit.MainActivity"
        android:label="@string/app_name" >

        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:theme="@style/Theme.AppCompat.Light"
              android:name=".SearchPageActivity">
          <meta-data android:name="android.app.default_searchable" android:value=".SearchResultsActivity" />
      <intent-filter>
         <action android:name="android.intent.action.SearchPage" />
      </intent-filter>
    </activity>

   <activity android:name="com.punit.rateit.SearchResultsActivity"   android:launchMode="singleTop" >
  <intent-filter>
    <action android:name="android.intent.action.SEARCH" />
     <meta-data android:name="android.app.searchable"
               android:resource="@xml/searchable"/>
    </intent-filter>
   </activity>

    </application>

 </manifest>
</code>```

Here is the Menu.xml

```<code><menu xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:com.punit.rateit="http://schemas.android.com/apk/res-auto" >
<!-- Search, should appear as action button -->
<item android:id="@+id/search"
      android:icon="@drawable/ic_search"
      android:title="@string/action_search"
      com.punit.rateit:actionViewClass="android.widget.SearchView"
       com.punit.rateit:showAsAction="ifRoom"

       />

   </menu>
</code>```

The activity which shows action bar.

```<code>     public boolean onCreateOptionsMenu(Menu menu) {

     MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu,menu);
     SearchManager searchManager =
             (SearchManager) getSystemService(Context.SEARCH_SERVICE);

      SearchView searchView =
              (SearchView) menu.findItem(R.id.search).getActionView();

      searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
      searchView.setIconifiedByDefault(false);
      searchView.setSubmitButtonEnabled (true);
     return super.onCreateOptionsMenu(menu);
 }
</code>```

The SearchResult activity which should be the activity called when search submit button is pressed

```<code>public class SearchResultsActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.d("search", "search triggered");
    setContentView(R.layout.searchpage);

    handleIntent(getIntent());
}
@Override
protected void onNewIntent(Intent intent) {
    Log.d("search", "search triggered");
    setIntent(intent);
    handleIntent(intent);
}
private void handleIntent(Intent intent)
{
     if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
            String query = intent.getStringExtra(SearchManager.QUERY);
            Log.d("search", query);
}
  }

 @Override
 public boolean onSearchRequested() {

     Log.d("search", "search triggered");

     return false;  // don't go ahead and show the search box
 }
</code>```

答:
I was not using the strings within searchable.xml.

You MUST set it up that way or you will get null. I had just put in text instead of using @string.

```<code><?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
    android:label="@string/app_label"
    android:hint="@string/search_hint" >
</searchable>
</code>```

Body:
Search activity not being launched when pressing enter.The search view is shown nicely on the action bar. But when i type the search query and press enter

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
   <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.punit.rateit"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="11"
    android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET"/>

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme"

    >
    <activity
        android:name="com.punit.rateit.MainActivity"
        android:label="@string/app_name" >

        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:theme="@style/Theme.AppCompat.Light"
              android:name=".SearchPageActivity">
          <meta-data android:name="android.app.default_searchable" android:value=".SearchResultsActivity" />
      <intent-filter>
         <action android:name="android.intent.action.SearchPage" />
      </intent-filter>
    </activity>

   <activity android:name="com.punit.rateit.SearchResultsActivity"   android:launchMode="singleTop" >
  <intent-filter>
    <action android:name="android.intent.action.SEARCH" />
     <meta-data android:name="android.app.searchable"
               android:resource="@xml/searchable"/>
    </intent-filter>
   </activity>

    </application>

 </manifest>

Here is the Menu.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:com.punit.rateit="http://schemas.android.com/apk/res-auto" >

<item android:id="@+id/search"
      android:icon="@drawable/ic_search"
      android:title="@string/action_search"
      com.punit.rateit:actionViewClass="android.widget.SearchView"
       com.punit.rateit:showAsAction="ifRoom"

       />

   </menu>

The activity which shows action bar.

     public boolean onCreateOptionsMenu(Menu menu) {

     MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu,menu);
     SearchManager searchManager =
             (SearchManager) getSystemService(Context.SEARCH_SERVICE);

      SearchView searchView =
              (SearchView) menu.findItem(R.id.search).getActionView();

      searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
      searchView.setIconifiedByDefault(false);
      searchView.setSubmitButtonEnabled (true);
     return super.onCreateOptionsMenu(menu);
 }

The SearchResult activity which should be the activity called when search submit button is pressed

public class SearchResultsActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.d("search", "search triggered");
    setContentView(R.layout.searchpage);

    handleIntent(getIntent());
}
@Override
protected void onNewIntent(Intent intent) {
    Log.d("search", "search triggered");
    setIntent(intent);
    handleIntent(intent);
}
private void handleIntent(Intent intent)
{
     if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
            String query = intent.getStringExtra(SearchManager.QUERY);
            Log.d("search", query);
}
  }

 @Override
 public boolean onSearchRequested() {

     Log.d("search", "search triggered");

     return false;  // don't go ahead and show the search box
 }

Body:
I was not using the strings within searchable.xml.

You MUST set it up that way or you will get null. I had just put in text instead of using @string.

<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
    android:label="@string/app_label"
    android:hint="@string/search_hint" >
</searchable>


问:
tf.nn.softmax_cross_entropy_with_logits() error: logits and labels must be same size
I am new to TensorFlow and am trying to write an algorithm to classify images in the CIFAR-10 dataset. I am getting this error:

```<code>InvalidArgumentError (see above for traceback): logits and labels must be same size: logits_size=[10000,10] labels_size=[1,10000]
     [[Node: SoftmaxCrossEntropyWithLogits = SoftmaxCrossEntropyWithLogits[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"](Reshape, Reshape_1)]]
</code>```

Here is my code:

```<code>import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import cPickle

n_nodes_hl1 = 500
n_nodes_hl2 = 500
n_nodes_hl3 = 500

n_classes = 10
batch_size = 100
image_size = 32*32*3 # because 3 channels

x = tf.placeholder('float', shape=(None, image_size))
y = tf.placeholder('float')

def neural_network_model(data):
    hidden_1_layer = {'weights':tf.Variable(tf.random_normal([image_size, n_nodes_hl1])), 'biases':tf.Variable(tf.random_normal([n_nodes_hl1]))}
    hidden_2_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl1, n_nodes_hl2])), 'biases':tf.Variable(tf.random_normal([n_nodes_hl2]))}
    hidden_3_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl2, n_nodes_hl3])), 'biases':tf.Variable(tf.random_normal([n_nodes_hl3]))}
    output_layer = {'weights':tf.Variable(I am new to TensorFlow and tf.random_normal([n_nodes_hl3, n_classes])), 'biases':tf.Variable(tf.random_normal([n_classes]))}
    # input_data * weights + biases
    l1 = tf.add(tf.matmul(data, hidden_1_layer['weights']), hidden_1_layer['biases'])
    # activation function
    l1 = tf.nn.relu(l1)

    l2 = tf.add(tf.matmul(l1, hidden_2_layer['weights']), hidden_2_layer['biases'])
    l2 = tf.nn.relu(l2)

    l3 = tf.add(tf.matmul(l2, hidden_3_layer['weights']), hidden_3_layer['biases'])
    l3 = tf.nn.relu(l3)

    output = tf.matmul(l3, output_layer['weights']) + output_layer['biases']
    return output

def train_neural_network(x):
    prediction = neural_network_model(x)
    cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(prediction, y))//THIS IS LINE 48 WHERE THE ERROR OCCURS
    #learning rate = 0.001
    optimizer = tf.train.AdamOptimizer().minimize(cost)
    hm_epochs = 10
    with tf.Session() as sess:
        sess.run(tf.initialize_all_variables())
        for epoch in range(hm_epochs):
            epoch_loss = 0
            for i in range(5):
                with open('data_batch_'+str(i+1),'rb') as f:
                    train_data = cPickle.load(f)
                print train_data
                print prediction.get_shape()
                #print len(y)
                _, c = sess.run([optimizer, cost], feed_dict={x:train_data['data'],y:train_data['labels']})
                epoch_loss += c
            print 'Epoch ' + str(epoch) + ' completed out of ' + str(hm_epochs) + ' loss: ' + str(epoch_loss)
        correct = tf.equal(tf.argmax(prediction,1), tf.argmax(y,1))
        accuracy = tf.reduce_mean(tf.cast(correct, 'float'))
        with open('test_batch','rb') as f:
            test_data = cPickle.load(f)
            accuracy = accuracy.eval({x:test_data['data'],y:test_data['labels']})
        print 'Accuracy: ' + str(accuracy)

train_neural_network(x)
</code>```

I'm pretty sure this means that in line 48 (shown above) prediction and y are not the same shape, but I don't understand TensorFlow well enough to know how to fix it. I don't even really understand where y is being set, I got most of this code from a tutorial and fiddled with it to apply it to a different dataset. How can I fix this error?

答:
Here are some updates to the code to support TensorFlow version 1.0:</p>
```<code>def train_neural_network(x):
    prediction = neural_network_model(x)
    #OLD VERSION:
    #cost = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(prediction,y) )
    #NEW:
    cost = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=y) )
    optimizer = tf.train.AdamOptimizer().minimize(cost)
    hm_epochs = 10
    with tf.Session() as sess:
        #OLD:
        #sess.run(tf.initialize_all_variables())
        #NEW:
        sess.run(tf.global_variables_initializer())
</code>```

Body:
I am new to TensorFlow and am trying to write an algorithm to classify images in the CIFAR-10 dataset. I am getting this error:

InvalidArgumentError (see above for traceback): logits and labels must be same size: logits_size=[10000,10] labels_size=[1,10000]
     [[Node: SoftmaxCrossEntropyWithLogits = SoftmaxCrossEntropyWithLogits[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"](Reshape, Reshape_1)]]

Here is my code:

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import cPickle

n_nodes_hl1 = 500
n_nodes_hl2 = 500
n_nodes_hl3 = 500

n_classes = 10
batch_size = 100
image_size = 32*32*3 # because 3 channels

x = tf.placeholder('float', shape=(None, image_size))
y = tf.placeholder('float')

def neural_network_model(data):
    hidden_1_layer = {'weights':tf.Variable(tf.random_normal([image_size, n_nodes_hl1])), 'biases':tf.Variable(tf.random_normal([n_nodes_hl1]))}
    hidden_2_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl1, n_nodes_hl2])), 'biases':tf.Variable(tf.random_normal([n_nodes_hl2]))}
    hidden_3_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl2, n_nodes_hl3])), 'biases':tf.Variable(tf.random_normal([n_nodes_hl3]))}
    output_layer = {'weights':tf.Variable(I am new to TensorFlow and tf.random_normal([n_nodes_hl3, n_classes])), 'biases':tf.Variable(tf.random_normal([n_classes]))}
    # input_data * weights + biases
    l1 = tf.add(tf.matmul(data, hidden_1_layer['weights']), hidden_1_layer['biases'])
    # activation function
    l1 = tf.nn.relu(l1)

    l2 = tf.add(tf.matmul(l1, hidden_2_layer['weights']), hidden_2_layer['biases'])
    l2 = tf.nn.relu(l2)

    l3 = tf.add(tf.matmul(l2, hidden_3_layer['weights']), hidden_3_layer['biases'])
    l3 = tf.nn.relu(l3)

    output = tf.matmul(l3, output_layer['weights']) + output_layer['biases']
    return output

def train_neural_network(x):
    prediction = neural_network_model(x)
    cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(prediction, y))//THIS IS LINE 48 WHERE THE ERROR OCCURS
    #learning rate = 0.001
    optimizer = tf.train.AdamOptimizer().minimize(cost)
    hm_epochs = 10
    with tf.Session() as sess:
        sess.run(tf.initialize_all_variables())
        for epoch in range(hm_epochs):
            epoch_loss = 0
            for i in range(5):
                with open('data_batch_'+str(i+1),'rb') as f:
                    train_data = cPickle.load(f)
                print train_data
                print prediction.get_shape()
                #print len(y)
                _, c = sess.run([optimizer, cost], feed_dict={x:train_data['data'],y:train_data['labels']})
                epoch_loss += c
            print 'Epoch ' + str(epoch) + ' completed out of ' + str(hm_epochs) + ' loss: ' + str(epoch_loss)
        correct = tf.equal(tf.argmax(prediction,1), tf.argmax(y,1))
        accuracy = tf.reduce_mean(tf.cast(correct, 'float'))
        with open('test_batch','rb') as f:
            test_data = cPickle.load(f)
            accuracy = accuracy.eval({x:test_data['data'],y:test_data['labels']})
        print 'Accuracy: ' + str(accuracy)

train_neural_network(x)

I'm pretty sure this means that in line 48 (shown above) prediction and y are not the same shape, but I don't understand TensorFlow well enough to know how to fix it. I don't even really understand where y is being set, I got most of this code from a tutorial and fiddled with it to apply it to a different dataset. How can I fix this error?

Body:
Here are some updates to the code to support TensorFlow version 1.0:

def train_neural_network(x):
    prediction = neural_network_model(x)
    #OLD VERSION:
    #cost = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(prediction,y) )
    #NEW:
    cost = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=y) )
    optimizer = tf.train.AdamOptimizer().minimize(cost)
    hm_epochs = 10
    with tf.Session() as sess:
        #OLD:
        #sess.run(tf.initialize_all_variables())
        #NEW:
        sess.run(tf.global_variables_initializer())


问:
How to make reply to comment reference the id of comment in forum
i have been battling with this piece of code for hours without any headway. Can anyone assist me in getting around this please?
I’m working on a forum page on my website, with comments and replies to comments functionalities.
On click of the Reply button under each comments, a textarea dynamically shows up for reply. The replies are inserted to the database with a reply id and the original comment id (the id generated while posting the original comment been replied to).
My challenge now is that replies to any of the comments on the forum seem to reference only the id of the latest comment (perhaps because the reply forms are dynamically generated). Thus in my database, they are having an Id of the latest comment. This in effect means on fetching, the replies will all queue up under the latest comment.What i need is a way of referencing the id of the comment been replied to.
Here’s my php code:

```<code><?php
        require("includes/conn.php");
        $stmt=$conn->prepare("SELECT post_id, user, topic, post, time FROM post_tb ORDER BY time DESC");
            $stmt->execute();
            $result = $stmt->get_result();
            $num_of_rows = $result->num_rows;
            if ($num_of_rows > 0){
                while ($row = $result->fetch_assoc()){
                    $post_id = $row['post_id'];
                    $user = $row['user'];
                    $topic = $row['topic'];
                    $post = $row['post'];
                    $time = $row['time'];
                    $time = date('M dS, Y g:i A', strtotime($time));
                    echo '<div>
                            <div>
                                <h5><strong>'.$user.'</strong></h5><h6>'.$time.'</h6>
                                <h5><strong>'.ucfirst($topic).'</strong></h5>
                                <p data-id="'.$post_id.'">'.$post.'</p>
                            </div>
                            <div>
                                <button type="button" class="btn btn-primary rep" id="but_rep" data-id="'.$post_id.'">Reply</button>
                            </div>
                            <form id="comment_reply" data-id="'.$post_id.'" method="post" action="">
                                <input type="text" class="hidden" value="'.$post_id.'" id="post_id">
                                <input type="text" class="hidden" value="'.$user.'" id="user">
                                <textarea class="form-control" rows="3" name="post_rep" id="post_rep"></textarea>
                                <button type="submit" class="btn btn-primary" id="post_rep_sub">Submit</button>
                            </form>
                        <div/>';
                    }
                }
    ?>
</code>```

And my Ajax/jquery here:

```<code>$("form#comment_reply").hide();//Comment reply form hidden at page load
//To hide reply button and show the reply form
$(document).on('click', 'button.rep', function(e){
    e.preventDefault();
    var closestDiv = $(this).closest('div');
    var closestForm = $(closestDiv).next('form#comment_reply');
    $(closestDiv).fadeOut();
    $(closestForm).fadeIn();
});
//To process comment reply
$(document).on("click", "form button#post_rep_sub", function(e){
        e.preventDefault();
    var reply = $("form textarea#post_rep").val();
    var name = $("input#user").val();
    var post_id = $("input#post_id").val();
    if (reply != ''){
        $.post('insert_post_reply.php', {'reply':reply, 'name':name, 'post_id':post_id}, function(data){
            if (data = 'yes'){
               $("form textarea#post_rep").val("");
               fetchCommentReply();
            }
        });
    }else{
        return false;
    }
});
</code>```

答:
The main issue is that your php-code generates html-elements (e.g. button) several times with the same id! And then jquery only attaches itself to the first button.
This was already explained with an example here:

How jQuery works when there are multiple elements with the same "id"?

Solution: replace id with name-attribute!

According to the HTML specification, the id attribute MUST be unique on a page (it's not a criteria web designers/developers just invented)

Is using the same id multiple times on a page bad practice even when I am not parsing through the page?

Let's take a closer look at what your php generates. You have multiple elements with same id, for example the button with id="but_rep" is generated many times. Please note your are only allowed to use an id one time only in an html-file!
And therefore you cannot assume that jquery reliably attaches an event-handler using an id!

```<code>                     <div>
                        <div>
                            <h5><strong>user 1</strong></h5><h6>'.$time.'</h6>
                            <h5><strong>topic 1</strong></h5>
                            <p data-id="101">post text1</p>
                        </div>
                        <div>
                            <button type="button" class="btxtn btn-primary rep" id="but_rep" data-id="101">Reply</button>
                        </div>
                        <form id="comment_reply" data-id="101" method="post" action="">
                            <input type="text" class="hidden" value="101" id="post_id">
                            <input type="text" class="hidden" value="user 1" id="user">
                            <textarea class="form-control" rows="3" name="post_rep" id="post_rep"></textarea>
                            <button type="submit" class="btn btn-primary" id="post_rep_sub">Submit</button>
                        </form>
                    <div/>
                    <div>
                        <div>
                            <h5><strong>user 2</strong></h5><h6>'.$time.'</h6>
                            <h5><strong>topic 2</strong></h5>
                            <p data-id="102">post text2</p>
                        </div>
                        <div>
                            <button type="button" class="btxtn btn-primary rep" id="but_rep" data-id="102">Reply</button>
                        </div>
                        <form id="comment_reply" data-id="102" method="post" action="">
                            <input type="text" class="hidden" value="102" id="post_id">
                            <input type="text" class="hidden" value="user 2" id="user">
                            <textarea class="form-control" rows="3" name="post_rep" id="post_rep"></textarea>
                            <button type="submit" class="btn btn-primary" id="post_rep_sub">Submit</button>
                        </form>
                    <div/>
</code>```

Body:
i have been battling with this piece of code for hours without any headway. Can anyone assist me in getting around this please?
I’m working on a forum page on my website, with comments and replies to comments functionalities.
On click of the Reply button under each comments, a textarea dynamically shows up for reply. The replies are inserted to the database with a reply id and the original comment id (the id generated while posting the original comment been replied to).
My challenge now is that replies to any of the comments on the forum seem to reference only the id of the latest comment (perhaps because the reply forms are dynamically generated). Thus in my database, they are having an Id of the latest comment. This in effect means on fetching, the replies will all queue up under the latest comment.What i need is a way of referencing the id of the comment been replied to.
Here’s my php code:

<?php
        require("includes/conn.php");
        $stmt=$conn->prepare("SELECT post_id, user, topic, post, time FROM post_tb ORDER BY time DESC");
            $stmt->execute();
            $result = $stmt->get_result();
            $num_of_rows = $result->num_rows;
            if ($num_of_rows > 0){
                while ($row = $result->fetch_assoc()){
                    $post_id = $row['post_id'];
                    $user = $row['user'];
                    $topic = $row['topic'];
                    $post = $row['post'];
                    $time = $row['time'];
                    $time = date('M dS, Y g:i A', strtotime($time));
                    echo '

'.$user.'

'.$time.'

'.ucfirst($topic).'

'.$post.'

                                <button type="button" class="btn btn-primary rep" id="but_rep" data-id="'.$post_id.'">Reply</button>

                            <form id="comment_reply" data-id="'.$post_id.'" method="post" action="">
                                <input type="text" class="hidden" value="'.$post_id.'" id="post_id">
                                <input type="text" class="hidden" value="'.$user.'" id="user">
                                <textarea class="form-control" rows="3" name="post_rep" id="post_rep"></textarea>
                                <button type="submit" class="btn btn-primary" id="post_rep_sub">Submit</button>
                            </form>

';
                    }
                }
    ?>

And my Ajax/jquery here:

$("form#comment_reply").hide();//Comment reply form hidden at page load
//To hide reply button and show the reply form
$(document).on('click', 'button.rep', function(e){
    e.preventDefault();
    var closestDiv = $(this).closest('div');
    var closestForm = $(closestDiv).next('form#comment_reply');
    $(closestDiv).fadeOut();
    $(closestForm).fadeIn();
});
//To process comment reply
$(document).on("click", "form button#post_rep_sub", function(e){
        e.preventDefault();
    var reply = $("form textarea#post_rep").val();
    var name = $("input#user").val();
    var post_id = $("input#post_id").val();
    if (reply != ''){
        $.post('insert_post_reply.php', {'reply':reply, 'name':name, 'post_id':post_id}, function(data){
            if (data = 'yes'){
               $("form textarea#post_rep").val("");
               fetchCommentReply();
            }
        });
    }else{
        return false;
    }
});

Body:
The main issue is that your php-code generates html-elements (e.g. button) several times with the same id! And then jquery only attaches itself to the first button.
This was already explained with an example here:

How jQuery works when there are multiple elements with the same "id"?

Solution: replace id with name-attribute!

According to the HTML specification, the id attribute MUST be unique on a page (it's not a criteria web designers/developers just invented)

Is using the same id multiple times on a page bad practice even when I am not parsing through the page?

Let's take a closer look at what your php generates. You have multiple elements with same id, for example the button with id="but_rep" is generated many times. Please note your are only allowed to use an id one time only in an html-file!
And therefore you cannot assume that jquery reliably attaches an event-handler using an id!

                     <div>
                        <div>
                            <h5><strong>user 1</strong></h5><h6>'.$time.'</h6>
                            <h5><strong>topic 1</strong></h5>
                            <p data-id="101">post text1</p>
                        </div>
                        <div>
                            <button type="button" class="btxtn btn-primary rep" id="but_rep" data-id="101">Reply</button>
                        </div>
                        <form id="comment_reply" data-id="101" method="post" action="">
                            <input type="text" class="hidden" value="101" id="post_id">
                            <input type="text" class="hidden" value="user 1" id="user">
                            <textarea class="form-control" rows="3" name="post_rep" id="post_rep"></textarea>
                            <button type="submit" class="btn btn-primary" id="post_rep_sub">Submit</button>
                        </form>
                    <div/>
                    <div>
                        <div>
                            <h5><strong>user 2</strong></h5><h6>'.$time.'</h6>
                            <h5><strong>topic 2</strong></h5>
                            <p data-id="102">post text2</p>
                        </div>
                        <div>
                            <button type="button" class="btxtn btn-primary rep" id="but_rep" data-id="102">Reply</button>
                        </div>
                        <form id="comment_reply" data-id="102" method="post" action="">
                            <input type="text" class="hidden" value="102" id="post_id">
                            <input type="text" class="hidden" value="user 2" id="user">
                            <textarea class="form-control" rows="3" name="post_rep" id="post_rep"></textarea>
                            <button type="submit" class="btn btn-primary" id="post_rep_sub">Submit</button>
                        </form>
                    <div/>


问:
Center position of logo in Action Bar Android
I want to display the logo at the centre of the Action Bar. Here's my custom layout code:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ActionBarWrapper"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/icon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/logo"
        android:layout_centerInParent="true"
        android:padding="8dp"/>

</RelativeLayout>
</code>```

And in the onCreate() I'm using it as:

```<code>getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.custom_logo);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#2A2A2A")));
</code>```

The issue is it displays fine in normal Fragments and Activity but shifts a little to the right when used with Navigation Drawer. Here are the images:

Wrong One:

Right One:

What am I doing wrong? Thanks.

答: Add app:contentInsetLeft="0dp" to your android.support.v7.widget.Toolbar, because a toolbar with menu drawer will automatically have a right margin.

Body:
I want to display the logo at the centre of the Action Bar. Here's my custom layout code:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ActionBarWrapper"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/icon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/logo"
        android:layout_centerInParent="true"
        android:padding="8dp"/>

</RelativeLayout>

And in the onCreate() I'm using it as:

getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.custom_logo);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#2A2A2A")));

The issue is it displays fine in normal Fragments and Activity but shifts a little to the right when used with Navigation Drawer. Here are the images:

Wrong One:

Right One:

What am I doing wrong? Thanks.


问:
Create large DataFrame with limited resource(RAM)
I have a very large pandas.Series of shape (200000, ) containing dict(s)

```<code>In[11]: series.head()
Out[12]:
train-1        {u'MI vs KKR': 7788, u'India vs Australia 2nd ...
train-10       {u'England Smarter with the Ball': 92, u'Dhoni...
train-100      {u'Star Sports 4': 13, u'Manchester United vs ...
train-1000     {u'SRH vs RCB': 701, u'KKR vs KXIP': 1042, u'M...
train-10000    {u'MI vs KKR': 304, u'Yeh Rishta Kya Kehlata H...
Name: titles, dtype: object
</code>```

I want to create a DataFrame from the series - which could have been done by:

```<code>df = pd.DataFrame(series.values.tolist(), index=series.index).fillna(0)
</code>```

From the above code it's clear that I want to create a column for every unique key from all the dictionaries and fill up the numerical value if present in the dictionary if not fill it with zero - which is done by fillna(0):

It is not possible to show what I want for my dataset but in a nutshell below is the code for what I want to do using small dummy data:

```<code>small_series = pd.Series([{'a':1, 'b': 2}, {'b': 3, 'c': 4}])

small_series
Out[15]:
0    {u'a': 1, u'b': 2}
1    {u'c': 4, u'b': 3}
dtype: object

pd.DataFrame(small_series.values.tolist()).fillna(0)
Out[17]:
     a  b    c
0  1.0  2  0.0
1  0.0  3  4.0
</code>```

Well this is straight forward, but a problem arises when the dictionary is HUGE and when I use the above technique it takes up all my RAM(16Gigs) and half of my SWAP memory(32 Gigs) and even then it never stops!

I have searched and people recommend using sparse data structures but I need to create a dense one first and then I can convert it to sparse !

Please help me create the dataframe - with limited 16 gigs of memory!

Here's the ready made template that will help (title.pic file(pickle'd in python 2.7)):

```<code>import pickle
import pandas as pd

series = pickle.load(open('titles.pic', 'rb'))

# print series

# This is where it take up the whole memory and forever long!
df = pd.DataFrame(series.values.tolist(), index=series.index).fillna(0)
</code>```

Any help/approach would be appreciated !

答:
Your dataframe would have 200k*10k=2 billion elements, which roughly translates to 2GB if every element was only 1 byte. Clearly a dense representation won't work, so you need to use a SparseDataFrame:

```<code>pd.SparseDataFrame.from_records(small_series.values)
</code>```

Body:
I have a very large pandas.Series of shape (200000, ) containing dict(s)

In[11]: series.head()
Out[12]:
train-1        {u'MI vs KKR': 7788, u'India vs Australia 2nd ...
train-10       {u'England Smarter with the Ball': 92, u'Dhoni...
train-100      {u'Star Sports 4': 13, u'Manchester United vs ...
train-1000     {u'SRH vs RCB': 701, u'KKR vs KXIP': 1042, u'M...
train-10000    {u'MI vs KKR': 304, u'Yeh Rishta Kya Kehlata H...
Name: titles, dtype: object

I want to create a DataFrame from the series - which could have been done by:

df = pd.DataFrame(series.values.tolist(), index=series.index).fillna(0)

From the above code it's clear that I want to create a column for every unique key from all the dictionaries and fill up the numerical value if present in the dictionary if not fill it with zero - which is done by fillna(0):

It is not possible to show what I want for my dataset but in a nutshell below is the code for what I want to do using small dummy data:

small_series = pd.Series([{'a':1, 'b': 2}, {'b': 3, 'c': 4}])

small_series
Out[15]:
0    {u'a': 1, u'b': 2}
1    {u'c': 4, u'b': 3}
dtype: object

pd.DataFrame(small_series.values.tolist()).fillna(0)
Out[17]:
     a  b    c
0  1.0  2  0.0
1  0.0  3  4.0

Well this is straight forward, but a problem arises when the dictionary is HUGE and when I use the above technique it takes up all my RAM(16Gigs) and half of my SWAP memory(32 Gigs) and even then it never stops!

I have searched and people recommend using sparse data structures but I need to create a dense one first and then I can convert it to sparse !

Please help me create the dataframe - with limited 16 gigs of memory!

Here's the ready made template that will help (title.pic file(pickle'd in python 2.7)):

import pickle
import pandas as pd

series = pickle.load(open('titles.pic', 'rb'))

# print series

# This is where it take up the whole memory and forever long!
df = pd.DataFrame(series.values.tolist(), index=series.index).fillna(0)

Any help/approach would be appreciated !

Body:
Your dataframe would have 200k*10k=2 billion elements, which roughly translates to 2GB if every element was only 1 byte. Clearly a dense representation won't work, so you need to use a SparseDataFrame:

pd.SparseDataFrame.from_records(small_series.values)


问:
How to run this subquery in Laravel 5.4 and MySQL
I need to run this subquery in Laravel 5.4 and the answers that I have found on StackOverflow are for Laravel <5.

```<code>SELECT DISTINCT *
                    FROM (
                           SELECT DISTINCT
                             testing_results.pluginName,
                             SUBSTRING_INDEX(SUBSTRING_INDEX(cvss_vector, '#', -1), '/', 1) AS access_vector,
                             SUBSTRING_INDEX(SUBSTRING_INDEX(cvss_vector, '/', 2), '/', -1) AS access_complexity,
                             SUBSTRING_INDEX(SUBSTRING_INDEX(cvss_vector, '/', 3), '/', -1) AS authentication,
                             SUBSTRING_INDEX(SUBSTRING_INDEX(cvss_vector, '/', 4), '/', -1) AS confidentiality,
                             SUBSTRING_INDEX(SUBSTRING_INDEX(cvss_vector, '/', 5), '/', -1) AS integrity,
                             SUBSTRING_INDEX(SUBSTRING_INDEX(cvss_vector, '/', 6), '/', -1) AS availability
                           FROM
                             testing_results
                           WHERE
                             testing_results.cvss_vector != ''
                         ) sub
                         WHERE sub.access_vector LIKE '%AV:L%'
</code>```

Thank you very in advanced for your help.

Best regards,

答:
//Building Inner Query

```<code>$sub_query = DB::table('testing_results')
->select([DB::raw('DISTINCT testing_results.pluginName'),
DB::raw('SUBSTRING_INDEX(SUBSTRING_INDEX(cvss_vector, '#', -1), '/', 1) AS access_vector'),
DB::raw('SUBSTRING_INDEX(SUBSTRING_INDEX(cvss_vector, '/', 2), '/', -1) AS access_complexity'),
DB::raw('SUBSTRING_INDEX(SUBSTRING_INDEX(cvss_vector, '/', 3), '/', -1) AS authentication'),
DB::raw('SUBSTRING_INDEX(SUBSTRING_INDEX(cvss_vector, '/', 4), '/', -1) AS confidentiality'),
DB::raw('SUBSTRING_INDEX(SUBSTRING_INDEX(cvss_vector, '/', 5), '/', -1) AS integrity'),
DB::raw('SUBSTRING_INDEX(SUBSTRING_INDEX(cvss_vector, '/', 6), '/', -1) AS availability')
])
->where('testing_results.cvss_vector', '!=', '');
</code>```

//Creating Outer Query

```<code>$query = DB::raw("({$sub_query->toSql()}) as sub_query");
$data = DB::table($query)
         ->mergeBindings($sub_query)
         ->where('access_vector', 'NOT LIKE', '%AV:L%')->get();
</code>```

Note : This works on Laravel 5.2, which means it will work on Laravel 5.4.

Body:
I need to run this subquery in Laravel 5.4 and the answers that I have found on StackOverflow are for Laravel <5.

SELECT DISTINCT *
                    FROM (
                           SELECT DISTINCT
                             testing_results.pluginName,
                             SUBSTRING_INDEX(SUBSTRING_INDEX(cvss_vector, '#', -1), '/', 1) AS access_vector,
                             SUBSTRING_INDEX(SUBSTRING_INDEX(cvss_vector, '/', 2), '/', -1) AS access_complexity,
                             SUBSTRING_INDEX(SUBSTRING_INDEX(cvss_vector, '/', 3), '/', -1) AS authentication,
                             SUBSTRING_INDEX(SUBSTRING_INDEX(cvss_vector, '/', 4), '/', -1) AS confidentiality,
                             SUBSTRING_INDEX(SUBSTRING_INDEX(cvss_vector, '/', 5), '/', -1) AS integrity,
                             SUBSTRING_INDEX(SUBSTRING_INDEX(cvss_vector, '/', 6), '/', -1) AS availability
                           FROM
                             testing_results
                           WHERE
                             testing_results.cvss_vector != ''
                         ) sub
                         WHERE sub.access_vector LIKE '%AV:L%'

Thank you very in advanced for your help.

Best regards,

Body:
//Building Inner Query

$sub_query = DB::table('testing_results')
->select([DB::raw('DISTINCT testing_results.pluginName'),
DB::raw('SUBSTRING_INDEX(SUBSTRING_INDEX(cvss_vector, '#', -1), '/', 1) AS access_vector'),
DB::raw('SUBSTRING_INDEX(SUBSTRING_INDEX(cvss_vector, '/', 2), '/', -1) AS access_complexity'),
DB::raw('SUBSTRING_INDEX(SUBSTRING_INDEX(cvss_vector, '/', 3), '/', -1) AS authentication'),
DB::raw('SUBSTRING_INDEX(SUBSTRING_INDEX(cvss_vector, '/', 4), '/', -1) AS confidentiality'),
DB::raw('SUBSTRING_INDEX(SUBSTRING_INDEX(cvss_vector, '/', 5), '/', -1) AS integrity'),
DB::raw('SUBSTRING_INDEX(SUBSTRING_INDEX(cvss_vector, '/', 6), '/', -1) AS availability')
])
->where('testing_results.cvss_vector', '!=', '');

//Creating Outer Query

$query = DB::raw("({$sub_query->toSql()}) as sub_query");
$data = DB::table($query)
         ->mergeBindings($sub_query)
         ->where('access_vector', 'NOT LIKE', '%AV:L%')->get();

Note : This works on Laravel 5.2, which means it will work on Laravel 5.4.