问:
What is the best method to sort a dynamic array of c-strings in a class in c++?
In my current programming class I've been tasked with creating a program that takes user input course (Consisting of course name, course grade, course units variables) and storing them in a dynamically generated array with a maximum size of 10.

Due to my unfamiliarity with object oriented programming and classes however I'm finding anything beyond the pure creation of the classes to be very difficult. I've figured out a way to create the entries, as well as how to edit them after they've been created using friend functions (I think that's the name?) stored in my programs header file.

However now that I've needed to perform a sort on the data (by the name variable of every entry) as well as to then search it I'm finding it very difficult to proceed. I understand how to make functions that can do both of these things (As I have done it for my previous class), but doing it with classes being involved is proving challenging.

My header file:

```<code>#ifndef COURSE_H
#define COURSE_H

#include <iostream>
#include <conio.h>
#include <stdio.h>
#include <cstdlib>
#include <vector>

class Course
{
private:
    char name[10] = ""; //name of course
    char grade; //grade in course
    int units; //units in course

public:
    Course()
    {
        name;
        grade;
        units;
    }

    void read() //Initializes course and collects information from user
    {
        std::cout << "\nEnter course name: ";
        std::cin.getline(name, 10, '\n');
        std::cout << "\nEnter number of units: ";
        std::cin >> units;
        std::cout << "\nEnter grade received: ";
        std::cin >> grade;
        std::cin.ignore();
    }

    void display() const //Displays course to user
    {
        std::cout << name << ' ' << units << ' ' << grade << std::endl;
    }

    ~Course() //Destructor frees allocated dynamic memory
    {
        std::cout << "\nDeleting any dynamically created object";
    }
};

#endif // COURSE_H
</code>```

My main source file:

```<code>#include <iostream>
#include <conio.h>
#include <stdio.h>
#include <cstdlib>
#include <vector>
#include "courses.h"

int menu();
void add(Course* co_ptr[], int& size);
void edit(Course* co_ptr[], int size);
void swap_ptrs(Course*& pt1, Course*& pt2);

int main()
{
    Course* courses[10] = {};
    int selection;

    int size = 0;
    do
    {
        selection = menu();

        if (selection == 1)
        {
            if (size < 10)
                add(courses, size);
            else
                std::cout << "\nUnable to add more classes.";
        }
        else if (selection == 2)
        {
            edit(courses, size);
        }
        else if (selection == 3)
        {

        }
        else if (selection == 4)
        {

        }
        else if (selection == 5)
        {

        }
        else if (selection == 6)
        {

        }
        else if (selection == 7)
        {
            break;
        }
        else
        {
            std::cout << "\nInvalid selection.";
        }
    } while (selection != 7);

    std::cout << "\nPress any key to exit.";
    (void)_getch();
    return 0;
}
</code>```

My functions source file:

```<code>#include <iostream>
#include <conio.h>
#include <stdio.h>
#include <cstdlib>
#include <vector>
#include "courses.h"

int menu()
{
    int selection;

    std::cout << "\nSelect one of the following actions: " << std::endl
        << "1. Add new course" << std::endl
        << "2. Edit an existing course" << std::endl
        << "3. Display a course" << std::endl
        << "4. List all courses" << std::endl
        << "5. Display GPA" << std::endl
        << "6. Delete all courses" << std::endl
        << "7. Quit";
    std::cout << "\nEnter selection number: ";
    std::cin >> selection;
    std::cin.ignore();

    return selection;
}

void add(Course* co_ptr[], int& size)
{
    co_ptr[size] = new Course;
    co_ptr[size]->read();
    size++;
}

void edit(Course* co_ptr[], int size)
{
    int selection;
    for (int i = 0; i < size; i++)
    {
        std::cout << std::endl << i << ". ";
        co_ptr[i]->display();
    }

    std::cout << "Enter your selection: ";
    std::cin >> selection;
    std::cin.ignore();

    co_ptr[selection]->read();
}
</code>```

My last attempt at making a sort function (I tried to create it within the header as whenever I ported in my old sorting code as a normal function it couldn't access the data it needed on account of those variables being "private")

```<code>void Course::sort_name(Course* co_ptr[], int size) //has to be apart of the class (Course::) to have access to the name data
{
    bool swap;

    do
    {
        swap = false;
        for (int i = 0; i < size - 1; i++)
        {
            if (strcmp(co_ptr[i]->name, co_ptr[i + 1]->name) > 0) //We're now comparing and swapping pointers
            {
                swap_ptrs(co_ptr[i], co_ptr[i + 1]);
                swap = true;
            }
        }
    } while (swap);
}
</code>```

Lastly my swap_ptrs function which was also in the function source file:

```<code>void swap_ptrs(Course*& pt1, Course*& pt2) //Passes the pointers by reference
{
    Course* tmp = pt1;
    pt1 = pt2;
    pt2 = tmp;
}
</code>```

I'm sorry for such a long post but this project has been a real struggle and I'm feeling like I'm not making any headway.

答:
Don't use a char array. Use string instead

```<code>char name[10]; //bad form
</code>```

instead use

```<code>std::string name;
</code>```

coming to your original query if you create a vector of Course such as

```<code>std::vector<Course> mycourselist;
</code>```

then all you need to do is

```<code>std::sort(mycourselist.begin(),mycourselist.end(), mysortfunc);
</code>```

so you need to write out your own comparison function to do what you want.

so you could do

```<code>   bool mysortfunc(Course c1, Course c2)
   {
    return c1.name<c2.name;
   }
</code>```

Read more about it here

Body:
In my current programming class I've been tasked with creating a program that takes user input course (Consisting of course name, course grade, course units variables) and storing them in a dynamically generated array with a maximum size of 10.

Due to my unfamiliarity with object oriented programming and classes however I'm finding anything beyond the pure creation of the classes to be very difficult. I've figured out a way to create the entries, as well as how to edit them after they've been created using friend functions (I think that's the name?) stored in my programs header file.

However now that I've needed to perform a sort on the data (by the name variable of every entry) as well as to then search it I'm finding it very difficult to proceed. I understand how to make functions that can do both of these things (As I have done it for my previous class), but doing it with classes being involved is proving challenging.

My header file:

#ifndef COURSE_H
#define COURSE_H

#include <iostream>
#include <conio.h>
#include <stdio.h>
#include <cstdlib>
#include <vector>

class Course
{
private:
    char name[10] = ""; //name of course
    char grade; //grade in course
    int units; //units in course

public:
    Course()
    {
        name;
        grade;
        units;
    }

    void read() //Initializes course and collects information from user
    {
        std::cout << "\nEnter course name: ";
        std::cin.getline(name, 10, '\n');
        std::cout << "\nEnter number of units: ";
        std::cin >> units;
        std::cout << "\nEnter grade received: ";
        std::cin >> grade;
        std::cin.ignore();
    }

    void display() const //Displays course to user
    {
        std::cout << name << ' ' << units << ' ' << grade << std::endl;
    }

    ~Course() //Destructor frees allocated dynamic memory
    {
        std::cout << "\nDeleting any dynamically created object";
    }
};

#endif // COURSE_H

My main source file:

#include <iostream>
#include <conio.h>
#include <stdio.h>
#include <cstdlib>
#include <vector>
#include "courses.h"

int menu();
void add(Course* co_ptr[], int& size);
void edit(Course* co_ptr[], int size);
void swap_ptrs(Course*& pt1, Course*& pt2);

int main()
{
    Course* courses[10] = {};
    int selection;

    int size = 0;
    do
    {
        selection = menu();

        if (selection == 1)
        {
            if (size < 10)
                add(courses, size);
            else
                std::cout << "\nUnable to add more classes.";
        }
        else if (selection == 2)
        {
            edit(courses, size);
        }
        else if (selection == 3)
        {

        }
        else if (selection == 4)
        {

        }
        else if (selection == 5)
        {

        }
        else if (selection == 6)
        {

        }
        else if (selection == 7)
        {
            break;
        }
        else
        {
            std::cout << "\nInvalid selection.";
        }
    } while (selection != 7);

    std::cout << "\nPress any key to exit.";
    (void)_getch();
    return 0;
}

My functions source file:

#include <iostream>
#include <conio.h>
#include <stdio.h>
#include <cstdlib>
#include <vector>
#include "courses.h"

int menu()
{
    int selection;

    std::cout << "\nSelect one of the following actions: " << std::endl
        << "1. Add new course" << std::endl
        << "2. Edit an existing course" << std::endl
        << "3. Display a course" << std::endl
        << "4. List all courses" << std::endl
        << "5. Display GPA" << std::endl
        << "6. Delete all courses" << std::endl
        << "7. Quit";
    std::cout << "\nEnter selection number: ";
    std::cin >> selection;
    std::cin.ignore();

    return selection;
}

void add(Course* co_ptr[], int& size)
{
    co_ptr[size] = new Course;
    co_ptr[size]->read();
    size++;
}

void edit(Course* co_ptr[], int size)
{
    int selection;
    for (int i = 0; i < size; i++)
    {
        std::cout << std::endl << i << ". ";
        co_ptr[i]->display();
    }

    std::cout << "Enter your selection: ";
    std::cin >> selection;
    std::cin.ignore();

    co_ptr[selection]->read();
}

