问:
multidimensional array for a discussion board
I have a multidimensional array of a discussion.

I'm using a recursive function (see below) to echo the values (comments) of this array. But with my function only the first child comment (per array level) appears.

How can I adapt this function, so that I can echo all child comments per array level, like in a normal discussion board?

In this example array the comment_id "4" and the comment_id "7" are on the same level, but with my current function only comment_id "4" comments is viewed.

```<code>Array
(
    [0] => Array
        (
            [comment_id] => 1
            [comment_content] => This is a comment...
            [child] => Array
                (
                    [0] => Array
                        (
                            [comment_id] => 3
                            [comment_content] => This is a reply to the comment...
                            [child] => Array
                                (
                                    [0] => Array
                                        (
                                            [comment_id] => 4
                                            [comment_content] => This is a reply to the reply...
                                            [child] => Array
                                                (
                                                )
                                        )

                                    [1] => Array
                                        (
                                            [comment_id] => 7
                                            [comment_content] => This is a another reply to the reply...
                                            [child] => Array
                                                (
                                                )
                                        )
                                )
                        )
                )
        )

    [1] => Array
        (
            [comment_id] => 2
            [comment_content] => This is another comment...
            [child] => Array
                (
                )

        )

    [2] => Array
        (
            [comment_id] => 6
            [comment_content] => This is another comment...
            [child] => Array
                (
                )
        )
)
</code>```

My current function looks like this:

```<code>function RecursiveWrite($array) {
    foreach ($array as $vals) {
        echo $vals['comment_content'] . "\n";
        RecursiveWrite($vals['child']);
    }
}
</code>```

答:
Maybe i don't understand you question, but function seems fine.

I've just added spacer and comment_id into your function

```<code>function RecursiveWrite($array, $spacer='') {
    foreach ($array as $vals) {
        echo $spacer . $vals['comment_id'] . ' - ' . $vals['comment_content'] . "\n";
        RecursiveWrite($vals['child'], $spacer . '  ');
    }
}
</code>```

And it outputs

```<code>1 - This is a comment...
  3 - This is a reply to the comment...
    4 - This is a reply to the reply...
    7 - This is a another reply to the reply...
2 - This is another comment...
6 - This is another comment...
</code>```

Body:
I have a multidimensional array of a discussion.

I'm using a recursive function (see below) to echo the values (comments) of this array. But with my function only the first child comment (per array level) appears.

How can I adapt this function, so that I can echo all child comments per array level, like in a normal discussion board?

In this example array the comment_id "4" and the comment_id "7" are on the same level, but with my current function only comment_id "4" comments is viewed.

Array
(
    [0] => Array
        (
            [comment_id] => 1
            [comment_content] => This is a comment...
            [child] => Array
                (
                    [0] => Array
                        (
                            [comment_id] => 3
                            [comment_content] => This is a reply to the comment...
                            [child] => Array
                                (
                                    [0] => Array
                                        (
                                            [comment_id] => 4
                                            [comment_content] => This is a reply to the reply...
                                            [child] => Array
                                                (
                                                )
                                        )

                                    [1] => Array
                                        (
                                            [comment_id] => 7
                                            [comment_content] => This is a another reply to the reply...
                                            [child] => Array
                                                (
                                                )
                                        )
                                )
                        )
                )
        )

    [1] => Array
        (
            [comment_id] => 2
            [comment_content] => This is another comment...
            [child] => Array
                (
                )

        )

    [2] => Array
        (
            [comment_id] => 6
            [comment_content] => This is another comment...
            [child] => Array
                (
                )
        )
)

My current function looks like this:

function RecursiveWrite($array) {
    foreach ($array as $vals) {
        echo $vals['comment_content'] . "\n";
        RecursiveWrite($vals['child']);
    }
}

Body:
Maybe i don't understand you question, but function seems fine.

I've just added spacer and comment_id into your function

function RecursiveWrite($array, $spacer='') {
    foreach ($array as $vals) {
        echo $spacer . $vals['comment_id'] . ' - ' . $vals['comment_content'] . "\n";
        RecursiveWrite($vals['child'], $spacer . '  ');
    }
}

And it outputs

1 - This is a comment...
  3 - This is a reply to the comment...
    4 - This is a reply to the reply...
    7 - This is a another reply to the reply...
2 - This is another comment...
6 - This is another comment...


来源: stackexchange

问:
List assignment index out of range when deleting columns in a nested list
I have a nested list with a couple of things in each list. It looks something like this:

```<code>itemsOnShelf=[[3,5,6,8],
              [2,3,7,3],
              [4,2,2,3]]
</code>```

Each column belongs to an item, for example column one/position 0 is potatoes.
In my program I have a function to add all the items for each column and save them into variables, for example potatoes=9

I also have a list where I saved these variables, it looks like this:

food=[potatoes, tomatoes, apples, peaches]

I also have a function that will delete a column if the sum of items in it is smaller than a specific number, for example 11.

```<code>minimumNumberAllowed=11
smallestNumber=[]

def throwAway(thing,pos):
   for item in smallestNumber:
    if item==thing:
        for shelf in itemsOnShelf:
            for veg in shelf:
                del shelf[pos]
                print(itemsOnShelf)
</code>```

Next I have a bit of code that goes like this:

```<code>for item in food:
       if item < minimumNumberAllowed:
              smallestNumber.append(min(food))
              print(smallestNumber)
              for item in smallestNumber:
               throwAway(potatoes,0)
               throwAway(tomatoes,1)
               throwAway(apples,2)
               throwAway(peaches,3)
</code>```

The idea is that one column (item) will be deleted if there is too few of it. My problem is that once one column is deleted, I get a "list assignment index out of range" error because now there are fewer columns and therefore column number 3 will not exist. This is a problem that prevents me from moving forward in my coding. I tried using while len(itemsOnShelf)<=3 or with other numbers but what it does is it stops before the column is deleted so I receive an unchanged list. How do I fix this index out of range error so the record deletes and the index corrects itself?

edit: I cannot manually delete the columns because the number of items in the main list can be changed so I do not always control which column needs to be deleted.

答:
You have already identified the problem -

now there are fewer columns and therefore column number 3 will not exist

So, obviously the column indexes are no longer the same. Once you delete column 0 ("potatoes"), column 0 is now replaced with "tomatoes" and so one.

There are a couple of ways to tackle this, but they depend on how you use this matrix later on. You could leave the "potatoes" column in there and set all the values to 0, or a "null" value like -1, this would indicate it has been "deleted" but still leaves the matrix intact. If you did this all your index values would still be valid.

If you must physically delete it then you have to adjust all your indexes to account for the fact that column 0 is now "tomatoes" etc.

ContentLicense: CC BY-SA 3.0

Body:
I have a nested list with a couple of things in each list. It looks something like this:

itemsOnShelf=[[3,5,6,8],
              [2,3,7,3],
              [4,2,2,3]]

Each column belongs to an item, for example column one/position 0 is potatoes.
In my program I have a function to add all the items for each column and save them into variables, for example potatoes=9

I also have a list where I saved these variables, it looks like this:

food=[potatoes, tomatoes, apples, peaches]

I also have a function that will delete a column if the sum of items in it is smaller than a specific number, for example 11.

minimumNumberAllowed=11
smallestNumber=[]

def throwAway(thing,pos):
   for item in smallestNumber:
    if item==thing:
        for shelf in itemsOnShelf:
            for veg in shelf:
                del shelf[pos]
                print(itemsOnShelf)

Next I have a bit of code that goes like this:

for item in food:
       if item < minimumNumberAllowed:
              smallestNumber.append(min(food))
              print(smallestNumber)
              for item in smallestNumber:
               throwAway(potatoes,0)
               throwAway(tomatoes,1)
               throwAway(apples,2)
               throwAway(peaches,3)

The idea is that one column (item) will be deleted if there is too few of it. My problem is that once one column is deleted, I get a "list assignment index out of range" error because now there are fewer columns and therefore column number 3 will not exist. This is a problem that prevents me from moving forward in my coding. I tried using while len(itemsOnShelf)<=3 or with other numbers but what it does is it stops before the column is deleted so I receive an unchanged list. How do I fix this index out of range error so the record deletes and the index corrects itself?

edit: I cannot manually delete the columns because the number of items in the main list can be changed so I do not always control which column needs to be deleted.


问:
Save ogg stream provided by AWS Polly into a wav file
I am trying to create a webpage, where user will be able to listen to the text he types. I also want to provide a functionality to download the media in .wav format.

I am able to get AudioStream from AmazonPollyClient but not able to save the stream to .wav file.

Here is what I am trying...

```<code>public void convertToWav(SynthesizeSpeechResult result, File convertedFile) throws IOException {

    try (AudioInputStream sias = AudioSystem.getAudioInputStream(result.getAudioStream())){

        AudioFormat newFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 8000f, 16, 1, 2, 8000f, false);
        AudioInputStream convert1AIS = AudioSystem.getAudioInputStream(newFormat, sias);

        AudioSystem.write(convert1AIS, AudioFileFormat.Type.WAVE, convertedFile);

        convert1AIS.close();
    } catch (UnsupportedAudioFileException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    System.gc();
}
</code>```

but everytime I call getAudioInputStream() it throws IOException

```<code>java.io.IOException: mark/reset not supported
    at java.io.InputStream.reset(InputStream.java:348)
    at com.amazonaws.internal.SdkFilterInputStream.reset(SdkFilterInputStream.java:112)
    at com.amazonaws.event.ProgressInputStream.reset(ProgressInputStream.java:168)
    at com.sun.media.sound.SoftMidiAudioFileReader.getAudioInputStream(SoftMidiAudioFileReader.java:139)
    at javax.sound.sampled.AudioSystem.getAudioInputStream(AudioSystem.java:1113)
</code>```

P.S: I have tried wrapping result.getAudioStream() in BufferedInputStream(). No show!

Any help will be appreciated.

答:
Finally, I have figured out way to save InputStream provided by polly-aws-sdk

```<code>public static boolean getWavFile(String filePath, InputStream audioStream) throws IOException {

    boolean result = false;
    try {

        byte[] decodedData = IOUtils.toByteArray(audioStream);

        System.out.println(">>Decoded Data" + Arrays.toString(decodedData));
        File outFile = new File(filePath);
        AudioFormat format = new AudioFormat(8000, 16, 1, true, false);
        AudioSystem.write(new AudioInputStream(new ByteArrayInputStream(
                decodedData), format, decodedData.length), AudioFileFormat.Type.WAVE, outFile);
        result = true;
        return result;
    } catch (IOException ex) {
        System.out.println("<<getWavFile - impl" + ex);
        return result;

    }
}
</code>```

