问:
Java Swing Help
I'm trying to create a grid of JButtons, with index values to the left and right of the button grid.

Here is my code, but I'm getting a NullPointerException.  What is the problem?

```<code>public class Test {
public static void main(String args[]) {
    JFrame myapp = new JFrame("test");
    myapp.setLayout(new FlowLayout());

    myapp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    myapp.setSize(400,400);
    myapp.setVisible(true);

    myapp.getContentPane().add(Board());
}

private static JPanel Board() {
    JButton[][] buttons = new JButton [10][10];

    JPanel board = new JPanel(new GridLayout(11,11));

    String[] rowlabels = {" ","A","B","C","D","E","F","G","H","I","J"};
    String[] columnlabels = {" ","1","2","3","4","5","6","7","8","9","10"};
    JTextField k;

    for (int i = 0; i < 11; i++) {
        for (int j = 0; j < 11; j++) {
            if ((j != 0) && (i != 0)) {
                //myboard[i-1][j-1].addActionListener(new ButtonHandler());
                board.add(buttons[i-1][j-1]);
            }
            if (i == 0) {
                if (j != 0) {
                    // used to display row of numbers
                    k = new JTextField(columnlabels[j]);
                    k.setEditable(false);
                    k.setHorizontalAlignment((int) JFrame.CENTER_ALIGNMENT);
                } else {
                    // used to display column of numbers
                    k = new JTextField();
                    k.setEditable(false);
                }
                board.add(k);
            } else if (j == 0) {
                k = new JTextField(rowlabels[i]);
                k.setEditable(false);
                k.setHorizontalAlignment((int) JFrame.CENTER_ALIGNMENT);
                board.add(k);
            }
        }
    }

    return board;
}
}
</code>```

I'm probably doing something obvious, but Swing is kind of new to me, so any help would be greatly appreciated.

答:
Just tried your code and noticed that you get NPE because you are just creating a buttons array but do not create buttons in it so your buttons array contains null values and when trying to add it in board it throws NPE.

Try something like this after creating array:

```<code> private static JPanel Board() {
    JButton[][] buttons = new JButton [10][10];
    for (int i = 0; i < 10; i++) {
        for (int j = 0; j < 10; j++) {
            buttons[i][j] = new JButton();
        }
    }
    JPanel board = new JPanel(new GridLayout(11,11));

    String[] rowlabels = {" ","A","B","C","D","E","F","G","H","I","J"};
    String[] columnlabels = {" ","1","2","3","4","5","6","7","8","9","10"};
    JTextField k;

    // ---- your remaining code.

 }
</code>```

Title: Java Swing Help

Body:
I'm trying to create a grid of JButtons, with index values to the left and right of the button grid.

Here is my code, but I'm getting a NullPointerException.  What is the problem?

public class Test {
public static void main(String args[]) {
    JFrame myapp = new JFrame("test");
    myapp.setLayout(new FlowLayout());

    myapp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    myapp.setSize(400,400);
    myapp.setVisible(true);

    myapp.getContentPane().add(Board());
}

private static JPanel Board() {
    JButton[][] buttons = new JButton [10][10];

    JPanel board = new JPanel(new GridLayout(11,11));

    String[] rowlabels = {" ","A","B","C","D","E","F","G","H","I","J"};
    String[] columnlabels = {" ","1","2","3","4","5","6","7","8","9","10"};
    JTextField k;

    for (int i = 0; i < 11; i++) {
        for (int j = 0; j < 11; j++) {
            if ((j != 0) && (i != 0)) {
                //myboard[i-1][j-1].addActionListener(new ButtonHandler());
                board.add(buttons[i-1][j-1]);
            }
            if (i == 0) {
                if (j != 0) {
                    // used to display row of numbers
                    k = new JTextField(columnlabels[j]);
                    k.setEditable(false);
                    k.setHorizontalAlignment((int) JFrame.CENTER_ALIGNMENT);
                } else {
                    // used to display column of numbers
                    k = new JTextField();
                    k.setEditable(false);
                }
                board.add(k);
            } else if (j == 0) {
                k = new JTextField(rowlabels[i]);
                k.setEditable(false);
                k.setHorizontalAlignment((int) JFrame.CENTER_ALIGNMENT);
                board.add(k);
            }
        }
    }

    return board;
}
}

I'm probably doing something obvious, but Swing is kind of new to me, so any help would be greatly appreciated.

Body:
Just tried your code and noticed that you get NPE because you are just creating a buttons array but do not create buttons in it so your buttons array contains null values and when trying to add it in board it throws NPE.

Try something like this after creating array:

 private static JPanel Board() {
    JButton[][] buttons = new JButton [10][10];
    for (int i = 0; i < 10; i++) {
        for (int j = 0; j < 10; j++) {
            buttons[i][j] = new JButton();
        }
    }
    JPanel board = new JPanel(new GridLayout(11,11));

    String[] rowlabels = {" ","A","B","C","D","E","F","G","H","I","J"};
    String[] columnlabels = {" ","1","2","3","4","5","6","7","8","9","10"};
    JTextField k;

    // ---- your remaining code.

 }


来源: stackexchange

问:
Why need list argument in list splice func cpp
Why do we need a list argument in the splice func cpp? Why only iterators aren't sufficient?
Result is the same if I pass l1 or l2 as a second argument
l1.splice(st, l1, it, it2); or l1.splice(st, l2, it, it2);

prints 1 4 5 2 3

```<code>#include <bits/stdc++.h>
using namespace std;

int main()
{

// initializing lists and iterator
list<int> l1 = { 1, 2, 3 };
list<int> l2 = { 4, 5 };

auto it = l2.begin();
auto it2 = l2.end();

auto st = l1.begin();
std::advance(st,1);

// result the same if in splice l1 or l2
// 1 4 5 2 3
l1.splice(st, l2, it, it2);

cout << "list l1 after splice operation" << endl;
for (auto x : l1)
    cout << x << " ";
return 0;
}
</code>```

答:
This call

```<code>l1.splice(st, l1, it, it2);
</code>```

invokes undefined behavior.

When you need to extract a range of elements then other data members of the list as for example size must be updated.

If you will execute for example this statement

```<code>std::cout << l2.size() << '\n';
</code>```

you can get unexpected result.

Here is a demonstrative program compiled with gcc 8.3.

```<code>#include <iostream>
#include <list>
#include <iterator>

int main()
{
    std::list<int> lst1 = { 1, 3, 5, 7, 9 };
    std::list<int> lst2 = { 0, 2, 4, 6, 8 };

    lst1.splice( std::next( std::begin( lst1 ) ),
                            lst1,
                            std::begin( lst2 ),
                            std::end( lst2 ) );

    for ( const auto &item : lst1 )
    {
        std::cout << item << ' ';
    }
    std::cout << '\n';

    for ( const auto &item : lst2 )
    {
        std::cout << item << ' ';
    }
    std::cout << '\n';

    std::cout << "the size of lst2 is " << lst2.size() << '\n';

    return 0;
}
</code>```

Its output is

```<code>1 0 2 4 6 8 3 5 7 9

the size of lst2 is 5
</code>```

If you will change lst1 to lst2 in this call

```<code>    lst1.splice( std::next( std::begin( lst1 ) ),
                            lst2,                 // <===
                            std::begin( lst2 ),
                            std::end( lst2 ) );
</code>```

then you will the correct output

```<code>1 0 2 4 6 8 3 5 7 9

the size of lst2 is 0
                   ^^^
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Why do we need a list argument in the splice func cpp? Why only iterators aren't sufficient?
Result is the same if I pass l1 or l2 as a second argument
l1.splice(st, l1, it, it2); or l1.splice(st, l2, it, it2);

prints 1 4 5 2 3

#include <bits/stdc++.h>
using namespace std;

int main()
{

// initializing lists and iterator
list<int> l1 = { 1, 2, 3 };
list<int> l2 = { 4, 5 };

auto it = l2.begin();
auto it2 = l2.end();

auto st = l1.begin();
std::advance(st,1);

// result the same if in splice l1 or l2
// 1 4 5 2 3
l1.splice(st, l2, it, it2);

cout << "list l1 after splice operation" << endl;
for (auto x : l1)
    cout << x << " ";
return 0;
}

Body:
This call

l1.splice(st, l1, it, it2);

invokes undefined behavior.

When you need to extract a range of elements then other data members of the list as for example size must be updated.

If you will execute for example this statement

std::cout << l2.size() << '\n';

you can get unexpected result.

Here is a demonstrative program compiled with gcc 8.3.

#include <iostream>
#include <list>
#include <iterator>

int main()
{
    std::list<int> lst1 = { 1, 3, 5, 7, 9 };
    std::list<int> lst2 = { 0, 2, 4, 6, 8 };

    lst1.splice( std::next( std::begin( lst1 ) ),
                            lst1,
                            std::begin( lst2 ),
                            std::end( lst2 ) );

    for ( const auto &item : lst1 )
    {
        std::cout << item << ' ';
    }
    std::cout << '\n';

    for ( const auto &item : lst2 )
    {
        std::cout << item << ' ';
    }
    std::cout << '\n';

    std::cout << "the size of lst2 is " << lst2.size() << '\n';

    return 0;
}

Its output is

1 0 2 4 6 8 3 5 7 9

the size of lst2 is 5

If you will change lst1 to lst2 in this call

    lst1.splice( std::next( std::begin( lst1 ) ),
                            lst2,                 // <===
                            std::begin( lst2 ),
                            std::end( lst2 ) );

then you will the correct output

1 0 2 4 6 8 3 5 7 9

the size of lst2 is 0
                   ^^^


问:
how to get the sum of values in 2 textboxes that gets updated C#
I have 2 textboxes that get updated regularly, via serial port each of them displays data on 1 line, I want to get the sum of these values from these textboxes and put the sum into another text box.

Code:

```<code>value 1 and 2 are type string
textbox1.text = value1;
textbox2.text = value2;

double value3 = convert.ToDouble(value1) + convert.ToDouble(value2);
textbox3.text = value3.ToString();
</code>```

Output textbox1:

```<code>100, after sometime updates to 200, then 300
</code>```

Output textbox2:

```<code>50, after sometime updates to 100, then 150
</code>```

What I'm getting, output in textbox3:

```<code>150, after some time updates to 300, then 450
</code>```

The value I should get is

```<code>100+200+300+50+100+150
</code>```

答:
I hope it will work for you

1) Declare below at class level:

```<code>List<double> txbxList1 = new List<double>();
List<double> txbxList2 = new List<double>();
</code>```

2) Use below code with the TextChanged event for both textbox1 and textbox2

```<code>    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        txbxList1.Add(double.Parse(textBox1.Text));
        textBox3.Text = sumList().ToString();
    }

    private void textBox2_TextChanged(object sender, EventArgs e)
    {
        txbxList2.Add(double.Parse(textBox2.Text));
        textBox3.Text = sumList().ToString();
    }

    private double sumList()
    {
        double sum = 0;

        foreach(double d in txbxList1)
        {
            sum += d;
        }

        foreach (double d in txbxList2)
        {
            sum += d;
        }

        return sum;
    }