My last attempt at making a sort function (I tried to create it within the header as whenever I ported in my old sorting code as a normal function it couldn't access the data it needed on account of those variables being "private")

void Course::sort_name(Course* co_ptr[], int size) //has to be apart of the class (Course::) to have access to the name data
{
    bool swap;

    do
    {
        swap = false;
        for (int i = 0; i < size - 1; i++)
        {
            if (strcmp(co_ptr[i]->name, co_ptr[i + 1]->name) > 0) //We're now comparing and swapping pointers
            {
                swap_ptrs(co_ptr[i], co_ptr[i + 1]);
                swap = true;
            }
        }
    } while (swap);
}

Lastly my swap_ptrs function which was also in the function source file:

void swap_ptrs(Course*& pt1, Course*& pt2) //Passes the pointers by reference
{
    Course* tmp = pt1;
    pt1 = pt2;
    pt2 = tmp;
}

I'm sorry for such a long post but this project has been a real struggle and I'm feeling like I'm not making any headway.

Body:
Don't use a char array. Use string instead

char name[10]; //bad form

instead use

std::string name;

coming to your original query if you create a vector of Course such as

std::vector<Course> mycourselist;

then all you need to do is

std::sort(mycourselist.begin(),mycourselist.end(), mysortfunc);

so you need to write out your own comparison function to do what you want.

so you could do

   bool mysortfunc(Course c1, Course c2)
   {
    return c1.name<c2.name;
   }

Read more about it here


来源: stackexchange

问:
Manual input from user while running selenium IDE script
can user is able to give manual input while running selenium IDE script?
For ex. If there is name field then can we open input box everytime script runs so that user can give his input for name field?

Let me know whether it is possible or not..

If yes then please suggest me a solution.

Thanks in advance

答:
As of 2020 using Selenium IDE 3.16.1, I found the following config worked by the suggested answers above. (I re-answered the question as above answers did not clearly combined all pieces)

```<code>Command : execute script

Target : return prompt("Question Text","Default value");

Value : yourVariableName
</code>```

and fill in the input box by the stored var:

```<code>Command : type

Target : (your selector)

Value : ${yourVariableName}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
As of 2020 using Selenium IDE 3.16.1, I found the following config worked by the suggested answers above. (I re-answered the question as above answers did not clearly combined all pieces)

Command : execute script

Target : return prompt("Question Text","Default value");

Value : yourVariableName

and fill in the input box by the stored var:

Command : type

Target : (your selector)

Value : ${yourVariableName}

ContentLicense: CC BY-SA 4.0


问:
jQuery does not find IMG component by its ID
I have a webpage which contains such code:

```<code><img class="img-qrcode" id="img_123.000.00.01"
     src="http://localhost:7777/data/code_img\123.000.00.01.png"
     alt="./data/code_img\123.000.00.01.png" style="display:none">
</code>```

I want to locate it with jQuery. For some reason jQuery does not find it by ID, with the code:

```<code>$("#img_123.000.00.01")
</code>```

The added screenshot shows that it returns an empty array.

Why does it not find the element with ID ?

答:
Since #id.className is a valid selector jQuery assumes it so and tries to find such element. In your case you will have to escape the dot.

Change $("#img_123.000.00.01") to $("#img_123\\.000\\.00\\.01") and it will work.

Official jQuery documentation(https://api.jquery.com/category/selectors/) states it clearly.

To use any of the meta-characters ( such as
  !"#$%&'()*+,./:;<=>?@[\]^{|}~` ) as a literal part of a name, it
  must be escaped with with two backslashes

Body:
I have a webpage which contains such code:

I want to locate it with jQuery. For some reason jQuery does not find it by ID, with the code:

$("#img_123.000.00.01")

The added screenshot shows that it returns an empty array.

Why does it not find the element with ID ?


问:
Ruby on rails: how to update an div with partial without making an ajax call to server
I want to update an div with contents of a partial when a user clicks on a radio button. Now the contents of that partial are static html (a form may be). So because I do not have any data to fetch from the server I am reluctant to make an ajax call to server just to fetch that partial and update the div. Here is what I have tried.

```<code> function loadControlPanel(type)
      {
        alert(type);
        $(controlPanelDiv).appendChild("<%=  render :partial => 'layouts/agency_selection' %>");
      }

<input type="radio" name="view" value="agencies" onClick ="loadControlPanel(this.value)" /> Agencies
</code>```

But this doesn't work because the render  replaces the entire partial there along with the new lines which throws javascript errors in the function loadControlPanel(type).

Is there any way to overcome this? or some other simpler solution?

Thanks
Shaunak

答:
Why dont you render the static part in your layout in a hidden div, then clone that id and put it in your innerHTML using javascrtipt? </p>

<p>By the way just calling "render :partial" does not mean its an Ajax call. </p>

Body:
I want to update an div with contents of a partial when a user clicks on a radio button. Now the contents of that partial are static html (a form may be). So because I do not have any data to fetch from the server I am reluctant to make an ajax call to server just to fetch that partial and update the div. Here is what I have tried.

 function loadControlPanel(type)
      {
        alert(type);
        $(controlPanelDiv).appendChild("<%=  render :partial => 'layouts/agency_selection' %>");
      }

<input type="radio" name="view" value="agencies" onClick ="loadControlPanel(this.value)" /> Agencies

But this doesn't work because the render  replaces the entire partial there along with the new lines which throws javascript errors in the function loadControlPanel(type).

Is there any way to overcome this? or some other simpler solution?

Thanks
Shaunak

Body:
Why dont you render the static part in your layout in a hidden div, then clone that id and put it in your innerHTML using javascrtipt?

By the way just calling "render :partial" does not mean its an Ajax call.


问:
Media Queries: How to target all landscape devices below 1024 using css media query
How to target all landscape devices below 1024 using css media query this should work only for mobile devices not desktop browsers</p>

答:
You can try it like this</p>

```<code>@media only screen
  and (min-device-width: 1024px)
  and (min-device-pixel-ratio : 2.0)
  and (orientation: landscape) {

  //styles here

}

</code>```

Body:
You can try it like this

@media only screen
  and (min-device-width: 1024px)
  and (min-device-pixel-ratio : 2.0)
  and (orientation: landscape) {

  //styles here

}


问:
Acknowledgement in I2C slave
I read the I2C specification provided by nxp.but I am still not clear on some points. can you explain to me?

normally slave is controlled by I2C master. Acknowledgment is enabled by I2C master then how slave generates I2C acknowledgment?

I2C slave address and I2C data byte both are 1-byte data then how I2C slave differentiate between them?

答:
Assuming i2c specification for nxp is identical to industry standard.

1) I don't think that "acknowledgement is enabled by Master" is the correct term here. After each (full) byte sent by the Master it waits for the Slave to send back the acknowledgement bit (or the not acknowledgement ). The slave does this by changing the level of the SDA line.

2) For transferring data from Master to Slave (and back) it is very important to keep the order of the sent bytes. A typical example would be like this:

Master sends: Start Signal

Master sends: Slave Address + Write-Bit

Slave sends: ACK

Master sends: Register Address the master wants to read

Slave sends: ACK

Master sends: repeated Start Signal

Master sends: Slave Address + Read-Bit

Slave sends: ACK

Slave sends: content of register Register Address the master wants to read

Master sends: NACK

Master sends: Stop Signal

If you are looking for some more details on the I2C, there is plenty of it throughout the internet. For me, section 21 of this data sheet helped me a lot to understand.

Title: Acknowledgement in I2C slave


问:
C++ secret message school assignment
I am working on a school project, in which I'm supposed to take a message or word like nice or {#&@ and convert it to a word using a vector and a loop.  I have the code running but I can't figure out why it doesn't convert. Any help would be greatly appreciated.</p>

```<code>#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main() {
    vector<char> normalV(26);
    vector<char> cipherV(26);
    string toDec = "";
    string beenDec = "";

    int i = 0;  // index normalV
    int n = 0; // index cipherV
    i = 0;
    n = 0;

    normalV.at(i) = 'n'; cipherV.at(n) = '{';
    normalV.at(i) = 'i'; cipherV.at(n) = '#';
    normalV.at(i) = 'c'; cipherV.at(n) = '&';
    normalV.at(i) = 'e'; cipherV.at(n) = '@';

    // Get secret message
    do {
        cout << "Enter a secret message: ";
        getline(cin, toDec);
    } while (toDec.length() == 0);

    beenDec = toDec;

    for (i = 0; i < toDec.size(); ++i) {
        for (n = 0; n < 26; ++n){
            if (toDec.at(i) == cipherV.at(n)){
                beenDec.at(i) = normalV.at(n);
            }
        }
    }

    cout << "Decrypted message: " << beenDec << endl;

    return 0;
}
</code>```

答:
Take a close look at this part of the code :

```<code>normalV.at(i) = 'n'; cipherV.at(n) = '{';
normalV.at(i) = 'i'; cipherV.at(n) = '#';
normalV.at(i) = 'c'; cipherV.at(n) = '&';
normalV.at(i) = 'e'; cipherV.at(n) = '@';
</code>```

i and n never change here. So, you're always overwriting the first entry in those vectors.

Title: C++ secret message school assignment

Body:
I am working on a school project, in which I'm supposed to take a message or word like nice or {#&@ and convert it to a word using a vector and a loop.  I have the code running but I can't figure out why it doesn't convert. Any help would be greatly appreciated.

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main() {
    vector<char> normalV(26);
    vector<char> cipherV(26);
    string toDec = "";
    string beenDec = "";

    int i = 0;  // index normalV
    int n = 0; // index cipherV
    i = 0;
    n = 0;

    normalV.at(i) = 'n'; cipherV.at(n) = '{';
    normalV.at(i) = 'i'; cipherV.at(n) = '#';
    normalV.at(i) = 'c'; cipherV.at(n) = '&';
    normalV.at(i) = 'e'; cipherV.at(n) = '@';

    // Get secret message
    do {
        cout << "Enter a secret message: ";
        getline(cin, toDec);
    } while (toDec.length() == 0);

    beenDec = toDec;

    for (i = 0; i < toDec.size(); ++i) {
        for (n = 0; n < 26; ++n){
            if (toDec.at(i) == cipherV.at(n)){
                beenDec.at(i) = normalV.at(n);
            }
        }
    }

    cout << "Decrypted message: " << beenDec << endl;

    return 0;
}