Body:
I am trying to create a webpage, where user will be able to listen to the text he types. I also want to provide a functionality to download the media in .wav format.

I am able to get AudioStream from AmazonPollyClient but not able to save the stream to .wav file.

Here is what I am trying...

public void convertToWav(SynthesizeSpeechResult result, File convertedFile) throws IOException {

    try (AudioInputStream sias = AudioSystem.getAudioInputStream(result.getAudioStream())){

        AudioFormat newFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 8000f, 16, 1, 2, 8000f, false);
        AudioInputStream convert1AIS = AudioSystem.getAudioInputStream(newFormat, sias);

        AudioSystem.write(convert1AIS, AudioFileFormat.Type.WAVE, convertedFile);

        convert1AIS.close();
    } catch (UnsupportedAudioFileException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    System.gc();
}

but everytime I call getAudioInputStream() it throws IOException

java.io.IOException: mark/reset not supported
    at java.io.InputStream.reset(InputStream.java:348)
    at com.amazonaws.internal.SdkFilterInputStream.reset(SdkFilterInputStream.java:112)
    at com.amazonaws.event.ProgressInputStream.reset(ProgressInputStream.java:168)
    at com.sun.media.sound.SoftMidiAudioFileReader.getAudioInputStream(SoftMidiAudioFileReader.java:139)
    at javax.sound.sampled.AudioSystem.getAudioInputStream(AudioSystem.java:1113)

P.S: I have tried wrapping result.getAudioStream() in BufferedInputStream(). No show!

Any help will be appreciated.

Body:
Finally, I have figured out way to save InputStream provided by polly-aws-sdk

public static boolean getWavFile(String filePath, InputStream audioStream) throws IOException {

    boolean result = false;
    try {

        byte[] decodedData = IOUtils.toByteArray(audioStream);

        System.out.println(">>Decoded Data" + Arrays.toString(decodedData));
        File outFile = new File(filePath);
        AudioFormat format = new AudioFormat(8000, 16, 1, true, false);
        AudioSystem.write(new AudioInputStream(new ByteArrayInputStream(
                decodedData), format, decodedData.length), AudioFileFormat.Type.WAVE, outFile);
        result = true;
        return result;
    } catch (IOException ex) {
        System.out.println("<<getWavFile - impl" + ex);
        return result;

    }
}


问:
Importing modules twice in python with different names
I did import the module with a name, and import it again without a name and both seems to be working fine and gives the same class type.

```<code>>>> from collections import Counter as c
>>> c
<class 'collections.Counter'>

>>> from collections import Counter
>>> Counter
<class 'collections.Counter'>
</code>```

How does that works in python, is that a single object points to the same reference?
Also why not that the previous name import got overwritten or removed.

I'm not sure about the terminology as well

答:
Using python 2.7.13:

```<code>>>> from collections import Counter as c
>>> c
<class 'collections.Counter'>
>>> from collections import Counter
>>> Counter
<class 'collections.Counter'>
>>> id(c), id(Counter)
(140244739511392, 140244739511392)
>>> id(c) == id(Counter)
True
</code>```

Yes, c and Counter are the same. Two variables (names) that reference the same object.

Body:
I did import the module with a name, and import it again without a name and both seems to be working fine and gives the same class type.

>>> from collections import Counter as c
>>> c
<class 'collections.Counter'>

>>> from collections import Counter
>>> Counter
<class 'collections.Counter'>

How does that works in python, is that a single object points to the same reference?
Also why not that the previous name import got overwritten or removed.

I'm not sure about the terminology as well

Body:
Using python 2.7.13:

>>> from collections import Counter as c
>>> c
<class 'collections.Counter'>
>>> from collections import Counter
>>> Counter
<class 'collections.Counter'>
>>> id(c), id(Counter)
(140244739511392, 140244739511392)
>>> id(c) == id(Counter)
True

Yes, c and Counter are the same. Two variables (names) that reference the same object.


问:
Transition time is only applied if target value changes

Note: I updated the question with a simpler example as I found that it is not an issue with transform in particular, but with how the transition timing is applied. You can still see the more complex example in the edit history.

Here is a simple example: when you mouse over the "Grow" button, the bar will grow to 400px in 5 seconds; and after exiting the "Grow" button, the bar will shrink automatically to 0px in 10 seconds. If you mouse over the "Shrink" button, the bar will shrink to 0px in 2 seconds.

Although it doesn't, it takes 10 seconds to go back to 0px even when mousing over "Shrink":

#bar {
  width:0;
  border-left:1px solid gray;
  height: 40px;
  transition: width 10s;
  background: green;
}

#grow,#shrink {
  display:inline-block;
  width: 60px;
  height: 60px;
  background: gray;
  margin-bottom: 10px;
  color: white;
  line-height: 60px;
  text-align: center;
  box-shadow: inset 0 0 0 1px black;
  margin-right: 20px;
}

#grow:hover ~ #bar {
  width: 400px;
  transition: width 5s;
}

#shrink:hover ~ #bar {
  width: 0px;
  transition: width 2s;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span id="grow">Grow</span>
<span id="shrink">Shrink</span>

<div id="bar"></div></code>```

At first I thought it could be a problem with specificity (even when #shrink:hover ~ #bar is more specific than just #bar), so I added an !important like this:

```<code>#shrink:hover ~ #bar {
  width: 0px;
  transition: width 2s !important;
}
</code>```

Still it didn't work. After some try-error, I found that changing the value actually makes the browser take the new transition time, even if the change is insignificant. So, for example, this will work:

#bar {
  width:0;
  border-left:1px solid gray;
  height: 40px;
  transition: width 10s;
  background: green;
}

#grow,#shrink {
  display:inline-block;
  width: 60px;
  height: 60px;
  background: gray;
  margin-bottom: 10px;
  color: white;
  line-height: 60px;
  text-align: center;
  box-shadow: inset 0 0 0 1px black;
  margin-right: 20px;
}

#grow:hover ~ #bar {
  width: 400px;
  transition: width 5s;
}

#shrink:hover ~ #bar {
  width: 0.000001px;
  transition: width 2s;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span id="grow">Grow</span>
<span id="shrink">Shrink</span>

<div id="bar"></div></code>```

That works. Also, I noticed another case in which it works: when it goes directly from "Grow" to "Shrink" without transitioning to anything else (you may be able to see it by moving from "Grow" to "Shrink" really fast or by removing the margin so they are together).

I have been able to replicate this issue in Chrome, Internet Explorer/Edge, Firefox, and Safari. So I don't know if it's a real issue or me misunderstanding how this should work (quite possible too).

Why does this happen? Is there a way to apply the new transition time without having to change the target value?

答:
I'm still digging but here are my conclusions.

First, this could just be a bug. That's always possible.

However, if we assume that it's functioning as it should, I think the real reason here are the "identical keyframes".

You see, it's not about the angle of rotate() function. It's about transform property being virtually identical for #arm and #brake. If I imagine css parsing your styles for animations and creating "keyframes", it might think that the first definition is the same as the second.

If we add a completely useless but unique function to one of those two declarations, then they are treated as two unique keyframes and behave as you want them to. That's what you were doing by decreasing the angle by one degree.

@import url("https://fonts.googleapis.com/css?family=Oswald|VT323");

.round {
  border-radius: 100%;
}

.center {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  box-sizing: border-box;
}

#board {
  width: 300px;
  height: 300px;
  background: white;
  border: 12px solid black;
  overflow: hidden;
  box-shadow: inset 0 0 0 12px red;
}

#pointer {
  z-index: 1;
}

#knot {
  width: 20px;
  height: 20px;
  background: black;
  z-index: 2;
}

#arm {
  width: 126px;
  height: 6px;
  background: red;
  transform: translate(-85%, -50%) rotate(-42deg);
  border-radius: 80% 6px 6px 80%;
  transform-origin: 85% 50%;
  transition: transform 14s;
}

#speed:hover~#board #pointer #arm {
  transform: translate(-85%, -50%) rotate(62deg);
  transition: transform 7s;
}

#brake:hover~#board #pointer #arm {
  transform: translate(-85%, -50%) rotate(-42deg) rotateX(0);/* I added this useless rotateX() */
  transition: transform 3s;
}

.bar {
  width: 300px;
  height: 2.30769px;
}

.bar:nth-of-type(4n+1) {
  height: 4.61538px;
}

.bar::after {
  content: "";
  position: absolute;
  left: 20px;
  height: 100%;
  width: 12px;
  background: black;
}

.bar:nth-of-type(odd)::after {
  width: 15.78947px;
}

.bar:nth-of-type(1) {
  transform: translate(-50%, -50%) rotate(-42deg);
}

.bar:nth-of-type(2) {
  transform: translate(-50%, -50%) rotate(-34deg);
}

.bar:nth-of-type(3) {
  transform: translate(-50%, -50%) rotate(-26deg);
}

.bar:nth-of-type(4) {
  transform: translate(-50%, -50%) rotate(-18deg);
}

.bar:nth-of-type(5) {
  transform: translate(-50%, -50%) rotate(-10deg);
}

.bar:nth-of-type(6) {
  transform: translate(-50%, -50%) rotate(-2deg);
}

.bar:nth-of-type(7) {
  transform: translate(-50%, -50%) rotate(6deg);
}

.bar:nth-of-type(8) {
  transform: translate(-50%, -50%) rotate(14deg);
}

.bar:nth-of-type(9) {
  transform: translate(-50%, -50%) rotate(22deg);
}

.bar:nth-of-type(10) {
  transform: translate(-50%, -50%) rotate(30deg);
}

.bar:nth-of-type(11) {
  transform: translate(-50%, -50%) rotate(38deg);
}

.bar:nth-of-type(12) {
  transform: translate(-50%, -50%) rotate(46deg);
}

.bar:nth-of-type(13) {
  transform: translate(-50%, -50%) rotate(54deg);
}

.bar:nth-of-type(14) {
  transform: translate(-50%, -50%) rotate(62deg);
}

