问:
WPF Override a trigger from a button style
I have below button style in window resources:

```<code><Style x:Key="MyStyle" TargetType="{x:Type Button}">

    <Setter Property="BorderBrush" Value="Transparent"/>
    <Setter Property="BorderThickness" Value="0 0 0 3"/>

    <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
            <Setter Property="BorderBrush" Value="Orange" />
        </Trigger>
        <Trigger Property="IsPressed" Value="True">
            <Setter Property="BorderBrush" Value="Red" />
        </Trigger>
    </Style.Triggers>

</Style>
</code>```

This style is shared by two wpf buttons. But there is a button I want to show a custom color when it is pressed, the color will be green.

So in this special button I would like to override the value specified for borderbrush property in the trigger, instead of Red I would like Green.

How to do this?

答:
You could set the BorderBrush property using a {DynamicResource} that you can override:

```<code><SolidColorBrush x:Key="pressed" Color="Red" />
<Style x:Key="MyStyle" TargetType="{x:Type Button}">
    <Setter Property="BorderBrush" Value="Transparent"/>
    <Setter Property="BorderThickness" Value="0 0 0 3"/>
    <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
            <Setter Property="BorderBrush" Value="Orange" />
        </Trigger>
        <Trigger Property="IsPressed" Value="True">
            <Setter Property="BorderBrush" Value="{DynamicResource pressed}" />
        </Trigger>
    </Style.Triggers>
</Style>
...
<Button Content="Red" Style="{StaticResource MyStyle}" />

<Button Content="Green" Style="{StaticResource MyStyle}">
    <Button.Resources>
        <SolidColorBrush x:Key="pressed" Color="Green" />
    </Button.Resources>
</Button>
</code>```

Or you could create another Style that overrides the entire trigger:

```<code><Button Content="Green">
    <Button.Style>
        <Style TargetType="Button" BasedOn="{StaticResource MyStyle}">
            <Style.Triggers>
                <Trigger Property="IsPressed" Value="True">
                    <Setter Property="Foreground" Value="Green" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>
</code>```

Body:
I have below button style in window resources:

</Style>

This style is shared by two wpf buttons. But there is a button I want to show a custom color when it is pressed, the color will be green.

So in this special button I would like to override the value specified for borderbrush property in the trigger, instead of Red I would like Green.

How to do this?

Body:
You could set the BorderBrush property using a {DynamicResource} that you can override:

<SolidColorBrush x:Key="pressed" Color="Red" />
<Style x:Key="MyStyle" TargetType="{x:Type Button}">
    <Setter Property="BorderBrush" Value="Transparent"/>
    <Setter Property="BorderThickness" Value="0 0 0 3"/>
    <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
            <Setter Property="BorderBrush" Value="Orange" />
        </Trigger>
        <Trigger Property="IsPressed" Value="True">
            <Setter Property="BorderBrush" Value="{DynamicResource pressed}" />
        </Trigger>
    </Style.Triggers>
</Style>
...
<Button Content="Red" Style="{StaticResource MyStyle}" />

<Button Content="Green" Style="{StaticResource MyStyle}">
    <Button.Resources>
        <SolidColorBrush x:Key="pressed" Color="Green" />
    </Button.Resources>
</Button>

Or you could create another Style that overrides the entire trigger:

<Button Content="Green">
    <Button.Style>
        <Style TargetType="Button" BasedOn="{StaticResource MyStyle}">
            <Style.Triggers>
                <Trigger Property="IsPressed" Value="True">
                    <Setter Property="Foreground" Value="Green" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>


来源: stackexchange

问:
Can I disable a CSS :hover effect via JavaScript?
I’m trying to prevent the browser from using the :hover effect of the CSS, via JavaScript.

I have set the a and a:hover styles in my CSS, because I want a hover effect, if JS isn’t available. But if JS is available, I want to overwrite my CSS hover effect with a smoother one (using the jQuery color plugin for example.)

I tried this:

```<code>$("ul#mainFilter a").hover(
     function(e){ e.preventDefault(); ...do my stuff... },
     function(e){ e.preventDefault(); ...do my stuff... });
</code>```

I also tried it with return false;, but it does not work.

Here is an example of my problem: http://jsfiddle.net/4rEzz/. The link should just fade without getting gray.