</code>```

Body:
I have 2 textboxes that get updated regularly, via serial port each of them displays data on 1 line, I want to get the sum of these values from these textboxes and put the sum into another text box.

Code:

value 1 and 2 are type string
textbox1.text = value1;
textbox2.text = value2;

double value3 = convert.ToDouble(value1) + convert.ToDouble(value2);
textbox3.text = value3.ToString();

Output textbox1:

100, after sometime updates to 200, then 300

Output textbox2:

50, after sometime updates to 100, then 150

What I'm getting, output in textbox3:

150, after some time updates to 300, then 450

The value I should get is

100+200+300+50+100+150

Body:
I hope it will work for you

1) Declare below at class level:

List<double> txbxList1 = new List<double>();
List<double> txbxList2 = new List<double>();

2) Use below code with the TextChanged event for both textbox1 and textbox2

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        txbxList1.Add(double.Parse(textBox1.Text));
        textBox3.Text = sumList().ToString();
    }

    private void textBox2_TextChanged(object sender, EventArgs e)
    {
        txbxList2.Add(double.Parse(textBox2.Text));
        textBox3.Text = sumList().ToString();
    }

    private double sumList()
    {
        double sum = 0;

        foreach(double d in txbxList1)
        {
            sum += d;
        }

        foreach (double d in txbxList2)
        {
            sum += d;
        }

        return sum;
    }


问:
Python - Using bs4 to parse specific data from html
I am still new to python and learning as I go so please bear with me..
How does one get bs4 to get only the 'value= * number *' data from the code provided?

```<code><div class="option-radios">
<label class="radio option-7">
    <em style="display: none"></em>

    <span class="radio-label">7</span>
    <input id="option-7"
            type="radio" name="option[1]"
            class=" property-uid1"
            value="59"              title="7" />
</label>

<label class="radio option-8">
    <em style="display: none"></em>

    <span class="radio-label">8</span>
    <input id="option-8"
            type="radio" name="option[1]"
            class=" property-uid1"
            value="61"              title="8" />
</label>

<label class="radio option-9">
    <em style="display: none"></em>

    <span class="radio-label">9</span>
    <input id="option-9"
            type="radio" name="option[1]"
            class=" property-uid1"
            value="62"              title="9" />
</label>

<label class="radio option-10">
    <em style="display: none"></em>

    <span class="radio-label">10</span>
    <input id="option-10"
            type="radio" name="option[1]"
            class=" property-uid1"
            value="63" checked="checked"                title="10" />
</label>

<label class="radio option-11">
    <em style="display: none"></em>

    <span class="radio-label">11</span>
    <input id="option-11"
            type="radio" name="option[1]"
            class=" property-uid1"
            value="60"              title="11" />
</label>
</code>```

I can get all the data within the div but I am unable to narrow down the search to what I want.

```<code>import requests
from bs4 import BeautifulSoup as bs

session = requests.session()
url = "url here"

a = session.get(url)

soup = bs(a.text,'html.parser')
sizes = soup.find('div',{'class':'option-radios'})
print(sizes)
</code>```

Apologies again for likely a very basic question!

答:
You will probably be better off with css selectors in this case:

```<code>for val in soup.select('label input'):
    print(val['value'])
</code>```

Output (for the snippet in your question):

```<code>59
61
62
63
60
</code>```

Body:
I am still new to python and learning as I go so please bear with me..
How does one get bs4 to get only the 'value= * number *' data from the code provided?

    7
    <input id="option-7"
            type="radio" name="option[1]"
            class=" property-uid1"
            value="59"              title="7" />

    8
    <input id="option-8"
            type="radio" name="option[1]"
            class=" property-uid1"
            value="61"              title="8" />

    9
    <input id="option-9"
            type="radio" name="option[1]"
            class=" property-uid1"
            value="62"              title="9" />

    10
    <input id="option-10"
            type="radio" name="option[1]"
            class=" property-uid1"
            value="63" checked="checked"                title="10" />

    11
    <input id="option-11"
            type="radio" name="option[1]"
            class=" property-uid1"
            value="60"              title="11" />

I can get all the data within the div but I am unable to narrow down the search to what I want.

import requests
from bs4 import BeautifulSoup as bs

session = requests.session()
url = "url here"

a = session.get(url)

soup = bs(a.text,'html.parser')
sizes = soup.find('div',{'class':'option-radios'})
print(sizes)

Apologies again for likely a very basic question!

Body:
You will probably be better off with css selectors in this case:

for val in soup.select('label input'):
    print(val['value'])

Output (for the snippet in your question):

59
61
62
63
60


问:
gvim and gdb for C?
In emacs there is a handy way to launch the gdb and gui options for gdb, the C debugger.

Is there a similar option in gvim?

答:
IMHO, NONE of vim's gdb plug-ins works RELIABLY mainly because vim doesn't natively support shell integration.
I use emacs+vimpulse.el. (vimpulse.el is an emacs package that emulates vim.) emacs+vimpulse.el behaves very similar to vim, and emacs supports gdb as nicely as anything out there.
cgdb is very good too, but I prefer emacs+vimpulse because I don't have to remember shortcut keys in emacs. (M-x gud- shows all possible debug commands, and shortcut keys are reminded whenever a command is executed.) Also, emacs is much more customizable than cgdb.</p>

OwnerDisplayName: zxcv

ContentLicense: CC BY-SA 3.0

Title: gvim and gdb for C?


问:
Is heap allocation more efficient for paging in large blocks?
For large (~64k+) allocations, is heap allocation more efficient?

For stack allocation, the pages need to be demand-paged in when used. Do allocators typically do this more efficiently for the heap, for instance mapping virtual memory pages to physical memory in bulk?

答: As I know always stack is more efficient. But the stack is static, but heap will grow dynamically. So it is better to use the heap for the large memory usage to prevent stack overflow</p>


问:
TextToSpeech API doesn't work when its called from OnStart
I'm using the TextToSpeech API in my code and it doesn't work when I try to call .speak() function from OnStart(), however it works when I call it from a button onClickListener().  Any idea why?  Thank you.</p>

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

    private TextToSpeech mTts;
    private OnClickListener buttonListener = new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            PlaySound();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ttsdemo);

        // Initialize Text To speech
        mTts = new TextToSpeech(this, new TextToSpeech.OnInitListener() {

            @Override
            public void onInit(int arg0) {
                // TODO Auto-generated method stub

            }
        });

        Button myButton = (Button)findViewById(R.id.buttontts1);
        myButton.setOnClickListener(buttonListener);
    }

    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        PlaySound();
    }

    protected void PlaySound()
    {
        String word = "Hello world";

        mTts.speak(word, TextToSpeech.QUEUE_FLUSH, null);

    }
</code>```

答:
You must wait until the TTS subsystem signals that it is ready: if it isn't ready when onStart is called, it will fail. If you are trying to speak as soon as it is ready call PlaySound from inside the OnInitListener:

```<code>@Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ttsdemo);

        // Initialize Text To speech
        mTts = new TextToSpeech(this, new TextToSpeech.OnInitListener() {

            @Override
            public void onInit(int arg0) {
if(arg0 == TextToSpeech.SUCCESS) PlaySound();

            }
        });

        Button myButton = (Button)findViewById(R.id.buttontts1);
        myButton.setOnClickListener(buttonListener);
    }
</code>```

Body:
I'm using the TextToSpeech API in my code and it doesn't work when I try to call .speak() function from OnStart(), however it works when I call it from a button onClickListener().  Any idea why?  Thank you.

public class TtsDemoActivity extends Activity {

    private TextToSpeech mTts;
    private OnClickListener buttonListener = new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            PlaySound();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ttsdemo);

        // Initialize Text To speech
        mTts = new TextToSpeech(this, new TextToSpeech.OnInitListener() {

            @Override
            public void onInit(int arg0) {
                // TODO Auto-generated method stub

            }
        });

        Button myButton = (Button)findViewById(R.id.buttontts1);
        myButton.setOnClickListener(buttonListener);
    }

    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        PlaySound();
    }

    protected void PlaySound()
    {
        String word = "Hello world";

        mTts.speak(word, TextToSpeech.QUEUE_FLUSH, null);

    }

Body:
You must wait until the TTS subsystem signals that it is ready: if it isn't ready when onStart is called, it will fail. If you are trying to speak as soon as it is ready call PlaySound from inside the OnInitListener:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ttsdemo);

        // Initialize Text To speech
        mTts = new TextToSpeech(this, new TextToSpeech.OnInitListener() {

            @Override
            public void onInit(int arg0) {
if(arg0 == TextToSpeech.SUCCESS) PlaySound();

            }
        });

        Button myButton = (Button)findViewById(R.id.buttontts1);
        myButton.setOnClickListener(buttonListener);
    }


问:
Compatible Data Type

I don't know if this issue already exists or not, I didn't find anything. By the way, I've got a problem with the data type.

For example, I've several data from server and these types are Int. So my Model should be Int too to receive the data from the server. Now if the server changes data type to Flot, My app will have a problem. so I should change the data type to Flot too and release a new version of the app. but here, my previous app versions won't work correctly. how can I handle it, if a data type changed from the server, my app work perfectly and get those data?

答:
It's not a good idea to change the data types from the server side.

But if you have to deal with it, one possible way is to declare the type of your variables as Any (the super type of all classes in Kotlin) and when using it, check the type of the variable via when, so you can benefit the smart cast too:

```<code>data class Person (val name: Any)

// Gathering data from the webservice and make an object of the Person class named person

when(person.name){
     is String -> {} // the name variable will be casted to String automatically
     is Float, is Double -> {}
     ..
     }
</code>```

Title: Compatible Data Type

Body:
It's not a good idea to change the data types from the server side.

But if you have to deal with it, one possible way is to declare the type of your variables as Any (the super type of all classes in Kotlin) and when using it, check the type of the variable via when, so you can benefit the smart cast too:

data class Person (val name: Any)

// Gathering data from the webservice and make an object of the Person class named person

when(person.name){
     is String -> {} // the name variable will be casted to String automatically
     is Float, is Double -> {}
     ..
     }


问:
Using R to count consecutive occurrences of a number and how long each occurrence lasts for?
I've got a large dataset (dt) which has a time columnn (where time is in seconds) and a column that records a 1 when some other variables meet a certain value and a 0 when they don't, e.g:

```<code>time (s) var
0        1
0.3      1
0.6      0
0.9      0
1.2      1
1.5      1
1.8      0
</code>```

Part 1) what I want to do is count each time 1 is repeated as a unique occurrence (more than twice) in a count column which would look like this:

```<code>time (s) var count
0        1   1
0.3      1   1
0.6      0   0
0.9      0   0
1.2      1   2
1.5      1   2
1.8      0   0

</code>```

where each occurrence in the same bout would have the same number and where 0 occurs is there is no counting.

For Part 1 I have this so far, but I would like it to print each unique occurrence as a count in a column which it doesn't do:

```<code>with(rle(dt$var), sum(lengths[values] > 2))
</code>```

Part 2) I also want to know the length of time each occurrence lasts.
(I also have a replicate column which has value of 1 for each row)

I tried this to calculate Part 2 but it doesn't work...

```<code>var_time <- dt %>%
  group_by(replicate) %>%
  mutate(var_time = cumsum(var != lag(var, default = ""))) %>%
  group_by(var, time) %>%
  summarise(start = min(time),
            end   = max(time),
            var = sum(var))
</code>```

答:
You can use rle to get answer to first part.

```<code>dt$count <- with(rle(dt$var), rep(values * cumsum(values & lengths >= 2),lengths))

dt
#  time var count
#1  0.0   1     1
#2  0.3   1     1
#3  0.6   0     0
#4  0.9   0     0
#5  1.2   1     2
#6  1.5   1     2
#7  1.8   0     0
</code>```

Body:
I've got a large dataset (dt) which has a time columnn (where time is in seconds) and a column that records a 1 when some other variables meet a certain value and a 0 when they don't, e.g:

time (s) var
0        1
0.3      1
0.6      0
0.9      0
1.2      1
1.5      1
1.8      0

Part 1) what I want to do is count each time 1 is repeated as a unique occurrence (more than twice) in a count column which would look like this:

time (s) var count
0        1   1
0.3      1   1
0.6      0   0
0.9      0   0
1.2      1   2
1.5      1   2
1.8      0   0

where each occurrence in the same bout would have the same number and where 0 occurs is there is no counting.

For Part 1 I have this so far, but I would like it to print each unique occurrence as a count in a column which it doesn't do:

with(rle(dt$var), sum(lengths[values] > 2))

Part 2) I also want to know the length of time each occurrence lasts.
(I also have a replicate column which has value of 1 for each row)

I tried this to calculate Part 2 but it doesn't work...

var_time <- dt %>%
  group_by(replicate) %>%
  mutate(var_time = cumsum(var != lag(var, default = ""))) %>%
  group_by(var, time) %>%
  summarise(start = min(time),
            end   = max(time),
            var = sum(var))

Body:
You can use rle to get answer to first part.

dt$count <- with(rle(dt$var), rep(values * cumsum(values & lengths >= 2),lengths))

dt
#  time var count
#1  0.0   1     1
#2  0.3   1     1
#3  0.6   0     0
#4  0.9   0     0
#5  1.2   1     2
#6  1.5   1     2
#7  1.8   0     0


问:
Can Pyomo solve non-convex MIQCP (bilinear problems) using Gurobi?
I want to model an optimization problem that contains quite some bilinear terms. As such, I want to make use of the functionality of Gurobi 9.0 to solve bilinear problems. Clearly, I can use the GurobiPy API. However, I might want to compare other solvers (like BARON). So, I wonder whether it is possible to use Pyomo to formulate the problem and then solve it using Gurobi? Will there be any problems?</p>

答:
As far as I can tell, there should not be a problem. The same Gurobi solver will be used. Your problem will just be modelled in a somewhat different syntax (PYOMO) which is easily portable for solving with a wider range of solvers.

If still in doubt, I suggest you try a very simple problem with a bilinear term.

Note however that BARON requires a commercial license unlike Gurobi which offers free academic licenses.

Best of luck!


问:
One liner to remove all occurrences of sub-strings in array with filter?
The title pretty much explains the question. I'd like to filter through an array and remove all occurrences of substrings. Similiar to how can be done by matching entire strings to remove like this

```<code>const x = ["don't delete", "delete", "delete", "don't delete", "delete", "don't delete"]
x= x.filter(i => i !== 'delete me');

> console.log(x)
["don't delete", "don't delete", "don't delete"]
</code>```

So let's say I want to just remove all the occurances of ' so every don't becomes dont, or maybe I just want to remove the every don't all together. I know you can match substrings with includes() but not sure how to implement it with a filter.

How could I go about this in a one liner? Thanks

答:
So let's say I want to just remove all the occurances of ' so every
  don't becomes dont

use map function instead of filter

const x = ["don't delete", "delete", "delete", "don't delete", "delete", "don't delete"]
const toRemove = "'";

const res = x.map(i => (i.includes(toRemove) ? i.replace(toRemove, '').trim() : i));

console.log(res)```
</div>
</div>
</p>

<blockquote>
  <p>or maybe I just want to remove the every don't all together</p>
</blockquote>

<p>use <code>map</code> function along with <code>filter</code> function</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const x = ["don't delete", "delete", "delete", "don't delete", "delete", "don't delete"]
const toRemove = "'";

const res = x.map(i => i.split(' ').filter(w => !w.includes(toRemove)).join(' '));

console.log(res)</code>```

Body:
The title pretty much explains the question. I'd like to filter through an array and remove all occurrences of substrings. Similiar to how can be done by matching entire strings to remove like this

const x = ["don't delete", "delete", "delete", "don't delete", "delete", "don't delete"]
x= x.filter(i => i !== 'delete me');

> console.log(x)
["don't delete", "don't delete", "don't delete"]

So let's say I want to just remove all the occurances of ' so every don't becomes dont, or maybe I just want to remove the every don't all together. I know you can match substrings with includes() but not sure how to implement it with a filter.

How could I go about this in a one liner? Thanks

Body:
So let's say I want to just remove all the occurances of ' so every
  don't becomes dont

use map function instead of filter

const x = ["don't delete", "delete", "delete", "don't delete", "delete", "don't delete"]
const toRemove = "'";

const res = x.map(i => (i.includes(toRemove) ? i.replace(toRemove, '').trim() : i));

console.log(res)

or maybe I just want to remove the every don't all together

use map function along with filter function

const x = ["don't delete", "delete", "delete", "don't delete", "delete", "don't delete"]
const toRemove = "'";

const res = x.map(i => i.split(' ').filter(w => !w.includes(toRemove)).join(' '));

console.log(res)


答:
Maybe I am blind, but in your onStart method, you aren't ever calling

```<code>PlaySound()
</code>```

Like you are in

@Override
        public void onClick(View arg0) {
            PlaySound();
        }

Title: TextToSpeech API doesn't work when its called from OnStart

Body:
Maybe I am blind, but in your onStart method, you aren't ever calling

PlaySound()

Like you are in

@Override
        public void onClick(View arg0) {
            PlaySound();
        }


问:
Docker Compose - adding identifier to network name
I trying to create network in docker-compose.vs.debug.yml file:

```<code>networks:
  myNetwork:
    driver: bridge
</code>```

But docker adding some identifier:

docker network ls ->

```<code>NETWORK ID          NAME                                         DRIVER              SCOPE
0e1fec1a9a30        dockercompose1163770330_myNetwork            bridge              local
</code>```

If there any option to name it like this:

```<code>NETWORK ID          NAME                                         DRIVER              SCOPE
0e1fec1a9a30        myNetwork                                    bridge              local
</code>```

I need it to connect automatically two containers on separate projects.

答:
Per https://docs.docker.com/compose/networking/:

Networks can also be given a custom name (since version 3.5):

```<code>version: "3.5"
networks:
  frontend:
    name: custom_frontend
    driver: custom-driver-1
</code>```

So you could choose to simply name your network myNetwork like this:

```<code>networks:
  myNetwork:
    name: myNetwork
    driver: bridge
</code>```

Alternatively, if you want your container to join an existing network (I know you say you want docker-compose to create the network for you, but for people reading this question this might be helpful), https://docs.docker.com/compose/networking/ states:

If you want your containers to join a pre-existing network, use the external option:

```<code>networks:
  default:
    external:
      name: my-pre-existing-network
</code>```

Body:
I trying to create network in docker-compose.vs.debug.yml file:

networks:
  myNetwork:
    driver: bridge

But docker adding some identifier:

docker network ls ->

NETWORK ID          NAME                                         DRIVER              SCOPE
0e1fec1a9a30        dockercompose1163770330_myNetwork            bridge              local

If there any option to name it like this:

NETWORK ID          NAME                                         DRIVER              SCOPE
0e1fec1a9a30        myNetwork                                    bridge              local

I need it to connect automatically two containers on separate projects.

Body:
Per https://docs.docker.com/compose/networking/:

Networks can also be given a custom name (since version 3.5):

version: "3.5"
networks:
  frontend:
    name: custom_frontend
    driver: custom-driver-1

So you could choose to simply name your network myNetwork like this:

networks:
  myNetwork:
    name: myNetwork
    driver: bridge

Alternatively, if you want your container to join an existing network (I know you say you want docker-compose to create the network for you, but for people reading this question this might be helpful), https://docs.docker.com/compose/networking/ states:

If you want your containers to join a pre-existing network, use the external option:

networks:
  default:
    external:
      name: my-pre-existing-network


问:
Consuming from React Context returns Cannot read property 'map' of undefined
I am  trying to pass data between two components in React using Context. The data that I want to pass is an array searchResults. I have setup the context and everything, but when I try to use the array in my second component I get Cannot read property 'map' of undefined, how can I consume the array in my second component that I have sent via the context?

Here is my first component:

```<code>import React, { Component } from "react";
import axios from "axios";
export const SearchContext = React.createContext();

class Search extends Component {
    state = {
        searchResults: [],
        isSearched: false
    }

    getSearchQuery = (event) => {
        const queryString = document.querySelector(
            ".search-input"
        ).value;

        if (event.keyCode === 13) {
            axios.post("http://localhost:3001/search", {
                queryString: queryString,

            }).then(response => {

                this.setState({ ...this.state, searchResults: response.data });

            });
            this.setState({ ...this.state, isSearched: true });
            window.location.href = '/blog/searchResults'
        }
    };

    render() {
        console.log(this.state.searchResults)
        return (
            <SearchContext.Provider value={this.state.searchResults}>
                <input
                    type="text"
                    className="search-input"
                    onKeyDown={(e) => this.getSearchQuery(e)}
                />
            </SearchContext.Provider>

        );
    }
}

export default Search;
</code>```

and my second component that should use the array:

```<code>import React, { Component } from 'react';
import Footer from '../Footer/Footer.jsx';
import CustomHeader from '../CustomHeader/CustomHeader.jsx';
import { SearchContext } from '../../components/Search/Search.jsx';
let title = 'Blog'

class SearchResultsPage extends Component {
    render() {
        return (
            <div>
                <CustomHeader
                    title={title}
                />

               <SearchContext.Consumer>
                {(value) => value.map(result => (
                    <div key={result._id}>
                        <div>
                        </div>
                        <article>
                            {value.postContent}
                        </article>
                    </div>
                  )
                )}
            </SearchContext.Consumer>
                <Footer />
            </div>
        )
    }
};
</code>```

答:
Context consumer takes a function as a child to which it passes the context value. You would write it like below

```<code><SearchContext.Consumer>
                {(value) => value.map(result => (
                    <div key={result._id}>
                        <div>
                        </div>
                        <article>
                            {value.postContent}
                        </article>
                    </div>
                  )
                )}
            </SearchContext.Consumer>
</code>```

Update: Based on your edit

Your SearchResultsPage isn't rendered as a child of Search component and for a context consumer to properly work it needs a context provider in the hierarchy.

Please render SearchResults page like

```<code><Search>
    <SearchResultsPage />
</Search>
</code>```

and also in Search component you will have to consume and render the children

```<code>render() {
    console.log(this.state.searchResults)
    return (
        <SearchContext.Provider value={this.state.searchResults}>
            <input
                type="text"
                className="search-input"
                onKeyDown={(e) => this.getSearchQuery(e)}
            />
            {this.props.children}
        </SearchContext.Provider>

    );
}
</code>```

Body:
I am  trying to pass data between two components in React using Context. The data that I want to pass is an array searchResults. I have setup the context and everything, but when I try to use the array in my second component I get Cannot read property 'map' of undefined, how can I consume the array in my second component that I have sent via the context?

Here is my first component:

import React, { Component } from "react";
import axios from "axios";
export const SearchContext = React.createContext();

class Search extends Component {
    state = {
        searchResults: [],
        isSearched: false
    }

    getSearchQuery = (event) => {
        const queryString = document.querySelector(
            ".search-input"
        ).value;

        if (event.keyCode === 13) {
            axios.post("http://localhost:3001/search", {
                queryString: queryString,

            }).then(response => {

                this.setState({ ...this.state, searchResults: response.data });

            });
            this.setState({ ...this.state, isSearched: true });
            window.location.href = '/blog/searchResults'
        }
    };

    render() {
        console.log(this.state.searchResults)
        return (
            <SearchContext.Provider value={this.state.searchResults}>
                <input
                    type="text"
                    className="search-input"
                    onKeyDown={(e) => this.getSearchQuery(e)}
                />
            </SearchContext.Provider>

        );
    }
}

export default Search;

and my second component that should use the array:

import React, { Component } from 'react';
import Footer from '../Footer/Footer.jsx';
import CustomHeader from '../CustomHeader/CustomHeader.jsx';
import { SearchContext } from '../../components/Search/Search.jsx';
let title = 'Blog'

class SearchResultsPage extends Component {
    render() {
        return (

                <CustomHeader
                    title={title}
                />

               <SearchContext.Consumer>
                {(value) => value.map(result => (

                            {value.postContent}

                  )
                )}
            </SearchContext.Consumer>

        )
    }
};

Body:
Context consumer takes a function as a child to which it passes the context value. You would write it like below

<SearchContext.Consumer>
                {(value) => value.map(result => (
                    <div key={result._id}>
                        <div>
                        </div>
                        <article>
                            {value.postContent}
                        </article>
                    </div>
                  )
                )}
            </SearchContext.Consumer>

Update: Based on your edit

Your SearchResultsPage isn't rendered as a child of Search component and for a context consumer to properly work it needs a context provider in the hierarchy.

Please render SearchResults page like

<Search>
    <SearchResultsPage />
</Search>

and also in Search component you will have to consume and render the children

render() {
    console.log(this.state.searchResults)
    return (
        <SearchContext.Provider value={this.state.searchResults}>
            <input
                type="text"
                className="search-input"
                onKeyDown={(e) => this.getSearchQuery(e)}
            />
            {this.props.children}
        </SearchContext.Provider>

    );
}


问:
Job Template in Ansible Tower using API Endpoint
How to create a job template in ansible tower using Api Endpoint in nodejs script.</p>

答:
I'm afraid I am not familiar with node.js.  But as far as the Ansible part goes, navigate your browser to https://my-ansible-tower/api/v2/job_templates.  At the bottom of the page, you will see the options you can set:

```<code>{
    "name": "",
    "description": "",
    "job_type": "run",
    "inventory": null,
    "project": null,
    "playbook": "",
    "forks": 0,
    "limit": "",
    "verbosity": 0,
    "extra_vars": "",
    "job_tags": "",
    "force_handlers": false,
    "skip_tags": "",
    "start_at_task": "",
    "timeout": 0,
    "use_fact_cache": false,
    "host_config_key": "",
    "ask_diff_mode_on_launch": false,
    "ask_variables_on_launch": false,
    "ask_limit_on_launch": false,
    "ask_tags_on_launch": false,
    "ask_skip_tags_on_launch": false,
    "ask_job_type_on_launch": false,
    "ask_verbosity_on_launch": false,
    "ask_inventory_on_launch": false,
    "ask_credential_on_launch": false,
    "survey_enabled": false,
    "become_enabled": false,
    "diff_mode": false,
    "allow_simultaneous": false,
    "custom_virtualenv": null,
    "job_slice_count": 1,
    "credential": null,
    "vault_credential": null
}
</code>```

Set those in your node.js script and pust to that URL.  That should work.

Good luck!

Body:
I'm afraid I am not familiar with node.js.  But as far as the Ansible part goes, navigate your browser to https://my-ansible-tower/api/v2/job_templates.  At the bottom of the page, you will see the options you can set:

{
    "name": "",
    "description": "",
    "job_type": "run",
    "inventory": null,
    "project": null,
    "playbook": "",
    "forks": 0,
    "limit": "",
    "verbosity": 0,
    "extra_vars": "",
    "job_tags": "",
    "force_handlers": false,
    "skip_tags": "",
    "start_at_task": "",
    "timeout": 0,
    "use_fact_cache": false,
    "host_config_key": "",
    "ask_diff_mode_on_launch": false,
    "ask_variables_on_launch": false,
    "ask_limit_on_launch": false,
    "ask_tags_on_launch": false,
    "ask_skip_tags_on_launch": false,
    "ask_job_type_on_launch": false,
    "ask_verbosity_on_launch": false,
    "ask_inventory_on_launch": false,
    "ask_credential_on_launch": false,
    "survey_enabled": false,
    "become_enabled": false,
    "diff_mode": false,
    "allow_simultaneous": false,
    "custom_virtualenv": null,
    "job_slice_count": 1,
    "credential": null,
    "vault_credential": null
}

Set those in your node.js script and pust to that URL.  That should work.

Good luck!


问:
Google Home "Couldn't update the setting. Check your connection.'
So this type of error is being reported on a lot of community boards over the course of the last year with no acceptable answer we could find. We have just started our journey integrating with Google Home and created a Home Automation Action and we are getting a similar error …

```<code>{
 insertId:  "10wvnj2fyb1thy"
 logName:  "projects/bitdog-home-f69bd/logs/actions.googleapis.com%2Factions"
Show matching entries
Hide matching entries
Add field to summary line

 receiveTimestamp:  "2018-12-06T13:28:13.939975519Z"
 resource: {
  labels: {
   action_id:  "SMART_HOME_SYNC"
   project_id:  "bitdog-home-f69bd"
   version_id:  ""
  }
  type:  "assistant_action"
 }
 severity:  "ERROR"
 textPayload:  "SYNC: Request ID 742344561631232315 failed with code: OPEN_AUTH_FAILURE"
 timestamp:  "2018-12-06T13:28:13.931998358Z"
}
</code>```

This shows on Google Home app as "Couldn't update the setting, check your connection"

The OAuth service logs show a successful account linking and a successful refresh_token request. Google does not attempt a SYNC call to the Action handler from what we can tell.

We have other systems using the OAuth server and they are working well and we are little lost on how to proceed to debug this issue. We created a support ticket today but I don't feel confident that we will get meaningful help.

We have also tried using the Google Home app on Android and iOS. We have tried changing the default browser from Chrome to Firefox. Nothing has changed the outcome. We also made sure that our access_token was in JWT format to see if google was sensitive to token size or format and nothing worked. We even made sure that the Google Home app user matched the user logged into the browser.

Help!

答:
My problem started when I connected by Sonoff Bridge.

So I got it working by removing my 'Sonoff Bridge' and connecting it to Google Home.  (All mu light are now working). Added the Bridge again to Sonoff and using IFTTT to connect to my Bridge

Body:
So this type of error is being reported on a lot of community boards over the course of the last year with no acceptable answer we could find. We have just started our journey integrating with Google Home and created a Home Automation Action and we are getting a similar error …

{
 insertId:  "10wvnj2fyb1thy"
 logName:  "projects/bitdog-home-f69bd/logs/actions.googleapis.com%2Factions"
Show matching entries
Hide matching entries
Add field to summary line

 receiveTimestamp:  "2018-12-06T13:28:13.939975519Z"
 resource: {
  labels: {
   action_id:  "SMART_HOME_SYNC"
   project_id:  "bitdog-home-f69bd"
   version_id:  ""
  }
  type:  "assistant_action"
 }
 severity:  "ERROR"
 textPayload:  "SYNC: Request ID 742344561631232315 failed with code: OPEN_AUTH_FAILURE"
 timestamp:  "2018-12-06T13:28:13.931998358Z"
}

This shows on Google Home app as "Couldn't update the setting, check your connection"

The OAuth service logs show a successful account linking and a successful refresh_token request. Google does not attempt a SYNC call to the Action handler from what we can tell.

We have other systems using the OAuth server and they are working well and we are little lost on how to proceed to debug this issue. We created a support ticket today but I don't feel confident that we will get meaningful help.

We have also tried using the Google Home app on Android and iOS. We have tried changing the default browser from Chrome to Firefox. Nothing has changed the outcome. We also made sure that our access_token was in JWT format to see if google was sensitive to token size or format and nothing worked. We even made sure that the Google Home app user matched the user logged into the browser.

Help!


问:
needing to emulate Win key in a batch file
I have been trying to find the answer, but my research has not come up with much that is helpful to my situation. I am needing to emulate the Windows Key in my batch file that I am creating. This is to help me Maximize the window, as well as easily move it between monitors without the use of a mouse. The workstation this batch will autorun on, will not have access to a mouse or physical Keyboard.

This is the code I am working with.