.bar:nth-of-type(15) {
  transform: translate(-50%, -50%) rotate(70deg);
}

.bar:nth-of-type(16) {
  transform: translate(-50%, -50%) rotate(78deg);
}

.bar:nth-of-type(17) {
  transform: translate(-50%, -50%) rotate(86deg);
}

.bar:nth-of-type(18) {
  transform: translate(-50%, -50%) rotate(94deg);
}

.bar:nth-of-type(19) {
  transform: translate(-50%, -50%) rotate(102deg);
}

.bar:nth-of-type(20) {
  transform: translate(-50%, -50%) rotate(110deg);
}

.bar:nth-of-type(21) {
  transform: translate(-50%, -50%) rotate(118deg);
}

.bar:nth-of-type(22) {
  transform: translate(-50%, -50%) rotate(126deg);
}

.bar:nth-of-type(23) {
  transform: translate(-50%, -50%) rotate(134deg);
}

.bar:nth-of-type(24) {
  transform: translate(-50%, -50%) rotate(142deg);
}

.bar:nth-of-type(25) {
  transform: translate(-50%, -50%) rotate(150deg);
}

.bar:nth-of-type(26) {
  transform: translate(-50%, -50%) rotate(158deg);
}

.bar:nth-of-type(27) {
  transform: translate(-50%, -50%) rotate(166deg);
}

.bar:nth-of-type(28) {
  transform: translate(-50%, -50%) rotate(174deg);
}

.bar:nth-of-type(29) {
  transform: translate(-50%, -50%) rotate(182deg);
}

.bar:nth-of-type(30) {
  transform: translate(-50%, -50%) rotate(190deg);
}

.bar:nth-of-type(31) {
  transform: translate(-50%, -50%) rotate(198deg);
}

.bar:nth-of-type(32) {
  transform: translate(-50%, -50%) rotate(206deg);
}

.bar:nth-of-type(33) {
  transform: translate(-50%, -50%) rotate(214deg);
}

.num {
  font-family: Oswald, Arial, Verdana, sans-serif;
  font-weight: bold;
  text-align: center;
  font-size: 1.3em;
  position: absolute;
}

.num:nth-of-type(1) {
  top: 66.66667px;
  left: -75px;
}

.num:nth-of-type(2) {
  top: 16.66667px;
  left: -96.77419px;
}

.num:nth-of-type(3) {
  top: -37.5px;
  left: -92.30769px;
}

.num:nth-of-type(4) {
  top: -78.94737px;
  left: -60px;
}

.num:nth-of-type(5) {
  top: -100px;
  left: -7.5px;
}

.num:nth-of-type(6) {
  top: -85.71429px;
  left: 42.85714px;
}

.num:nth-of-type(7) {
  top: -50px;
  left: 78.94737px;
}

.num:nth-of-type(8) {
  top: 3.75px;
  left: 93.75px;
}

.num:nth-of-type(9) {
  top: 51.72414px;
  left: 76.92308px;
}

#mileage {
  padding-top: 187.5px;
}

#box {
  width: 75px;
  height: 25px;
  background: black;
  display: inline-block;
  float: left;
  color: rgba(200, 255, 0, 0.8);
  line-height: 1.2em;
  text-align: right;
  padding-right: 0.325em;
  box-sizing: border-box;
  font-family: VT323, Oswald;
  font-size: 1.3em;
  margin-left: 1em;
}

#miles {
  float: left;
  line-height: 25px;
  margin-left: 0.325em;
  font-family: Oswald, Arial, Verdana, sans-serif;
  font-size: 1em;
}

#red-bar {
  width: 200%;
  height: 200%;
  background: white;
  border-radius: 100% 0 0;
  transform: translate(-101%, -61.7%) rotate(28deg);
}

#red-bar::before {
  content: "";
  background-color: white;
  display: block;
  width: 50%;
  height: 50%;
  position: absolute;
  bottom: 0;
  right: 0;
  transform: translate(86%, -22.5%) rotate(97deg);
}

#speed,
#brake {
  text-align: center;
  line-height: 100px;
  font-family: Oswald, Arial, Verdana, sans-serif;
  font-size: 1.3em;
  width: 100px;
  height: 100px;
  margin-right: 10px;
  background: gray;
  z-index: 9;
  cursor: pointer;
  transform: translate(-300px, -50%);
}