Body:
Take a close look at this part of the code :

normalV.at(i) = 'n'; cipherV.at(n) = '{';
normalV.at(i) = 'i'; cipherV.at(n) = '#';
normalV.at(i) = 'c'; cipherV.at(n) = '&';
normalV.at(i) = 'e'; cipherV.at(n) = '@';

i and n never change here. So, you're always overwriting the first entry in those vectors.


问:
Bigquery: Extract data from an array of json
(This is an extension to this question, but my reputation is too low to comment or ask more questions on that topic...)

We work on bigquery, hence limited in importing packages or using other languages. And, as per the link above, js is a solution, but not what I'm looking for here. I implemented it in js, and it was too slow for our needs.

Suppose one of our columns is a string that look like this (array of json):

[{"location":[22.99902,66.000],"t":1},{"location":[55.32168,140.556],"t":2},{"location":[85.0002,20.0055],"t":3}]

I want to extract from the column the json for which "t":2

Where:

some columns don't have elements "t":2

Some columns have several elements "t":2

The number of json elements in each string can change

element "t":2 is not always in second position.

I don't know regexp well enough for this. We tried regexp_extract with  this pattern: r'(\{.*?\"t\":2.*?\})')), but that doesn't work. It extracts everything that precedes "t":2, including the json for "t":2. We only want the json of element "t":2.

Could you advise a regexp pattern that would work?

EDIT:

I have a preference for a solution that gives me 1 match. Suppose I have this string:
[{"location":[22.99902,66.000],"t":1},{"location":[55.32168,140.556],"t":2},{"location":[55.33,141.785],"t":2}],

I would prefer receiving only 1 answer, the first one.

In that case perhaps regexp is less appropriate, but I'm really not sure?

答:
There is another solution but it is not regexp based (as I had originally asked). So this should not count as the final answer to my own question, nonetheless could be useful.

It is based on a split of the string in array and then chosing the element in the array that satisfies my needs.

Steps:

transform the string into something better for splits (using '|' as seperator):

replace(replace(replace(my_field,'},{','}|{'),'[{','{'),'}]','}')

split it using split(), which yields an array of strings (each one a json element)

find the relevant element ("t":2) - in my case, the first one is good enough, so I limit the query to 1: array( select data from unnest(split(replace(replace(replace(my_field,'},{','}|{'),'[{','{'),'}]','}'),'|')) as data where data like '%"t":2%' limit 1)

Convert that into a useable string with array_to_string() and use json_extract on that string to extract the relevant info from the element that I need (say for example, location coordinate x).

So putting it all together:

round(safe_cast(json_extract(array_to_string(array( select data from unnest(split(replace(replace(replace(my_field,'},{','}|{'),'[{','{'),'}]','}'),'|')) as data where data like '%"t":2%' limit 1),''),'$.location[0]') as float64),3) loc_x


问:
How to add a Branch to An Already Existing TTree: ROOT
I have an existing TTree after doing a simulation. I would like to add a Branch to this TTree and I want to call it Muon.Mass to the tree. I would also want to give the Muon.Mass branch a value of 0.1.

How can I write that?

I have seen how to create TTrees from scratch and to have branches of different variables. But I am not sure exactly what to do when I already have a TTree.

答:
You can call the TTree::Branch method on an existing TTree the same way as for a new TTree. Just for filling you need to ensure you only fill the branch. (this is a strongly cut down example from https://github.com/pseyfert/tmva-branch-adder)

void AddABranch(TTree* tree) {
  Float_t my_local_variable;
  TBranch* my_new_branch = tree->AddBranch( ... /* use address of my_local_variable */ );
  for (Long64_t entry = 0 ; entry < tree->GetEntries() ; ++e ) {
    tree->GetEntry();
    /* something to compute my_local_variable */
    my_new_branch->Fill();
  }
}
```

As alternative you might want to look at the root tutorials for tree friends.

As a side note, depending what you want to do with the tree / whom you give the tree to, I advise against using . in branch names as they cause headache when running MakeClass (branch names can contain periods, but c++ variables can't, so the automatically generated class members for each branch will undergo character replacement).

Body:
You can call the TTree::Branch method on an existing TTree the same way as for a new TTree. Just for filling you need to ensure you only fill the branch. (this is a strongly cut down example from https://github.com/pseyfert/tmva-branch-adder)

void AddABranch(TTree* tree) {
  Float_t my_local_variable;
  TBranch* my_new_branch = tree->AddBranch( ... /* use address of my_local_variable */ );
  for (Long64_t entry = 0 ; entry < tree->GetEntries() ; ++e ) {
    tree->GetEntry();
    /* something to compute my_local_variable */
    my_new_branch->Fill();
  }
}

As alternative you might want to look at the root tutorials for tree friends.

As a side note, depending what you want to do with the tree / whom you give the tree to, I advise against using . in branch names as they cause headache when running MakeClass (branch names can contain periods, but c++ variables can't, so the automatically generated class members for each branch will undergo character replacement).


问:
can't store an object into array? C++
I'm trying to do something simple and store an object into an Array in C++ but it keeps saying that I can't use the = operator with the right hand operand being of my class. Here's the code:

```<code>class Player {
    string name;
    double points;
    bool wonLastRound;
public:
    Player() {}
    Player(string n)
    {
        name = n;
    }
    const Player &operator=(const Player &);
    void addPoints(double p)
    {
        points += p;
    }
};
</code>```

and here's the code to instantiate

```<code>void initPlayers()
{
    for(int i = 0; i < 4; i++)
        players[i] = new Player("Player " + i);
}
</code>```

any help would be appreciated, I really need to get this project finished soon!

答:
It should be,

```<code>Player& operator = (const Player &);  // remove "const" (it's not mandatory though)
</code>```

Actual problem lies in assignment inside for loop. You don't have to new the objects, as you are storing value and not the pointer.
Usage:

```<code>players[i] = Player("Player " + i);  // no need to do "new"
</code>```

Title: can't store an object into array? C++

Body:
I'm trying to do something simple and store an object into an Array in C++ but it keeps saying that I can't use the = operator with the right hand operand being of my class. Here's the code:

class Player {
    string name;
    double points;
    bool wonLastRound;
public:
    Player() {}
    Player(string n)
    {
        name = n;
    }
    const Player &operator=(const Player &);
    void addPoints(double p)
    {
        points += p;
    }
};

and here's the code to instantiate

void initPlayers()
{
    for(int i = 0; i < 4; i++)
        players[i] = new Player("Player " + i);
}

any help would be appreciated, I really need to get this project finished soon!

Body:
It should be,

Player& operator = (const Player &);  // remove "const" (it's not mandatory though)

Actual problem lies in assignment inside for loop. You don't have to new the objects, as you are storing value and not the pointer.
Usage:

players[i] = Player("Player " + i);  // no need to do "new"


问:
Problem with passing data to graphql from react
I have username and password which I want to send to graphql backend from react on frontend. I'm using apollo client for that

on my client side I have this

```<code>const REGISTER_USER = gql`
  mutation RegisterUser($username: String!, $password: String!) {
    registerUser(username: $username, password: $password) {
      username,
      password
    }
  }
`;
</code>```

And I'm calling it like this

```<code>registerUser({ variables: { username: values.username, password: values.password } })
</code>```

On my server

```<code>const UserType = new GraphQLObjectType({
    name: 'user',
    fields: () => ({
        username: { type: GraphQLString },
        password: { type: GraphQLString }
    })
});
const Mutations = new GraphQLObjectType({
    name: 'Mutation',
    fields: {
        registerUser: {
            type: UserType,
            args: {
                username: { type: GraphQLString },
                password: { type: GraphQLString }
            },
            resolve(username, password) {
                console.log(username, password, 123)
            }
        },
    }
})
</code>```

The problem is - I'm passing password and username separatly as strings, but my console.log(username, password, 123) in mutations gives back undefined and full object with username, password fields.

I'm not sure where I'm doing something wrong.
All the help will be much appreciated.

答:
The resolve function has source, args, context and info as params. You can read more about it in resolver function signature.

So basically you're asking for source and args, that is why one is undefined and the other is the object of arguments. The way to get your variables in your resolver is:

```<code>const Mutations = new GraphQLObjectType({
    name: 'Mutation',
    fields: {
        registerUser: {
            type: UserType,
            args: {
                username: { type: GraphQLString },
                password: { type: GraphQLString }
            },
            resolve: (source, args) {
                console.log(args.username, args.password)
                // HERE: you can access your arguments input as part of the 'args' object
            }
        },
    }
})
</code>```

Body:
I have username and password which I want to send to graphql backend from react on frontend. I'm using apollo client for that

on my client side I have this

const REGISTER_USER = gql`
  mutation RegisterUser($username: String!, $password: String!) {
    registerUser(username: $username, password: $password) {
      username,
      password
    }
  }
`;

And I'm calling it like this

registerUser({ variables: { username: values.username, password: values.password } })

On my server

const UserType = new GraphQLObjectType({
    name: 'user',
    fields: () => ({
        username: { type: GraphQLString },
        password: { type: GraphQLString }
    })
});
const Mutations = new GraphQLObjectType({
    name: 'Mutation',
    fields: {
        registerUser: {
            type: UserType,
            args: {
                username: { type: GraphQLString },
                password: { type: GraphQLString }
            },
            resolve(username, password) {
                console.log(username, password, 123)
            }
        },
    }
})

The problem is - I'm passing password and username separatly as strings, but my console.log(username, password, 123) in mutations gives back undefined and full object with username, password fields.

I'm not sure where I'm doing something wrong.
All the help will be much appreciated.

Body:
The resolve function has source, args, context and info as params. You can read more about it in resolver function signature.

So basically you're asking for source and args, that is why one is undefined and the other is the object of arguments. The way to get your variables in your resolver is:

const Mutations = new GraphQLObjectType({
    name: 'Mutation',
    fields: {
        registerUser: {
            type: UserType,
            args: {
                username: { type: GraphQLString },
                password: { type: GraphQLString }
            },
            resolve: (source, args) {
                console.log(args.username, args.password)
                // HERE: you can access your arguments input as part of the 'args' object
            }
        },
    }
})


问:
Running commands in rust (vim)
```<code>std::process::Command::new("/usr/bin/sh")
    .arg("-c")
    .arg("vim")
    .arg("file")
    .spawn()
    .expect("Error: Failed to run editor");
</code>```

When I run this code, a vim process is ran, editing the file, although it is not opened up in the terminal (not sure the exact terminology) how could I/is it possible to actually have vim open in the terminal

答:
When I run your code, vim does open in the terminal, but my shell is also running in the same terminal, and both vim and the shell fight for the display and they both receive any key I type. If this is the issue you are seeing too, you need to wait on the child process:

```<code>std::process::Command::new("/usr/bin/sh")
    .arg("-c")
    .arg("vim")
    .arg("file")
    .spawn()
    .expect("Error: Failed to run editor")
    .wait()
    .expect("Error: Editor returned a non-zero status");
</code>```

Title: Running commands in rust (vim)

Body:
std::process::Command::new("/usr/bin/sh")
    .arg("-c")
    .arg("vim")
    .arg("file")
    .spawn()
    .expect("Error: Failed to run editor");

When I run this code, a vim process is ran, editing the file, although it is not opened up in the terminal (not sure the exact terminology) how could I/is it possible to actually have vim open in the terminal

Body:
When I run your code, vim does open in the terminal, but my shell is also running in the same terminal, and both vim and the shell fight for the display and they both receive any key I type. If this is the issue you are seeing too, you need to wait on the child process:

std::process::Command::new("/usr/bin/sh")
    .arg("-c")
    .arg("vim")
    .arg("file")
    .spawn()
    .expect("Error: Failed to run editor")
    .wait()
    .expect("Error: Editor returned a non-zero status");


问:
Is there something in c# similar to java's @override annotation?
I've used the @Override in java and has come in quite handy. Is there anything similar in c#?</p>

答: The C# compiler provides compile-time checking for method overrides, including checking if the method is actually overriding as you intended.  You can indicate that a method should be overridden using the .NET override keyword.


答:
WITH RECURSIVE
cte1 AS
(
SELECT 1 num
UNION ALL
SELECT num + 1
FROM cte1
WHERE num < ( SELECT MAX(LENGTH(path) - LENGTH(REPLACE(path, '/', '')))
              FROM mdl_course_categories )
),
cte2 AS
(
SELECT cte1.num,
       cat.*,
       SUBSTRING_INDEX(SUBSTRING_INDEX(cat.path, '/', cte1.num+1), '/', -1) onechar
FROM cte1, mdl_course_categories cat
WHERE cte1.num <= (LENGTH(path) - LENGTH(REPLACE(cat.path, '/', '')))
),
cte3 AS
(
SELECT cte2.*, cat.name onecharname
FROM cte2, mdl_course_categories cat
WHERE cte2.onechar = cat.id
)
SELECT id, name, parent, depth, path, GROUP_CONCAT(onecharname ORDER BY num SEPARATOR ' - ') breadcrumb
FROM cte3
GROUP BY id, name, parent, depth, path;
```

<p>fiddle</p>

<p>Of course it can be compacted, but I think you can do it by yourself.</p>

<hr>

<p>At the request of @Shadow I also give a simple solution</p>

```SELECT t1.id,
       t1.name,
       t1.parent,
       t1.depth,
       t1.path,
       GROUP_CONCAT(t2.name ORDER BY LOCATE(CONCAT('/', t2.id, '/'), CONCAT(t1.path, '/')) SEPARATOR ' - ') breadcrumb
FROM mdl_course_categories t1,
     mdl_course_categories t2
WHERE LOCATE(CONCAT('/', t2.id, '/'), CONCAT(t1.path, '/'))
GROUP BY t1.id,
         t1.name,
         t1.parent,
         t1.depth,
         t1.path;
```

PS. Remember, 1st is O(N*AVG(M)) whereas 2nd is O(N*N) - where N is amount of records, and M is tree depth.

Title: How can I generate a breadcrumb of Categories in pure MySQL?

Body:
Say I have the mdl_course_categories table:

select cat.id, cat.name, cat.parent, cat.depth, cat.path
from mdl_course_categories cat

| id | name | parent | depth | path     |
|----|------|--------|-------|----------|
| 1  | a    | 0      | 1     | /1       |
| 2  | b    | 0      | 1     | /2       |
| 3  | c    | 1      | 2     | /1/3     |
| 4  | d    | 3      | 3     | /1/3/4   |
| 5  | e    | 4      | 4     | /1/3/4/5 |
| 6  | f    | 0      | 1     | /6       |
| 7  | g    | 6      | 2     | /6/7     |
| 8  | h    | 7      | 3     | /6/7/8   |
| 9  | i    | 3      | 3     | /1/3/9   |
| 10 | j    | 7      | 3     | /6/7/10  |

How can I generate the breadcrumbs as per below? I'm a complete rookie to SQL, and have no experience managing hierarchial data. I had a look at this answer, but was unable to translate it to my table and situation. Thanks in advance!

| id | name | parent | depth | path     | breadcrumb    |
|----|------|--------|-------|----------|---------------|
| 1  | a    | 0      | 1     | /1       | a             |
| 2  | b    | 0      | 1     | /2       | b             |
| 3  | c    | 1      | 2     | /1/3     | a - c         |
| 4  | d    | 3      | 3     | /1/3/4   | a - c - d     |
| 5  | e    | 4      | 4     | /1/3/4/5 | a - c - d - e |
| 6  | f    | 0      | 1     | /6       | f             |
| 7  | g    | 6      | 2     | /6/7     | f - g         |
| 8  | h    | 7      | 3     | /6/7/8   | f - g - h     |
| 9  | i    | 3      | 3     | /1/3/9   | a - b - i     |
| 10 | j    | 7      | 3     | /6/7/10  | f - g - j     |

Body:
WITH RECURSIVE
cte1 AS
(
SELECT 1 num
UNION ALL
SELECT num + 1
FROM cte1
WHERE num < ( SELECT MAX(LENGTH(path) - LENGTH(REPLACE(path, '/', '')))
              FROM mdl_course_categories )
),
cte2 AS
(
SELECT cte1.num,
       cat.*,
       SUBSTRING_INDEX(SUBSTRING_INDEX(cat.path, '/', cte1.num+1), '/', -1) onechar
FROM cte1, mdl_course_categories cat
WHERE cte1.num <= (LENGTH(path) - LENGTH(REPLACE(cat.path, '/', '')))
),
cte3 AS
(
SELECT cte2.*, cat.name onecharname
FROM cte2, mdl_course_categories cat
WHERE cte2.onechar = cat.id
)
SELECT id, name, parent, depth, path, GROUP_CONCAT(onecharname ORDER BY num SEPARATOR ' - ') breadcrumb
FROM cte3
GROUP BY id, name, parent, depth, path;

fiddle

Of course it can be compacted, but I think you can do it by yourself.

At the request of @Shadow I also give a simple solution

SELECT t1.id,
       t1.name,
       t1.parent,
       t1.depth,
       t1.path,
       GROUP_CONCAT(t2.name ORDER BY LOCATE(CONCAT('/', t2.id, '/'), CONCAT(t1.path, '/')) SEPARATOR ' - ') breadcrumb
FROM mdl_course_categories t1,
     mdl_course_categories t2
WHERE LOCATE(CONCAT('/', t2.id, '/'), CONCAT(t1.path, '/'))
GROUP BY t1.id,
         t1.name,
         t1.parent,
         t1.depth,
         t1.path;

PS. Remember, 1st is O(N*AVG(M)) whereas 2nd is O(N*N) - where N is amount of records, and M is tree depth.


问:
data.table frollmean very slow
I'm trying to calculate the rolling mean of a column in a large data.table (~30M rows) aggregated by two other columns.
The rolling mean should include only the preceding N row values, not the row value itself.
For this purpose, i had to define my own rolling mean function based on frollmean function. (N=3)
Applying the function to the column is really really slow, rendering it rather useless.

Here is sample data:

```<code>require(data.table)
DT <- data.table(ID=c('A', 'A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C')
               , value_type =c('type 1', 'type 1','type 2','type 1','type 2','type 2','type 1','type 1','type 2','type 1','type 1','type 1')
               , value=c(1,4,7,2,3,5,1,6,8,2,2,3))
    DT
         ID value_type value
     1:  A     type 1     1
     2:  A     type 1     4
     3:  A     type 2     7
     4:  A     type 1     2
     5:  A     type 2     3
     6:  A     type 2     5
     7:  B     type 1     1
     8:  B     type 1     6
     9:  B     type 2     8
    10:  C     type 1     2
    11:  C     type 1     2
    12:  C     type 1     3

#this is the customised rolling function
lrollmean<-function(x){

  head(frollmean(c(NA,NA,NA,x), n = 3, fill = NA, algo ="exact", align="right", na.rm = TRUE)[-(1:2)], -1)

}

> DT[, roll_mean := lrollmean(value), by=.(ID, value_type)]
> DT
    ID value_type value roll_mean
 1:  A     type 1     1       NaN
 2:  A     type 1     4       1.0
 3:  A     type 2     7       NaN
 4:  A     type 1     2       2.5
 5:  A     type 2     3       7.0
 6:  A     type 2     5       5.0
 7:  B     type 1     1       NaN
 8:  B     type 1     6       1.0
 9:  B     type 2     8       NaN
10:  C     type 1     2       NaN
11:  C     type 1     2       2.0
12:  C     type 1     3       2.0
</code>```

This operation takes more than 30 minutes! I've got a reasonable machine which ample RAM, and I feel the long time of the operation has something to do with my code rather than the machine.

答:
You can try frollapply and  since frollmean doesn't completely suit your needs. You can also optimize the function you apply to the window, since you don't need a very complicated operation. I've tried a few modifications to your function that should cut your time down by around 50%.

library(data.table)
library(stringi)
N=1e6
set.seed(123)
DT <- data.table(ID=stri_rand_strings(N,3),
                 value=rnorm(N,5,5))
head(DT)
#>     ID      value
#> 1: HmP 12.2667538
#> 2: sw2 -2.2397053
#> 3: WtY  7.0911933
#> 4: SxS  0.4029431
#> 5: gZ6  8.6800795
#> 6: tF2  0.8228594
DT[,.(.N),by=ID][order(N)]
#>          ID  N
#>      1: HoR  1
#>      2: eNM  1
#>      3: I9h  1
#>      4: xjb  1
#>      5: eFH  1
#>     ---
#> 234823: 34Y 15
#> 234824: Xcm 15
#> 234825: IOu 15
#> 234826: tob 16
#> 234827: f70 16

# Your function
lrollmean<-function(x){
  head(frollmean(c(NA,NA,NA,x), n = 3, fill = NA, algo ="exact", align="right", na.rm = TRUE)[-(1:2)], -1)
}

#Possible modifications:
lrollmean1<-function(x,n){
  frollapply(c(rep(NA,n),x),n+1,weighted.mean,c(rep(1,n),0),na.rm=T)[-(1:3)]
}
lrollmean2<-function(x,n){
  frollapply(c(rep(NA,n),x),n+1,function(x) sum(x*c(rep(1,n),0)/n,na.rm = T))[-(1:3)]
}
lrollmean3<-function(x){ # More optimized assuming n=3
  frollapply(c(NA,NA,NA,x),4,function(x) sum(x[1:3]/3,na.rm = T))[-(1:3)]
}

library(rbenchmark)

benchmark(original={DT[, roll_mean := lrollmean1(value,3), by=.(ID)]},
          a={DT[, roll_mean := lrollmean1(value,3), by=.(ID)]},
          b={DT[, roll_mean := lrollmean2(value,3), by=.(ID)]},
          c={DT[, roll_mean := lrollmean3(value), by=.(ID)]}
          ,replications = 1,order = 'relative')
#>       test replications elapsed relative user.self sys.self user.child
#> 4        c            1   6.740    1.000     6.829    0.000          0
#> 3        b            1   8.038    1.193     8.085    0.012          0
#> 1 original            1  13.599    2.018    13.692    0.000          0
#> 2        a            1  14.180    2.104    14.233    0.008          0
#>   sys.child
#> 4         0
#> 3         0
#> 1         0
#> 2         0
```

Created on 2020-02-17 by the reprex package (v0.3.0)

Title: data.table frollmean very slow

Body:
I'm trying to calculate the rolling mean of a column in a large data.table (~30M rows) aggregated by two other columns.
The rolling mean should include only the preceding N row values, not the row value itself.
For this purpose, i had to define my own rolling mean function based on frollmean function. (N=3)
Applying the function to the column is really really slow, rendering it rather useless.

Here is sample data:

require(data.table)
DT <- data.table(ID=c('A', 'A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C')
               , value_type =c('type 1', 'type 1','type 2','type 1','type 2','type 2','type 1','type 1','type 2','type 1','type 1','type 1')
               , value=c(1,4,7,2,3,5,1,6,8,2,2,3))
    DT
         ID value_type value
     1:  A     type 1     1
     2:  A     type 1     4
     3:  A     type 2     7
     4:  A     type 1     2
     5:  A     type 2     3
     6:  A     type 2     5
     7:  B     type 1     1
     8:  B     type 1     6
     9:  B     type 2     8
    10:  C     type 1     2
    11:  C     type 1     2
    12:  C     type 1     3

#this is the customised rolling function
lrollmean<-function(x){

  head(frollmean(c(NA,NA,NA,x), n = 3, fill = NA, algo ="exact", align="right", na.rm = TRUE)[-(1:2)], -1)

}

> DT[, roll_mean := lrollmean(value), by=.(ID, value_type)]
> DT
    ID value_type value roll_mean
 1:  A     type 1     1       NaN
 2:  A     type 1     4       1.0
 3:  A     type 2     7       NaN
 4:  A     type 1     2       2.5
 5:  A     type 2     3       7.0
 6:  A     type 2     5       5.0
 7:  B     type 1     1       NaN
 8:  B     type 1     6       1.0
 9:  B     type 2     8       NaN
10:  C     type 1     2       NaN
11:  C     type 1     2       2.0
12:  C     type 1     3       2.0

This operation takes more than 30 minutes! I've got a reasonable machine which ample RAM, and I feel the long time of the operation has something to do with my code rather than the machine.

Body:
You can try frollapply and  since frollmean doesn't completely suit your needs. You can also optimize the function you apply to the window, since you don't need a very complicated operation. I've tried a few modifications to your function that should cut your time down by around 50%.

library(data.table)
library(stringi)
N=1e6
set.seed(123)
DT <- data.table(ID=stri_rand_strings(N,3),
                 value=rnorm(N,5,5))
head(DT)
#>     ID      value
#> 1: HmP 12.2667538
#> 2: sw2 -2.2397053
#> 3: WtY  7.0911933
#> 4: SxS  0.4029431
#> 5: gZ6  8.6800795
#> 6: tF2  0.8228594
DT[,.(.N),by=ID][order(N)]
#>          ID  N
#>      1: HoR  1
#>      2: eNM  1
#>      3: I9h  1
#>      4: xjb  1
#>      5: eFH  1
#>     ---
#> 234823: 34Y 15
#> 234824: Xcm 15
#> 234825: IOu 15
#> 234826: tob 16
#> 234827: f70 16

# Your function
lrollmean<-function(x){
  head(frollmean(c(NA,NA,NA,x), n = 3, fill = NA, algo ="exact", align="right", na.rm = TRUE)[-(1:2)], -1)
}

#Possible modifications:
lrollmean1<-function(x,n){
  frollapply(c(rep(NA,n),x),n+1,weighted.mean,c(rep(1,n),0),na.rm=T)[-(1:3)]
}
lrollmean2<-function(x,n){
  frollapply(c(rep(NA,n),x),n+1,function(x) sum(x*c(rep(1,n),0)/n,na.rm = T))[-(1:3)]
}
lrollmean3<-function(x){ # More optimized assuming n=3
  frollapply(c(NA,NA,NA,x),4,function(x) sum(x[1:3]/3,na.rm = T))[-(1:3)]
}

library(rbenchmark)

benchmark(original={DT[, roll_mean := lrollmean1(value,3), by=.(ID)]},
          a={DT[, roll_mean := lrollmean1(value,3), by=.(ID)]},
          b={DT[, roll_mean := lrollmean2(value,3), by=.(ID)]},
          c={DT[, roll_mean := lrollmean3(value), by=.(ID)]}
          ,replications = 1,order = 'relative')
#>       test replications elapsed relative user.self sys.self user.child
#> 4        c            1   6.740    1.000     6.829    0.000          0
#> 3        b            1   8.038    1.193     8.085    0.012          0
#> 1 original            1  13.599    2.018    13.692    0.000          0
#> 2        a            1  14.180    2.104    14.233    0.008          0
#>   sys.child
#> 4         0
#> 3         0
#> 1         0
#> 2         0

Created on 2020-02-17 by the reprex package (v0.3.0)


问:
How to change the Back Button Text on Xamarin.Forms
I have been trying to change the text of the back button in Xamarin.Forms without luck.

I tried already this code with no luck:

```<code>NavigationPage.SetBackButtonTitle(this, "");
</code>```

I'm using a MasterDetailPage.

I tried to add the code into the constructor of the XAML cs file.

Libraries used: PRISM 6.2.0, Xamarin Forms 2.3.1.114

Any suggestion or idea?

Thanks in advance

答:
You can set the attribute NavigationPage.BackButtonTitle on ContentPage

For example:

<?xml version="1.0" encoding="utf-8"?>
  <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
               xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
               xmlns:d="http://xamarin.com/schemas/2014/forms/design"
               xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
               xmlns:local="clr-namespace:T3R"
               mc:Ignorable="d"
               Title="Title of Page"
               NavigationPage.BackButtonTitle="Cancel"
               x:Class="T3R.MainPage">

Remember the following:

I understand this only works on iOS

For any given page, the back button title is set by the page that presents it. This way, the button label can vary with respect to the page that precedes it on the navigation stack (of which there can be many).

Body:
I have been trying to change the text of the back button in Xamarin.Forms without luck.

I tried already this code with no luck:

NavigationPage.SetBackButtonTitle(this, "");

I'm using a MasterDetailPage.

I tried to add the code into the constructor of the XAML cs file.

Libraries used: PRISM 6.2.0, Xamarin Forms 2.3.1.114

Any suggestion or idea?

Thanks in advance


答:
In C#, you must use the override keyword to override functions.

If you use override without a matching virtual or abstract base function, you'll get a compiler error.

If you don't use override, and there is a matching base function, you'll get a compiler warning (unless you add new).

Title: Is there something in c# similar to java's @override annotation?

Body: I've used the @Override in java and has come in quite handy. Is there anything similar in c#?


问:
How can I receive the JSON by using setRequestMethod("GET")?
I want to receive a JSON from server. So I used setRequestMethod("GET").
I already modified my code some times, but It doesn't work still now.

```<code>package com.example.myapplication;

import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

//"http://ec2-15-164-98-71.ap-northeast-2.compute.amazonaws.com:8888/code/list"

public class MainActivity extends AppCompatActivity {

    TextView tvData;
    Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tvData = findViewById(R.id.textView);
        btn = findViewById(R.id.button);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new JSONTask().execute();
            }
        });

    }

    public class JSONTask extends AsyncTask<String, Void, String>{

        @Override
        protected String doInBackground(String... urls) {
            URL url = null;
            try {
                //JSONObject를 만들고 key value 형식으로 값을 저장해준다.
                url = new URL("http://ec2-15-164-98-71.ap-northeast-2.compute.amazonaws.com:8888/code/list");
                JSONObject jsonObject = new JSONObject();
                //jsonObject.accumulate("user_id", "androidTest");
                //jsonObject.accumulate("name", "yun");

                HttpURLConnection con = null;
                BufferedReader reader = null;

                try{
                    con = (HttpURLConnection) url.openConnection();

                    con.setRequestMethod("GET");
                    con.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.146 Whale/2.6.90.18 Safari/537.36");
                    con.setRequestProperty("Accept", "application/json");

                    con.setConnectTimeout(3000);
                    con.setReadTimeout(3000);

                    con.setDoOutput(true);//Outstream으로 post 데이터를 넘겨주겠다는 의미
                    con.setDoInput(true);//Inputstream으로 서버로부터 응답을 받겠다는 의미
                    con.connect();

                    System.out.println(con.getResponseCode());
                    System.out.println(con.getResponseMessage());
                    //서버로 보내기위해서 스트림 만듬
                    OutputStream outStream = con.getOutputStream();
                    //버퍼를 생성하고 넣음
                    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outStream));
                    writer.write(jsonObject.toString());
                    writer.flush();
                    writer.close();//버퍼를 받아줌

                    //서버로 부터 데이터를 받음
                    InputStream stream = con.getInputStream();

                    reader = new BufferedReader(new InputStreamReader(stream));

                    StringBuffer buffer = new StringBuffer();

                    String line = "";
                    while((line = reader.readLine()) != null){
                        buffer.append(line);
                    }

                    return buffer.toString();//서버로 부터 받은 값을 리턴해줌 아마 OK!!가 들어올것임

                } catch (MalformedURLException e){
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if(con != null){
                        con.disconnect();
                    }
                    try {
                        if(reader != null){
                            reader.close();//버퍼를 닫아줌
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            tvData.setText(result);//서버로 부터 받은 값을 출력해주는 부
        }
    }
}
</code>```

Here's a logcat. 403 is a value of getResponseCode(), and Forbidden is getResponseMessage()'s result.
Some people said "(HTTPLog)-Static: isSBSettingEnabled false" problem can resolve by asyncTask. But I already used asyncTask in my code.

```<code>2020-02-17 16:00:12.480 9517-10273/? I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
2020-02-17 16:00:12.559 9517-10273/? I/System.out: 403
2020-02-17 16:00:12.560 9517-10273/? I/System.out: Forbidden
</code>```

答:
Instead of getOutputStream(), You need to use getInputStream() since you read input from connection.

PS. Don't know why you still use URLConnection. I reccommends you to use OKHttp Connection. It's much easier than this.

Body:
I want to receive a JSON from server. So I used setRequestMethod("GET").
I already modified my code some times, but It doesn't work still now.

package com.example.myapplication;

import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

//"http://ec2-15-164-98-71.ap-northeast-2.compute.amazonaws.com:8888/code/list"

public class MainActivity extends AppCompatActivity {

    TextView tvData;
    Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tvData = findViewById(R.id.textView);
        btn = findViewById(R.id.button);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new JSONTask().execute();
            }
        });

    }

    public class JSONTask extends AsyncTask<String, Void, String>{

        @Override
        protected String doInBackground(String... urls) {
            URL url = null;
            try {
                //JSONObject를 만들고 key value 형식으로 값을 저장해준다.
                url = new URL("http://ec2-15-164-98-71.ap-northeast-2.compute.amazonaws.com:8888/code/list");
                JSONObject jsonObject = new JSONObject();
                //jsonObject.accumulate("user_id", "androidTest");
                //jsonObject.accumulate("name", "yun");

                HttpURLConnection con = null;
                BufferedReader reader = null;

                try{
                    con = (HttpURLConnection) url.openConnection();

                    con.setRequestMethod("GET");
                    con.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.146 Whale/2.6.90.18 Safari/537.36");
                    con.setRequestProperty("Accept", "application/json");

                    con.setConnectTimeout(3000);
                    con.setReadTimeout(3000);

                    con.setDoOutput(true);//Outstream으로 post 데이터를 넘겨주겠다는 의미
                    con.setDoInput(true);//Inputstream으로 서버로부터 응답을 받겠다는 의미
                    con.connect();

                    System.out.println(con.getResponseCode());
                    System.out.println(con.getResponseMessage());
                    //서버로 보내기위해서 스트림 만듬
                    OutputStream outStream = con.getOutputStream();
                    //버퍼를 생성하고 넣음
                    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outStream));
                    writer.write(jsonObject.toString());
                    writer.flush();
                    writer.close();//버퍼를 받아줌

                    //서버로 부터 데이터를 받음
                    InputStream stream = con.getInputStream();

                    reader = new BufferedReader(new InputStreamReader(stream));

                    StringBuffer buffer = new StringBuffer();

                    String line = "";
                    while((line = reader.readLine()) != null){
                        buffer.append(line);
                    }

                    return buffer.toString();//서버로 부터 받은 값을 리턴해줌 아마 OK!!가 들어올것임

                } catch (MalformedURLException e){
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if(con != null){
                        con.disconnect();
                    }
                    try {
                        if(reader != null){
                            reader.close();//버퍼를 닫아줌
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            tvData.setText(result);//서버로 부터 받은 값을 출력해주는 부
        }
    }
}

Here's a logcat. 403 is a value of getResponseCode(), and Forbidden is getResponseMessage()'s result.
Some people said "(HTTPLog)-Static: isSBSettingEnabled false" problem can resolve by asyncTask. But I already used asyncTask in my code.

2020-02-17 16:00:12.480 9517-10273/? I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
2020-02-17 16:00:12.559 9517-10273/? I/System.out: 403
2020-02-17 16:00:12.560 9517-10273/? I/System.out: Forbidden


问:
How to assign values in an Angular form without an input element or hiding the UI element?
I am working on this template-driven form, where I have a dropdown.

The dropdown has an ID as value and Name as the display value.

When I submit the form, I need both the values ID and Name to be in the form output

```<code>   <mat-form-field>
            <mat-label>State</mat-label>
            <mat-select [(ngModel)]="data.stateCode" name="StateCode" #yddfyty>
              <mat-option *ngFor="let state of stateOptions" [value]="state.ID">
                {{state.name}}
              </mat-option>
            </mat-select>
   </mat-form-field>
</code>```

After submitting the form, I get a JSON

```<code>{
  StateCode: "Option I select in the Dropdown"
}
</code>```

When I submit the form, I also want the StateName to be in the form output.

How do I assign the StateName selected in the Dropdown, to a model property in the template-driven form?

I can think of a way where we can use an  element and hide the element, Is there any other way?

Is the only way to do it in the Typescript file after submitting?

答:
ViewChild comes handy in these situations:

HTML File:

```<code><mat-form-field>
            <mat-label>State</mat-label>
            <mat-select  name="StateCode" #ElementRef>
              <mat-option *ngFor="let state of stateOptions" [value]="state.ID">
                {{state.name}}
              </mat-option>
            </mat-select>
   </mat-form-field>
</code>```

Component TS File:

first declare an viewchild variable:

```<code>@ViewChild('ElementRef') stateElement: any;
</code>```

and later on you can use this variable when you submit the form:

```<code>    OnSubmit(){
     let selectedStateCode = this.stateElement.nativeElement.value//selected dropdown value
     let selectedStateText = this.stateElement.nativeElement.textContent //selected dropdown text
     //rest of your submit code;
    }
</code>```

Body:
I am working on this template-driven form, where I have a dropdown.

The dropdown has an ID as value and Name as the display value.

When I submit the form, I need both the values ID and Name to be in the form output

   <mat-form-field>
            <mat-label>State</mat-label>
            <mat-select [(ngModel)]="data.stateCode" name="StateCode" #yddfyty>
              <mat-option *ngFor="let state of stateOptions" [value]="state.ID">
                {{state.name}}
              </mat-option>
            </mat-select>
   </mat-form-field>

After submitting the form, I get a JSON

{
  StateCode: "Option I select in the Dropdown"
}

When I submit the form, I also want the StateName to be in the form output.

How do I assign the StateName selected in the Dropdown, to a model property in the template-driven form?

I can think of a way where we can use an  element and hide the element, Is there any other way?

Is the only way to do it in the Typescript file after submitting?

Body:
ViewChild comes handy in these situations:

HTML File:

<mat-form-field>
            <mat-label>State</mat-label>
            <mat-select  name="StateCode" #ElementRef>
              <mat-option *ngFor="let state of stateOptions" [value]="state.ID">
                {{state.name}}
              </mat-option>
            </mat-select>
   </mat-form-field>

Component TS File:

first declare an viewchild variable:

@ViewChild('ElementRef') stateElement: any;

and later on you can use this variable when you submit the form:

    OnSubmit(){
     let selectedStateCode = this.stateElement.nativeElement.value//selected dropdown value
     let selectedStateText = this.stateElement.nativeElement.textContent //selected dropdown text
     //rest of your submit code;
    }


问:
In an android ListView, how can I iterate/manipulate all the child views, not just the visible ones?
The code below does NOT change the text of all of a ListView's rows because getChildCount() does not get all of a ListView's rows, but just the rows that are visible.

```<code>for (int i = 0; i < listView.getChildCount(); i++)
{
    View v = listView.getChildAt(i);
    TextView tx = (TextView) v.findViewById(R.id.mytext);
    tx.setTextSize(newTextSize);
}
</code>```

So, what SHOULD I do?

Is there code for getting a notification when a ListView's row becomes visible, so I can set its text size then?

答:
```<code>//Create layout file containing views you want to read input from
//layout/gen_edt_layout.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/parLay"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <com.google.android.material.textfield.TextInputEditText
        android:id="@+id/edtGName"
        android:layout_width = "match_parent"
        android:layout_height ="wrap_content"
        android:hint="Name"
        android:inputType="text" />

    <com.google.android.material.textfield.TextInputEditText
        android:id="@+id/edtGIdPass"
        style="@style/edt"
        android:hint="Id number"
        android:inputType="number" />

</LinearLayout>

//Create Empty Activity -> MultipleInput

//layout/activity_multiple_input.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".OpenAccount">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent">

      <ListView
            android:id="@+id/inputLView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="60dp" />

    </LinearLayout>

    <Button
        android:layout_width="wrap_content
        android:layout_height="wrap_content"
        android:text="Read"
        android:onClick="readInput"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent>

</androidx.constraintlayout.widget.ConstraintLayout>

public class MultipleInput extends AppCompatActivity {

    //Declare and intialize arrays to store input fields as public modifiers
    ArrayList<TextInputEditText> edtNameArr = new ArrayList<>();
    ArrayList<TextInputEditText> edtIdsArr = new ArrayList<>();

    //Intialize arrays to store input values as public modifiers
    ArrayList<String> arr0 = new ArrayList<>();
    ArrayList<String> arr1 = new ArrayList<>();

    ListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        listView = findViewById(R.id.listView);

        edtNameArr.clear();
        edtIdsArr.clear();

        arr0.clear();
        arr1.clear();

        //set number of group fields to be generated
        int members = 4;

        //initialize class passing fields number and context
        edtAdapter = new EdtAdapter(members, getApplicationContext());

        //Set retured fields in listView
        listView.setAdapter(edtAdapter);

    }

    public class EdtAdapter extends BaseAdapter {

        class ViewHolder {

            TextInputEditText edtGName, edtGIdPass;
        }

        public Context context;

        ArrayList<EdtClass> edtArrayList;
        int members;

        EdtAdapter(int members, Context context) {

            this.members = members;
            this.context = context;

        }

        @Override
        public int getCount() {
            return members;
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View contentView, ViewGroup parent) {

            View rowView = contentView;

            if (rowView == null) {

                viewHolder = new ViewHolder();

                LayoutInflater inflater = getLayoutInflater();
                rowView = inflater.inflate(R.layout.gen_edt_layout, parent, false);
                viewHolder.edtGName = rowView.findViewById(R.id.edtGName);
                viewHolder.edtGIdPass = rowView.findViewById(R.id.edtGIdPass);

                viewPosition = position;

                //loop adding input fields in arrays
                for (int i = 0; i < members; i++) {
                    edtNameArr.add(viewHolder.edtGName);
                    edtIdsArr.add(viewHolder.edtGIdPass);
                }

            } else {
                viewHolder = (ViewHolder) contentView.getTag();
            }

            return rowView;

        }

    }

    //Read input when button clicked
    public void readInput(View view){

        for(int edt = 0; edt<edtNameArr.size(); edt++){

            String name = Objects.requireNonNull(edtNameArr.get(edt).getText()).toString();

            if(!arr0.contains(name)) {
                arr0.add(name);
            }

            String ids = Objects.requireNonNull(edtIdsArr.get(edt).getText()).toString();

            if(!arr1.contains(ids)) {
                arr1.add(ids);
            }

        }

        StringBuilder name = new StringBuilder();
        StringBuilder idno = new StringBuilder();

        //loop through arrays with input, reading and appending values in StringBuilder
        for (int m = 0; m < arr0.size(); m++) {

            name.append(arr0.get(m)).append(",");

            idno.append(arr1.get(m)).append(",");

        }

        //Show input values in logcat/Toast
        Log.e("Names ", name.toString());
        Log.e("Ids ", idno.toString());
        Toast.makeText(MultipleInput.this, "Names "+ name.toString(), Toast.LENGTH_LONG).show();

    }
</code>```

Body:
The code below does NOT change the text of all of a ListView's rows because getChildCount() does not get all of a ListView's rows, but just the rows that are visible.

for (int i = 0; i < listView.getChildCount(); i++)
{
    View v = listView.getChildAt(i);
    TextView tx = (TextView) v.findViewById(R.id.mytext);
    tx.setTextSize(newTextSize);
}

So, what SHOULD I do?

Is there code for getting a notification when a ListView's row becomes visible, so I can set its text size then?


问:
How to generate Map<String, ...> with Swagger Codegen?
I'm working on an API where we define the API definition in the swagger.yaml file. The API which I am working on returns an output object which contains a map.

Output Object : OutputClass

public class OutputClass {
   private Map<String, MapValue> map;

}
```
<p>Right now, I used:</p>
<pre class="lang-yaml prettyprint-override"><code> OutputClass:
    type: object
    additionalProperties:
      $ref: '#/definitions/MapValue'
</code>```

But Swagger Codegen generates the following Java code:

public class OutputClass extends HashMap<String, MapValue> implements Serializable {
}
```

Is there any way to achieve what I need?

答: Your map definition is correct. There's an open issue with Swagger Codegen about the way it translates OpenAPI maps to Java code: https://github.com/swagger-api/swagger-codegen/issues/5187</p>

Body:
I'm working on an API where we define the API definition in the swagger.yaml file. The API which I am working on returns an output object which contains a map.

Output Object : OutputClass

public class OutputClass {
   private Map<String, MapValue> map;

}

Right now, I used:

 OutputClass:
    type: object
    additionalProperties:
      $ref: '#/definitions/MapValue'

But Swagger Codegen generates the following Java code:

public class OutputClass extends HashMap<String, MapValue> implements Serializable {
}

Is there any way to achieve what I need?


问:
Best way to include other CSS/JS libraries in a Github repo?
I'm wanting to include FontAwesome, Bulma, jquery, and jquery-ui in one of my Github repos for the frontend portion. Currently what I'm doing is using the JS file or CSS files from these projects in my own JS/CSS folders, but I feel like there is a neater way to do this. I've tried git submodules for it and they work fine, although I'm unsure if that is the best way to go about doing it.</p>

答:
you can use a package manager like yarn , npm , bower

you can require them at your index html file
check this
https://www.w3schools.com/jquery/jquery_get_started.asp
this line

```<code><script src="jquery-3.4.1.min.js"></script>
</code>```

require jquery as $

for jquery ui check this
https://learn.jquery.com/jquery-ui/getting-started/

```<code><link rel="stylesheet" href="jquery-ui.min.css">
<script src="external/jquery/jquery.js"></script>
<script src="jquery-ui.min.js"></script>
</code>```

in the document

for Font-Awesome

https://fontawesome.com/how-to-use/on-the-web/setup/hosting-font-awesome-yourself

Body:
you can use a package manager like yarn , npm , bower

you can require them at your index html file
check this
https://www.w3schools.com/jquery/jquery_get_started.asp
this line

<script src="jquery-3.4.1.min.js"></script>

require jquery as $

for jquery ui check this
https://learn.jquery.com/jquery-ui/getting-started/

<link rel="stylesheet" href="jquery-ui.min.css">
<script src="external/jquery/jquery.js"></script>
<script src="jquery-ui.min.js"></script>

in the document

for Font-Awesome

https://fontawesome.com/how-to-use/on-the-web/setup/hosting-font-awesome-yourself


问:
How to mock libraries that are unknown in Javascript on my local environment?
I am developing a website using Javascript for a device which has a particular Javascript library that can be used. This Javascript library is known on the device but it is not known locally. F.e. I execute library.function(). For this, locally I get the error: library is not defined.

Is there a way to avoid this error locally so that I can test those parts without commenting it out? To mock the libraries that are unknown locally.

答:
Is this a global scoped library? If yes, you can substitute it and mock the behaviour:

```<code>var MockLib = {
   someFunction: () => console.log("someFunction called"),
   someOtherFunc: (args) => console.log("someOtherFunc called", args),
   someProp: "value-123",
};

window.library = window.library || MockLib;
</code>```

Then, executing library.someFunction() will execute the function on the library if it was already defined or your mock if not.

Just make sure to put the window.library assignment AFTER the library should have been loaded.

Body:
Is this a global scoped library? If yes, you can substitute it and mock the behaviour:

var MockLib = {
   someFunction: () => console.log("someFunction called"),
   someOtherFunc: (args) => console.log("someOtherFunc called", args),
   someProp: "value-123",
};

window.library = window.library || MockLib;

Then, executing library.someFunction() will execute the function on the library if it was already defined or your mock if not.

Just make sure to put the window.library assignment AFTER the library should have been loaded.


问:
Stripe payment charge
I want to charge payment using paymentMethod as a source but it does not charge, how do I get token as the source using payment method? I tried to charge using </p>

<pre class="lang-php prettyprint-override"><code>\Stripe\Stripe::setApiKey('sk_test_**************');
\Stripe\Charge::create([
    'amount' => $menuPrice*100,
    'currency' => 'usd',
    'customer' => $user->stripe_id,
    'source' => 'pm_*************'
]);
</code>```

答: Charges are the older way of doing this; the new way is Payment Intents (with Payment Methods).  You can find out about the differences here: https://stripe.com/docs/payments/payment-intents/migration</p>

Title: Stripe payment charge

Body:
I want to charge payment using paymentMethod as a source but it does not charge, how do I get token as the source using payment method? I tried to charge using

\Stripe\Stripe::setApiKey('sk_test_**************');
\Stripe\Charge::create([
    'amount' => $menuPrice*100,
    'currency' => 'usd',
    'customer' => $user->stripe_id,
    'source' => 'pm_*************'
]);


问:
How to get the integer portion of a float column in pandas
Suppose I have a dataframe df as shown below

```<code>    qty
0   1.300
1   1.909
</code>```

Now I want to extract only the integer portion of the qty column and the df should look like

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

Tried using df['qty'].round(0) but didn't get the desired result as it rounds of the number to the nearest integer.

Java has a function intValue() which does the desired operation. Is there a similar function in pandas ?

Body:
Suppose I have a dataframe df as shown below

    qty
0   1.300
1   1.909

Now I want to extract only the integer portion of the qty column and the df should look like

   qty
0   1
1   1

Tried using df['qty'].round(0) but didn't get the desired result as it rounds of the number to the nearest integer.

Java has a function intValue() which does the desired operation. Is there a similar function in pandas ?

Body:
You can use the method floordiv:

df['col'].floordiv(1).astype(int)

For example:

        col
0  9.748333
1  6.612708
2  2.888753
3  8.913470
4  2.354213

Output:

0    9
1    6
2    2
3    8
4    2
Name: col, dtype: int64


问:
Python Pandas - Find rows where element is in row's array
I want to find all rows where a certain value is present inside the column's list value.

So imagine I have a dataframe set up like this:

```<code>|  placeID |                             users |
------------------------------------------------
|    134986|   [U1030, U1017, U1123, U1044...] |
|    133986|   [U1034, U1011, U1133, U1044...] |
|    134886|   [U1031, U1015, U1133, U1044...] |
|    134976|   [U1130, U1016, U1133, U1044...] |
</code>```

How can I get all rows where 'U1030' exists in the users column?

Or... is the real problem that I should not have my data arranged like this, and I should instead explode that column to have a row for each user?

What's the right way to approach this?

答:
The way you have stored data looks fine to me. You do not need to change the format of storing data.

Try this :

```<code>df1 = df[df['users'].str.contains("U1030")]

print(df1)

</code>```

This will give you all the rows containing specified user in df format.

Body:
I want to find all rows where a certain value is present inside the column's list value.

So imagine I have a dataframe set up like this:

|  placeID |                             users |
------------------------------------------------
|    134986|   [U1030, U1017, U1123, U1044...] |
|    133986|   [U1034, U1011, U1133, U1044...] |
|    134886|   [U1031, U1015, U1133, U1044...] |
|    134976|   [U1130, U1016, U1133, U1044...] |

How can I get all rows where 'U1030' exists in the users column?

Or... is the real problem that I should not have my data arranged like this, and I should instead explode that column to have a row for each user?

What's the right way to approach this?

Body:
The way you have stored data looks fine to me. You do not need to change the format of storing data.

Try this :

df1 = df[df['users'].str.contains("U1030")]

print(df1)

This will give you all the rows containing specified user in df format.


问:
`elementFormDefault` sometimes doesn't work
Introduction

elementFormDefault="unqualified" on the <schema> element sets a default form="unqualified" for the elements defined in that schema.

The following valid XML segment used a schema defined with elementFormDefault="unqualified"

```<code><asnx:module xmlns:asnx="urn:ietf:params:xml:ns:asnx">
   <sequence/>
</asnx:module>
</code>```

The <sequence> element doesn't have namespace qualification because the schema was defined like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
       xmlns="urn:ietf:params:xml:ns:asnx"
       targetNamespace="urn:ietf:params:xml:ns:asnx"
       elementFormDefault="unqualified">
....
</code>```

Abnormality

In a specific system I'm working with, modularised XHTML was used in the descriptive part of XML data, like this:

```<code><product:description>
 <xhtml:div>
  <xhtml:p>This product is discontinued</xhtml:p>
 </xhtml:div>
</product:description>
</code>```

Due to the way the software application I'm working on was assembled, it won't work unless it's written in this form:

```<code><product:description>
  <xhtml:div>
    <p>This product is discontinued</p>
  </xhtml:div>
</product:description>
</code>```

That is, the software application fails to process the embedded XHTML if elements are qualified.

I thought a quick fix is to modify the schema for XHTML namespace to make validator accept embeded XHTML elements unqualified. That is, to change XHTML's schema xhtml1-strict.xsd (only locally - the system won't reach out to w3.org website to get the official xsd file), by changing the root <schema> element from elementFormDefault="qualified" to elementFormDefault="unqualified".