As mentioned by fudgey, a workaround would be to reset the hover styles using .css() but I would have to overwrite every single property, specified in the CSS (see here: http://jsfiddle.net/raPeX/1/ ). I am looking for a generic solution.

Does anyone know how to do this?

PS: I do not want to overwrite every style i have set for the hover.

答:
I'd recommend to replace all :hover properties to :active when you detect that device supports touch. Just call this function when you do so as touch().

```<code>function touch() {
  if ('ontouchstart' in document.documentElement) {
    for (var sheetI = document.styleSheets.length - 1; sheetI >= 0; sheetI--) {
      var sheet = document.styleSheets[sheetI];
      if (sheet.cssRules) {
        for (var ruleI = sheet.cssRules.length - 1; ruleI >= 0; ruleI--) {
          var rule = sheet.cssRules[ruleI];

          if (rule.selectorText) {
            rule.selectorText = rule.selectorText.replace(':hover', ':active');
          }
        }
      }
    }
  }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I’m trying to prevent the browser from using the :hover effect of the CSS, via JavaScript.

I have set the a and a:hover styles in my CSS, because I want a hover effect, if JS isn’t available. But if JS is available, I want to overwrite my CSS hover effect with a smoother one (using the jQuery color plugin for example.)

I tried this:

$("ul#mainFilter a").hover(
     function(e){ e.preventDefault(); ...do my stuff... },
     function(e){ e.preventDefault(); ...do my stuff... });

I also tried it with return false;, but it does not work.

Here is an example of my problem: http://jsfiddle.net/4rEzz/. The link should just fade without getting gray.

As mentioned by fudgey, a workaround would be to reset the hover styles using .css() but I would have to overwrite every single property, specified in the CSS (see here: http://jsfiddle.net/raPeX/1/ ). I am looking for a generic solution.

Does anyone know how to do this?

PS: I do not want to overwrite every style i have set for the hover.

Body:
I'd recommend to replace all :hover properties to :active when you detect that device supports touch. Just call this function when you do so as touch().

function touch() {
  if ('ontouchstart' in document.documentElement) {
    for (var sheetI = document.styleSheets.length - 1; sheetI >= 0; sheetI--) {
      var sheet = document.styleSheets[sheetI];
      if (sheet.cssRules) {
        for (var ruleI = sheet.cssRules.length - 1; ruleI >= 0; ruleI--) {
          var rule = sheet.cssRules[ruleI];

          if (rule.selectorText) {
            rule.selectorText = rule.selectorText.replace(':hover', ':active');
          }
        }
      }
    }
  }
}


问:
libcurl rtsp keep alive with rtsp server
I was implementing rtsp with libcurl(sample code https://curl.haxx.se/libcurl/c/rtsp.html)
I received RTP data after sending PLAY option.
But the connection broke about ten minutes.
I thought it might send heartbeat message to rtsp sever to keep session alive.

How to keep connection alive with libcurl ?

Code Flow :

```<code>// Set Option

// Set Describe

// Set Setup

// PLAY

/* Receive RTP DATA*/

while(1)

{

curl_easy_set_opt(curl, CURLOPT_WRITEFUNCTION, rtsp_write);

curl_easy_set_opt(curl, CURLOPT_WRITEDATA, NULL);

.....

}
</code>```

答:
The RTSP connection indeed requires the heartbeat. It is specified in RCF 2326, section 12.37 and ONVIF streaming specification, section 5.2.1.1.1.

Basically you do:

Optionally set the timeout parameter (in seconds), the usual default is 60sec.

The RTSP SETUP response should contain timeout and client should use it to keep-alive the connection.

Client should call the RTSP server using any RTSP method or send RTCP RR. The recommended meethod is to send RTSP SET_PARAMETER request.

Body:
I was implementing rtsp with libcurl(sample code https://curl.haxx.se/libcurl/c/rtsp.html)
I received RTP data after sending PLAY option.
But the connection broke about ten minutes.
I thought it might send heartbeat message to rtsp sever to keep session alive.

How to keep connection alive with libcurl ?

Code Flow :

// Set Option

// Set Describe

// Set Setup

// PLAY

/* Receive RTP DATA*/

while(1)

{

curl_easy_set_opt(curl, CURLOPT_WRITEFUNCTION, rtsp_write);

curl_easy_set_opt(curl, CURLOPT_WRITEDATA, NULL);

.....

}


问:
how to make a tag change properties after a specific input is checked?
I am creating a quiz website for a school project. Whenever a correct answer is selected (input type=radio) then I want the line adjacent to it to become green and when an incorrect answer is selected I want the line to become red.

Is there any way to do this using css only and not JavaScript.

答:
That can't be done without involving javascript or jquery. You must have to trigger your code when checkbox is selected. Here is an example:

function myFunction() {
var radios = document.getElementsByName('rd1');
for (var i = 0, length = radios.length; i < length; i++) {
    if (radios[i].checked) {
        // use if condition to check if selected answer is correct or not
        // and then simply change text color OR add a css class, which have predefined text colors for success and error

        alert(radios[i].value);

        // only one radio can be logically checked, don't check the rest
        break;
    }
}
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="radio" name="rd1" id="red" value="Option 1" onchange="myFunction()"><label>Option 1</label><br>
<input type="radio" name="rd1" id="red" value="Option 2" onchange="myFunction()"><label>Option 2</label><br>
<input type="radio" name="rd1" id="red" value="Option 3" onchange="myFunction()"><label>Option 3</label><br>
<input type="radio" name="rd1" id="red" value="Option 4" onchange="myFunction()"><label>Option 4</label><br></code>```

Body:
That can't be done without involving javascript or jquery. You must have to trigger your code when checkbox is selected. Here is an example:

function myFunction() {
var radios = document.getElementsByName('rd1');
for (var i = 0, length = radios.length; i < length; i++) {
    if (radios[i].checked) {
        // use if condition to check if selected answer is correct or not
        // and then simply change text color OR add a css class, which have predefined text colors for success and error

        alert(radios[i].value);

        // only one radio can be logically checked, don't check the rest
        break;
    }
}
}

<input type="radio" name="rd1" id="red" value="Option 1" onchange="myFunction()"><label>Option 1</label><br>
<input type="radio" name="rd1" id="red" value="Option 2" onchange="myFunction()"><label>Option 2</label><br>
<input type="radio" name="rd1" id="red" value="Option 3" onchange="myFunction()"><label>Option 3</label><br>
<input type="radio" name="rd1" id="red" value="Option 4" onchange="myFunction()"><label>Option 4</label><br>


问:
Different colorplots for scatter
Hello I want to create a scatter plot to combine both subplots into one, but with the code below only one color is plotted (blue), like here: http://imgur.com/a/KmOCs. What do I need to change?:
For those who cannot set the picture I've uploaded below: http://imgur.com/a/MHou8

```<code>oranges = cm.ScalarMappable(cmap=plt.cm.Oranges)
blues = cm.ScalarMappable(cmap=plt.cm.Blues)
RN1 = {}
for i in range(100):
    for j in range(100):
        RN1[(i / 100.0, j / 100.0)] = (np.random.uniform(0, 400), np.random.uniform(0, 400))

R_0s = RN1.values()

R_01s = np.array([k[0] / 400.0 for k in R_0s])
R_02s = np.array([k[1] / 400.0 for k in R_0s])
x = [k[0] for k in RN1.keys()]
y = [k[1] for k in RN1.keys()]
oranges.set_array(R_01s)
blues.set_array(R_02s)
s1 = plt.scatter(x, y, c=R_01s, marker='s', cmap=plt.cm.Oranges)
s2 = plt.scatter(x, y, c=R_02s, marker='s', cmap=plt.cm.Blues)
plt.colorbar(oranges)
plt.colorbar(blues)
</code>```

答:
I don't think this can be nicely summarized by a single graph. Right now blue scatterplot just completely eclipses the orange one. If you make blue squares semi transparent like this:

```<code>s2 = plt.scatter(x, y, c=R_02s, marker='s', cmap=plt.cm.Blues, alpha=.3)
</code>```

you can actually see the orange squares behind them, but the overall figure still looks quite messy.

Maybe it would be easier to simply subtract two matrices R_02s - R_01s and plot the difference?

Title: Different colorplots for scatter

Body:
Hello I want to create a scatter plot to combine both subplots into one, but with the code below only one color is plotted (blue), like here: http://imgur.com/a/KmOCs. What do I need to change?:
For those who cannot set the picture I've uploaded below: http://imgur.com/a/MHou8

oranges = cm.ScalarMappable(cmap=plt.cm.Oranges)
blues = cm.ScalarMappable(cmap=plt.cm.Blues)
RN1 = {}
for i in range(100):
    for j in range(100):
        RN1[(i / 100.0, j / 100.0)] = (np.random.uniform(0, 400), np.random.uniform(0, 400))

R_0s = RN1.values()

R_01s = np.array([k[0] / 400.0 for k in R_0s])
R_02s = np.array([k[1] / 400.0 for k in R_0s])
x = [k[0] for k in RN1.keys()]
y = [k[1] for k in RN1.keys()]
oranges.set_array(R_01s)
blues.set_array(R_02s)
s1 = plt.scatter(x, y, c=R_01s, marker='s', cmap=plt.cm.Oranges)
s2 = plt.scatter(x, y, c=R_02s, marker='s', cmap=plt.cm.Blues)
plt.colorbar(oranges)
plt.colorbar(blues)

Body:
I don't think this can be nicely summarized by a single graph. Right now blue scatterplot just completely eclipses the orange one. If you make blue squares semi transparent like this:

s2 = plt.scatter(x, y, c=R_02s, marker='s', cmap=plt.cm.Blues, alpha=.3)

you can actually see the orange squares behind them, but the overall figure still looks quite messy.

Maybe it would be easier to simply subtract two matrices R_02s - R_01s and plot the difference?


问:
"Process with an Id of #### is not running" in Visual Studio
I am trying to run any program on visual studio 2013 update 3 and I get the following alert box:

Process with an Id of #### is not running.

Every time there is different ID number showing.

and in the error windows, I get this error message:

The program '[3148] iisexpress.exe' has exited with code -1073741816 (0xc0000008) 'An invalid handle was specified'.

Sometimes it runs and in the browser I get the following message:

The webpage is not available.

Why is this occurring and how can I resolve it?

答:
```<code>cmd - regedit-HKEY_LOCAL_MACHINE-SYSTEM-CurrentControlSet-Services-HTTP-START=3
</code>```

Computer restarted.

worked for me!

ContentLicense: CC BY-SA 4.0

Body:
cmd - regedit-HKEY_LOCAL_MACHINE-SYSTEM-CurrentControlSet-Services-HTTP-START=3

Computer restarted.

worked for me!


问:
How can I iterate over a list of lists?
I'm trying to sort through a list of lists. How could I go about printing or iterating over the first and last elements in each list? non-working code below:

```<code>from numpy import *
xs=[[1.,2.,3.],[4.,5.,6.],[7.,8.,9.]]

for i in xs:
    for j in xs[i]:
        print(xs[1],xs[-1])
</code>```

Traceback error if needed:

```<code>runfile('/Users/Alex/untitled9.py', wdir='/Users/Alex')
Traceback (most recent call last):

  File "<ipython-input-14-8a28382c7f81>", line 1, in <module>
    runfile('/Users/Alex/untitled9.py', wdir='/Users/Alex')

  File "/anaconda/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 880, in runfile
    execfile(filename, namespace)

  File "/anaconda/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 102, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "/Users/Alex/untitled9.py", line 13, in <module>
    for j in xs[i]:

TypeError: list indices must be integers or slices, not list
</code>```

答:
You've already been given the answer in the comments. But to understand why your code doesn't work in its current state, take a look at this:

```<code>>>> xs = [[1.,2.,3.], [4.,5.,6.], [7.,8.,9.]]
>>> for i in xs:
...    print(i)
...
[1.0, 2.0, 3.0]
[4.0, 5.0, 6.0]
[7.0, 8.0, 9.0]
</code>```

The for loop iterates over the elements, not the indices. The variable i is probably confusing here. Anyway, inside the loop, i will contain a sublist at each iteration. So xs[i] is an invalid operation here -- you may only provide integers as indices to a python list.

If you want to get the first and last element of each sublist, all you've got to do is print out i[0] and i[-1].

On a related note, you can iterate over the indices using the range function:

```<code> for i in range(len(xs)):
     print(xs[i][0], xs[i][-1])
</code>```

But this is not recommended, since it is more efficient to just iterate over the elements directly, especially for this use case.

You can also also use enumerate, if you need both:

```<code> for c, i in enumerate(xs):
     print(i[0], xs[c][-1]) # both work here
</code>```

Title: How can I iterate over a list of lists?

Body:
I'm trying to sort through a list of lists. How could I go about printing or iterating over the first and last elements in each list? non-working code below:

from numpy import *
xs=[[1.,2.,3.],[4.,5.,6.],[7.,8.,9.]]

for i in xs:
    for j in xs[i]:
        print(xs[1],xs[-1])

Traceback error if needed:

runfile('/Users/Alex/untitled9.py', wdir='/Users/Alex')
Traceback (most recent call last):

  File "<ipython-input-14-8a28382c7f81>", line 1, in <module>
    runfile('/Users/Alex/untitled9.py', wdir='/Users/Alex')

  File "/anaconda/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 880, in runfile
    execfile(filename, namespace)

  File "/anaconda/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 102, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "/Users/Alex/untitled9.py", line 13, in <module>
    for j in xs[i]:

TypeError: list indices must be integers or slices, not list

Body:
You've already been given the answer in the comments. But to understand why your code doesn't work in its current state, take a look at this:

>>> xs = [[1.,2.,3.], [4.,5.,6.], [7.,8.,9.]]
>>> for i in xs:
...    print(i)
...
[1.0, 2.0, 3.0]
[4.0, 5.0, 6.0]
[7.0, 8.0, 9.0]

The for loop iterates over the elements, not the indices. The variable i is probably confusing here. Anyway, inside the loop, i will contain a sublist at each iteration. So xs[i] is an invalid operation here -- you may only provide integers as indices to a python list.

If you want to get the first and last element of each sublist, all you've got to do is print out i[0] and i[-1].

On a related note, you can iterate over the indices using the range function:

 for i in range(len(xs)):
     print(xs[i][0], xs[i][-1])

But this is not recommended, since it is more efficient to just iterate over the elements directly, especially for this use case.

You can also also use enumerate, if you need both:

 for c, i in enumerate(xs):
     print(i[0], xs[c][-1]) # both work here


问:
When trying to issue an identity, it says my CA does not exist
I'm trying to issue an identity by

```<code>composer identity issue -p hlfv1 -n bonusetis -i PeerAdmin -s password -u perelluis -x true -a perelluis
</code>```

But I get

```<code>Error: fabric-ca request register failed with errors [[{"code":0,"message":"CA 'ca_peerOrg1' does not exist"}]]
Command failed.

Command succeeded
</code>```

And I do have a CA named ca_peerOrg1, as I have used it so far and it shows up in my docker containers:

```<code>CONTAINER ID        IMAGE                                        COMMAND                  CREATED             STATUS              PORTS                                              NAMES
425df4a2d729        hyperledger/composer-playground              "pm2-docker compos..."   30 minutes ago      Up 30 minutes       0.0.0.0:8080->8080/tcp                             composer-playground
5d6ac09d2f41        dev-peer0.org1.example.com-bonusetis-0.9.0   "chaincode -peer.a..."   2 hours ago         Up 2 hours                                                             dev-peer0.org1.example.com-bonusetis-0.9.0
b115a06eebdb        dev-peer1.org1.example.com-bonusetis-0.9.0   "chaincode -peer.a..."   2 hours ago         Up 2 hours                                                             dev-peer1.org1.example.com-bonusetis-0.9.0
bd2b4a5dfced        hyperledger/fabric-tools                     "/bin/bash"              3 hours ago         Up 3 hours                                                             cli
76a1159e510c        hyperledger/fabric-ca                        "sh -c 'fabric-ca-..."   3 hours ago         Up 3 hours          0.0.0.0:8054->7054/tcp                             ca_peerOrg2
92c6786f3ff1        hyperledger/fabric-peer                      "peer node start"        3 hours ago         Up 3 hours          0.0.0.0:10051->7051/tcp, 0.0.0.0:10053->7053/tcp   peer1.org2.example.com
f439f9f809c6        hyperledger/fabric-orderer                   "orderer"                3 hours ago         Up 3 hours          0.0.0.0:7050->7050/tcp                             orderer.example.com
8584208cd8a8        hyperledger/fabric-peer                      "peer node start"        3 hours ago         Up 3 hours          0.0.0.0:9051->7051/tcp, 0.0.0.0:9053->7053/tcp     peer0.org2.example.com
7e68ac2e33b4        hyperledger/fabric-peer                      "peer node start"        3 hours ago         Up 3 hours          0.0.0.0:7051->7051/tcp, 0.0.0.0:7053->7053/tcp     peer0.org1.example.com
8688c0ef16da        hyperledger/fabric-ca                        "sh -c 'fabric-ca-..."   3 hours ago         Up 3 hours          0.0.0.0:7054->7054/tcp                             ca_peerOrg1
baa42aa6bb12        hyperledger/fabric-peer                      "peer node start"        3 hours ago         Up 3 hours          0.0.0.0:8051->7051/tcp, 0.0.0.0:8053->7053/tcp     peer1.org1.example.com
</code>```

My connection profile shows the same name for the CA, with the correct ports.

If it's of any help, if I try to access the ports of the peers I get a

This page isn’t working

0.0.0.0 sent an invalid response.

message, but if I try to access the localhost:7054, I get a 404 page not found. I think this is expected, but just in case it tells something.

As seen in the containers, I'm using latest versions of Fabric(beta) and Composer(0.9) and I'm on Ubuntu 16.04 TLS.

答:
Problem was the name of the CA on the Connection Profile must be the name of the server, as a global defined by

- FABRIC_CA_SERVER_CA_NAME= $CA_NAME
So the $CA_NAME must be set in your Connection Profile, and not the containers name.
Hope it helps if someone is facing the same problem

Body:
I'm trying to issue an identity by

composer identity issue -p hlfv1 -n bonusetis -i PeerAdmin -s password -u perelluis -x true -a perelluis

But I get

Error: fabric-ca request register failed with errors [[{"code":0,"message":"CA 'ca_peerOrg1' does not exist"}]]
Command failed.

Command succeeded

And I do have a CA named ca_peerOrg1, as I have used it so far and it shows up in my docker containers:

CONTAINER ID        IMAGE                                        COMMAND                  CREATED             STATUS              PORTS                                              NAMES
425df4a2d729        hyperledger/composer-playground              "pm2-docker compos..."   30 minutes ago      Up 30 minutes       0.0.0.0:8080->8080/tcp                             composer-playground
5d6ac09d2f41        dev-peer0.org1.example.com-bonusetis-0.9.0   "chaincode -peer.a..."   2 hours ago         Up 2 hours                                                             dev-peer0.org1.example.com-bonusetis-0.9.0
b115a06eebdb        dev-peer1.org1.example.com-bonusetis-0.9.0   "chaincode -peer.a..."   2 hours ago         Up 2 hours                                                             dev-peer1.org1.example.com-bonusetis-0.9.0
bd2b4a5dfced        hyperledger/fabric-tools                     "/bin/bash"              3 hours ago         Up 3 hours                                                             cli
76a1159e510c        hyperledger/fabric-ca                        "sh -c 'fabric-ca-..."   3 hours ago         Up 3 hours          0.0.0.0:8054->7054/tcp                             ca_peerOrg2
92c6786f3ff1        hyperledger/fabric-peer                      "peer node start"        3 hours ago         Up 3 hours          0.0.0.0:10051->7051/tcp, 0.0.0.0:10053->7053/tcp   peer1.org2.example.com
f439f9f809c6        hyperledger/fabric-orderer                   "orderer"                3 hours ago         Up 3 hours          0.0.0.0:7050->7050/tcp                             orderer.example.com
8584208cd8a8        hyperledger/fabric-peer                      "peer node start"        3 hours ago         Up 3 hours          0.0.0.0:9051->7051/tcp, 0.0.0.0:9053->7053/tcp     peer0.org2.example.com
7e68ac2e33b4        hyperledger/fabric-peer                      "peer node start"        3 hours ago         Up 3 hours          0.0.0.0:7051->7051/tcp, 0.0.0.0:7053->7053/tcp     peer0.org1.example.com
8688c0ef16da        hyperledger/fabric-ca                        "sh -c 'fabric-ca-..."   3 hours ago         Up 3 hours          0.0.0.0:7054->7054/tcp                             ca_peerOrg1
baa42aa6bb12        hyperledger/fabric-peer                      "peer node start"        3 hours ago         Up 3 hours          0.0.0.0:8051->7051/tcp, 0.0.0.0:8053->7053/tcp     peer1.org1.example.com

My connection profile shows the same name for the CA, with the correct ports.

If it's of any help, if I try to access the ports of the peers I get a

This page isn’t working

0.0.0.0 sent an invalid response.

message, but if I try to access the localhost:7054, I get a 404 page not found. I think this is expected, but just in case it tells something.

As seen in the containers, I'm using latest versions of Fabric(beta) and Composer(0.9) and I'm on Ubuntu 16.04 TLS.


问:
PHP Button click not reloading the page
I have button.php and this code is there in button.php

```<code><a href="Cancel.php<button type="button">Cancel</button></a>
</code>```

I have Cancel.php

```<code><?php
//Do something
header("location:button.php")
?>
</code>```

When I click the Cancel button it should process something and return to the same PHP file.
It's returning but not reloading or updating the page content.
Is there any method to reload or my method of coding is wrong? Can I use jQuery here? Please help me!

答:
use header("Refresh:0");

```<code><?php
//Do something
header("Refresh:0");
?>
</code>```

use this for different page

```<code>header("Refresh:0; url=button.php");
</code>```

Title: PHP Button click not reloading the page

Body:
I have button.php and this code is there in button.php

<a href="Cancel.php<button type="button">Cancel</button>

I have Cancel.php

<?php
//Do something
header("location:button.php")
?>

When I click the Cancel button it should process something and return to the same PHP file.
It's returning but not reloading or updating the page content.
Is there any method to reload or my method of coding is wrong? Can I use jQuery here? Please help me!

Body:
use header("Refresh:0");

<?php
//Do something
header("Refresh:0");
?>

use this for different page

header("Refresh:0; url=button.php");


问:
Binding Combobox SelectedItem by a field's value
Combobox bind to a set of Provinces, Village object has ProvinceID field and i want to bind SelectedItem of Combobox to a Province with Village's ProvinceID.

My code is:

```<code><ComboBox ItemsSource="{Binding ProvincesList}"
          DisplayMemberPath="ProvinceName"
          SelectedValuePath="ProvinceID"
          SelectedValue="{Binding Village.ProvinceID}" />
</code>```

But SelectedItem is anything.

答: Not sure I understand the question, but what about setting the ComboBox's ValueMember to ProvinceID?</p>

ContentLicense: CC BY-SA 2.5

Body:
Combobox bind to a set of Provinces, Village object has ProvinceID field and i want to bind SelectedItem of Combobox to a Province with Village's ProvinceID.

My code is:

<ComboBox ItemsSource="{Binding ProvincesList}"
          DisplayMemberPath="ProvinceName"
          SelectedValuePath="ProvinceID"
          SelectedValue="{Binding Village.ProvinceID}" />

But SelectedItem is anything.


问:
java.lang.UnsatisfiedLinkError:
I am creating Fingerprint appliation . In this application have libNBioBSP.so file inside this path src/main/jniLibs/armeabi. Adding Realm function for database concept. But when run the application getting error like.

```<code>java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader[DexPathList[[zip file "/data/app/com.nitgen.SDK.AndroidBSP-2/base.apk"],nativeLibraryDirectories=[/data/app/com.nitgen.SDK.AndroidBSP-2/lib/arm, /vendor/lib, /system/lib]]] couldn't find "libNBioBSP.so"
</code>```

When run the application without Realm ,working well.

答:
Realm doesn't support armeabi, only armeabi-v7a and above. By the looks of it libNBioBSP.so doesn't come in a v7a variant?

This, unfortunately, confuses Android when it loads native code, which results in your application crashing like that. All native libraries must support the same set of architectures.

Unless you're able to build your native code for armeabi-v7a, you are unfortunately not able to combine Realm with your other native library.

Title: java.lang.UnsatisfiedLinkError:

Body:
I am creating Fingerprint appliation . In this application have libNBioBSP.so file inside this path src/main/jniLibs/armeabi. Adding Realm function for database concept. But when run the application getting error like.

java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader[DexPathList[[zip file "/data/app/com.nitgen.SDK.AndroidBSP-2/base.apk"],nativeLibraryDirectories=[/data/app/com.nitgen.SDK.AndroidBSP-2/lib/arm, /vendor/lib, /system/lib]]] couldn't find "libNBioBSP.so"

When run the application without Realm ,working well.


问:
Read only replication of remote pouchdb
I would like to have a local to the browser DB which updates itself from a remote source.  Am attempting to use pouchdb / cloudant to solve this.  The remote DB is used by many clients so should be read only and not require authentication.  In cloudant my permissions config for relevant db (e.g. "remoteDB")  is as follows:

```<code>{"cloudant":{"admin_user":["_writer","_admin","_replicator","_reader"],"nobody":["_reader"],"apiKey":["_writer","_admin","_replicator","_reader"]}}
</code>```

In my setup code I have the following:

```<code>var localDB = new PouchDB('local');
var remoteDB = new PouchDB('https://account.cloudant.com/remoteDB');

localDB.replicate.from(remoteDB, {live: false}).on('change', function (change) {
  console.log("change", change);
}).on('error', function (err) {
  console.log("err-replicate", err);
});
</code>```

I am getting a 401 unauthorised error when loading a page which includes this.  The request that causes this is a PUT request for:

https://account.cloudant.com/remoteDB/_local/JqXQso2dZEjdZsU1e_2Qxw==

The header params are:

_id: _local/JqXQso2dZEjdZsU1e_2Qxw==

last_seq: "0"

If I have the nobody user in cloudant for this DB have writer permission the error goes away.   Any ideas what is wrong here?

Is this the right way to have oneway replication from a remote source?

答:
The error you are seeing is PouchDB attempting to write "checkpoint" documents to the the remote Cloudant database. The checkpoints mark where the client got to in the revision timeline, making future replications more efficient as they can resume from where they left off.

You correctly surmise that the way to solve this for a read-only replication is grant "_reader" & "_replicator" permissions to the user (or to everyone). The _replicator permission allows only local documents to be written, not the core documents themselves. This is enough to allow checkpoint documents to be saved and for PouchDB to proceed without any errors.

Title: Read only replication of remote pouchdb

Body:
I would like to have a local to the browser DB which updates itself from a remote source.  Am attempting to use pouchdb / cloudant to solve this.  The remote DB is used by many clients so should be read only and not require authentication.  In cloudant my permissions config for relevant db (e.g. "remoteDB")  is as follows:

{"cloudant":{"admin_user":["_writer","_admin","_replicator","_reader"],"nobody":["_reader"],"apiKey":["_writer","_admin","_replicator","_reader"]}}

In my setup code I have the following:

var localDB = new PouchDB('local');
var remoteDB = new PouchDB('https://account.cloudant.com/remoteDB');

localDB.replicate.from(remoteDB, {live: false}).on('change', function (change) {
  console.log("change", change);
}).on('error', function (err) {
  console.log("err-replicate", err);
});

I am getting a 401 unauthorised error when loading a page which includes this.  The request that causes this is a PUT request for:

https://account.cloudant.com/remoteDB/_local/JqXQso2dZEjdZsU1e_2Qxw==

The header params are:

_id: _local/JqXQso2dZEjdZsU1e_2Qxw==

last_seq: "0"

If I have the nobody user in cloudant for this DB have writer permission the error goes away.   Any ideas what is wrong here?

Is this the right way to have oneway replication from a remote source?


问:
Link to open a Google Drive file in Sheets
Using the Google Drive API I can get a file's webViewLink to link to the file-preview in Drive, and the user can then select 'Open with Google Sheets' in the top bar to open the file up in Sheets.

Is there a way to skip that intermediary step, and link directly to that file in Google Sheets?

答:
File.resource also contains a link called webViewLink

webViewLink    string  A link for opening the file in a relevant Google editor or viewer in a browser.

This will not work on all file types but it should work on sheets.


问:
RegEx select whole string but omit substring match
Consider a long html string: I need to have the whole content without certain tags sections.

Example:

Consider the following string:

```<code>;decreasing'>1</a> <span class='active'>2</span><a href='F;search&
</code>```

I need to select all but the span section, thus removing the following

```<code><span class='active'>2</span>
</code>```

and ending up with only the following

```<code>;decreasing'>1</a> <a href='F;search&
</code>```

I tried the following with negative look behind selections in regex101.com but no luck.

```<code>^(?!=(<span class='active'>(.*?)<\/span>)).*$
</code>```

[Additional Info]

If I could combine the two following selections it would solve the problem:

1.Selects everything up to the span tag

```<code>.*?(?=<span)
</code>```

Selects everything from the closing span tag onward:

```<code>(?<=span>).*
</code>```

Thanks your help in advance.

答:
If your coding language permits you to do a regex split or replace call, you can use this pattern:

~<(span).*?(/\1)>~ or expand your tag list like this: ~<(span|div).*?(/\1)>~

Demo Link

There are risks involved in processing html with regex patterns, but they may or may not come into play depending on the structure of your html.

Body:
Consider a long html string: I need to have the whole content without certain tags sections.

Example:

Consider the following string:

;decreasing'>1 2<a href='F;search&

I need to select all but the span section, thus removing the following

2

and ending up with only the following

;decreasing'>1 <a href='F;search&

I tried the following with negative look behind selections in regex101.com but no luck.

^(?!=((.*?)<\/span>)).*$

[Additional Info]

If I could combine the two following selections it would solve the problem:

1.Selects everything up to the span tag

.*?(?=<span)

Selects everything from the closing span tag onward:

(?<=span>).*

Thanks your help in advance.


问:
How to print an iFrame with stylesheet?
I've created this code to print data from an iFrame

```<code>function (data) {
    var frame = $("<iframe>", {
        name: "iFrame",
        class: "printFrame"
    });

    frame.appendTo("body");

    var head = $("<head></head>");

    _.each($("head link[rel=stylesheet]"), function (link) {
        var csslink = $("<link/>", { rel: "stylesheet", href: $(link).prop("href") })
        head.append(csslink);
    ;});

    frame.contents().find("head")
        .replaceWith(head);

    frame.contents().find("body")
        .append(this.html());

    window.frames["iFrame"].focus();
    window.frames["iFrame"].print();
}
</code>```

This creates an iFrame, adds a head to where it sets all the css links that are needed for this website. Then it creates the body.

Trouble is, the styling won't get applied to the print, unless I break at line frame.contents().find("head").replaceWith(head), which means that something in that part is running asynchronously.

Question is, can I somehow get the code to wait for a short while before running that line, or is there perhaps another way to do this? Unfortunately I'm not all that familiar with iFrames, so I have no clue what it's trying to do there.

答:
This turned out to be a real hassle. I've always been reluctant to using iframes, but since there are many resources saying that using an iframe for printing more stuff than what's on the screen, we figured we'd give it a try.

This was instead solved by putting the data inside a hidden div which then was shown before a window.print(). At the same time, all other elements on the page were given a "hidden-print" class which is a class we're already using to hide elements for prints.

This might not be as elegant for the user (The div will show briefly before the user exits the print dialogue), but it's a way more simpler code to use and manage.

Title: How to print an iFrame with stylesheet?

Body:
I've created this code to print data from an iFrame

function (data) {
    var frame = $("", {
        name: "iFrame",
        class: "printFrame"
    });

    frame.appendTo("body");

    var head = $("");

    _.each($("head link[rel=stylesheet]"), function (link) {
        var csslink = $("<link/>", { rel: "stylesheet", href: $(link).prop("href") })
        head.append(csslink);
    ;});

    frame.contents().find("head")
        .replaceWith(head);

    frame.contents().find("body")
        .append(this.html());

    window.frames["iFrame"].focus();
    window.frames["iFrame"].print();
}

This creates an iFrame, adds a head to where it sets all the css links that are needed for this website. Then it creates the body.

Trouble is, the styling won't get applied to the print, unless I break at line frame.contents().find("head").replaceWith(head), which means that something in that part is running asynchronously.

Question is, can I somehow get the code to wait for a short while before running that line, or is there perhaps another way to do this? Unfortunately I'm not all that familiar with iFrames, so I have no clue what it's trying to do there.


问:
Do I need to add thread locking to simple variables?
Let's say I have an object for which multiple threads can read/write to the state and someValue variables. Do I need to add locking if these variables are types like int, double, enums etc.?

```<code>enum State: String {
  case one
  case two
}

class Object {
  var state: State
  var someValue: Double
}
</code>```

答:
Strictly speaking, no (although "yes" would also be a valid answer, and arguably a more correct one for the general case).

Depending on what you need/want, you may very well just use atomic operations using functions like e.g. OSAtomicIncrement32 or OSAtomicCompareAndSwapPtr which is not locking.

Note, however, that even if one operation is atomic, two individually atomic, consecutive operations are not atomic in their entirety. Thus, if for example, you want to update both state and someValue consistently, then going without a lock is sheer impossible if correctness matters (unless, by coincidence, they're small enough so you can cheat and squeeze them into a single larger atomic type).

Also note that even though you either need to lock or use atomic operations for program correctness, you can occasionally very well "get away" without doing so. That's because on the majority of platforms, ordinary loads and stores to properly aligned memory addresses are atomic anyway.

However, do not get tempted, this is not as good as it sounds, and indeed not a good thing at all -- relying that things will just work (even if you "tested", and it works fine by all means) creates the kind of program which works fine during development and then causes a thousand support tickets a month after shipping, and there's no obvious indication to what's gone wrong.

Body:
Let's say I have an object for which multiple threads can read/write to the state and someValue variables. Do I need to add locking if these variables are types like int, double, enums etc.?

enum State: String {
  case one
  case two
}

class Object {
  var state: State
  var someValue: Double
}


问:
How do I fetch data based on user id using Laravel 5.4
I have models User and Diares set up with the hasMany and BelongTo relstionship. I'm trying to fetch data from the  Diaries table associated with a particular user. I tried auth but it didnt work for me. How can i achieve that and display it in the blade view as well. Here is my current code:

```<code>public function index(User $id)
    {
      $user = User::find($id);
    $record =  $user->diary;

      return view('home')->with('record', $record);

    }
</code>```

The blade file it should display to:

```<code> @foreach ($record as $diary)
    {{ $diary->error }}
      {{ $diary->fix }}
@endforeach
</code>```

答:
In your index function the $id is not integer - this is a User instance, so you can try use this:</p>

```<code>public function index(User $user)
{
  $record =  $user->diary;

  return view('home')->with('record', $record);

}
</code>```

Body:
I have models User and Diares set up with the hasMany and BelongTo relstionship. I'm trying to fetch data from the  Diaries table associated with a particular user. I tried auth but it didnt work for me. How can i achieve that and display it in the blade view as well. Here is my current code:

public function index(User $id)
    {
      $user = User::find($id);
    $record =  $user->diary;

      return view('home')->with('record', $record);

    }

The blade file it should display to:

 @foreach ($record as $diary)
    {{ $diary->error }}
      {{ $diary->fix }}
@endforeach

Body:
In your index function the $id is not integer - this is a User instance, so you can try use this:

public function index(User $user)
{
  $record =  $user->diary;

  return view('home')->with('record', $record);

}


问:
Entity Framework Ignore properties on inserting data with temporal tables
I have a class named Address that is a system versioned table. I am trying to insert into this table using entity framework context adding an object to the context and then doing a SaveChanges call. This worked as expected when the table was not system versioned. In my model that looks something like this minus some properties that are not related to this question:

```<code>        [DataMember]
        public System.DateTime SysStartTime
        {
            get { return _sysStartTime; }
            set
            {
                if (_sysStartTime != value)
                {
                    _sysStartTime = value;
                    OnPropertyChanged("SysStartTime");
                }
            }
        }
        private System.DateTime _sysStartTime;

        [DataMember]
        public System.DateTime SysEndTime
        {
            get { return _sysEndTime; }
            set
            {
                if (_sysEndTime != value)
                {
                    _sysEndTime = value;
                    OnPropertyChanged("SysEndTime");
                }
            }
        }
        private System.DateTime _sysEndTime;

        [DataMember]
        public int AddressId
        {
            get { return _addressId; }
            set
            {
                if (_addressId != value)
                {
                    if (ChangeTracker.ChangeTrackingEnabled && ChangeTracker.State != ObjectState.Added)
                    {
                        throw new InvalidOperationException("The property 'AddressId' is part of the object's key and cannot be changed. Changes to key properties can only be made when the object is not being tracked or is in the Added state.");
                    }
                    _addressId = value;
                    OnPropertyChanged("AddressId");
                }
            }
        }
        private int _addressId;
</code>```

This historical table was created as per documentation with a generated always property hidden and default value.
When I try to do a simple insert I get the Error:

Cannot insert value into generated always identity column

I understand what the error is saying but I don't know how to fix it. I have tried to remove the SysStartTime and SysEndTime properties from the model but that gives me validation issues. I have also tried not setting the properties on the model as DataMember and even IgnoreDataMember but the result was always the same. My question is how can I remove the SysStartTime and SysEndTime properties from the object with the address model before adding it to the context? Thank you.

UPDATE:
I have used this code to create my temporal table:

```<code>ALTER TABLE [dbo].[Address] ADD
                             [SysStartTime] datetime2(0) GENERATED ALWAYS AS ROW START HIDDEN NOT NULL CONSTRAINT DF_Telco_SysStartTime DEFAULT '1900-01-01 00:00:00',
                             [SysEndTime] datetime2(0) GENERATED ALWAYS AS ROW END HIDDEN NOT NULL CONSTRAINT DF_Telco_SysEndTime DEFAULT '9999-12-31 23:59:59',
                             PERIOD FOR SYSTEM_TIME ([SysStartTime], [SysEndTime])

ALTER TABLE [dbo].[Address]
                             SET (SYSTEM_VERSIONING = ON (HISTORY_TABLE = [dbo].[Address_History]));
</code>```

答: I have found a workaround for this issue by modifying the model.edmx file and adding to the SysStartTime and SysEndTime StoreGeneratedPattern="Computed" property.

Body:
I have a class named Address that is a system versioned table. I am trying to insert into this table using entity framework context adding an object to the context and then doing a SaveChanges call. This worked as expected when the table was not system versioned. In my model that looks something like this minus some properties that are not related to this question:

        [DataMember]
        public System.DateTime SysStartTime
        {
            get { return _sysStartTime; }
            set
            {
                if (_sysStartTime != value)
                {
                    _sysStartTime = value;
                    OnPropertyChanged("SysStartTime");
                }
            }
        }
        private System.DateTime _sysStartTime;

        [DataMember]
        public System.DateTime SysEndTime
        {
            get { return _sysEndTime; }
            set
            {
                if (_sysEndTime != value)
                {
                    _sysEndTime = value;
                    OnPropertyChanged("SysEndTime");
                }
            }
        }
        private System.DateTime _sysEndTime;

        [DataMember]
        public int AddressId
        {
            get { return _addressId; }
            set
            {
                if (_addressId != value)
                {
                    if (ChangeTracker.ChangeTrackingEnabled && ChangeTracker.State != ObjectState.Added)
                    {
                        throw new InvalidOperationException("The property 'AddressId' is part of the object's key and cannot be changed. Changes to key properties can only be made when the object is not being tracked or is in the Added state.");
                    }
                    _addressId = value;
                    OnPropertyChanged("AddressId");
                }
            }
        }
        private int _addressId;

This historical table was created as per documentation with a generated always property hidden and default value.
When I try to do a simple insert I get the Error:

Cannot insert value into generated always identity column

I understand what the error is saying but I don't know how to fix it. I have tried to remove the SysStartTime and SysEndTime properties from the model but that gives me validation issues. I have also tried not setting the properties on the model as DataMember and even IgnoreDataMember but the result was always the same. My question is how can I remove the SysStartTime and SysEndTime properties from the object with the address model before adding it to the context? Thank you.

UPDATE:
I have used this code to create my temporal table:

ALTER TABLE [dbo].[Address] ADD
                             [SysStartTime] datetime2(0) GENERATED ALWAYS AS ROW START HIDDEN NOT NULL CONSTRAINT DF_Telco_SysStartTime DEFAULT '1900-01-01 00:00:00',
                             [SysEndTime] datetime2(0) GENERATED ALWAYS AS ROW END HIDDEN NOT NULL CONSTRAINT DF_Telco_SysEndTime DEFAULT '9999-12-31 23:59:59',
                             PERIOD FOR SYSTEM_TIME ([SysStartTime], [SysEndTime])

ALTER TABLE [dbo].[Address]
                             SET (SYSTEM_VERSIONING = ON (HISTORY_TABLE = [dbo].[Address_History]));


问:
Uncaught ReferenceError: Invalid left-hand side in assignment while fetching value from JSON.stringify(data)
I want to get value from JSON.stringify(data) to textbox but it showing Uncaught ReferenceError error in window console browser. I am confusing that when I am doing alert to the JSON.stringify(data) at that time it shows the value in alert while when I insert that value from JSON.stringify(data) to the textbox at that time it shows the Uncaught ReferenceError in window console browser.

Here is my code

```<code>  function blurFunction() {
        var c = $find("<%=dropdwn_consignor.ClientID %>");

        $.ajax({
            type: "POST",
            url: "Booking123.aspx/GetCnorGSTNo",
            data: "{ Param1: '" + c.get_textBoxControl().value + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: "true",
            cache: "false",
            success: function (data) {
                alert(document.getElementById("#<%=txtbx_cnortin.ClientID%>") = JSON.stringify(data));
            },
            error: function () {
                alert("something went wrong...!!!");
            }
        });
    }
</code>```

Please help me to solve this issues.

Thank You.

答:
You need to set value and get rid of alert() its not a debugging tool

```<code>document.getElementById("#<%=txtbx_cnortin.ClientID%>").value = JSON.stringify(data)
</code>```

instead of

```<code>document.getElementById("#<%=txtbx_cnortin.ClientID%>") = JSON.stringify(data);
</code>```

As you are using jQuery use

```<code>$("#<%=txtbx_cnortin.ClientID%>").val(JSON.stringify(data))
</code>```

Body:
I want to get value from JSON.stringify(data) to textbox but it showing Uncaught ReferenceError error in window console browser. I am confusing that when I am doing alert to the JSON.stringify(data) at that time it shows the value in alert while when I insert that value from JSON.stringify(data) to the textbox at that time it shows the Uncaught ReferenceError in window console browser.

Here is my code

  function blurFunction() {
        var c = $find("<%=dropdwn_consignor.ClientID %>");

        $.ajax({
            type: "POST",
            url: "Booking123.aspx/GetCnorGSTNo",
            data: "{ Param1: '" + c.get_textBoxControl().value + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: "true",
            cache: "false",
            success: function (data) {
                alert(document.getElementById("#<%=txtbx_cnortin.ClientID%>") = JSON.stringify(data));
            },
            error: function () {
                alert("something went wrong...!!!");
            }
        });
    }

Please help me to solve this issues.

Thank You.

Body:
You need to set value and get rid of alert() its not a debugging tool

document.getElementById("#<%=txtbx_cnortin.ClientID%>").value = JSON.stringify(data)

instead of

document.getElementById("#<%=txtbx_cnortin.ClientID%>") = JSON.stringify(data);

As you are using jQuery use

$("#<%=txtbx_cnortin.ClientID%>").val(JSON.stringify(data))


问:
Copy value of div and put in it another div
I would like to know how i am suppose to copy the value of a div (for instance, the first one), and paste it to a second div via a mouse click event.

Workflow:

Click on the first div (to copy the value number 1)

If i click again, it will become 2, if i click again, it will become 3 and so forth.

I'm looking forward to seeing your response.

Example : Image Link

ok

from copying here:

```<code>                  <li class="active">
                    <a href="#"  on-click="chip_amnt">
                      <img src="chip.jpg" alt="">
                      <span>250</span>
                    </a>
                  </li>

                  <li class="active">
                    <a href="#"  on-click="chip_amnt">
                      <img src="{{image_url}}" alt="">
                      <span>500/span>
                    </a>
                  </li>

                  <li class="active">
                    <a href="#"  on-click="chip_amnt">
                      <img src="{{image_url}}" alt="">
                      <span>100</span>
                    </a>
                  </li>
</code>```

to here:

```<code>            <li class="">
                  Player Pair
                </li>
                <li class="">
                  Tie
                </li>
                <li class="">
                  Banker Pair
                </li>
                <li class="">
                  Player
                </li>
                <li class="">
                  Banker
                </li>
</code>```

答:
var tmp=0;

function chip_amnt(o){
  tmp = Number(o.innerText);
}

function chip_provide(o){
  var value = (Number(o.innerHTML) || 0) + (tmp || 0);

  value && (o.innerHTML = value);

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
<li class="active">

    <img src="chip.jpg" alt="">
    <span>250</span>

</li>

<li class="active">

    <img src="{{image_url}}" alt="">
    <span>500</span>

 </li>
<li class="active">

   <img src="{{image_url}}" alt="">
   <span>100</span>

</li>
</ul>
to here:
<ul>
<li class="" onclick="chip_provide(this)">
  Player Pair
</li>
<li class=""  onclick="chip_provide(this)">
  Tie
</li>
<li class=""  onclick="chip_provide(this)">
  Banker Pair
</li>
<li class=""  onclick="chip_provide(this)">
  Player
</li>
<li class=""  onclick="chip_provide(this)">
  Banker
</li>
</ul></code>```

Body:
I would like to know how i am suppose to copy the value of a div (for instance, the first one), and paste it to a second div via a mouse click event.

Workflow:

Click on the first div (to copy the value number 1)

If i click again, it will become 2, if i click again, it will become 3 and so forth.

I'm looking forward to seeing your response.

Example : Image Link

ok

from copying here:

                      250

                      500/span>

                      100

to here:

                  Player Pair

                  Tie

                  Banker Pair

                  Player

                  Banker

Body:
var tmp=0;

function chip_amnt(o){
  tmp = Number(o.innerText);
}

function chip_provide(o){
  var value = (Number(o.innerHTML) || 0) + (tmp || 0);

  value && (o.innerHTML = value);

}

<ul>
<li class="active">
  <a href="#" onclick="chip_amnt(this)">
    <img src="chip.jpg" alt="">
    <span>250</span>
  </a>
</li>

<li class="active">
  <a href="#" onclick="chip_amnt(this)">
    <img src="{{image_url}}" alt="">
    <span>500</span>
  </a>
 </li>
<li class="active">
  <a href="#"  onclick="chip_amnt(this)">
   <img src="{{image_url}}" alt="">
   <span>100</span>
  </a>
</li>
</ul>
to here:
<ul>
<li class="" onclick="chip_provide(this)">
  Player Pair
</li>
<li class=""  onclick="chip_provide(this)">
  Tie
</li>
<li class=""  onclick="chip_provide(this)">
  Banker Pair
</li>
<li class=""  onclick="chip_provide(this)">
  Player
</li>
<li class=""  onclick="chip_provide(this)">
  Banker
</li>
</ul>


问:
Error : could not find function "ImportMethodFrom"
I tried to run the code in Chapter 7 Data mining with R learning with case study book but I got an error in following line:

```<code>rankWorkflows(svm, maxs = TRUE)
</code>```

The error was:

Error in as.character.default(X[[i]], ...) :    no method for coercing
  this S4 class to a vector

Then I searched on the internet and found following solution:

```<code>importMethodsFrom(GenomicRanges, as.data.frame)
</code>```

and again again I got a new error:

Error: could not find function "importMethodFrom"

I searched a lot but I got nothing :(

答:
You can try using library(sos) to find the packages where your function is located.

```<code>library(sos)
findFn("replaceherewithyourfunction")
</code>```

Body:
I tried to run the code in Chapter 7 Data mining with R learning with case study book but I got an error in following line:

rankWorkflows(svm, maxs = TRUE)

The error was:

Error in as.character.default(X[[i]], ...) :    no method for coercing
  this S4 class to a vector

Then I searched on the internet and found following solution:

importMethodsFrom(GenomicRanges, as.data.frame)

and again again I got a new error:

Error: could not find function "importMethodFrom"

I searched a lot but I got nothing :(

Body:
You can try using library(sos) to find the packages where your function is located.

library(sos)
findFn("replaceherewithyourfunction")


问:
Pop open a mail window that has HTML formatting, C#
I currently have a text box in a program where the user can input text and format it in HTML (  tags around bold text, etc).

I was using MAPI32.DLL to open an email window in Outlook with this text, but it seems like MAPI is not a good interface for HTML, as it left the raw HTML in there, displaying the actual <> tags.

So, I am currently pursuing alternative ways to pop open an email window, with the HTML text formatted.  I have read suggestions of using SMTP, but will that still allow me to pop open the email window with the user's email program, or is it going to send the email directly?  I would prefer the former, with the email popping open in the user's email client.

Thanks.

答:
Seems to me that the simplest solution would to be to use one of the many WYSIWYG HTML text editors out there to display/edit the email, then use SMTP to send it.

Here is an editor that I have used in the past that is pretty simple:

http://www.codeproject.com/KB/edit/editor_in_windows_forms.aspx


答:
Use value property to assign a value. Dont use # in getElementById() use # in jquery

```<code> document.getElementById("<%=txtbx_cnortin.ClientID%>").value = data.D;
</code>```

OR
Just use jquery

```<code>$("#<%=txtbx_cnortin.ClientID%>").value =data.D;
</code>```

Title: Uncaught ReferenceError: Invalid left-hand side in assignment while fetching value from JSON.stringify(data)

Body:
Use value property to assign a value. Dont use # in getElementById() use # in jquery

 document.getElementById("<%=txtbx_cnortin.ClientID%>").value = data.D;

OR
Just use jquery

$("#<%=txtbx_cnortin.ClientID%>").value =data.D;


问:
Need architecture hint: Data replication into the cloud + data cleansing
I need to sync customer data from several on-premise databases into the cloud. In a second step, the customer data there needs some cleanup in order to remove duplicates (of different types). Based on that cleansed data I need to do some data analytics.

To achieve this goal, I'm searching for an open source framework or cloud solution I can use for. I took a look into Apache Apex and Apache Kafka, but I'm not sure whether these are the right solutions.

Can you give me a hint which frameworks you would use for such an task?

答: Yes, you can use Apache Apex for your use case. Apache Apex is supported with Apache Malhar which can help you build application quickly to load data using JDBC input operator and then either store it to your cloud storage ( may be S3 ) or you can do de-duplication before storing it to any sink. It also supports Dedup operator for such kind of operations. But as mentioned in previous reply, Apex do need Hadoop underneath to function.  </p>


问:
how to make a tag change properties after a specific input is checked?
I am creating a quiz website for a school project. Whenever a correct answer is selected (input type=radio) then I want the line adjacent to it to become green and when an incorrect answer is selected I want the line to become red.

Is there any way to do this using css only and not JavaScript.

答:
Have some attribute in your input indicating that it's the right option and then listen for it in CSS using the [attribute="value"] then select the next tag (p etc.) with some kind of operator (like +)

JSfiddle demo


问:
numpy type conversion during broadcast
I'm using the numpy broadcast function to map a set of values over a set of coordinates. The values can be of heterogeneous type, including primitives. My problem is that the broadcast function is converting the primitive types under certain conditions. See for example this code:

```<code>In [11]: x = np.array([1])
    ...: y = np.array(['test', 10])
    ...: list(np.broadcast(x, y))

Out[11]: [(1, 'test'), (1, '10')]
</code>```

The int 10 that was passed in the y value has been converted to a string '10' after the broadcast.

Is it possible to prevent this casting behaviour somehow?

答:
This is because when you do

```<code>y = np.array(['test', 10])
</code>```

the result is

```<code>array(['test', '10'],
  dtype='<U4')
</code>```

If you do y = np.array(['test', 10], dtype=object)
the result will be as you wish.

Title: numpy type conversion during broadcast

Body:
I'm using the numpy broadcast function to map a set of values over a set of coordinates. The values can be of heterogeneous type, including primitives. My problem is that the broadcast function is converting the primitive types under certain conditions. See for example this code:

In [11]: x = np.array([1])
    ...: y = np.array(['test', 10])
    ...: list(np.broadcast(x, y))

Out[11]: [(1, 'test'), (1, '10')]

The int 10 that was passed in the y value has been converted to a string '10' after the broadcast.

Is it possible to prevent this casting behaviour somehow?

Body:
This is because when you do

y = np.array(['test', 10])

the result is

array(['test', '10'],
  dtype='<U4')

If you do y = np.array(['test', 10], dtype=object)
the result will be as you wish.


问:
Spark ML Pipeline with RandomForest takes too long on 20MB dataset
I am using Spark ML to run some ML experiments, and on a small dataset of 20MB (Poker dataset) and a Random Forest with parameter grid, it takes 1h and 30 minutes to finish. Similarly with scikit-learn it takes much much less.

In terms of environment, I was testing with 2 slaves, 15GB memory each, 24 cores. I assume it was not supposed to take that long and I am wondering if the problem lies within my code, since I am fairly new to Spark.

Here it is:

```<code>df = pd.read_csv(http://archive.ics.uci.edu/ml/machine-learning-databases/poker/poker-hand-testing.data)
dataframe = sqlContext.createDataFrame(df)

train, test = dataframe.randomSplit([0.7, 0.3])

columnTypes = dataframe.dtypes

for ct in columnTypes:
    if ct[1] == 'string' and ct[0] != 'label':
        categoricalCols += [ct[0]]
    elif ct[0] != 'label':
        numericCols += [ct[0]]

stages = []

for categoricalCol in categoricalCols:

    stringIndexer = StringIndexer(inputCol=categoricalCol, outputCol=categoricalCol+"Index")

stages += [stringIndexer]

assemblerInputs = map(lambda c: c + "Index", categoricalCols) + numericCols

assembler = VectorAssembler(inputCols=assemblerInputs, outputCol="features")

stages += [assembler]

labelIndexer = StringIndexer(inputCol='label', outputCol='indexedLabel', handleInvalid='skip')

stages += [labelIndexer]

estimator = RandomForestClassifier(labelCol="indexedLabel", featuresCol="features")

stages += [estimator]

parameters = {"maxDepth" : [3, 5, 10, 15], "maxBins" : [6, 12, 24, 32], "numTrees" : [3, 5, 10]}

paramGrid = ParamGridBuilder()
for key, value in parameters.iteritems():
    paramGrid.addGrid(estimator.getParam(key), value)
estimatorParamMaps = (paramGrid.build())

pipeline = Pipeline(stages=stages)

crossValidator = CrossValidator(estimator=pipeline, estimatorParamMaps=estimatorParamMaps, evaluator=MulticlassClassificationEvaluator(labelCol='indexedLabel', predictionCol='prediction', metricName='f1'), numFolds=3)

pipelineModel = crossValidator.fit(train)

predictions = pipelineModel.transform(test)

evaluator = pipeline.getEvaluator().evaluate(predictions)
</code>```

Thanks in advance, any comments/suggestions are highly appreciated :)

答:
The following may not solve your problem completely but it should give you some pointer to start.

The first problem that you are facing is the disproportion between the amount of data and the resources.

This means that since you are parallelizing a local collection (pandas dataframe), Spark will use the default parallelism configuration. Which is most likely to be resulting in 48 partitions with less than 0.5mb per partition. (Spark doesn't do well with small files nor small partitions)

The second problem is related to expensive optimizations/approximations techniques used by Tree models in Spark.

Spark tree models use some tricks to optimally bucket continuous variables. With small data it is way cheaper to just get the exact splits.
It mainly uses approximated quantiles in this case.

Usually, in a single machine framework scenario, like scikit, the tree model uses unique feature values for continuous features as splits candidates for the best fit calculation. Whereas in Apache Spark, the tree model uses quantiles for each feature as a split candidate.

Also to add that you shouldn't forget as well that cross validation is a heavy and long tasks as it's proportional to the combination of your 3 hyper-parameters times the number of folds times the time spent to train each model (GridSearch approach). You might want to cache your data per example for a start but it will still not gain you much time. I believe that spark is an overkill for this amount of data. You might want to use scikit learn instead and maybe use spark-sklearn to distributed local model training.

Spark will learn each model separately and sequentially with the hypothesis that data is distributed and big.

You can of course optimize performance using columnar data based file formats like parquet and tuning spark itself, etc. it's too broad to talk about it here.

You can read more about tree models scalability with spark-mllib in this following blogpost :

Scalable Decision Trees in MLlib

Body:
I am using Spark ML to run some ML experiments, and on a small dataset of 20MB (Poker dataset) and a Random Forest with parameter grid, it takes 1h and 30 minutes to finish. Similarly with scikit-learn it takes much much less.

In terms of environment, I was testing with 2 slaves, 15GB memory each, 24 cores. I assume it was not supposed to take that long and I am wondering if the problem lies within my code, since I am fairly new to Spark.

Here it is:

df = pd.read_csv(http://archive.ics.uci.edu/ml/machine-learning-databases/poker/poker-hand-testing.data)
dataframe = sqlContext.createDataFrame(df)

train, test = dataframe.randomSplit([0.7, 0.3])

columnTypes = dataframe.dtypes

for ct in columnTypes:
    if ct[1] == 'string' and ct[0] != 'label':
        categoricalCols += [ct[0]]
    elif ct[0] != 'label':
        numericCols += [ct[0]]

stages = []

for categoricalCol in categoricalCols:

    stringIndexer = StringIndexer(inputCol=categoricalCol, outputCol=categoricalCol+"Index")

stages += [stringIndexer]

assemblerInputs = map(lambda c: c + "Index", categoricalCols) + numericCols

assembler = VectorAssembler(inputCols=assemblerInputs, outputCol="features")

stages += [assembler]

labelIndexer = StringIndexer(inputCol='label', outputCol='indexedLabel', handleInvalid='skip')

stages += [labelIndexer]

estimator = RandomForestClassifier(labelCol="indexedLabel", featuresCol="features")

stages += [estimator]

parameters = {"maxDepth" : [3, 5, 10, 15], "maxBins" : [6, 12, 24, 32], "numTrees" : [3, 5, 10]}

paramGrid = ParamGridBuilder()
for key, value in parameters.iteritems():
    paramGrid.addGrid(estimator.getParam(key), value)
estimatorParamMaps = (paramGrid.build())

pipeline = Pipeline(stages=stages)

crossValidator = CrossValidator(estimator=pipeline, estimatorParamMaps=estimatorParamMaps, evaluator=MulticlassClassificationEvaluator(labelCol='indexedLabel', predictionCol='prediction', metricName='f1'), numFolds=3)

pipelineModel = crossValidator.fit(train)

predictions = pipelineModel.transform(test)

evaluator = pipeline.getEvaluator().evaluate(predictions)

Thanks in advance, any comments/suggestions are highly appreciated :)


问:
Laravel chmod(/var/dev/project/storage/oauth-public.key): Operation failed: Operation not permitted
After I updated the following packages I got an error that the oauth-public.key file couldn't be found.

Package operations: 1 install, 2 updates, 0 removals

Updating laravel/framework (v5.4.27 => v5.4.28): Downloading (100%)

    Installing defuse/php-encryption (v2.1.0): Downloading (100%)

    Updating league/oauth2-server (5.1.3 => 5.1.4): Downloading (100%)

Firstly I deleted the two oauth- files in project/storage and then executed this command: php artisan passport:install to generate new oauth- files.

Now I get the following error when trying to access an api route.

(1/1) ErrorException
  chmod(/var/dev/project/storage/oauth-public.key): Operation failed: Operation not permitted

Stack trace

in CryptKey.php (line 51)

at HandleExceptions->handleError(2, 'chmod(/var/dev/project/storage/oauth-public.key): Operation failed: Operation not permitted', '/var/dev/project/vendor/league/oauth2-server/src/CryptKey.php', 51, array('keyPath' => 'file:///var/dev/project/storage/oauth-public.key', 'passPhrase' => null, 'keyPathPerms' => '644'))

at chmod('file:///var/dev/project/storage/oauth-public.key', 384)
  in CryptKey.php (line 51)

at CryptKey->__construct('file:///var/dev/project/storage/oauth-public.key')
  in ResourceServer.php (line 50)

File permissions

```<code>-rw-r--r-- user:user oauth-private.key
-rw-r--r-- user:user oauth-public.key
</code>```

Update 1

I found out that oauth Libaray introduced a security fix. Oauth V5 Security Improvements

Version 5.1.4 is a backwards compatbile with other 5.1.x releases.

You will notice in your server logs a message like this:

You must set the encryption key going forward to improve the security of this library - see this page for more information https://oauth2.thephpleague.com/v5-security-improvements/

To supress this notice once you have instantiated an instance of \League\OAuth2\Server\AuthorizationServer you should call the setEncryptionKey() method passing in at least 32 bytes of random data.

You can generate this using base64_encode(random_bytes(32)). Alternatively if you’re using a framework such as Laravel which has a encryption key already generated you can pass in that (in the case of Laravel use env('APP_KEY')).

Problem is that the maintainer of Laravel Passport has to fix this.

Update 2

After I removed the vendor folder and executed composer install again I get still the same error.

答:
Same issue here, i've temporarily rolled back to an earlier version of my composer.lock file. It looks like the OAuth package is trying to modify the permissions of the keys within the storage folder and my server is not having it.

Im going to take a look at the packages change log and see whats changed and perhaps rerun the updates after hours.

Body:
After I updated the following packages I got an error that the oauth-public.key file couldn't be found.

Package operations: 1 install, 2 updates, 0 removals

Updating laravel/framework (v5.4.27 => v5.4.28): Downloading (100%)

    Installing defuse/php-encryption (v2.1.0): Downloading (100%)

    Updating league/oauth2-server (5.1.3 => 5.1.4): Downloading (100%)

Firstly I deleted the two oauth- files in project/storage and then executed this command: php artisan passport:install to generate new oauth- files.

Now I get the following error when trying to access an api route.

(1/1) ErrorException
  chmod(/var/dev/project/storage/oauth-public.key): Operation failed: Operation not permitted

Stack trace

in CryptKey.php (line 51)

at HandleExceptions->handleError(2, 'chmod(/var/dev/project/storage/oauth-public.key): Operation failed: Operation not permitted', '/var/dev/project/vendor/league/oauth2-server/src/CryptKey.php', 51, array('keyPath' => 'file:///var/dev/project/storage/oauth-public.key', 'passPhrase' => null, 'keyPathPerms' => '644'))

at chmod('file:///var/dev/project/storage/oauth-public.key', 384)
  in CryptKey.php (line 51)

at CryptKey->__construct('file:///var/dev/project/storage/oauth-public.key')
  in ResourceServer.php (line 50)

File permissions

-rw-r--r-- user:user oauth-private.key
-rw-r--r-- user:user oauth-public.key

Update 1

I found out that oauth Libaray introduced a security fix. Oauth V5 Security Improvements

Version 5.1.4 is a backwards compatbile with other 5.1.x releases.

You will notice in your server logs a message like this:

You must set the encryption key going forward to improve the security of this library - see this page for more information https://oauth2.thephpleague.com/v5-security-improvements/

To supress this notice once you have instantiated an instance of \League\OAuth2\Server\AuthorizationServer you should call the setEncryptionKey() method passing in at least 32 bytes of random data.

You can generate this using base64_encode(random_bytes(32)). Alternatively if you’re using a framework such as Laravel which has a encryption key already generated you can pass in that (in the case of Laravel use env('APP_KEY')).

Problem is that the maintainer of Laravel Passport has to fix this.

Update 2

After I removed the vendor folder and executed composer install again I get still the same error.


问:
WordPress Pagination/Infinite Scroll breaking another plugin
I've implemented infinite scroll on a site I'm developing using WordPress, the Thesis theme, and the plugin Infinite Scroll v2.6.2 by Beaver6813 et al.

Unfortunately, it seems to breaking another plugin, kk Star Ratings v2.6 by Kamal Khan.

My site is configured to display posts with a certain category on the home page via Settings > Reading > Your Latest Posts and the following code in my functions.php file:

```<code>add_action( 'pre_get_posts', function ( $q )
{
    if (    $q->is_home()
         && $q->is_main_query()
    ) {
        $q->set( 'category_name',  'strip' );
        $q->set( 'posts_per_page', 3 );
    }
});
</code>```

Infinite scrolling is working. The star ratings plugin displays as I want it to between the post title and post content.

However, the core functionality -- the ability to click on a star and rate the post -- only works on the initial load of three posts. Everything lazy-loaded after that displays the stars and the number of ratings, but I can't actually click a star to rate the post.

Here's an example of it working on one of the top posts: working.

And here's an example of the broken functionality: not-working.

The difference appears to be in the styling.

The working ones have a width of 80%, as follows:

```<code><div class="kksr-fuel kksr-star orange" style="width: 80%;"</div>
</code>```

The broken ones have a width of 0%:

```<code><div class="kksr-fuel kksr-star yellow" style="width:0%;"</div>
</code>```

I did try forcing "width: 80% !important" via my stylesheet. While it visually changed the interface, I still wasn't able to save a rating by clicking.

Although I can see the non-working plugins, I'm hypothesizing that the width is essentially hiding the piece of functionality I need in order to rate the posts.

I just can't quite figure out how to tell it to knock it off.

I've tried a few different plugins and had the same results. I'm a novice, but I suspect the way I'm using infinite scroll for pagination is preventing the plugin from fully... I don't know, loading, I guess.

I feel like I'm very close to figuring this out... just need a nudge over the finish line, please!

答:
Here's the fix I mentioned earlier in my comment.

The code below was provided by someone from Fiverr. I added it to a script and enqueued it.

```<code>jQuery(document).ready(function($){
  setInterval(function(){
    if(!$('.home .content > div:last-child').hasClass('lg')){
      $('.home .content > div:last-child').addClass('lg');
      $(".kk-star-ratings").kkstarratings();
    }
  }, 2000);
});
</code>```

Body:
I've implemented infinite scroll on a site I'm developing using WordPress, the Thesis theme, and the plugin Infinite Scroll v2.6.2 by Beaver6813 et al.

Unfortunately, it seems to breaking another plugin, kk Star Ratings v2.6 by Kamal Khan.

My site is configured to display posts with a certain category on the home page via Settings > Reading > Your Latest Posts and the following code in my functions.php file:

add_action( 'pre_get_posts', function ( $q )
{
    if (    $q->is_home()
         && $q->is_main_query()
    ) {
        $q->set( 'category_name',  'strip' );
        $q->set( 'posts_per_page', 3 );
    }
});

Infinite scrolling is working. The star ratings plugin displays as I want it to between the post title and post content.

However, the core functionality -- the ability to click on a star and rate the post -- only works on the initial load of three posts. Everything lazy-loaded after that displays the stars and the number of ratings, but I can't actually click a star to rate the post.

Here's an example of it working on one of the top posts: working.

And here's an example of the broken functionality: not-working.

The difference appears to be in the styling.

The working ones have a width of 80%, as follows:

<div class="kksr-fuel kksr-star orange" style="width: 80%;"

The broken ones have a width of 0%:

<div class="kksr-fuel kksr-star yellow" style="width:0%;"

I did try forcing "width: 80% !important" via my stylesheet. While it visually changed the interface, I still wasn't able to save a rating by clicking.

Although I can see the non-working plugins, I'm hypothesizing that the width is essentially hiding the piece of functionality I need in order to rate the posts.

I just can't quite figure out how to tell it to knock it off.

I've tried a few different plugins and had the same results. I'm a novice, but I suspect the way I'm using infinite scroll for pagination is preventing the plugin from fully... I don't know, loading, I guess.

I feel like I'm very close to figuring this out... just need a nudge over the finish line, please!

Body:
Here's the fix I mentioned earlier in my comment.

The code below was provided by someone from Fiverr. I added it to a script and enqueued it.

jQuery(document).ready(function($){
  setInterval(function(){
    if(!$('.home .content > div:last-child').hasClass('lg')){
      $('.home .content > div:last-child').addClass('lg');
      $(".kk-star-ratings").kkstarratings();
    }
  }, 2000);
});


问:
How to make button's "pushed" effect?
I have 3 buttons that represents 3 states. I'd like when I push some of them that button stays in visual "push" state and other 2 are in normal non-pushed state.

Here's the code I use:

if (itemType === 'default') {
  document.getElementById("defaultMode").classList.remove('non-pushed');
  document.getElementById("defaultMode").classList.add('pushed');
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.pushed {
  border-style: inset;
}

.non-pushed {
  border-style: solid;
}</code>```

<button id="defaultMode" class="non-pushed" onclick="setMode('link', 'default');">Default</button>
<button id="orthoMode" onclick="setMode('link', 'ortho');">Ortho</button>
<button id="cornerMode" onclick="setMode('link', 'corner');">Corner</button>```

But, it's not working.

答:
Here's a CSS-only solution with actual buttons:

.pushed {
  border-style: inset;
  margin: 0 1px
}

#buttons > span {
  position: relative;
}

#buttons input[type=radio] {
  position: absolute;
  width: 100%;
  height: 1.4em;
  opacity: 0
}
#buttons input[type=radio]:checked ~ button {
  border: inset
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="buttons">
  <span><input id="default" type="radio" name="mode" checked><button>Default</button></span>
  <span><input id="ortho" type="radio" name="mode"><button>Ortho</button></span>
  <span><input id="corner" type="radio" name="mode"><button>Corner</button></span>
</div></code>```

Title: How to make button's "pushed" effect?

Body:
I have 3 buttons that represents 3 states. I'd like when I push some of them that button stays in visual "push" state and other 2 are in normal non-pushed state.

Here's the code I use:

if (itemType === 'default') {
  document.getElementById("defaultMode").classList.remove('non-pushed');
  document.getElementById("defaultMode").classList.add('pushed');
}

.pushed {
  border-style: inset;
}

.non-pushed {
  border-style: solid;
}

<button id="defaultMode" class="non-pushed" onclick="setMode('link', 'default');">Default</button>
<button id="orthoMode" onclick="setMode('link', 'ortho');">Ortho</button>
<button id="cornerMode" onclick="setMode('link', 'corner');">Corner</button>

But, it's not working.

Body:
Here's a CSS-only solution with actual buttons:

.pushed {
  border-style: inset;
  margin: 0 1px
}

#buttons > span {
  position: relative;
}

#buttons input[type=radio] {
  position: absolute;
  width: 100%;
  height: 1.4em;
  opacity: 0
}
#buttons input[type=radio]:checked ~ button {
  border: inset
}

<div id="buttons">
  <span><input id="default" type="radio" name="mode" checked><button>Default</button></span>
  <span><input id="ortho" type="radio" name="mode"><button>Ortho</button></span>
  <span><input id="corner" type="radio" name="mode"><button>Corner</button></span>
</div>


问:
How to import to GraphFrame the text time follow structure
I have a file follow structure.Where first column it's nodeID. After ":" it's a node which has a connection with nodeID. Each nodeID can have more than one connection.

```<code>0: 5305811,
1: 4798401,
2: 7922543,
3: 7195074,
4: 6399935,
5: 5697217,
6: 5357407,
7: 4798401,
8: 629131,5330605,6481451,6280292,6909396,7325128,
...
</code>```

How to apply transformations to import to GraphFrame?

答:
import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.functions._
import org.apache.spark.sql.types.LongType
import org.graphframes.GraphFrame
import scala.util.Try

val spark = SparkSession.builder()
  .master("local[2]")
  .appName("test")
  .getOrCreate()

spark.sparkContext.setCheckpointDir(spark.conf.getOption(s"spark.checkpointdir").getOrElse("/tmp"))

import spark.implicits._

def cleanIds = udf((ids: Seq[String]) => ids.flatMap(x => Try(x.trim.toLong).toOption))

val ds = spark
  .read
  .option("mode", "PERMISSIVE")
  .option("header", "false")
  .option("delimiter", ":")
  .csv("src/main/resources/connections.txt")
  .toDF("id", "links")
  .select(
    'id.cast(LongType),
    cleanIds(split(trim('links), ",")).as("links"))
  .cache()

val vertices = ds.select('id).distinct()

val edges = ds.select(
  'id.as("src"),
  explode('links).as("dst")
)

val graphFrame = GraphFrame(vertices, edges)

val connectedComponents = graphFrame.connectedComponents.run()

connectedComponents
  .groupBy('component).agg(
  collect_list(struct('id)).as("vertices")
).show(false)
```

<p>Given input like this:</p>

```0: 5,6,
1: 4,
2: 3,4,5,
3: 2,
4: 2,1,
5: 2,0,
6: 0,7,
10: 11,13,
11: 12,14,
12: 13,14,
13: 10,12,
14: 11,12,
```

<p>This will create a vertex dataframe looking like this:</p>

```+---+
| id|
+---+
|  0|
|  6|
|  5|
|  1|
| 10|
|  3|
| 12|
| 11|
|  2|
|  4|
| 13|
| 14|
+---+
```

<p>and edges like this: </p>

```+---+---+
|src|dst|
+---+---+
|  0|  5|
|  0|  6|
|  1|  4|
|  2|  3|
|  2|  4|
|  2|  5|
|  3|  2|
|  4|  2|
|  4|  1|
|  5|  2|
|  5|  0|
|  6|  0|
|  6|  7|
| 10| 11|
| 10| 13|
| 11| 12|
| 11| 14|
| 12| 13|
| 12| 14|
| 13| 10|
+---+---+
```

<p>and connected components like this: </p>

```+---------+-----------------------------------+
|component|vertices                           |
+---------+-----------------------------------+
|0        |[[0], [6], [5], [1], [3], [2], [4]]|
|10       |[[10], [12], [11], [13], [14]]     |
+---------+-----------------------------------+
```

Body:
I have a file follow structure.Where first column it's nodeID. After ":" it's a node which has a connection with nodeID. Each nodeID can have more than one connection.

0: 5305811,
1: 4798401,
2: 7922543,
3: 7195074,
4: 6399935,
5: 5697217,
6: 5357407,
7: 4798401,
8: 629131,5330605,6481451,6280292,6909396,7325128,
...

How to apply transformations to import to GraphFrame?

Body:
import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.functions._
import org.apache.spark.sql.types.LongType
import org.graphframes.GraphFrame
import scala.util.Try

val spark = SparkSession.builder()
  .master("local[2]")
  .appName("test")
  .getOrCreate()

spark.sparkContext.setCheckpointDir(spark.conf.getOption(s"spark.checkpointdir").getOrElse("/tmp"))

import spark.implicits._

def cleanIds = udf((ids: Seq[String]) => ids.flatMap(x => Try(x.trim.toLong).toOption))

val ds = spark
  .read
  .option("mode", "PERMISSIVE")
  .option("header", "false")
  .option("delimiter", ":")
  .csv("src/main/resources/connections.txt")
  .toDF("id", "links")
  .select(
    'id.cast(LongType),
    cleanIds(split(trim('links), ",")).as("links"))
  .cache()

val vertices = ds.select('id).distinct()

val edges = ds.select(
  'id.as("src"),
  explode('links).as("dst")
)

val graphFrame = GraphFrame(vertices, edges)

val connectedComponents = graphFrame.connectedComponents.run()

connectedComponents
  .groupBy('component).agg(
  collect_list(struct('id)).as("vertices")
).show(false)

Given input like this:

0: 5,6,
1: 4,
2: 3,4,5,
3: 2,
4: 2,1,
5: 2,0,
6: 0,7,
10: 11,13,
11: 12,14,
12: 13,14,
13: 10,12,
14: 11,12,

This will create a vertex dataframe looking like this:

+---+
| id|
+---+
|  0|
|  6|
|  5|
|  1|
| 10|
|  3|
| 12|
| 11|
|  2|
|  4|
| 13|
| 14|
+---+

and edges like this:

+---+---+
|src|dst|
+---+---+
|  0|  5|
|  0|  6|
|  1|  4|
|  2|  3|
|  2|  4|
|  2|  5|
|  3|  2|
|  4|  2|
|  4|  1|
|  5|  2|
|  5|  0|
|  6|  0|
|  6|  7|
| 10| 11|
| 10| 13|
| 11| 12|
| 11| 14|
| 12| 13|
| 12| 14|
| 13| 10|
+---+---+

and connected components like this:

+---------+-----------------------------------+
|component|vertices                           |
+---------+-----------------------------------+
|0        |[[0], [6], [5], [1], [3], [2], [4]]|
|10       |[[10], [12], [11], [13], [14]]     |
+---------+-----------------------------------+


问:
If I delete an image in my application it has to be deleted in the gallery too (using objective C)
I have developed a camera application with all basic functionalities. When you take a picture that image will be saved in the newly created folder but if I delete an image in my application its not getting deleted in that folder. I need to delete it permanently using objective C</p>

答: You can't delete something from gallery, you can just use photos from gallery in your app and save to Gallery, but iOS doesn't give such permissions to other app as deleting something from Gallery.(if it is not jailbroken) There is no such functionality in WhatsApp too(or I can't see it).</p>


问:
MSVCP140.dll despite /MT runtime library setting
I tried to run a program I wrote on a remote computer. As I knew there might be a dll problem, I set the runtime library option to /MT, so I can rely on static linking.

However, I still receive the error message on my remote computer, stating that MSCVP140.dll is missing. Isn't this what the /MT flag should take care of?

I even tried to install the redistributable, but no luck. I'm still stuck with the error.

Another thing I tried was placing a MSVCP140.dll I downloaded in the folder, but that way my program is simply crashing on startup. I suspect that the MSCVP140.dll version is not the expected one, so I'm not relying on the validity of this test.

Any ideas?

答:
Someone please punch me for being this stupid... I was compiling on x86 instead of x64 all the time. No surprise the dlls didn't work.

Thanks for the help nevertheless. At least you got me on track to take a closer look at my dlls.


问:
to pass data around using event handling
Anyone can detail the pros and cons to pass data from one class to another using event mechanism? When is the best time to use event to pass data?</p>

答:
Using events will among other things:

Decouple the event source from the event receiver

Allow multiple event receivers to subscribe to the same event

Provide a well known pattern for implementing eventing

One thing to be aware of is how delegates may create unexpected "leaks" in your code: Memory Leak in C#.


问:
links do not open jquery dialog after a form save
setup: cakephp, jquery 1.8.7, cakephp.bee.pl ajax helper

I have a website who is set to load all pages through ajax. In the administration page I load the 'users/index' action and load the users. I have inserted a link to open a jquery dialog to add a new user. Once the admin clicks save it will send the data to the server, save the user and return the 'index' view back to update the administration page 'div'. Until now there are no problems. The problem is after the update the links in the newly updated div instead of opening a  jquery dialog or delete the user and retun the index view through ajax they redirect the browser to the 'index' view but in new page and not loading it through ajax.

here is my dialog creation code:

```<code><script type="text/javascript">
    $(document).ready(function(){
        $('a[name=modal]').click(function (e){
            e.preventDefault();
            var $link = $(this);
            var $form = $link.attr('formid');
            // var $dv = $body.append('<div id="dlg"></div>');

        $('#useDlg').load($link.attr('href')).dialog({
         autoOpen: false,
         modal: true,
         title: $link.attr('title'),
         resizable: false,
         width: 370,
         height: 350,
         buttons: {
            "Close": function(){
                $(this).dialog("close");
                //$(this).dialog("destroy");
            },
            " Save ... ": function(){
                $.ajax({
                    async: true,
                    type: 'POST',
                    url: $link.attr('href'),
                    data: $("form").serialize(),
                    dataType: "html",
                    success: function (response, json){
                        //alert(response);
                        $('#viewUsers').empty().html(response);
                        $('#useDlg').dialog("close");
                       // $('#useDlg').dialog("destroy");
                    }
                });
            }
         }
      });
   });
});

  $('a[name=modal]').click(function(){
       $('#useDlg').dialog('open');
    });
</code>```

I am using the dialog multiple times to also edit the user profile. The user table has two links related to a user. View profile and Delete. The view profile opens the jquery dialog with the user profile and delete deletes the user and return through ajax the index action to update the users portion of the administration page.

does someone have any ideas why the links for view profile will not be catched after the users div has been refreshed?

thank you in advance,
denis

答:
thank you Mikesname...that did the trick...for anybody else who might encouter this issue I also removed the

$('a[name=modal]').click(function(){
       $('#useDlg').dialog('open');
    });

and only added the  $('#useDlg').dialog('open');  to the first click event..without the second modification the event will still not trigger after reload and it will cause unforeseen results in page as well...

I would have set this as the answer but I really do not see how :)

regards,
denis