#speed {
  transform: translate(200px, -50%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="center" id="speed">Speed</div>
<div class="center" id="brake">Brake</div>
<div class="center round" id="board">
  <div class="center" id="red-bar"></div>
  <div class="center" id="pointer">
    <div class="center round" id="knot"></div>
    <div class="center" id="arm"></div>
  </div>
  <div class="center" id="bars">
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
  </div>
  <div class="center" id="numbers">
    <div class="num center">0</div>
    <div class="num center">20</div>
    <div class="num center">40</div>
    <div class="num center">60</div>
    <div class="num center">80</div>
    <div class="num center">100</div>
    <div class="num center">120</div>
    <div class="num center">140</div>
    <div class="num center">160</div>
  </div>
  <div class="center" id="mileage">
    <div id="box">31415</div>
    <div id="miles">miles</div>
  </div>
</div></code>```

Body:
Note: I updated the question with a simpler example as I found that it is not an issue with transform in particular, but with how the transition timing is applied. You can still see the more complex example in the edit history.

Here is a simple example: when you mouse over the "Grow" button, the bar will grow to 400px in 5 seconds; and after exiting the "Grow" button, the bar will shrink automatically to 0px in 10 seconds. If you mouse over the "Shrink" button, the bar will shrink to 0px in 2 seconds.

Although it doesn't, it takes 10 seconds to go back to 0px even when mousing over "Shrink":

#bar {
  width:0;
  border-left:1px solid gray;
  height: 40px;
  transition: width 10s;
  background: green;
}

#grow,#shrink {
  display:inline-block;
  width: 60px;
  height: 60px;
  background: gray;
  margin-bottom: 10px;
  color: white;
  line-height: 60px;
  text-align: center;
  box-shadow: inset 0 0 0 1px black;
  margin-right: 20px;
}

#grow:hover ~ #bar {
  width: 400px;
  transition: width 5s;
}

#shrink:hover ~ #bar {
  width: 0px;
  transition: width 2s;
}

Grow
Shrink

At first I thought it could be a problem with specificity (even when #shrink:hover ~ #bar is more specific than just #bar), so I added an !important like this:

#shrink:hover ~ #bar {
  width: 0px;
  transition: width 2s !important;
}

Still it didn't work. After some try-error, I found that changing the value actually makes the browser take the new transition time, even if the change is insignificant. So, for example, this will work:

#bar {
  width:0;
  border-left:1px solid gray;
  height: 40px;
  transition: width 10s;
  background: green;
}

#grow,#shrink {
  display:inline-block;
  width: 60px;
  height: 60px;
  background: gray;
  margin-bottom: 10px;
  color: white;
  line-height: 60px;
  text-align: center;
  box-shadow: inset 0 0 0 1px black;
  margin-right: 20px;
}

#grow:hover ~ #bar {
  width: 400px;
  transition: width 5s;
}

#shrink:hover ~ #bar {
  width: 0.000001px;
  transition: width 2s;
}

Grow
Shrink

That works. Also, I noticed another case in which it works: when it goes directly from "Grow" to "Shrink" without transitioning to anything else (you may be able to see it by moving from "Grow" to "Shrink" really fast or by removing the margin so they are together).

I have been able to replicate this issue in Chrome, Internet Explorer/Edge, Firefox, and Safari. So I don't know if it's a real issue or me misunderstanding how this should work (quite possible too).

Why does this happen? Is there a way to apply the new transition time without having to change the target value?

Body:
I'm still digging but here are my conclusions.

First, this could just be a bug. That's always possible.

However, if we assume that it's functioning as it should, I think the real reason here are the "identical keyframes".

You see, it's not about the angle of rotate() function. It's about transform property being virtually identical for #arm and #brake. If I imagine css parsing your styles for animations and creating "keyframes", it might think that the first definition is the same as the second.

If we add a completely useless but unique function to one of those two declarations, then they are treated as two unique keyframes and behave as you want them to. That's what you were doing by decreasing the angle by one degree.

@import url("https://fonts.googleapis.com/css?family=Oswald|VT323");

.round {
  border-radius: 100%;
}

.center {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  box-sizing: border-box;
}

#board {
  width: 300px;
  height: 300px;
  background: white;
  border: 12px solid black;
  overflow: hidden;
  box-shadow: inset 0 0 0 12px red;
}

#pointer {
  z-index: 1;
}

#knot {
  width: 20px;
  height: 20px;
  background: black;
  z-index: 2;
}

#arm {
  width: 126px;
  height: 6px;
  background: red;
  transform: translate(-85%, -50%) rotate(-42deg);
  border-radius: 80% 6px 6px 80%;
  transform-origin: 85% 50%;
  transition: transform 14s;
}

#speed:hover~#board #pointer #arm {
  transform: translate(-85%, -50%) rotate(62deg);
  transition: transform 7s;
}

#brake:hover~#board #pointer #arm {
  transform: translate(-85%, -50%) rotate(-42deg) rotateX(0);/* I added this useless rotateX() */
  transition: transform 3s;
}

.bar {
  width: 300px;
  height: 2.30769px;
}

.bar:nth-of-type(4n+1) {
  height: 4.61538px;
}

.bar::after {
  content: "";
  position: absolute;
  left: 20px;
  height: 100%;
  width: 12px;
  background: black;
}

.bar:nth-of-type(odd)::after {
  width: 15.78947px;
}

.bar:nth-of-type(1) {
  transform: translate(-50%, -50%) rotate(-42deg);
}

.bar:nth-of-type(2) {
  transform: translate(-50%, -50%) rotate(-34deg);
}

.bar:nth-of-type(3) {
  transform: translate(-50%, -50%) rotate(-26deg);
}

.bar:nth-of-type(4) {
  transform: translate(-50%, -50%) rotate(-18deg);
}

.bar:nth-of-type(5) {
  transform: translate(-50%, -50%) rotate(-10deg);
}

.bar:nth-of-type(6) {
  transform: translate(-50%, -50%) rotate(-2deg);
}

.bar:nth-of-type(7) {
  transform: translate(-50%, -50%) rotate(6deg);
}

.bar:nth-of-type(8) {
  transform: translate(-50%, -50%) rotate(14deg);
}

.bar:nth-of-type(9) {
  transform: translate(-50%, -50%) rotate(22deg);
}

.bar:nth-of-type(10) {
  transform: translate(-50%, -50%) rotate(30deg);
}

.bar:nth-of-type(11) {
  transform: translate(-50%, -50%) rotate(38deg);
}

.bar:nth-of-type(12) {
  transform: translate(-50%, -50%) rotate(46deg);
}

.bar:nth-of-type(13) {
  transform: translate(-50%, -50%) rotate(54deg);
}

.bar:nth-of-type(14) {
  transform: translate(-50%, -50%) rotate(62deg);
}

.bar:nth-of-type(15) {
  transform: translate(-50%, -50%) rotate(70deg);
}

.bar:nth-of-type(16) {
  transform: translate(-50%, -50%) rotate(78deg);
}

.bar:nth-of-type(17) {
  transform: translate(-50%, -50%) rotate(86deg);
}

.bar:nth-of-type(18) {
  transform: translate(-50%, -50%) rotate(94deg);
}

.bar:nth-of-type(19) {
  transform: translate(-50%, -50%) rotate(102deg);
}

.bar:nth-of-type(20) {
  transform: translate(-50%, -50%) rotate(110deg);
}

.bar:nth-of-type(21) {
  transform: translate(-50%, -50%) rotate(118deg);
}

.bar:nth-of-type(22) {
  transform: translate(-50%, -50%) rotate(126deg);
}

.bar:nth-of-type(23) {
  transform: translate(-50%, -50%) rotate(134deg);
}

.bar:nth-of-type(24) {
  transform: translate(-50%, -50%) rotate(142deg);
}

.bar:nth-of-type(25) {
  transform: translate(-50%, -50%) rotate(150deg);
}

.bar:nth-of-type(26) {
  transform: translate(-50%, -50%) rotate(158deg);
}

.bar:nth-of-type(27) {
  transform: translate(-50%, -50%) rotate(166deg);
}

.bar:nth-of-type(28) {
  transform: translate(-50%, -50%) rotate(174deg);
}

.bar:nth-of-type(29) {
  transform: translate(-50%, -50%) rotate(182deg);
}

.bar:nth-of-type(30) {
  transform: translate(-50%, -50%) rotate(190deg);
}

.bar:nth-of-type(31) {
  transform: translate(-50%, -50%) rotate(198deg);
}

.bar:nth-of-type(32) {
  transform: translate(-50%, -50%) rotate(206deg);
}

.bar:nth-of-type(33) {
  transform: translate(-50%, -50%) rotate(214deg);
}

.num {
  font-family: Oswald, Arial, Verdana, sans-serif;
  font-weight: bold;
  text-align: center;
  font-size: 1.3em;
  position: absolute;
}

.num:nth-of-type(1) {
  top: 66.66667px;
  left: -75px;
}

.num:nth-of-type(2) {
  top: 16.66667px;
  left: -96.77419px;
}

.num:nth-of-type(3) {
  top: -37.5px;
  left: -92.30769px;
}

.num:nth-of-type(4) {
  top: -78.94737px;
  left: -60px;
}

.num:nth-of-type(5) {
  top: -100px;
  left: -7.5px;
}

.num:nth-of-type(6) {
  top: -85.71429px;
  left: 42.85714px;
}

.num:nth-of-type(7) {
  top: -50px;
  left: 78.94737px;
}

.num:nth-of-type(8) {
  top: 3.75px;
  left: 93.75px;
}

.num:nth-of-type(9) {
  top: 51.72414px;
  left: 76.92308px;
}

#mileage {
  padding-top: 187.5px;
}

#box {
  width: 75px;
  height: 25px;
  background: black;
  display: inline-block;
  float: left;
  color: rgba(200, 255, 0, 0.8);
  line-height: 1.2em;
  text-align: right;
  padding-right: 0.325em;
  box-sizing: border-box;
  font-family: VT323, Oswald;
  font-size: 1.3em;
  margin-left: 1em;
}

#miles {
  float: left;
  line-height: 25px;
  margin-left: 0.325em;
  font-family: Oswald, Arial, Verdana, sans-serif;
  font-size: 1em;
}

#red-bar {
  width: 200%;
  height: 200%;
  background: white;
  border-radius: 100% 0 0;
  transform: translate(-101%, -61.7%) rotate(28deg);
}

#red-bar::before {
  content: "";
  background-color: white;
  display: block;
  width: 50%;
  height: 50%;
  position: absolute;
  bottom: 0;
  right: 0;
  transform: translate(86%, -22.5%) rotate(97deg);
}

#speed,
#brake {
  text-align: center;
  line-height: 100px;
  font-family: Oswald, Arial, Verdana, sans-serif;
  font-size: 1.3em;
  width: 100px;
  height: 100px;
  margin-right: 10px;
  background: gray;
  z-index: 9;
  cursor: pointer;
  transform: translate(-300px, -50%);
}

#speed {
  transform: translate(200px, -50%);
}

<div class="center" id="speed">Speed</div>
<div class="center" id="brake">Brake</div>
<div class="center round" id="board">
  <div class="center" id="red-bar"></div>
  <div class="center" id="pointer">
    <div class="center round" id="knot"></div>
    <div class="center" id="arm"></div>
  </div>
  <div class="center" id="bars">
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
    <div class="bar center"></div>
  </div>
  <div class="center" id="numbers">
    <div class="num center">0</div>
    <div class="num center">20</div>
    <div class="num center">40</div>
    <div class="num center">60</div>
    <div class="num center">80</div>
    <div class="num center">100</div>
    <div class="num center">120</div>
    <div class="num center">140</div>
    <div class="num center">160</div>
  </div>
  <div class="center" id="mileage">
    <div id="box">31415</div>
    <div id="miles">miles</div>
  </div>
</div>


问:
Copy text to clipboard on toolbar button click
I am making a ff webextension that is a browser_action button on the toolbar, and when clicked it generates a password and copies it to the clipboard.
I added the clipboardWrite permission to the manifest, and my code is really simple:

html:

```<code><body>
  <form>

      <label for"pw">your password</label>
      <input type="text" id="pw" name="pw">

      <button id="copy">copy to clipboard</button>

  </form>
  <script src="pwgen.js"></script>
</body>
</code>```

now, when I click the copy button, this js is executed:

```<code>function copypasstoclippboard() {
  var copyText = document.getElementById('pw');
  copyText.select();
  document.execCommand('copy');
}
</code>```

If I execute the function by pressing the button it works, but if I execute the same function on load of the html of the popup, the document.execCommand('copy') line gets executed, and I see no error in the console, but the text is not copied to the clipboard.

What am I doing wrong here?

答:
This is a limitation that is imposed by Firefox for security reasons. However, there is a way to make it work. I haven't tested this code, but this is the idea (from within a background script):

```<code>var code = `
  window.addEventListener("paste", function(){
    var copyText = document.getElementById("pw");
    copyText.select();
    document.execCommand('copy');
  });
  document.execCommand("paste");
`
browser.tabs.executeScript({code: code});
</code>```

You trigger an event (in this case, paste) which is allowed to copy to the clipboard. You're running the code in the content script in this case, so the execCommand methods should work. Let me know if this works for you.

Body:
I am making a ff webextension that is a browser_action button on the toolbar, and when clicked it generates a password and copies it to the clipboard.
I added the clipboardWrite permission to the manifest, and my code is really simple:

html:

  <form>

      your password
      <input type="text" id="pw" name="pw">

      <button id="copy">copy to clipboard</button>

  </form>

now, when I click the copy button, this js is executed:

function copypasstoclippboard() {
  var copyText = document.getElementById('pw');
  copyText.select();
  document.execCommand('copy');
}

If I execute the function by pressing the button it works, but if I execute the same function on load of the html of the popup, the document.execCommand('copy') line gets executed, and I see no error in the console, but the text is not copied to the clipboard.

What am I doing wrong here?

Body:
This is a limitation that is imposed by Firefox for security reasons. However, there is a way to make it work. I haven't tested this code, but this is the idea (from within a background script):

var code = `
  window.addEventListener("paste", function(){
    var copyText = document.getElementById("pw");
    copyText.select();
    document.execCommand('copy');
  });
  document.execCommand("paste");
`
browser.tabs.executeScript({code: code});

You trigger an event (in this case, paste) which is allowed to copy to the clipboard. You're running the code in the content script in this case, so the execCommand methods should work. Let me know if this works for you.


问:
Extract bit from two dimensional bit-array
For an Minimax-Algorithm I code I want to experiment with bitwise operations to speed things up. Each gamestate is saved as an UInt128 and describes a 4x4 tile-based board. Each tile can have a value from 0 to 32 (exclusive) so 5 bits per tile.

```<code>+-------+-------+-------+-------+
| 0-4   | 5-9   | 10-14 | 15-19 |
+-------+-------+-------+-------+
| 20-24 | 25-29 | 30-34 | 35-39 |
+-------+-------+-------+-------+
| 40-44 | 45-49 | 50-54 | 55-59 |
+-------+-------+-------+-------+
| 60-64 | 65-69 | 70-74 | 75-79 |
+-------+-------+-------+-------+
</code>```

For actually performing operations on the board I need to extract a 3x3 block out of the 4x4 based on the center of the 3x3. How would I go about to to that? I have no problem doing it manually by simple acessing every cell via bitshifting, but I wonder if there is a faster way.

Thanks in Advance!

(Language is C# in case that matters)

答:
Bit ops are pretty fast. Since you already have no problem doing it manually using bit shifting, make a copy of the 4x4 and reduce it to 3x3, then perform your operations on that, and see if there are performance issues.

If performing your 'operations' means read only, depending on the cost of directly accessing bits in the 4x4 versus copying, shifting and still need to access to the 3x3, then the extra copy may prove more expensive.

On a side note, since you are using a 128 bit type, it would be possible to use a byte[16] (or byte[9] for the 3x3 operations). This would make it faster to access individual cells.

Body:
For an Minimax-Algorithm I code I want to experiment with bitwise operations to speed things up. Each gamestate is saved as an UInt128 and describes a 4x4 tile-based board. Each tile can have a value from 0 to 32 (exclusive) so 5 bits per tile.

+-------+-------+-------+-------+
| 0-4   | 5-9   | 10-14 | 15-19 |
+-------+-------+-------+-------+
| 20-24 | 25-29 | 30-34 | 35-39 |
+-------+-------+-------+-------+
| 40-44 | 45-49 | 50-54 | 55-59 |
+-------+-------+-------+-------+
| 60-64 | 65-69 | 70-74 | 75-79 |
+-------+-------+-------+-------+

For actually performing operations on the board I need to extract a 3x3 block out of the 4x4 based on the center of the 3x3. How would I go about to to that? I have no problem doing it manually by simple acessing every cell via bitshifting, but I wonder if there is a faster way.

Thanks in Advance!

(Language is C# in case that matters)


问:
get java class for type tag of Scala case class
Using the type safe configuration and configs ("com.github.kxbmap" %% "configs" % "0.4.4",) library

```<code>def loadConfiguration[T <: Product: TypeTag]: T = {
    import configs.syntax._
    val conf = ConfigFactory.load
    conf.get[MyCaseClass]
</code>```

should load the config, but fails as T is not a class.
How can I actually transform T to fit for configs as a java class?

答:
<s>I'd suggest simply replacing TypeTag with ClassTag since you aren't using the TypeTag. And if you were, you could combine them: T <: Product : TypeTag : ClassTag] or use this solution: https://stackoverflow.com/a/18730004/9204</s>

From the question I assumed "configs" could work given a Java Class object (or a ClassTag wrapping one). But after checking the documentation I see that it doesn't, so the above isn't relevant.

Instead you should use

```<code>def loadConfiguration[T : Configs]: T = ...
</code>```

Body:
Using the type safe configuration and configs ("com.github.kxbmap" %% "configs" % "0.4.4",) library

def loadConfiguration[T <: Product: TypeTag]: T = {
    import configs.syntax._
    val conf = ConfigFactory.load
    conf.get[MyCaseClass]

should load the config, but fails as T is not a class.
How can I actually transform T to fit for configs as a java class?

Body:
<s>I'd suggest simply replacing TypeTag with ClassTag since you aren't using the TypeTag. And if you were, you could combine them: T <: Product : TypeTag : ClassTag] or use this solution: https://stackoverflow.com/a/18730004/9204</s>

From the question I assumed "configs" could work given a Java Class object (or a ClassTag wrapping one). But after checking the documentation I see that it doesn't, so the above isn't relevant.

Instead you should use

def loadConfiguration[T : Configs]: T = ...


问:
svn diff for a complete file?
Given: an SVN repository, a bin directory inside it and a script.pl inside this bin. Some revisions ago, bin and script.pl has been added to the repository in one commit. Since then, some revisions has been applied to script.pl.

Needed: a diff command which would return a complete diff for script.pl from zero to HEAD, i.e. a diff with all lines added.

Background: this diff is needed for code review, for feeding to ReviewBoard

Problem: svn diff with -r X:HEAD (X being the first revision of script.pl) produces a diff between the first version and HEAD while -r X-1:HEAD tell me the file script.pl is unknown in the revision X-1, which is actually correct. However, I can't find a proper solution which would include the diff from an empty file. I also can't diff the bin directory, since it has been added in the same commit as script.pl

Solution: ?

答:
I faced the same problem and also didn't find a solution.

The workaround was to produce diff of a couple of recent revisions of the file, then "Expand changes" shows you the complete file and allows to comment anywhere.

ContentLicense: CC BY-SA 2.5

Title: svn diff for a complete file?


问:
Rails 5 Model Association has_many :through, validate child can only belong to one parent
3 models in question. Outage, Child, Relationship.

An outage can have many children.
A child belongs to an outage.
Relationship is the middleman table.

A child can only belong to ONE outage at a time (ie, if child 123 belongs to outage A, you cant associate child 123 with a different outage)

The children in each outage must be unique. (I've solved this with validates_uniqueness_of in the Relationship model).

```<code>class Outage < ApplicationRecord
    has_many :relationships
    has_many :children, :through => :relationships
end

class Child < ApplicationRecord
    has_many :relationships
    has_many :outages, :through => :relationships
end

class Relationship < ApplicationRecord
    belongs_to :outage
    belongs_to :child
    validates_uniqueness_of :outage_id, :scope => :child_id
end
</code>```

I've tried to set up a custom validator like so (in child.rb):

```<code>def has_one_outage
    if outages.length > 1
        errors.add(:base, "a child can only belong to one outage at a time")
    end
end
</code>```

That validation does not seem to have an affect though.

Any insight to what I'm doing wrong here?

答:
Was able to solve it with the following:</p>

```<code>class Outage < ApplicationRecord
    has_many :relationships
    has_many :children, through: :relationships
end

class Child < ApplicationRecord
    has_many :relationships
    has_many :outages, through: :relationships
end

  class Relationship < ApplicationRecord
    belongs_to :child
    belongs_to :outage
    validate :ensure_one_relationship

    def ensure_one_relationship
      if Relationship.where(child_id: self.child_id).present?
          errors.add(:base, "A trouble ticket can only be associated with one outage ticket.")
      end
    end
  end
</code>```

Body:
3 models in question. Outage, Child, Relationship.

An outage can have many children.
A child belongs to an outage.
Relationship is the middleman table.

A child can only belong to ONE outage at a time (ie, if child 123 belongs to outage A, you cant associate child 123 with a different outage)

The children in each outage must be unique. (I've solved this with validates_uniqueness_of in the Relationship model).

class Outage < ApplicationRecord
    has_many :relationships
    has_many :children, :through => :relationships
end

class Child < ApplicationRecord
    has_many :relationships
    has_many :outages, :through => :relationships
end

class Relationship < ApplicationRecord
    belongs_to :outage
    belongs_to :child
    validates_uniqueness_of :outage_id, :scope => :child_id
end

I've tried to set up a custom validator like so (in child.rb):

def has_one_outage
    if outages.length > 1
        errors.add(:base, "a child can only belong to one outage at a time")
    end
end

That validation does not seem to have an affect though.

Any insight to what I'm doing wrong here?

Body:
Was able to solve it with the following:

class Outage < ApplicationRecord
    has_many :relationships
    has_many :children, through: :relationships
end

class Child < ApplicationRecord
    has_many :relationships
    has_many :outages, through: :relationships
end

  class Relationship < ApplicationRecord
    belongs_to :child
    belongs_to :outage
    validate :ensure_one_relationship

    def ensure_one_relationship
      if Relationship.where(child_id: self.child_id).present?
          errors.add(:base, "A trouble ticket can only be associated with one outage ticket.")
      end
    end
  end


问:
Would calling statvfs / statfs periodically cause wear on disk?
I'm having an app that shows the current free disk space and that finds this out via calls to statfs on macOS. Does anyone have an insight in the implementation of statfs how this might affect the disk if I call this function periodically? Assuming it will be similar on Linux and other posix system with statvfs. </p>

答:
POSIX doesn't require that any timestamps or counters are updated for a statvfs call, so there is no quasi-mandatory overhead.

However, periodic polling could still affect battery life and consume network bandwidth (for network file systems).


问:
Filter based on a string and count number of rows
I have recently started working with VBA and I have to filter a column with string 'NEWV' and to count number of rows that end after that filtering,Currently am using the below code but that doesnt seem to work,</p>

```<code>ByrNbr = Watchlist.Range("B" & i).Value

LookFor = ByrNbr

Set Age_rng = Total.Sheets("Counts").Range("A:S")

If Total.Sheets("Counts").Range("G:G").Value = "NEWV" Then

 .Range("L27").Value = Application.WorksheetFunction.CountIf(Age_rng, Range("A:A"))

End If
</code>```

答:
Not sure what workbook and worksheet these ranges are on, but you could use something like this, just have to clarify where each range resides.</p>

```<code>ByrNbr = Watchlist.Range("B" & i).Value
     Worksheets(???).Range("L27").Value =WorksheetFunction.CountIfs(Watchlist.Range("B:B" ), ByrNbr,
    Watchlist.Range("G:G"), "NEWV")
</code>```

Body:
I have recently started working with VBA and I have to filter a column with string 'NEWV' and to count number of rows that end after that filtering,Currently am using the below code but that doesnt seem to work,

ByrNbr = Watchlist.Range("B" & i).Value

LookFor = ByrNbr

Set Age_rng = Total.Sheets("Counts").Range("A:S")

If Total.Sheets("Counts").Range("G:G").Value = "NEWV" Then

 .Range("L27").Value = Application.WorksheetFunction.CountIf(Age_rng, Range("A:A"))

End If

Body:
Not sure what workbook and worksheet these ranges are on, but you could use something like this, just have to clarify where each range resides.

ByrNbr = Watchlist.Range("B" & i).Value
     Worksheets(???).Range("L27").Value =WorksheetFunction.CountIfs(Watchlist.Range("B:B" ), ByrNbr,
    Watchlist.Range("G:G"), "NEWV")


问:
json_encode not returning anything
I am trying to convert my MYSQL table data into JSON. I am trying with json_encode(). But it does not work. It does not return anything. I have checked the console,doesn't even throw any errors. What am i missing?</p>

```<code><?php
    //open connection to mysql db
    $connection = mysqli_connect("localhost","root","","maps") or die("Error " . mysqli_error($connection));

    //fetch table rows from mysql db
    $sql = "select * from locations";
    $result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));

    //create an array
    $emparray[] = array();
    while($row =mysqli_fetch_assoc($result))
    {
        $emparray[] = $row;
    }
    echo json_encode($emparray);

    //close the db connection
    mysqli_close($connection);