To my surprise, the change has no effects. The validator (xmllint) still demand
 to be qualified:

element p: Schemas validity error : Element 'p': This element is not expected. Expected is one of ( {http://www.w3.org/1999/xhtml}p, {http://www.w3.org/1999/xhtml}div, {http://www.w3.org/1999/xhtml}fieldset, {http://www.w3.org/1999/xhtml}table, {http://www.w3.org/1999/xhtml}noscript, {http://www.w3.org/1999/xhtml}h1, {http://www.w3.org/1999/xhtml}h2, {http://www.w3.org/1999/xhtml}h3, {http://www.w3.org/1999/xhtml}h4, {http://www.w3.org/1999/xhtml}h5 )

Ruled-out probable causes

I thought maybe I was editing a xhtml1-strict.xsd not used by the system, so I edited parts of it like changing "div" to "vid" and observe the resulting error. That way I verified that the file I edit is the file used by the validator.

I also tried to change the other schemas imported in the product namespace and verified that changing elementFormDefault in any imported schema does have the anticipated effect on the way validator requires the children element to be qualified/unqualified, and that effect is clearly missing when I do the same to xhtml1-strict.xsd, so there is something magical about xhtml schema.

答:
(This is a comment on your answer, but too long to submit as a comment).

Answering the point that you "spent a lot of time trying to search in the defining documents" - yes, it's hard to navigate the W3C XSD specification, but it's actually pretty clear when you know where to look and know the correct terminology.

Using the 1.0 spec, section 3.3.2 has a sub section "If the <element> element information item has <schema> as its parent, the corresponding schema component is as follows:" that says the target namespace is that of the schema.

It then has another section "otherwise if the <element> element information item has <complexType> or <group> as an ancestor and the ref [attribute] is absent" which says "If form is present and its ·actual value· is qualified, or if form is absent and the ·actual value· of elementFormDefault on the <schema> ancestor is qualified, then the [target namespace is the] ·actual value· of the targetNamespace [attribute] of the parent <schema> element information item, or ·absent· if there is none, otherwise ·absent·.

Body:
Introduction

elementFormDefault="unqualified" on the <schema> element sets a default form="unqualified" for the elements defined in that schema.

The following valid XML segment used a schema defined with elementFormDefault="unqualified"

<asnx:module xmlns:asnx="urn:ietf:params:xml:ns:asnx">
   <sequence/>
</asnx:module>

The <sequence> element doesn't have namespace qualification because the schema was defined like this:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
       xmlns="urn:ietf:params:xml:ns:asnx"
       targetNamespace="urn:ietf:params:xml:ns:asnx"
       elementFormDefault="unqualified">
....

Abnormality

In a specific system I'm working with, modularised XHTML was used in the descriptive part of XML data, like this:

<product:description>
 <xhtml:div>
  <xhtml:p>This product is discontinued</xhtml:p>
 </xhtml:div>
</product:description>

Due to the way the software application I'm working on was assembled, it won't work unless it's written in this form:

<product:description>
  <xhtml:div>

This product is discontinued

  </xhtml:div>
</product:description>

That is, the software application fails to process the embedded XHTML if elements are qualified.

I thought a quick fix is to modify the schema for XHTML namespace to make validator accept embeded XHTML elements unqualified. That is, to change XHTML's schema xhtml1-strict.xsd (only locally - the system won't reach out to w3.org website to get the official xsd file), by changing the root <schema> element from elementFormDefault="qualified" to elementFormDefault="unqualified".

To my surprise, the change has no effects. The validator (xmllint) still demand
 to be qualified:

element p: Schemas validity error : Element 'p': This element is not expected. Expected is one of ( {http://www.w3.org/1999/xhtml}p, {http://www.w3.org/1999/xhtml}div, {http://www.w3.org/1999/xhtml}fieldset, {http://www.w3.org/1999/xhtml}table, {http://www.w3.org/1999/xhtml}noscript, {http://www.w3.org/1999/xhtml}h1, {http://www.w3.org/1999/xhtml}h2, {http://www.w3.org/1999/xhtml}h3, {http://www.w3.org/1999/xhtml}h4, {http://www.w3.org/1999/xhtml}h5 )

Ruled-out probable causes

I thought maybe I was editing a xhtml1-strict.xsd not used by the system, so I edited parts of it like changing "div" to "vid" and observe the resulting error. That way I verified that the file I edit is the file used by the validator.

I also tried to change the other schemas imported in the product namespace and verified that changing elementFormDefault in any imported schema does have the anticipated effect on the way validator requires the children element to be qualified/unqualified, and that effect is clearly missing when I do the same to xhtml1-strict.xsd, so there is something magical about xhtml schema.