```<code>    @if (@CodeSection == @Batch) @then

    @echo off

    rem Use %SendKeys% to send keys to the keyboard buffer
    set SendKeys=CScript //nologo //E:JScript "%~F0"

    rem Start the other program in the same Window
    Start "Progam"

    rem the script only works if the application in question is the active window. Set a timer

    timeout /t 10

    rem use the tab key to move the cursor to the login and password inputs.

    %SendKeys% "This would be the username{TAB}"
    %SendKeys% "this would be the password{ENTER}"

    rem I then have a timer to let the login happen

    timeout /t 10

    rem this where I am now trying to maximize and move the active window around.

    goto :EOF

    @end
    // JScript section

    var WshShell = WScript.CreateObject("WScript.Shell");
    WshShell.SendKeys(WScript.Arguments(0));
</code>```

答:
you can use http://nircmd.nirsoft.net/ </p>

```<code>nircmd sendkeypress key
</code>```

Body:
I have been trying to find the answer, but my research has not come up with much that is helpful to my situation. I am needing to emulate the Windows Key in my batch file that I am creating. This is to help me Maximize the window, as well as easily move it between monitors without the use of a mouse. The workstation this batch will autorun on, will not have access to a mouse or physical Keyboard.

This is the code I am working with.

    @if (@CodeSection == @Batch) @then

    @echo off

    rem Use %SendKeys% to send keys to the keyboard buffer
    set SendKeys=CScript //nologo //E:JScript "%~F0"

    rem Start the other program in the same Window
    Start "Progam"

    rem the script only works if the application in question is the active window. Set a timer

    timeout /t 10

    rem use the tab key to move the cursor to the login and password inputs.

    %SendKeys% "This would be the username{TAB}"
    %SendKeys% "this would be the password{ENTER}"

    rem I then have a timer to let the login happen

    timeout /t 10

    rem this where I am now trying to maximize and move the active window around.

    goto :EOF

    @end
    // JScript section

    var WshShell = WScript.CreateObject("WScript.Shell");
    WshShell.SendKeys(WScript.Arguments(0));

Body:
you can use http://nircmd.nirsoft.net/

nircmd sendkeypress key


问:
How do I store a checkbox value as yes in MySql Database - PHP
So when a user creates an account and they have to tick the checkbox to proceed which works, but how do I store that they accepted it (even though they cannot make an account without accpecting it). But we want to store it nonetheless.

Checkbox

```<code><input type="checkbox" name="agree" value="accepted">
</code>```

PHP

```<code>if ($_POST['agree'] != 'accepted') {
             $error[] = 'Please indicate that you have read and agree to the Terms and Conditions and Privacy Policy';
    } else {
            $stmt = $db->prepare('SELECT termsAccepted FROM members WHERE termsAccepted = :??????');
    $stmt->execute(array(':??????' => $?????));
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    }
</code>```

答:
You can make a if query in your "else" query

```<code>if ($_POST['agree'] == 'accepted') {
 $checkbox = "true";
} else {
 $checkbox = "false";
}
</code>```

And than you can add $checkbox to your executing array, but you should revise the prepared statement.

Body:
So when a user creates an account and they have to tick the checkbox to proceed which works, but how do I store that they accepted it (even though they cannot make an account without accpecting it). But we want to store it nonetheless.

Checkbox

<input type="checkbox" name="agree" value="accepted">

PHP

if ($_POST['agree'] != 'accepted') {
             $error[] = 'Please indicate that you have read and agree to the Terms and Conditions and Privacy Policy';
    } else {
            $stmt = $db->prepare('SELECT termsAccepted FROM members WHERE termsAccepted = :??????');
    $stmt->execute(array(':??????' => $?????));
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    }

Body:
You can make a if query in your "else" query

if ($_POST['agree'] == 'accepted') {
 $checkbox = "true";
} else {
 $checkbox = "false";
}

And than you can add $checkbox to your executing array, but you should revise the prepared statement.


问:
How to get the whole row based on a max value from one column in pandas.groupby().max()?
I want to specify that I need to get the whole row for a max value, not different max values from multiple rows, in my example this should be based on the column 'Number'. Such as this way:

```<code>import pandas as pd

data = {
    'Number':[12,55,3,2,88,17],
    'People':['Zack','Zack','Merry','Merry','Cross','Cross'],
    'Random':[353,0.5454,0.5454336,32,-7,4]
}

df = pd.DataFrame (data, columns = ['Number','People','Random'])

print(df,'\n')

max_values = df.groupby('People').max()

print(max_values)
</code>```

Here is the result:

```<code>   Number People      Random
0      12   Zack  353.000000
1      55   Zack    0.545400
2       3  Merry    0.545434
3       2  Merry   32.000000
4      88  Cross   -7.000000
5      17  Cross    4.000000

        Number  Random
People
Cross       88     4.0
Merry        3    32.0
Zack        55   353.0
</code>```

Here is the expected result for max_values:

```<code>        Number  Random
People
Cross       88    -7.000000
Merry        3    0.545434
Zack        55   353.0
</code>```

答:
You could do the following:

```<code>import pandas as pd

data = {
    'Number':[12,55,3,2,88,17],
    'People':['Zack','Zack','Merry','Merry','Cross','Cross'],
    'Random':[353,0.5454,0.5454336,32,-7,4]
}

df = pd.DataFrame (data, columns = ['Number','People','Random'])

print(df,'\n')

res = df[df.groupby(['People'])['Number'].transform(max) == df['Number']].set_index('People')
print(res)
</code>```

Which gives the following output:

```<code>        Number    Random
People
Zack        55  0.545400
Merry        3  0.545434
Cross       88 -7.000000
</code>```

The problem in your code was that max() is applied per column so by using slicing you can avoid this issue.

Note The expected output is a mistake in the question

Body:
I want to specify that I need to get the whole row for a max value, not different max values from multiple rows, in my example this should be based on the column 'Number'. Such as this way:

import pandas as pd

data = {
    'Number':[12,55,3,2,88,17],
    'People':['Zack','Zack','Merry','Merry','Cross','Cross'],
    'Random':[353,0.5454,0.5454336,32,-7,4]
}

df = pd.DataFrame (data, columns = ['Number','People','Random'])

print(df,'\n')

max_values = df.groupby('People').max()

print(max_values)

Here is the result:

   Number People      Random
0      12   Zack  353.000000
1      55   Zack    0.545400
2       3  Merry    0.545434
3       2  Merry   32.000000
4      88  Cross   -7.000000
5      17  Cross    4.000000

        Number  Random
People
Cross       88     4.0
Merry        3    32.0
Zack        55   353.0

Here is the expected result for max_values:

        Number  Random
People
Cross       88    -7.000000
Merry        3    0.545434
Zack        55   353.0

Body:
You could do the following:

import pandas as pd

data = {
    'Number':[12,55,3,2,88,17],
    'People':['Zack','Zack','Merry','Merry','Cross','Cross'],
    'Random':[353,0.5454,0.5454336,32,-7,4]
}

df = pd.DataFrame (data, columns = ['Number','People','Random'])

print(df,'\n')

res = df[df.groupby(['People'])['Number'].transform(max) == df['Number']].set_index('People')
print(res)

Which gives the following output:

        Number    Random
People
Zack        55  0.545400
Merry        3  0.545434
Cross       88 -7.000000

The problem in your code was that max() is applied per column so by using slicing you can avoid this issue.

Note The expected output is a mistake in the question


问:
Android: How to return to previous screen from Preferences (pressing Back button)
When calling my PreferenceActivity from a screen, and after pressing the Back button, the return screen is always the main screen (the activity that shows after app start) of the application. Is it possible to go back to the previous screen?

I tried to solve it through overriding the onKeyDown (inside my PreferenceActivity class) method without luck:

```<code>@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        finish();
        return true;
    }
    return super.onKeyDown(keyCode, event);
}
</code>```

Thanks in advance for any help.

答: Assuming you use Activities/Intents as designed, there's actually no special code required. Pushing back will automatically stop the current activity, and go back to the activity which called it. See the Android Activity and Task guide. </p>

Body:
When calling my PreferenceActivity from a screen, and after pressing the Back button, the return screen is always the main screen (the activity that shows after app start) of the application. Is it possible to go back to the previous screen?

I tried to solve it through overriding the onKeyDown (inside my PreferenceActivity class) method without luck:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        finish();
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

Thanks in advance for any help.


问:
Scroll to an element in a different, scrollable div in React using refs
I'm looking to scroll an element to view when a callback is called in a separate div.

I'm following this thread which seems to work if the element is in the same div, but if the reference is to an element in a different div, is does not work.

React Sandbox: https://codesandbox.io/s/unruffled-carson-w8o46?file=/src/App.js

How can I achieve this?

答:
You are trying to scroll the window, but you need to scroll the parent block. Inspect the elements through the developer tools and see.</p>

```<code>const scrollToRef = ref => {
  ref.current.parentElement.scrollTo(0, ref.current.offsetTop);
};
</code>```

Body:
You are trying to scroll the window, but you need to scroll the parent block. Inspect the elements through the developer tools and see.

const scrollToRef = ref => {
  ref.current.parentElement.scrollTo(0, ref.current.offsetTop);
};


问:
rotate (reopen) file in python3, when signal is received
I have simple script, that logs to a logfile. This is the core of my script:

```<code>with open('/var/log/mail/mail.log', 'a', buffering=1) as f:
    for line in sys.stdin:
        f.write(line)
</code>```

The file being written /var/log/mail/mail.log has to be rotated regularly by logrotate. At the moment, when logrotate rotates the file, my script does not realize it, and continues writing to the old (now renamed) file.

logrotate has the possibility to execute command after the file has been rotated. Normally, when rsyslog is logging, the command would be:

```<code>postrotate
    invoke-rc.d rsyslog rotate > /dev/null
endscript
</code>```

But in my case, I need to send some signal to my script, and handle the signal in my script.

Also, I don't know in advance the PID my script is running as.

How can I best implement this ?

答:
As a solution for this you can watch if the inode of the open log file is the same as the path. If not reopen the file. This only works on Unix.

```<code>import os, sys, stat

logfile = '/var/log/mail/mail.log'

while True:
    with open(logfile, 'a', buffering=1) as f:
        f_ino = os.stat(logfile)[stat.ST_INO]
        f_dev = os.stat(logfile)[stat.ST_DEV]
        for line in sys.stdin:
            f.write(line)
            try:
                if os.stat(logfile)[stat.ST_INO] != f_ino or
                   os.stat(logfile)[stat.ST_DEV] != f_dev:
                     break
            except OSError: # Was IOError with python < 3.4
                pass

</code>```

Closing the file is not required as it’s handled by the with context manager.

The try..except OSError block is used to catch any error by the system function os.stat. It can be that during the change of the file the function returns an OSError (For example a FileNotFoundError). In this case it will pass the exception and retry the check if the inode is changed. If we omit this try..except block you might end up with a program that terminates.