?>
</code>```

答: I had a similar problem but when I tried the solutions above it returned me a 1-dimensional array of JSON-like strings instead of a 2-d array. I solved it by running $.parseJSON (jQuery) on each element.

Title: json_encode not returning anything

Body:
I am trying to convert my MYSQL table data into JSON. I am trying with json_encode(). But it does not work. It does not return anything. I have checked the console,doesn't even throw any errors. What am i missing?

<?php
    //open connection to mysql db
    $connection = mysqli_connect("localhost","root","","maps") or die("Error " . mysqli_error($connection));

    //fetch table rows from mysql db
    $sql = "select * from locations";
    $result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));

    //create an array
    $emparray[] = array();
    while($row =mysqli_fetch_assoc($result))
    {
        $emparray[] = $row;
    }
    echo json_encode($emparray);

    //close the db connection
    mysqli_close($connection);
?>


问:
WordPress: Same content from either a subdomain or subdirectory
I apologize in advance for not having very many examples of effort already put into solving this. I've been googling and racking my brain but I can't even begin to visualize how this should be done.

We have a WordPress site with a Woocommerce store. To put it simply, we will be selling products for various resorts, and each resort will have their own product category to keep everything separate. So for instance if someone goes to https://www.oursite.com/resort-1, it'll be a page with all of Resort 1's products. This is all fine and good.

The problem: for each resort, we also have iPad kiosks that will use Kiosk Pro to display each resort's products and allow them to be purchased. These kiosk versions of the site must be accessible via a subdomain, e.g. https://resort-1.oursite.com. These subdomain versions should start with a landing page, then lead to the expected product listing but with a slightly different look (all via css).

My questions:

How can I set up a subdomain to lead to a specific page without using a multisite?

How can I adjust all links on each page so if someone starts on the kiosk subdomain, they'll stay on the kiosk version no matter where they navigate to?

答:
It strikes me that one way to accomplish this would be to:

a) use htaccess to route to a page with the subdomain passed as a var, for example subdomain.domain.com/page to domain.com/page?sd=subdomain

Mod Rewrite Subdomain to PHP with GET variable

Sub-domain as variable in mod_rewrite

and then;

b) include code in your theme if (sd = sudomain ) {do_something()} where do something uses a different style.css and modifies any html within the page as desired.


问:
Parse command line arguments into a IP : Port format using argparse in Python
I'm trying to use argparse to parse 2 command line arguments to my script in the following format client.py [-n IP] [-p PORT]

So far I've implemented the following:

```<code>connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
## Gets IP and PORT from command line and parses them
ConnectionInfo = argparse.ArgumentParser()
ConnectionInfo.add_argument("-n",  default=socket.gethostname())
ConnectionInfo.add_argument("-p", type=int, default='58000')
ConnectionInfoParsed = ConnectionInfo.parse_args()
# Saves the parsed IP and Port
HOST = ConnectionInfoParsed.n
PORT = ConnectionInfoParsed.p
# Connects to Server
connection.connect((HOST, PORT))
</code>```

However when I execute:

```<code>py client.py [-n 127.0.0.1] [-p 58000]
</code>```

I get the following error

```<code>usage: client.py [-h] [-n N] [-p P]
client.py: error: unrecognized arguments: [-n 127.0.0.1] [-p 58000]
</code>```

Can anyone help me out where is the problem here, also where does the [-h] argument in the error comes from since I don't add any argument for it?

答:
As hpaulj mentioned

I'd expect you to use py client.py -n 127.0.0.1 -p 58000. No brackets.

The issue is solved

Body:
I'm trying to use argparse to parse 2 command line arguments to my script in the following format client.py [-n IP] [-p PORT]

So far I've implemented the following:

connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
## Gets IP and PORT from command line and parses them
ConnectionInfo = argparse.ArgumentParser()
ConnectionInfo.add_argument("-n",  default=socket.gethostname())
ConnectionInfo.add_argument("-p", type=int, default='58000')
ConnectionInfoParsed = ConnectionInfo.parse_args()
# Saves the parsed IP and Port
HOST = ConnectionInfoParsed.n
PORT = ConnectionInfoParsed.p
# Connects to Server
connection.connect((HOST, PORT))

However when I execute:

py client.py [-n 127.0.0.1] [-p 58000]

I get the following error

usage: client.py [-h] [-n N] [-p P]
client.py: error: unrecognized arguments: [-n 127.0.0.1] [-p 58000]

Can anyone help me out where is the problem here, also where does the [-h] argument in the error comes from since I don't add any argument for it?


答:
As I remember , everything you define in python is an object belongs to a class. And yes if a variable object has assigned some value and if you create another variable with same value then python wont create a new reference for the second variable but it will use first variables reference for second variable as well.

For example:

```<code>>>> a=10
>>> id(a)
2001255152
>>> b=20
>>> id(b)
2001255472
>>> c=10
>>> id(c)
2001255152
>>>
</code>```

I may not explain in much better way but my example does I hope.

Title: Importing modules twice in python with different names

Body:
As I remember , everything you define in python is an object belongs to a class. And yes if a variable object has assigned some value and if you create another variable with same value then python wont create a new reference for the second variable but it will use first variables reference for second variable as well.

For example:

>>> a=10
>>> id(a)
2001255152
>>> b=20
>>> id(b)
2001255472
>>> c=10
>>> id(c)
2001255152
>>>

I may not explain in much better way but my example does I hope.


问:
Get Hard disk serial Number
I want to get hard disk serial number. How I can I do that?
I tried with two code but I am not getting

```<code>StringCollection propNames = new StringCollection();
ManagementClass driveClass = new ManagementClass("Win32_DiskDrive");
PropertyDataCollection  props = driveClass.Properties;
foreach (PropertyData driveProperty in props)
{
    propNames.Add(driveProperty.Name);
}
int idx = 0;
ManagementObjectCollection drives = driveClass.GetInstances();
foreach (ManagementObject drv in drives)
       {
          Label2.Text+=(idx + 1);
          foreach (string strProp in propNames)
           {
            //Label2.Text+=drv[strProp];
         Response.Write(strProp + "   =   " + drv[strProp] + "</br>");
          }
    }
</code>```

In this one I am not getting any Unique Serial number.

And Second one is

```<code>string drive = "C";
ManagementObject disk = new ManagementObject("win32_logicaldisk.deviceid=\"" + drive + ":\"");
disk.Get();
Label3.Text = "VolumeSerialNumber="+ disk["VolumeSerialNumber"].ToString();
</code>```

Here I am getting VolumeSerialNumber. But it is not unique one. If I format the hard disk, this will change. How Can I get this?

答:
Here's some code that may help:</p>

```<code>ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");

string serial_number="";

foreach (ManagementObject wmi_HD in searcher.Get())
{
    serial_number = wmi_HD["SerialNumber"].ToString();
}

MessageBox.Show(serial_number);
</code>```

Title: Get Hard disk serial Number

Body:
I want to get hard disk serial number. How I can I do that?
I tried with two code but I am not getting

StringCollection propNames = new StringCollection();
ManagementClass driveClass = new ManagementClass("Win32_DiskDrive");
PropertyDataCollection  props = driveClass.Properties;
foreach (PropertyData driveProperty in props)
{
    propNames.Add(driveProperty.Name);
}
int idx = 0;
ManagementObjectCollection drives = driveClass.GetInstances();
foreach (ManagementObject drv in drives)
       {
          Label2.Text+=(idx + 1);
          foreach (string strProp in propNames)
           {
            //Label2.Text+=drv[strProp];
         Response.Write(strProp + "   =   " + drv[strProp] + "
");
          }
    }

In this one I am not getting any Unique Serial number.

And Second one is

string drive = "C";
ManagementObject disk = new ManagementObject("win32_logicaldisk.deviceid=\"" + drive + ":\"");
disk.Get();
Label3.Text = "VolumeSerialNumber="+ disk["VolumeSerialNumber"].ToString();

Here I am getting VolumeSerialNumber. But it is not unique one. If I format the hard disk, this will change. How Can I get this?

Body:
Here's some code that may help:

ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");

string serial_number="";

foreach (ManagementObject wmi_HD in searcher.Get())
{
    serial_number = wmi_HD["SerialNumber"].ToString();
}

MessageBox.Show(serial_number);


问:
Javascript is not parsing JSON
NOTE:- I am just beginning with JSON with javascript and was trying this simple script. I want to make use of JSON.parse() here to fetch the data

Here is a snippet of my code

```

Nothing is getting displayed. I don't understand what is the problem. Can anyone help?
Edit- I corrected the string which spanned multiple lines but it still doesn't work

答:
There are many problems with this snippit.

JavaScript doesn't tolerate newlines within "", you must use a template string within ``.

The JSON string you provide is not valid JSON: it uses single quotes, and it needs an extra object wrapper {}. When in doubt, hit https://jsonlint.com/ and see if it parses.

You are prasing the string, which returns an object, and attempting to print that into a web page. That will produce the string representation of an object, which is [Object object], which is rather useless.

So you need to stringify the object to see it, which is where you started...

var text = `
{
    "college": {
        "stream": {
            "commerce": {
                "junior": ["FY", "SY"],
                "bachelor": ["Bcom", "BMM"]
            },
            "science": {
                "junior": ["FY", "SY"],
                "bachelor": ["Bsc", "BTech"]
            },
            "arts": {
                "junior": ["FY", "SY"],
                "bachelor": ["BA", "B.Ed"]
            }
        }
    }
}`;
var jcontent = JSON.parse(text);
// JSON.parse() returns an object, whose string representation is
// "[Object object]", so you actually want to JSON.stringify() this to see it

document.getElementById('output').innerHTML += jcontent;
document.getElementById('output2').innerHTML += JSON.stringify(jcontent, 0, 2);
document.getElementById('output3').innerHTML += JSON.stringify(jcontent['college']['stream']['arts']['junior'], 0, 2);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>

<body>
  Original output:
  <pre id="output">```

  Junior arts?

```

  Whole thing:
  <pre id="output2">```

```

Title: Javascript is not parsing JSON

Body:
NOTE:- I am just beginning with JSON with javascript and was trying this simple script. I want to make use of JSON.parse() here to fetch the data

Here is a snippet of my code

Nothing is getting displayed. I don't understand what is the problem. Can anyone help?
Edit- I corrected the string which spanned multiple lines but it still doesn't work

Body:
There are many problems with this snippit.

JavaScript doesn't tolerate newlines within "", you must use a template string within ``.

The JSON string you provide is not valid JSON: it uses single quotes, and it needs an extra object wrapper {}. When in doubt, hit https://jsonlint.com/ and see if it parses.

You are prasing the string, which returns an object, and attempting to print that into a web page. That will produce the string representation of an object, which is [Object object], which is rather useless.

So you need to stringify the object to see it, which is where you started...

var text = `
{
    "college": {
        "stream": {
            "commerce": {
                "junior": ["FY", "SY"],
                "bachelor": ["Bcom", "BMM"]
            },
            "science": {
                "junior": ["FY", "SY"],
                "bachelor": ["Bsc", "BTech"]
            },
            "arts": {
                "junior": ["FY", "SY"],
                "bachelor": ["BA", "B.Ed"]
            }
        }
    }
}`;
var jcontent = JSON.parse(text);
// JSON.parse() returns an object, whose string representation is
// "[Object object]", so you actually want to JSON.stringify() this to see it