Body:
I have simple script, that logs to a logfile. This is the core of my script:

with open('/var/log/mail/mail.log', 'a', buffering=1) as f:
    for line in sys.stdin:
        f.write(line)

The file being written /var/log/mail/mail.log has to be rotated regularly by logrotate. At the moment, when logrotate rotates the file, my script does not realize it, and continues writing to the old (now renamed) file.

logrotate has the possibility to execute command after the file has been rotated. Normally, when rsyslog is logging, the command would be:

postrotate
    invoke-rc.d rsyslog rotate > /dev/null
endscript

But in my case, I need to send some signal to my script, and handle the signal in my script.

Also, I don't know in advance the PID my script is running as.

How can I best implement this ?

Body:
As a solution for this you can watch if the inode of the open log file is the same as the path. If not reopen the file. This only works on Unix.

import os, sys, stat

logfile = '/var/log/mail/mail.log'

while True:
    with open(logfile, 'a', buffering=1) as f:
        f_ino = os.stat(logfile)[stat.ST_INO]
        f_dev = os.stat(logfile)[stat.ST_DEV]
        for line in sys.stdin:
            f.write(line)
            try:
                if os.stat(logfile)[stat.ST_INO] != f_ino or
                   os.stat(logfile)[stat.ST_DEV] != f_dev:
                     break
            except OSError: # Was IOError with python < 3.4
                pass

Closing the file is not required as it’s handled by the with context manager.

The try..except OSError block is used to catch any error by the system function os.stat. It can be that during the change of the file the function returns an OSError (For example a FileNotFoundError). In this case it will pass the exception and retry the check if the inode is changed. If we omit this try..except block you might end up with a program that terminates.


问:
Jquery when checkbox is checked can't find closest inputs values
when i check checkbox i need get closest inputs value but no luck adding my code. Tried several combinations most of time undefined. Can someone tell me how correctly i can get those values? Maybe i need to create div to find those elements better? Then i need to slice those values and put in closest input with classname="barkodas".