document.getElementById('output').innerHTML += jcontent;
document.getElementById('output2').innerHTML += JSON.stringify(jcontent, 0, 2);
document.getElementById('output3').innerHTML += JSON.stringify(jcontent['college']['stream']['arts']['junior'], 0, 2);

<html>

<body>
  Original output:
  <pre id="output"></pre>

  Junior arts?
  <pre id="output3"></pre>

  Whole thing:
  <pre id="output2"></pre>
</body>

</html>


问:
Keep only dataframe rows closest to given values
I have a dataframe df1 with some variables, given for certain values A:

```<code>df1 = pd.DataFrame({"A": [110.035,110.078,110.732,112.828,112.930],
               "var1": np.random.random(5),
               "var2":np.random.random(5)})

       A          var1        var2
0   110.035     0.500537    0.571497
1   110.078     0.234550    0.732815
2   110.732     0.337149    0.098250
3   112.828     0.190261    0.366118
4   112.930     0.990539    0.892640
</code>```

and a dataframe df2 of values A like

```<code>df2 = pd.DataFrame({"A": [110.04, 112.83]})

      A
0   110.04
1   112.83
</code>```

Now I want to keep all values in df1, that are closest to one of the values in df2 and drop all the others. In my example I want to keep rows 0 and 3 only.

My idea is to build the absolute differences and use argsort():

```<code>(df1.A-x).abs().argsort()[:1]
</code>```

but this works for one value x only, how can I extend this to all values in df2?

答:
Use reindex with method='nearest':

```<code>df = df1.set_index('A').reindex(df2.A, method='nearest').reset_index()
df

        A      var1      var2
0  110.04  0.262062  0.624065
1  112.83  0.107757  0.167591
</code>```

If you want the original A values back, perform a second merge step with df1:

```<code>df.merge(df1, on=['var1', 'var2']).reindex(columns=df1.columns)

         A      var1      var2
0  110.035  0.262062  0.624065
1  112.828  0.107757  0.167591
</code>```

Body:
I have a dataframe df1 with some variables, given for certain values A:

df1 = pd.DataFrame({"A": [110.035,110.078,110.732,112.828,112.930],
               "var1": np.random.random(5),
               "var2":np.random.random(5)})

       A          var1        var2
0   110.035     0.500537    0.571497
1   110.078     0.234550    0.732815
2   110.732     0.337149    0.098250
3   112.828     0.190261    0.366118
4   112.930     0.990539    0.892640

and a dataframe df2 of values A like

df2 = pd.DataFrame({"A": [110.04, 112.83]})

      A
0   110.04
1   112.83

Now I want to keep all values in df1, that are closest to one of the values in df2 and drop all the others. In my example I want to keep rows 0 and 3 only.

My idea is to build the absolute differences and use argsort():

(df1.A-x).abs().argsort()[:1]

but this works for one value x only, how can I extend this to all values in df2?

Body:
Use reindex with method='nearest':

df = df1.set_index('A').reindex(df2.A, method='nearest').reset_index()
df

        A      var1      var2
0  110.04  0.262062  0.624065
1  112.83  0.107757  0.167591

If you want the original A values back, perform a second merge step with df1:

df.merge(df1, on=['var1', 'var2']).reindex(columns=df1.columns)

         A      var1      var2
0  110.035  0.262062  0.624065
1  112.828  0.107757  0.167591


问:
Convert PCM raw bytes to WAV bytes
I am listening to live phone calls and am able to get the raw PCM bytes.
I also able to listen to these bytes through java's audio api.
These all works on an applet.

Now I want to be able to convert the raw PCM bytes of the phone call to WAV bytes so I could write it directly to a ServletOutputStream. This would allow browsers to actually listen to the phone calls.

Does anybody have any idea how I would be able to convert, on the fly, some raw PCM bytes[] to WAV bytes[]?

The examples I've seen all pertain to converting a file to another file.

java pcm to wav

How can I write a WAV file from byte array in java?

Thank you.

答:
I was also stuck in quite same situation, here's how I figured things out.</p>

```<code>public static boolean getWavFile(String filePath, InputStream audioStream) throws IOException {

    boolean result = false;
    try {

        byte[] decodedData = IOUtils.toByteArray(audioStream);

        System.out.println(">>Decoded Data" + Arrays.toString(decodedData));
        File outFile = new File(filePath);
        AudioFormat format = new AudioFormat(8000, 16, 1, true, false);
        AudioSystem.write(new AudioInputStream(new ByteArrayInputStream(
                decodedData), format, decodedData.length), AudioFileFormat.Type.WAVE, outFile);
        result = true;
        return result;
    } catch (IOException ex) {
        System.out.println("<<getWavFile - impl" + ex);
        return result;

    }
}
</code>```

Title: Convert PCM raw bytes to WAV bytes

Body:
I was also stuck in quite same situation, here's how I figured things out.

public static boolean getWavFile(String filePath, InputStream audioStream) throws IOException {

    boolean result = false;
    try {

        byte[] decodedData = IOUtils.toByteArray(audioStream);

        System.out.println(">>Decoded Data" + Arrays.toString(decodedData));
        File outFile = new File(filePath);
        AudioFormat format = new AudioFormat(8000, 16, 1, true, false);
        AudioSystem.write(new AudioInputStream(new ByteArrayInputStream(
                decodedData), format, decodedData.length), AudioFileFormat.Type.WAVE, outFile);
        result = true;
        return result;
    } catch (IOException ex) {
        System.out.println("<<getWavFile - impl" + ex);
        return result;

    }
}


问:
Function in SQL Server 2008 similar to GREATEST in mysql?
I want to find the maximum value of multiple columns.

MySQL supports the GREATEST function but SQL Server doesn't.

Is there any function similar to this in SQL Server 2008?

答:
For this, I created a scalar function as follows:

```<code>CREATE FUNCTION [dbo].[MaxOrNull](@val1 int, @val2 int)
returns int
as
begin
    if @val1 >= @val2 RETURN @val1
    if @val1 < @val2 RETURN @val2

    RETURN NULL
end
</code>```

It's the most elegant solution and can be used anywhere in your SQL code.

Body:
For this, I created a scalar function as follows:

CREATE FUNCTION [dbo].[MaxOrNull](@val1 int, @val2 int)
returns int
as
begin
    if @val1 >= @val2 RETURN @val1
    if @val1 < @val2 RETURN @val2

    RETURN NULL
end

It's the most elegant solution and can be used anywhere in your SQL code.


问:
How to organize Twitter data of CSV in PhpMyAdmin
I'm working on an application where I need to store a collection of tweets along with attributes such as Tweet ID, Date of Tweet, Language and Username inside of a MySQL database.

This is an image of what I'm aiming for: https://i.imgur.com/1EC3ICc.png

To do this, I created a program in python that collects 100+ tweets on Twitter in a JSON file. I then converted the JSON file to a CSV file using Microsoft Excel. After this I imported the CSV file in PHPMyAdmin as a table and I got the following outcome: https://i.imgur.com/tLkIA0T.png (10 rows x 185 columns).

The problem with the above is that some tweets have more data such as media, this causes the data to expand over multiple columns.

How do I quickly clean this table so that I only have my desired attributes in the table? Do I need to go back to scratch and work from my Python code or can I clean from the Table/CSV file?

答:
If Tweets are parsed in JSON format and you need only some of the fields, I recommend you to use JSON module to parse the needed fields and Pandas module to convert them into structured table in order to write it to MySQL, for example:</p>

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

#Open and read the text file where all the Tweets are
with open('tweets.txt') as f:
    tweets = f.readlines()
#Convert the read Tweets into JSON object
tweets_json = [json.loads(tweet) for tweet in tweets]
#Convert the list of Tweets into a structured dataframe
df = pd.DataFrame(tweets_json)
#Finally choose the attributes you need
df = df[['created_at', 'id', ...]]
#To write table into MySQL
df.to_sql(...)
</code>```

Body:
If Tweets are parsed in JSON format and you need only some of the fields, I recommend you to use JSON module to parse the needed fields and Pandas module to convert them into structured table in order to write it to MySQL, for example:

import json
import pandas as pd

#Open and read the text file where all the Tweets are
with open('tweets.txt') as f:
    tweets = f.readlines()
#Convert the read Tweets into JSON object
tweets_json = [json.loads(tweet) for tweet in tweets]
#Convert the list of Tweets into a structured dataframe
df = pd.DataFrame(tweets_json)
#Finally choose the attributes you need
df = df[['created_at', 'id', ...]]
#To write table into MySQL
df.to_sql(...)


问:
How to crop, resize and center an  with a fixed height using CSS
I'm trying to find a way to crop and resize image to fit in its container without distortion. I have set the height of the container, so the image will have to fill 100% this height, and the center of the image has to match the center of the container.

This is my html:

```<code><div class="container">
     <img src="image.jpg" class="img-responsive">
</div>
</code>```

And this is CSS:

```<code>.container {
overflow: hidden;
position: relative;
height: 280px;
}
.img-responsive {
display: block;
max-width: 100%;
height: auto;
}
</code>```

答:
This technique works quite well:</p>

```<code>.container {
overflow: hidden;
position: relative;
height: 260px;
width: 358px;
}
.img-responsive {
position: absolute;
width: auto;
height: 100%;
left: 50%;
top: 50%;
-webkit-transform: translate(-50%,-50%);
-ms-transform: translate(-50%,-50%);
transform: translate(-50%,-50%);
}
</code>```

Title: How to crop, resize and center an <img> with a fixed height using CSS

Body:
I'm trying to find a way to crop and resize image to fit in its container without distortion. I have set the height of the container, so the image will have to fill 100% this height, and the center of the image has to match the center of the container.

This is my html:

And this is CSS:

.container {
overflow: hidden;
position: relative;
height: 280px;
}
.img-responsive {
display: block;
max-width: 100%;
height: auto;
}

Body:
This technique works quite well:

.container {
overflow: hidden;
position: relative;
height: 260px;
width: 358px;
}
.img-responsive {
position: absolute;
width: auto;
height: 100%;
left: 50%;
top: 50%;
-webkit-transform: translate(-50%,-50%);
-ms-transform: translate(-50%,-50%);
transform: translate(-50%,-50%);
}


问:
How can I open my phone settings with a menu item click in android studio?
I need to open my phone settings by a click of a menu item "Open Device Settings" Here I had tried something, But when I try to run the project,the app crashes when I clicked the menu item, when I checked the Logcat it shows No activity to handle intent. Should I need to create another activity? Even if I create another activity, I don't know how to proceed further. Please help me friends.

MainActivity.java

```<code>import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            Intent intent = new Intent(Settings.ACTION_SETTINGS);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            startActivity(intent);
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
</code>```

activity_main.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="arun.com.androidmenu.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:srcCompat="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>
</code>```

content_main.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="arun.com.androidmenu.MainActivity"
    tools:showIn="@layout/activity_main">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>
</code>```

menu_main.xml:

```<code><menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="arun.com.androidmenu.MainActivity">
    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:title="Open Device Settings"
        app:showAsAction="never" />

    <item
        android:id="@+id/action_exit"
        android:orderInCategory="100"
        android:title="Exit"
        app:showAsAction="never" />
</menu>
</code>```

Here's my coding., I need to open my device settings when I click the Open
Device settings menu item. Please let me know the mistakes what I've done, Thanks.

答:
You can try simple intent:
Intent intent = new Intent(android.provider.Settings.ACTION_SETTINGS);         intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);</p>

Body:
I need to open my phone settings by a click of a menu item "Open Device Settings" Here I had tried something, But when I try to run the project,the app crashes when I clicked the menu item, when I checked the Logcat it shows No activity to handle intent. Should I need to create another activity? Even if I create another activity, I don't know how to proceed further. Please help me friends.

MainActivity.java

import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            Intent intent = new Intent(Settings.ACTION_SETTINGS);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            startActivity(intent);
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="arun.com.androidmenu.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:srcCompat="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>

content_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="arun.com.androidmenu.MainActivity"
    tools:showIn="@layout/activity_main">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

menu_main.xml:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="arun.com.androidmenu.MainActivity">
    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:title="Open Device Settings"
        app:showAsAction="never" />

    <item
        android:id="@+id/action_exit"
        android:orderInCategory="100"
        android:title="Exit"
        app:showAsAction="never" />
</menu>

Here's my coding., I need to open my device settings when I click the Open
Device settings menu item. Please let me know the mistakes what I've done, Thanks.


问:
How to install multiple openjdk versions on alpine-based docker container
I wish to install jdk7 and jdk8 on an alpine container side by side. I would like to pick jdk7 only if an env variable is set.

I've chained FROM openjdk:7-alpine and FROM openjdk:8-alpine, but regardless of their relative order, the latter one overwrites the former. So, I am left with only 1 installation as seen in '/usr/lib/jvm'.

Why I need this:

I need this setup for a slave container for Jenkins. Now, jenkins remoting jar runs ONLY on jdk8 now. So, I need it. Plus, since I am spawning this container for a project which needs jdk7 as default jdk, I need that too.

My Dockerfile: https://github.com/ankurshashcode/docker-slave/blob/alpine/Dockerfile

答:
You can use Docker multistage build to achieve that. You would basically copy the java installation from one image into another image. Here is what the dockerfile might look like:

```<code>FROM openjdk:7-alpine as java7

FROM openjdk:8-alpine
COPY --from=java7 /usr/lib/jvm/java-1.7-openjdk /usr/lib/jvm/java-1.7-openjdk
</code>```

Now you will have both java installations with the jdk7 installation being under /usr/lib/jvm/java-1.7-openjdk

ContentLicense: CC BY-SA 4.0

Body:
You can use Docker multistage build to achieve that. You would basically copy the java installation from one image into another image. Here is what the dockerfile might look like:

FROM openjdk:7-alpine as java7

FROM openjdk:8-alpine
COPY --from=java7 /usr/lib/jvm/java-1.7-openjdk /usr/lib/jvm/java-1.7-openjdk

Now you will have both java installations with the jdk7 installation being under /usr/lib/jvm/java-1.7-openjdk


问:
Instant App screen orientation
How can I disable screen orientation in Android Instant app???

I used
android:screenOrientation="portrait"
in every Manifest file (in 3 files) but it doens`t help!

答: Thanks for reporting the bug Igor. The fix for setting screenOrientation through Manifest in instant apps is coming soon.</p>

Title: Instant App screen orientation


问:
Initialize QByteArray avoiding [-Wnarrowing]
I am on an architecture where char is interpreted as signed by default.

I construct a char array similar as mentioned in the Qt5 documentation for QByteArray:

```<code>const char char_buffer[] = {
    0xFF, 0x00, 0x03
};
</code>```

When I later call QByteArray::fromRawData(char_buffer) respectively QByteArray(char_buffer), the compiler will complain:

```<code>error: narrowing conversion of ‘255’ from ‘int’ to ‘char’ inside { } [-Wnarrowing]
</code>```

(There is no unsigned char * parameter overload for fromRawData())

Solutions:

Whenever I have to interact with one of the in-built function, I cast an unsigned char *.

```<code>const char uchar_buffer[] = {
    0xFF, 0x00, 0x03
};
QByteArray::fromRawData(reinterpret_cast<const char*>(uchar_buffer), sizeof(uchar_buffer))
</code>```

Question:

Did I oversee any easier/straight forward solution without casting (and keeping the warning for narrowing)?

答:
The solution of casting the unsigned char * whenever interacting with a Qt function expecting a char * is okay.

An alternative to casting

Use the compiler flag -funsigned-char to make the compiler use unsigned char by default.

With .pro:

```<code>QMAKE_CXXFLAGS += -funsigned-char
</code>```

With CMake:

```<code>set( CMAKE_CXX_FLAGS "-funsigned-char")
</code>```

The proper solution

The initial issue is how the char_buffer is initialised. Integer literals (e.g. 0xFF) are from type integer. It's best to use character literals in the first place, e.g.,

```<code>const char char_buffer[] = {
    '\xFF', '\x00', '\x03'
};
</code>```

Body:
I am on an architecture where char is interpreted as signed by default.

I construct a char array similar as mentioned in the Qt5 documentation for QByteArray:

const char char_buffer[] = {
    0xFF, 0x00, 0x03
};

When I later call QByteArray::fromRawData(char_buffer) respectively QByteArray(char_buffer), the compiler will complain:

error: narrowing conversion of ‘255’ from ‘int’ to ‘char’ inside { } [-Wnarrowing]

(There is no unsigned char * parameter overload for fromRawData())

Solutions:

Whenever I have to interact with one of the in-built function, I cast an unsigned char *.

const char uchar_buffer[] = {
    0xFF, 0x00, 0x03
};
QByteArray::fromRawData(reinterpret_cast<const char*>(uchar_buffer), sizeof(uchar_buffer))

Question:

Did I oversee any easier/straight forward solution without casting (and keeping the warning for narrowing)?

Body:
The solution of casting the unsigned char * whenever interacting with a Qt function expecting a char * is okay.

An alternative to casting

Use the compiler flag -funsigned-char to make the compiler use unsigned char by default.

With .pro:

QMAKE_CXXFLAGS += -funsigned-char

With CMake:

set( CMAKE_CXX_FLAGS "-funsigned-char")

The proper solution

The initial issue is how the char_buffer is initialised. Integer literals (e.g. 0xFF) are from type integer. It's best to use character literals in the first place, e.g.,

const char char_buffer[] = {
    '\xFF', '\x00', '\x03'
};


问:
Get full path of executable of running process on HPUX
I want to get the full path of the running process (executable) without having root permission using C++ code. Can someone suggest a way to achieve this.

on Linux platforms i can do it by using following way.

```<code>char exepath[1024] = {0};
char procid[1024] = {0};
char exelink[1024] = {0};

sprintf(procid, "%u", getpid());

strcpy(exelink, "/proc/");
strcat(exelink, procid);
strcat(exelink, "/exe");

readlink(exelink, exepath, sizeof(exepath));
</code>```

Here exepath gives us the full path of the  executable.

Similarly for windows we do it using

```<code>GetModuleFileName(NULL, exepath, sizeof(exepath));  /* get fullpath of the service */
</code>```

Please help me how to do it on HP-UX since there is no /proc directory in HP-UX.

答:
On HP-UX, use pstat:</p>

```
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <unistd.h>

#define _PSTAT64
#include <sys/pstat.h>

int main(int argc, char *argv[])
{
  char filename[PATH_MAX];
  struct pst_status s;

  if (pstat_getproc(&s,sizeof(s),0,getpid()) == -1) {
    perror("pstat_getproc");
    return EXIT_FAILURE;
  }

  if (pstat_getpathname(filename,sizeof(filename),&s.pst_fid_text) == -1) {
    perror("pstat_getpathname");
    return EXIT_FAILURE;
  }

  printf("filename: %s\n",filename);

  return EXIT_SUCCESS;
}
```

Body:
I want to get the full path of the running process (executable) without having root permission using C++ code. Can someone suggest a way to achieve this.

on Linux platforms i can do it by using following way.

char exepath[1024] = {0};
char procid[1024] = {0};
char exelink[1024] = {0};

sprintf(procid, "%u", getpid());

strcpy(exelink, "/proc/");
strcat(exelink, procid);
strcat(exelink, "/exe");

readlink(exelink, exepath, sizeof(exepath));

Here exepath gives us the full path of the  executable.

Similarly for windows we do it using

GetModuleFileName(NULL, exepath, sizeof(exepath));  /* get fullpath of the service */

Please help me how to do it on HP-UX since there is no /proc directory in HP-UX.

LastEditorDisplayName: Martin York

Body:
On HP-UX, use pstat:

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <unistd.h>

#define _PSTAT64
#include <sys/pstat.h>

int main(int argc, char *argv[])
{
  char filename[PATH_MAX];
  struct pst_status s;

  if (pstat_getproc(&s,sizeof(s),0,getpid()) == -1) {
    perror("pstat_getproc");
    return EXIT_FAILURE;
  }

  if (pstat_getpathname(filename,sizeof(filename),&s.pst_fid_text) == -1) {
    perror("pstat_getpathname");
    return EXIT_FAILURE;
  }

  printf("filename: %s\n",filename);

  return EXIT_SUCCESS;
}

OwnerDisplayName: Randy Proctor