$(".skaiciuoja").change(function() {
  if (this.checked) {
    var a = "";
    var b = "";
    var c = "";
    var d = "";
    a = $(this).closest('table').find('.A');
    b += $('.vaikai').closest(".B").find("input[name='b']").val();
    c += $('.vaikai').closest(".C").find("input[name='c']").val();
    d += $('.vaikai').closest(".D").find("input[name='d']").val();

    var atsakymas = a + b + c + d;

  }
  console.log(a);
  $(".barkodas").val(atsakymas);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="skaiciuoja" type="checkbox" style="margin-bottom: 20px;">
<label for="skaiciuoja">Generuoti</label>
<br>
<table border="1">
  <tr class="vaikai">
    <td><input class="A bar" name="a" type="text" value="AAAA"></td>
    <td><input class="B bar" name="b" type="text" value="BBBB"></td>
    <td><input class="C bar" name="c" type="text" value="CCCC"></td>
    <td><input class="D bar" name="d" type="text" value="DDDD"></td>
  </tr>
  <tr>
    <td colspan="4" style="background-color:yellow;height:50px;"></td>
  </tr>
  <tr>
    <td colspan="4"><input class="barkodas" type="text" placeholder="Barkodas"></td>
  </tr>
  </tr>
</table>
<br>
<br>
<br>
<br><br>
<br>
<input class="skaiciuoja" type="checkbox" style="margin-bottom: 20px;">
<label for="skaiciuoja">Generuoti</label>
<br>
<table border="1">
  <tr class="vaikai">
    <td><input class="A bar" name="a" type="text" value="1111"></td>
    <td><input class="B bar" name="b" type="text" value="2222"></td>
    <td><input class="C bar" name="c" type="text" value="3333"></td>
    <td><input class="D bar" name="d" type="text" value="4444"></td>
  </tr>
  <tr>
    <td colspan="4" style="background-color:yellow;height:50px;"></td>
  </tr>
  <tr>
    <td colspan="4"><input class="barkodas" type="text" placeholder="Barkodas"></td>
  </tr>
  </tr>
</table></code>```

答:
You can achieve this by searching for the adjacent table and find the inputs. Then concatenate the values.

See this example:

$(".skaiciuoja").change(function() {
  // Find the frist table after this checkbox and get the inputs
  let input = $(this).nextAll("table:first").find("input.bar");

  // store display input to add/remove values
  let display = $(this).nextAll("table:first").find(".barkodas");

  if (this.checked) {
    let total = '';
    // Loop through inputs and concatenate the value
    input.each((i, e) => {
      total += e.value;
    });

    // Display and return so the rest of the code is not processed
    display.val(total);
    return;
  }
  // if not checked empty the input
  display.val("");
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="skaiciuoja" type="checkbox" style="margin-bottom: 20px;">
<label for="skaiciuoja">Generuoti</label>
<br>
<table border="1">
  <tr class="vaikai">
    <td><input class="A bar" name="a" type="text" value="AAAA"></td>
    <td><input class="B bar" name="b" type="text" value="BBBB"></td>
    <td><input class="C bar" name="c" type="text" value="CCCC"></td>
    <td><input class="D bar" name="d" type="text" value="DDDD"></td>
  </tr>
  <tr>
    <td colspan="4" style="background-color:yellow;height:50px;"></td>
  </tr>
  <tr>
    <td colspan="4"><input class="barkodas" type="text" placeholder="Barkodas"></td>
  </tr>
</table>
<br>
<br>
<br>
<br><br>
<br>
<input class="skaiciuoja" type="checkbox" style="margin-bottom: 20px;">
<label for="skaiciuoja">Generuoti</label>
<br>
<table border="1">
  <tr class="vaikai">
    <td><input class="A bar" name="a" type="text" value="1111"></td>
    <td><input class="B bar" name="b" type="text" value="2222"></td>
    <td><input class="C bar" name="c" type="text" value="3333"></td>
    <td><input class="D bar" name="d" type="text" value="4444"></td>
  </tr>
  <tr>
    <td colspan="4" style="background-color:yellow;height:50px;"></td>
  </tr>
  <tr>
    <td colspan="4"><input class="barkodas" type="text" placeholder="Barkodas"></td>
  </tr>
</table></code>```

Body:
when i check checkbox i need get closest inputs value but no luck adding my code. Tried several combinations most of time undefined. Can someone tell me how correctly i can get those values? Maybe i need to create div to find those elements better? Then i need to slice those values and put in closest input with classname="barkodas".

$(".skaiciuoja").change(function() {
  if (this.checked) {
    var a = "";
    var b = "";
    var c = "";
    var d = "";
    a = $(this).closest('table').find('.A');
    b += $('.vaikai').closest(".B").find("input[name='b']").val();
    c += $('.vaikai').closest(".C").find("input[name='c']").val();
    d += $('.vaikai').closest(".D").find("input[name='d']").val();

    var atsakymas = a + b + c + d;

  }
  console.log(a);
  $(".barkodas").val(atsakymas);
});

<input class="skaiciuoja" type="checkbox" style="margin-bottom: 20px;">
Generuoti

    <input class="A bar" name="a" type="text" value="AAAA">
    <input class="B bar" name="b" type="text" value="BBBB">
    <input class="C bar" name="c" type="text" value="CCCC">
    <input class="D bar" name="d" type="text" value="DDDD">

    <input class="barkodas" type="text" placeholder="Barkodas">

<input class="skaiciuoja" type="checkbox" style="margin-bottom: 20px;">
Generuoti

    <input class="A bar" name="a" type="text" value="1111">
    <input class="B bar" name="b" type="text" value="2222">
    <input class="C bar" name="c" type="text" value="3333">
    <input class="D bar" name="d" type="text" value="4444">

    <input class="barkodas" type="text" placeholder="Barkodas">

Body:
You can achieve this by searching for the adjacent table and find the inputs. Then concatenate the values.

See this example:

$(".skaiciuoja").change(function() {
  // Find the frist table after this checkbox and get the inputs
  let input = $(this).nextAll("table:first").find("input.bar");

  // store display input to add/remove values
  let display = $(this).nextAll("table:first").find(".barkodas");

  if (this.checked) {
    let total = '';
    // Loop through inputs and concatenate the value
    input.each((i, e) => {
      total += e.value;
    });

    // Display and return so the rest of the code is not processed
    display.val(total);
    return;
  }
  // if not checked empty the input
  display.val("");
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="skaiciuoja" type="checkbox" style="margin-bottom: 20px;">
<label for="skaiciuoja">Generuoti</label>
<br>
<table border="1">
  <tr class="vaikai">
    <td><input class="A bar" name="a" type="text" value="AAAA"></td>
    <td><input class="B bar" name="b" type="text" value="BBBB"></td>
    <td><input class="C bar" name="c" type="text" value="CCCC"></td>
    <td><input class="D bar" name="d" type="text" value="DDDD"></td>
  </tr>
  <tr>
    <td colspan="4" style="background-color:yellow;height:50px;"></td>
  </tr>
  <tr>
    <td colspan="4"><input class="barkodas" type="text" placeholder="Barkodas"></td>
  </tr>
</table>
<br>
<br>
<br>
<br><br>
<br>
<input class="skaiciuoja" type="checkbox" style="margin-bottom: 20px;">
<label for="skaiciuoja">Generuoti</label>
<br>
<table border="1">
  <tr class="vaikai">
    <td><input class="A bar" name="a" type="text" value="1111"></td>
    <td><input class="B bar" name="b" type="text" value="2222"></td>
    <td><input class="C bar" name="c" type="text" value="3333"></td>
    <td><input class="D bar" name="d" type="text" value="4444"></td>
  </tr>
  <tr>
    <td colspan="4" style="background-color:yellow;height:50px;"></td>
  </tr>
  <tr>
    <td colspan="4"><input class="barkodas" type="text" placeholder="Barkodas"></td>
  </tr>
</table>


问:
Silverligth 4 [XAML] - giving letters in a text a background color/highligth
I am making some things in silverligth with marked up text in XAML.
Everything is going fine until i came up with this.

I am trying to give my text a background color but it says the property does not exist.
the property for a foreground does exist.

is there a way to still give my text parts a background color?

image in link:
http://img146.imageshack.us/img146/537/highligths.png

答: Please tell me you did that with Textblock and Runs. I think the Run element can support foreground and background properties. I know you can twist the content to support both you just have to be clever about the controls inside the Textblock.</p>


问:
Get value node in XML with vbscript ASP
i'm trying to get the node value in an XML Response. I'm very new to ASP.

Here is the XML:

```<code>    <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
   <SOAP-ENV:Header xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"/>
   <soap:Body>
      <ns2:getTextoTsjResponse xmlns:ns2="http://x.com/x/act" xmlns:ns3="http://i.e.com" xmlns:ns4="http://comun.e.com">
         <return>
            <ns3:texto>
               <ns3:datos>
                  <xop:Include href="cid:888a-4ad6-a511-9c6f0490590e-398@entidad.com" xmlns:xop="http://www.w3.org/2004/08/xop/include"/>
               </ns3:datos>
               <ns3:extension>pdf</ns3:extension>
            </ns3:texto>
            <ns3:textoAnonimizado>
               <ns3:datos>
                  <xop:Include href="cid:888a-4ad6-a511-9c6f0490590e-399@entidad.com" xmlns:xop="http://www.w3.org/2004/08/xop/include"/>
               </ns3:datos>
               <ns3:extension>pdf</ns3:extension>
            </ns3:textoAnonimizado>
         </return>
      </ns2:getTextoTsjResponse>
   </soap:Body>
</soap:Envelope>
</code>```

I succeded geting the XMLDoc and parse. What im trying to do then is get href values within  node.

Here is the ASP code.

```<code>'Response from server with the XML
xmlParseado = response.Text
Set xmlDoc = Server.CreateObject("MSXML2.DOMDocument")
xmlDoc.loadXML(xmlParseado)

if xmlDoc.parseError.errorcode <> 0 then
  Response.Write("XML Error...<br>")
else

  Call xmlDoc.setProperty("SelectionLanguage", "XPath")
  Call xmlDoc.setProperty("SelectionNamespaces", "xmlns:ns3")

  Dim node
 'Here im trying to get href value from <ns3:datos> node.

  Set node = xmlDoc.selectSingleNode("//ns3:texto//ns3:datos//*")

  If (node Is Nothing) Then
    Response.write "nothing"
  Else

  response.write(TypeName(node) & "<br />")

  End If

end if
</code>```

Some help would be apreciated.

Thanks in advance

答:
You are really close.

Sadly your XML (like many poorly designed XML documents) suffers from namespace overkill.  If you think of elements like data files on a file system, these XML designers are paranoid that two files (elements) will have the same name, so they put every file (element) on a separate disk instead of just using folders (nesting elements) for context.  In my entire career, I've never run into an issue with two files having the same name, but every day, there's a post on Stackoverflow from someone having trouble with namespaces.

So think of namespaces like a separate disk in a filesystem.  The document specifies each "disk" with a nick name (the prefix like ns3), and a location (the URI like http://i.e.com).  Now when you're querying XML with XPath, have to tell the parser about all of the namespaces (disks), and you specify the prefix in front of every element on the "disk".  You're XPath will look like "//ns3:datos", not just "//datos".

So armed with namespaces, they became the "solution" for everything.  When SOAP was created, the designers went crazy with namespaces, and as a result, everyone put namespaces in everything. The designers of SOAP must have been worried that their Header, Envelope and Body element names would be re-used in SOAP message data.  Instead of naming the elements "SOAP_Header", "SOAP_Envelope", and "SOAP_Body" that everyone could remember, they implemented SOAP with XML namespaces just in case the message content accidentally also included an element named "Header", "Envelope" or "Body".

When you set the SelectionNamesSpaces, you need to set both the prefix and the URI.  In this example I have all the namespaces in your document.

Good luck with your project, and please join me in killing namespaces where ever possible :)

```<code>if xmlDoc.parseError.errorcode <> 0 then
    Response.Write("XML Error...<br>")
    ' NOTE: Avoid nesting else statements, just stop.
    Response.End
End If

Call xmlDoc.setProperty("SelectionLanguage", "XPath")

' NOTE: you're missing the URI here in your namespace http://i.e.com
' Call xmlDoc.setProperty("SelectionNamespaces", "xmlns:ns3")

' Add all of the namespaces, including the prefix and URI
Call xmlDoc.setProperty("SelectionNamespaces", "xmlns:xop='http://www.w3.org/2004/08/xop/include' xmlns:ns2='http://x.com/x/act' xmlns:ns3='http://i.e.com' xmlns:ns4='http://comun.e.com'")

'Here im trying to get href value from <ns3:datos> node.
Dim node
Set node = xmlDoc.selectSingleNode("//ns3:texto//ns3:datos//xop:Include")
If (node Is Nothing) Then
    Response.write "nothing"
Else
    Response.write( node.getAttribute( "href" ) )
End If

' Here's how to get all of the Includes
Dim ndList
set ndList = xmlDoc.selectNodes( "//xop:Include" )
for each ndInclude in ndList
    Response.write( ndInclude.getAttribute( "href" ) )
next
</code>```

Title: Get value node in XML with vbscript ASP

Body:
i'm trying to get the node value in an XML Response. I'm very new to ASP.

Here is the XML:

    <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
   <SOAP-ENV:Header xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"/>
   <soap:Body>
      <ns2:getTextoTsjResponse xmlns:ns2="http://x.com/x/act" xmlns:ns3="http://i.e.com" xmlns:ns4="http://comun.e.com">
         <return>
            <ns3:texto>
               <ns3:datos>
                  <xop:Include href="cid:888a-4ad6-a511-9c6f0490590e-398@entidad.com" xmlns:xop="http://www.w3.org/2004/08/xop/include"/>
               </ns3:datos>
               <ns3:extension>pdf</ns3:extension>
            </ns3:texto>
            <ns3:textoAnonimizado>
               <ns3:datos>
                  <xop:Include href="cid:888a-4ad6-a511-9c6f0490590e-399@entidad.com" xmlns:xop="http://www.w3.org/2004/08/xop/include"/>
               </ns3:datos>
               <ns3:extension>pdf</ns3:extension>
            </ns3:textoAnonimizado>
         </return>
      </ns2:getTextoTsjResponse>
   </soap:Body>
</soap:Envelope>

I succeded geting the XMLDoc and parse. What im trying to do then is get href values within  node.

Here is the ASP code.

'Response from server with the XML
xmlParseado = response.Text
Set xmlDoc = Server.CreateObject("MSXML2.DOMDocument")
xmlDoc.loadXML(xmlParseado)

if xmlDoc.parseError.errorcode <> 0 then
  Response.Write("XML Error...
")
else

  Call xmlDoc.setProperty("SelectionLanguage", "XPath")
  Call xmlDoc.setProperty("SelectionNamespaces", "xmlns:ns3")

  Dim node
 'Here im trying to get href value from <ns3:datos> node.

  Set node = xmlDoc.selectSingleNode("//ns3:texto//ns3:datos//*")

  If (node Is Nothing) Then
    Response.write "nothing"
  Else

  response.write(TypeName(node) & "
")

  End If

end if

Some help would be apreciated.

Thanks in advance

Body:
You are really close.

Sadly your XML (like many poorly designed XML documents) suffers from namespace overkill.  If you think of elements like data files on a file system, these XML designers are paranoid that two files (elements) will have the same name, so they put every file (element) on a separate disk instead of just using folders (nesting elements) for context.  In my entire career, I've never run into an issue with two files having the same name, but every day, there's a post on Stackoverflow from someone having trouble with namespaces.

So think of namespaces like a separate disk in a filesystem.  The document specifies each "disk" with a nick name (the prefix like ns3), and a location (the URI like http://i.e.com).  Now when you're querying XML with XPath, have to tell the parser about all of the namespaces (disks), and you specify the prefix in front of every element on the "disk".  You're XPath will look like "//ns3:datos", not just "//datos".

So armed with namespaces, they became the "solution" for everything.  When SOAP was created, the designers went crazy with namespaces, and as a result, everyone put namespaces in everything. The designers of SOAP must have been worried that their Header, Envelope and Body element names would be re-used in SOAP message data.  Instead of naming the elements "SOAP_Header", "SOAP_Envelope", and "SOAP_Body" that everyone could remember, they implemented SOAP with XML namespaces just in case the message content accidentally also included an element named "Header", "Envelope" or "Body".

When you set the SelectionNamesSpaces, you need to set both the prefix and the URI.  In this example I have all the namespaces in your document.

Good luck with your project, and please join me in killing namespaces where ever possible :)

if xmlDoc.parseError.errorcode <> 0 then
    Response.Write("XML Error...<br>")
    ' NOTE: Avoid nesting else statements, just stop.
    Response.End
End If

Call xmlDoc.setProperty("SelectionLanguage", "XPath")

' NOTE: you're missing the URI here in your namespace http://i.e.com
' Call xmlDoc.setProperty("SelectionNamespaces", "xmlns:ns3")

' Add all of the namespaces, including the prefix and URI
Call xmlDoc.setProperty("SelectionNamespaces", "xmlns:xop='http://www.w3.org/2004/08/xop/include' xmlns:ns2='http://x.com/x/act' xmlns:ns3='http://i.e.com' xmlns:ns4='http://comun.e.com'")

'Here im trying to get href value from <ns3:datos> node.
Dim node
Set node = xmlDoc.selectSingleNode("//ns3:texto//ns3:datos//xop:Include")
If (node Is Nothing) Then
    Response.write "nothing"
Else
    Response.write( node.getAttribute( "href" ) )
End If

' Here's how to get all of the Includes
Dim ndList
set ndList = xmlDoc.selectNodes( "//xop:Include" )
for each ndInclude in ndList
    Response.write( ndInclude.getAttribute( "href" ) )
next


答:
I think need return</p>

```<code><SearchContext.Consumer>
                    {value.map(result => {
                    return (    <div key={result._id}>
                            <div>
                            </div>
                            <article>
                                {value.postContent}
                            </article>
                        </div>

                    )}
                    )}
                </SearchContext.Consumer>
</code>```

Title: Consuming from React Context returns Cannot read property 'map' of undefined

Body:
I am  trying to pass data between two components in React using Context. The data that I want to pass is an array searchResults. I have setup the context and everything, but when I try to use the array in my second component I get Cannot read property 'map' of undefined, how can I consume the array in my second component that I have sent via the context?

Here is my first component:

import React, { Component } from "react";
import axios from "axios";
export const SearchContext = React.createContext();

class Search extends Component {
    state = {
        searchResults: [],
        isSearched: false
    }

    getSearchQuery = (event) => {
        const queryString = document.querySelector(
            ".search-input"
        ).value;

        if (event.keyCode === 13) {
            axios.post("http://localhost:3001/search", {
                queryString: queryString,

            }).then(response => {

                this.setState({ ...this.state, searchResults: response.data });

            });
            this.setState({ ...this.state, isSearched: true });
            window.location.href = '/blog/searchResults'
        }
    };

    render() {
        console.log(this.state.searchResults)
        return (
            <SearchContext.Provider value={this.state.searchResults}>
                <input
                    type="text"
                    className="search-input"
                    onKeyDown={(e) => this.getSearchQuery(e)}
                />
            </SearchContext.Provider>

        );
    }
}

export default Search;

and my second component that should use the array:

import React, { Component } from 'react';
import Footer from '../Footer/Footer.jsx';
import CustomHeader from '../CustomHeader/CustomHeader.jsx';
import { SearchContext } from '../../components/Search/Search.jsx';
let title = 'Blog'

class SearchResultsPage extends Component {
    render() {
        return (

                <CustomHeader
                    title={title}
                />

               <SearchContext.Consumer>
                {(value) => value.map(result => (

                            {value.postContent}

                  )
                )}
            </SearchContext.Consumer>

        )
    }
};

Body:
I think need return

<SearchContext.Consumer>
                    {value.map(result => {
                    return (    <div key={result._id}>
                            <div>
                            </div>
                            <article>
                                {value.postContent}
                            </article>
                        </div>

                    )}
                    )}
                </SearchContext.Consumer>


问:
What is referencing in Python (applied to lists, specifically)?
I started to learn python and encountered something strange and wanted to ask about it.

Below is the coding and I highlighted the part of the function I have a question about.

At the end of the function def add_attraction(destination, attraction), return alone is written not specifying what value it is returning. But it still returns the value stored in variable attractions_for_destination. How could this be?

To put it differently, how I understand is attractions_for_destination = attractions[destination_index] this code stores the value of attractions[destination_index] in the newly made attractions_for_destination variable. And throughattractions_for_destination.append(attraction), this code adds a change to the newly made
variable. But in the end what is changed is the attractions variable.
In short, changes are added to attractions_for_destination but I don’t understand how attractions are also changed.

I asked this question somewhere else on the internet and the someone helped me and mentioned something about referencing. I don't actually get it, because still a value is appended to attractions_for_destination variable and not attractions variable, but the console shows that attractions variable is appended. Can someone clarify this for me?

```<code>destinations = ["Paris, France",
"Shanghai, China", "Los Angeles, USA", "Sao Paulo, Brazil", "Cairo, Egypt"]

test_traveler = ['Erin Wilkes', 'Shanghai, China', ['historical site', 'art']]

#destination index
destination_index = 0
def get_destination_index(destination):
  destination_index = destinations.index(destination)
  return destination_index

#traveler current destination
def get_traveler_location(traveler):
  traveler_destination = traveler[1]
  traveler_destination_index = get_destination_index(traveler_destination)
  return traveler_destination_index

#finding traveler current destination index
test_destination_index = get_traveler_location(test_traveler)

attractions = [[] for destination in destinations]

def add_attraction(destination, attraction):
  try:
    destination_index = get_destination_index(destination)
  except ValueError:
    return
  ***attractions_for_destination = attractions[destination_index]
  attractions_for_destination.append(attraction)
  return***

add_attraction("Los Angeles, USA", ['venice Beach' , ['beach']])

print(attractions)
</code>```

答:
attractions is a list of lists.

In the assignment statement:

```<code>attractions_for_destination = attractions[destination_index]
</code>```

This associates the name attractions_for_destination with one of the inner lists that are elements of the attractions list.  That is to say, it does not make a copy of it, but rather, the name attractions_for_destination now refers to exactly the same list object in memory.  So when that list is modified (in this case, by calling its append method), the modified value can be seen, regardless of which reference to the list is used to access it.  In particular, there is also still a reference to the same list as an element of the attractions list, so the modified value of the sub-list is seen when you do print(attractions).

The two lines which you highlighted have a similar overall effect to doing simply:

```<code>    attractions[destination_index].append(attraction)
</code>```

Aside from answering the direct question, I would also add that in this code, having a list in the same order as another list (in this case attractions and destinations) is a poor choice of data type, and it would be better to use a dictionary.  For example:

```<code>attractions = dict((destination, []) for destination in destinations)

def add_attraction(destination, attraction):
    try:
        attractions[destination].append(attraction)
    except KeyError:
        return
</code>```

Body:
I started to learn python and encountered something strange and wanted to ask about it.

Below is the coding and I highlighted the part of the function I have a question about.

At the end of the function def add_attraction(destination, attraction), return alone is written not specifying what value it is returning. But it still returns the value stored in variable attractions_for_destination. How could this be?

To put it differently, how I understand is attractions_for_destination = attractions[destination_index] this code stores the value of attractions[destination_index] in the newly made attractions_for_destination variable. And throughattractions_for_destination.append(attraction), this code adds a change to the newly made
variable. But in the end what is changed is the attractions variable.
In short, changes are added to attractions_for_destination but I don’t understand how attractions are also changed.

I asked this question somewhere else on the internet and the someone helped me and mentioned something about referencing. I don't actually get it, because still a value is appended to attractions_for_destination variable and not attractions variable, but the console shows that attractions variable is appended. Can someone clarify this for me?

destinations = ["Paris, France",
"Shanghai, China", "Los Angeles, USA", "Sao Paulo, Brazil", "Cairo, Egypt"]

test_traveler = ['Erin Wilkes', 'Shanghai, China', ['historical site', 'art']]

#destination index
destination_index = 0
def get_destination_index(destination):
  destination_index = destinations.index(destination)
  return destination_index

#traveler current destination
def get_traveler_location(traveler):
  traveler_destination = traveler[1]
  traveler_destination_index = get_destination_index(traveler_destination)
  return traveler_destination_index

#finding traveler current destination index
test_destination_index = get_traveler_location(test_traveler)

attractions = [[] for destination in destinations]

def add_attraction(destination, attraction):
  try:
    destination_index = get_destination_index(destination)
  except ValueError:
    return
  ***attractions_for_destination = attractions[destination_index]
  attractions_for_destination.append(attraction)
  return***

add_attraction("Los Angeles, USA", ['venice Beach' , ['beach']])

print(attractions)

Body:
attractions is a list of lists.

In the assignment statement:

attractions_for_destination = attractions[destination_index]

This associates the name attractions_for_destination with one of the inner lists that are elements of the attractions list.  That is to say, it does not make a copy of it, but rather, the name attractions_for_destination now refers to exactly the same list object in memory.  So when that list is modified (in this case, by calling its append method), the modified value can be seen, regardless of which reference to the list is used to access it.  In particular, there is also still a reference to the same list as an element of the attractions list, so the modified value of the sub-list is seen when you do print(attractions).

The two lines which you highlighted have a similar overall effect to doing simply:

    attractions[destination_index].append(attraction)

Aside from answering the direct question, I would also add that in this code, having a list in the same order as another list (in this case attractions and destinations) is a poor choice of data type, and it would be better to use a dictionary.  For example:

attractions = dict((destination, []) for destination in destinations)

def add_attraction(destination, attraction):
    try:
        attractions[destination].append(attraction)
    except KeyError:
        return


问:
float not working in mysql database
i am using $_GET['var'] to get a variable then compare it with a variable in my database. the variable is 1.1 the var is set to "float" on the database so i know it can handle decimals but when i compare them with the code below i get nothing.</p>

```<code>include 'connect.php';

$sql=mysql_query("SELECT * FROM table WHERE stuff='$stuff'");

while ($row=mysql_fetch_assoc($sql)) {

$start=$row['start'];

}

echo $start; //nothing happens
</code>```

答:
You might not be seeing any output because your echo is outside the loop.

The scope of your variable $start would be confined to the loop.

Title: float not working in mysql database

Body:
i am using $_GET['var'] to get a variable then compare it with a variable in my database. the variable is 1.1 the var is set to "float" on the database so i know it can handle decimals but when i compare them with the code below i get nothing.

include 'connect.php';

$sql=mysql_query("SELECT * FROM table WHERE stuff='$stuff'");

while ($row=mysql_fetch_assoc($sql)) {

$start=$row['start'];

}

echo $start; //nothing happens


问:
Get the last entered id from a table in sql
enter image description hereI have an employee table. In that table I have n number of loan.. Now I want to select all the employees with his last taken loan value and date.. can anyone help me out in this.

There's what I've done so far:

```<code>SELECT employee_id,employee_name,department_name,
       designation_name,PF_type,PF_number,Opening_balance,
       MAX(Loan_id),MAX(loan_date), MAX(loan_amount)
FROM single_roww1
GROUP BY employee_id
</code>```

I tried group by, limit and order by for this but of no use... I also tried to take the last occurence of the employee_id that also didn't work..

答:
If only the row containing the last loan_id is required than a correlated sub query is what you want</p>

```<code>SELECT *
FROM single_roww1 SR
WHERE LOAN_ID = (SELECT MAX(LOAN_ID) FROM single_roww1 WHERE EMPLOYEE_ID = SR.EMPLOYEE_ID);
</code>```

Body:
enter image description hereI have an employee table. In that table I have n number of loan.. Now I want to select all the employees with his last taken loan value and date.. can anyone help me out in this.

There's what I've done so far:

SELECT employee_id,employee_name,department_name,
       designation_name,PF_type,PF_number,Opening_balance,
       MAX(Loan_id),MAX(loan_date), MAX(loan_amount)
FROM single_roww1
GROUP BY employee_id

I tried group by, limit and order by for this but of no use... I also tried to take the last occurence of the employee_id that also didn't work..

Body:
If only the row containing the last loan_id is required than a correlated sub query is what you want

SELECT *
FROM single_roww1 SR
WHERE LOAN_ID = (SELECT MAX(LOAN_ID) FROM single_roww1 WHERE EMPLOYEE_ID = SR.EMPLOYEE_ID);


问:
Use Object.keys() instead of .length on Firebase Object
How to use Object.keys() to correct this snippet? When the comments ids are numbers the code works fine. Now How to make it  works with auto generated ids from firebase.

(Data structure is below)

ngOnInit() {
 this.route.params
.pipe(switchMap((params: Params) => this.dishservice.getDish(params['id'])))
     .subscribe(dish => {
          this.dish = dish
          this.favorite = this.favoriteService.isFavorite(this.dish.id);

          //compute the average of ratings and render the number of comments
          this.numcomments =  this.dish.comments.length;
          let total =0;
          this.dish.comments.forEach(comment =>total += comment.rating);
          this.avgstars = (total/this.numcomments).toFixed(2);
           },
          errmess => this.errMess = <any>errmess);
}```

答:
Try this</p>

```<code>const commentIds  = Object.keys(this.dish.comments);
this.numcomments =  commentIds.length;
let total = 0;
commentIds.forEach(commentId => total += this.dish.comments[commentId].rating);
this.avgstars = (total/this.numcomments).toFixed(2);
</code>```

Body:
Try this

const commentIds  = Object.keys(this.dish.comments);
this.numcomments =  commentIds.length;
let total = 0;
commentIds.forEach(commentId => total += this.dish.comments[commentId].rating);
this.avgstars = (total/this.numcomments).toFixed(2);