问:
cannot restore recyclerview scroll position after rotation
I made a recyclerview grid that gets filled with data from an api once a user presses a button. After rotating the screen, the scroll position is briefly restored before scrolling back up to the top of the grid.  I am using this tutorial to preserve my scroll position:

```<code>class MainActivity : AppCompatActivity(), Main.View {
    private lateinit var carAdapter: CarAdapter
    private lateinit var presenter: Main.MainPresenter
    private lateinit var cars: ArrayList<Car?>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        carsAdapter = CarsAdapter(mutableListOf())
        // line suggested by androiddevelopers article
        carsAdapter.stateRestorationPolicy =
        RecyclerView.Adapter.StateRestorationPolicy.PREVENT_WHEN_EMPTY

        gridRV.layoutManager = GridLayoutManager(this, 3)
        gridRV.adapter = carsAdapter
        if (savedInstanceState != null) {
            cars = savedInstanceState.getParcelableArrayList<Car?>(CARS_ARG)
                    as ArrayList<Car?>
            carsAdapter.cars = cars
            carsAdapter.notifyDataSetChanged()
        }
        presenter = Main.MainPresenter(this, CarService(R.string.api_ul))
        search_button.setOnClickListener { presenter.onSearchClick() }
    }

    // presenter.onSearchClick() calls this
    override fun displayGrid() {
        this.cars = cars
        carsAdapter.cars = cars
        carsAdapter.notifyDataSetChanged()
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        outState.putParcelableArrayList(CARS_ARG, cars)
    }
}
</code>```

I also tried saving the layout state in this tutorial.

My manifest entry is:

```<code><activity
    android:name=".main.MainActivity"
    android:launchMode="singleTop">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>
</code>```

答:
Well the screen rotation is a configuration change, that causes the activity to recreate and thus you lose the position of scroll.

Although you can save the position and restore.

You can also make your activity ignore the configuration change so that it doesn't recreate. By doing this in manifest:

```<code><activity
    android:name=".main.MainActivity"
    android:configChanges="keyboardHidden|orientation|screenSize"
    android:launchMode="singleTop">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>
</code>```

Body:
I made a recyclerview grid that gets filled with data from an api once a user presses a button. After rotating the screen, the scroll position is briefly restored before scrolling back up to the top of the grid.  I am using this tutorial to preserve my scroll position:

class MainActivity : AppCompatActivity(), Main.View {
    private lateinit var carAdapter: CarAdapter
    private lateinit var presenter: Main.MainPresenter
    private lateinit var cars: ArrayList<Car?>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        carsAdapter = CarsAdapter(mutableListOf())
        // line suggested by androiddevelopers article
        carsAdapter.stateRestorationPolicy =
        RecyclerView.Adapter.StateRestorationPolicy.PREVENT_WHEN_EMPTY

        gridRV.layoutManager = GridLayoutManager(this, 3)
        gridRV.adapter = carsAdapter
        if (savedInstanceState != null) {
            cars = savedInstanceState.getParcelableArrayList<Car?>(CARS_ARG)
                    as ArrayList<Car?>
            carsAdapter.cars = cars
            carsAdapter.notifyDataSetChanged()
        }
        presenter = Main.MainPresenter(this, CarService(R.string.api_ul))
        search_button.setOnClickListener { presenter.onSearchClick() }
    }

    // presenter.onSearchClick() calls this
    override fun displayGrid() {
        this.cars = cars
        carsAdapter.cars = cars
        carsAdapter.notifyDataSetChanged()
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        outState.putParcelableArrayList(CARS_ARG, cars)
    }
}

I also tried saving the layout state in this tutorial.

My manifest entry is:

<activity
    android:name=".main.MainActivity"
    android:launchMode="singleTop">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

Body:
Well the screen rotation is a configuration change, that causes the activity to recreate and thus you lose the position of scroll.

Although you can save the position and restore.

You can also make your activity ignore the configuration change so that it doesn't recreate. By doing this in manifest:

<activity
    android:name=".main.MainActivity"
    android:configChanges="keyboardHidden|orientation|screenSize"
    android:launchMode="singleTop">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>


来源: stackexchange

问:
Opening Modal from different component
CardComponent:

```<code>export class Card extends Component<Prop, State> {
      state = {
        isCancelModalOpen: false,
      };

      marketService = new MarketService();
      deleteMarket = () => {
        this.marketService
          .deleteMar()
          .then((response) => {
          })
          .catch((error) => {
            console.log(error);
          });
      };
      handleModalToggle = () => {
        this.setState(({ isCancelModalOpen }) => ({
          isCancelModalOpen: !isCancelModalOpen,
        }));
      };

      render() {
        const {isCancelModalOpen, isDropdownOpen } = this.state;
        const dropdownItems = [
          <DropdownItem
            key="action"
            component="button"
            onClick={this.handleModalToggle}
          >
            Delete
          </DropdownItem>
        ];
        return (
            {this.CancelModal.map((listing) => (
        <DeleteModal handleModal={this.handleModalToggle}
        deleteProd = {this.deleteProduct}
        description = {listing.description} ></DeleteModal>
            ))}
        );
      }
    }
</code>```

DeleteModal Component:

```<code>interface Prop {
 description: string;
 handleModal: Function;
 deleteProd: Function;
}
class DeleteModal extends Component<Prop, State> {
  state = {
    deleteConfirmModel: false
  };

  render() {
    const { deleteConfirmModel } = this.state;
const {description} = this.props;
    return (

        <Modal
          isSmall
         title="Confirmation"
         isOpen={deleteConfirmModel}
        onClose={() => this.props.handleModal}
        showClose = {false}
          actions={[
            <Button
              key="confirm"
              variant="primary"
              onClick={() => this.props.deleteProd}
            >
              Delete
            </Button>,
              <Button key="cancel" variant="link"  onClick={() => this.props.handleModal}>
              Cancel
            </Button>

          ]}
        >
{description}
        </Modal>

    );
  }
}

export default DeleteModal;
</code>```

I want DeleteModal component to get open on click of Dropdown Delete button available in Card component. There is no error in the code, still I am not able to trigger modal on click of Dropdown from Card component. Can anyone help me with what's wrong with the code?

答:
So I found the solution to call the modal from different component:
 In the card component: to call deleteModal component:

```<code><DeleteModal
      displayModal={deleteModalOpen}
      handleModal={this.handleModalToggle}
      description="Are you sure you want to delete"
    />
</code>```

DisplayModal, handleModal,decription will be props in DeleteModal component:

DeleteModal:

```<code>interface Prop {
      displayModal: boolean;
      handleModal: Function;
      description: string;
    }
 <Modal
          isSmall
          title="Confirmation"
          isOpen={this.props.displayModal}
          onClose={() => this.props.handleModal()}
          showClose={false}
          actions={[
            <Button
              key="cancel"
              variant="link"
              onClick={() => this.props.handleModal()}
            >
              Cancel
            </Button>,
          ]}
        >
          {this.props.description}
        </Modal>
</code>```

ContentLicense: CC BY-SA 4.0

Title: Opening Modal from different component

Body:
CardComponent:

export class Card extends Component<Prop, State> {
      state = {
        isCancelModalOpen: false,
      };

      marketService = new MarketService();
      deleteMarket = () => {
        this.marketService
          .deleteMar()
          .then((response) => {
          })
          .catch((error) => {
            console.log(error);
          });
      };
      handleModalToggle = () => {
        this.setState(({ isCancelModalOpen }) => ({
          isCancelModalOpen: !isCancelModalOpen,
        }));
      };

      render() {
        const {isCancelModalOpen, isDropdownOpen } = this.state;
        const dropdownItems = [
          <DropdownItem
            key="action"
            component="button"
            onClick={this.handleModalToggle}
          >
            Delete
          </DropdownItem>
        ];
        return (
            {this.CancelModal.map((listing) => (
        <DeleteModal handleModal={this.handleModalToggle}
        deleteProd = {this.deleteProduct}
        description = {listing.description} ></DeleteModal>
            ))}
        );
      }
    }

DeleteModal Component:

interface Prop {
 description: string;
 handleModal: Function;
 deleteProd: Function;
}
class DeleteModal extends Component<Prop, State> {
  state = {
    deleteConfirmModel: false
  };

  render() {
    const { deleteConfirmModel } = this.state;
const {description} = this.props;
    return (

        <Modal
          isSmall
         title="Confirmation"
         isOpen={deleteConfirmModel}
        onClose={() => this.props.handleModal}
        showClose = {false}
          actions={[
            <Button
              key="confirm"
              variant="primary"
              onClick={() => this.props.deleteProd}
            >
              Delete
            </Button>,
              <Button key="cancel" variant="link"  onClick={() => this.props.handleModal}>
              Cancel
            </Button>

          ]}
        >
{description}
        </Modal>

    );
  }
}

export default DeleteModal;

I want DeleteModal component to get open on click of Dropdown Delete button available in Card component. There is no error in the code, still I am not able to trigger modal on click of Dropdown from Card component. Can anyone help me with what's wrong with the code?

Body:
So I found the solution to call the modal from different component:
 In the card component: to call deleteModal component:

<DeleteModal
      displayModal={deleteModalOpen}
      handleModal={this.handleModalToggle}
      description="Are you sure you want to delete"
    />

DisplayModal, handleModal,decription will be props in DeleteModal component:

DeleteModal:

interface Prop {
      displayModal: boolean;
      handleModal: Function;
      description: string;
    }
 <Modal
          isSmall
          title="Confirmation"
          isOpen={this.props.displayModal}
          onClose={() => this.props.handleModal()}
          showClose={false}
          actions={[
            <Button
              key="cancel"
              variant="link"
              onClick={() => this.props.handleModal()}
            >
              Cancel
            </Button>,
          ]}
        >
          {this.props.description}
        </Modal>


问:
c# List view focus
I have a problem in focusing the listview.In my form i have a listview which contains two columns(Question_text, question_id).When a button is get clicked(Show button) a dialog box is get opened and it show show the selected question_text and question_id.Right now i am able to show the information in the dialog box.But the problem only occurs only when i close the dialog box,the focus on the list view is gone.I what the focus to remain on the same item of list view after closing the dialog box.Can any one help me.Thanks in advance.

Ok this is my code.

There i am reading getting the selected item question id using the listview1_selectionIndexchanged();

```<code>     private void btnAdd_Question_Click(object sender, EventArgs e)
    {
        //Add Question Dialog box is shown
        add.ShowDialog();
    }

    private void btnEdit_Question_Click(object sender, EventArgs e)
    {
        //Getting the listview selected Item
        for (int i = 0; i < listView1.SelectedItems.Count; i++)
        {

            String a1 = listView1.SelectedItems[i].Text;
            int b1 = listView1.SelectedIndices[i];
            //Open the connection
             myConnection = new SqlConnection(@"User ID=sa;Password=password123;Initial Catalog=dishtv;Persist Security Info=True;Data Source=ENMEDIA-EA6278E\ENMEDIA");
            try
            {

                myConnection.Open();
                String start_time = string.Format("SELECT Question_text  from otvtbl_question where question_id={0}", a1);
                com = new SqlCommand(start_time, myConnection);
                dr = com.ExecuteReader();

                if (dr.HasRows)
                {
                    while (dr.Read())
                    {
                        now = DateTime.Now;
                     //Getting the start time and convert into date time Format
                       String a = dr["question_id"].ToString();
                       date = Convert.ToDateTime(a);

                    }
                    myConnection.Close();
                }
                //If data and time is greater then current time then allow the
               // Edit question dialog box to launch
                if (date > now)
                {
                    edit.question_id = a1;

                    edit.ShowDialog();
                }
                else
                {
                    MessageBox.Show("you cant edit this question");
                }

            }

            //Catch the Exceptional error
            catch (Exception ex)
            {
                MessageBox.Show("Error while Deleteing the Data" + ex);
            }

        }

    }
</code>```

After that i am calling a another form and showing the information.Here i created a class edit.showdialog() to launch a dialog box.

In my edit dialog box:

Here I am passing  the question_id from the main form to dialog box and displaying the question_text in the dialog box.When the cancel button is get clicked then the dialog box get closed.But the focus is not remaining on the same item in list view.Once again i click on edit button for editing without selecting the item in list view it select the previous one automatically without showing the focus on it.

public String question_id;

private void Edit_Question_Load(object sender, EventArgs e)
        {

```<code>        EditData();
    }

   public void EditData()
    {
         myConnection = new SqlConnection(@"User ID=sa;Password=password123;Initial Catalog=dishtv;Persist Security Info=True;Data Source=ENMEDIA-EA6278E\ENMEDIA");
           myConnection.Open();
            String question = string.Format("SELECT question_text from otvtbl_question where question_id={0}", question_id);
            com = new SqlCommand(question, myConnection);
            dr = com.ExecuteReader();

            if (dr.HasRows)
            {
                while (dr.Read())
                {
                    //Assign to your textbox here
                    txtQuestion.Text = dr["question_text"].ToString();
                }
            }
            myConnection.Close();

     private void btnCancel_Click_1(object sender, EventArgs e)
    {

        this.Close();
    }
</code>```

答:
When ShowDialog method is called, the code following it is not executed until after the dialog box is closed. So, you can set the focus to the ListView in next line.

Eg:

```<code>private void btnAdd_Question_Click(object sender, EventArgs e)
    {
        //Add Question Dialog box is shown
        add.ShowDialog();
        ListView.Focus();
    }
</code>```

ContentLicense: CC BY-SA 3.0

Title: c# List view focus

Body:
I have a problem in focusing the listview.In my form i have a listview which contains two columns(Question_text, question_id).When a button is get clicked(Show button) a dialog box is get opened and it show show the selected question_text and question_id.Right now i am able to show the information in the dialog box.But the problem only occurs only when i close the dialog box,the focus on the list view is gone.I what the focus to remain on the same item of list view after closing the dialog box.Can any one help me.Thanks in advance.

Ok this is my code.

There i am reading getting the selected item question id using the listview1_selectionIndexchanged();

     private void btnAdd_Question_Click(object sender, EventArgs e)
    {
        //Add Question Dialog box is shown
        add.ShowDialog();
    }

    private void btnEdit_Question_Click(object sender, EventArgs e)
    {
        //Getting the listview selected Item
        for (int i = 0; i < listView1.SelectedItems.Count; i++)
        {

            String a1 = listView1.SelectedItems[i].Text;
            int b1 = listView1.SelectedIndices[i];
            //Open the connection
             myConnection = new SqlConnection(@"User ID=sa;Password=password123;Initial Catalog=dishtv;Persist Security Info=True;Data Source=ENMEDIA-EA6278E\ENMEDIA");
            try
            {

                myConnection.Open();
                String start_time = string.Format("SELECT Question_text  from otvtbl_question where question_id={0}", a1);
                com = new SqlCommand(start_time, myConnection);
                dr = com.ExecuteReader();

                if (dr.HasRows)
                {
                    while (dr.Read())
                    {
                        now = DateTime.Now;
                     //Getting the start time and convert into date time Format
                       String a = dr["question_id"].ToString();
                       date = Convert.ToDateTime(a);

                    }
                    myConnection.Close();
                }
                //If data and time is greater then current time then allow the
               // Edit question dialog box to launch
                if (date > now)
                {
                    edit.question_id = a1;

                    edit.ShowDialog();
                }
                else
                {
                    MessageBox.Show("you cant edit this question");
                }

            }

            //Catch the Exceptional error
            catch (Exception ex)
            {
                MessageBox.Show("Error while Deleteing the Data" + ex);
            }

        }

    }

After that i am calling a another form and showing the information.Here i created a class edit.showdialog() to launch a dialog box.

In my edit dialog box:

Here I am passing  the question_id from the main form to dialog box and displaying the question_text in the dialog box.When the cancel button is get clicked then the dialog box get closed.But the focus is not remaining on the same item in list view.Once again i click on edit button for editing without selecting the item in list view it select the previous one automatically without showing the focus on it.

public String question_id;

private void Edit_Question_Load(object sender, EventArgs e)
        {

        EditData();
    }

   public void EditData()
    {
         myConnection = new SqlConnection(@"User ID=sa;Password=password123;Initial Catalog=dishtv;Persist Security Info=True;Data Source=ENMEDIA-EA6278E\ENMEDIA");
           myConnection.Open();
            String question = string.Format("SELECT question_text from otvtbl_question where question_id={0}", question_id);
            com = new SqlCommand(question, myConnection);
            dr = com.ExecuteReader();

            if (dr.HasRows)
            {
                while (dr.Read())
                {
                    //Assign to your textbox here
                    txtQuestion.Text = dr["question_text"].ToString();
                }
            }
            myConnection.Close();

     private void btnCancel_Click_1(object sender, EventArgs e)
    {

        this.Close();
    }

Body:
When ShowDialog method is called, the code following it is not executed until after the dialog box is closed. So, you can set the focus to the ListView in next line.

Eg:

private void btnAdd_Question_Click(object sender, EventArgs e)
    {
        //Add Question Dialog box is shown
        add.ShowDialog();
        ListView.Focus();
    }


问:
How to check which checkboxes are checked in PyQt5
I'm trying to create a simple desktop app that gets an IP address and show it's location using a REST API (including country, city, isp, regionName and timezone). I have 5 checkboxes in my form so that the user can decide what data will be shown (city, country, isp etc).

The way i did it was by using 5 If statements for each checkbox which don't seem a good way of doing it.
Also in order to set the returned values from API to the lineEdits, again i had to use 5 if statements for each lineEdit.

Is there any other way of checking which checkboxes are checked so that i can call the API with the data related to those checkboxes?
My snippet:

```<code>def set_params(self,IP):
        try:
            socket.inet_aton("%s" %IP)
        except:
            pass #for now

        else:

            if self.ui.checkBox_City.isChecked():

                city = "city"
            else:
                city = None

            if self.ui.checkBox_Country.isChecked():
                country = "country"
            else:
                country = None

            if self.ui.checkBox_Rname.isChecked():
                Rname = "regionName"
            else:
                Rname = None

            if self.ui.checkBox_ISP.isChecked():
                ISP = "isp"
            else:
                ISP = None

            if self.ui.checkBox_Time.isChecked():
                time = "timezone"
            else:
                time = None

            param = {"fields": "{},{},{},{},{}".format(country,city,ISP,Rname,time)}

            r = requests.get("http://ip-api.com/json/{}".format(IP), params=param)

            resdict = r.json()
            #print(resdict)

            if "country" in resdict.keys():
                self.ui.lineEdit_Country.setText(resdict["country"])

            if "city" in resdict.keys():
                self.ui.lineEdit_City.setText(resdict["city"])

            if "isp" in resdict.keys():
                self.ui.lineEdit_ISP.setText(resdict["isp"])

            if "timezone" in resdict.keys():
                self.ui.lineEdit_Time.setText(resdict["timezone"])

            if "regionName" in resdict.keys():
                self.ui.lineEdit_Country.setText(resdict["regionName"])
</code>```

答:
You could store the check boxes and the line edits in a dictionaries using "city", "country", etc. as keys and use these in set_params to check the state of the check boxes and set the text of the line edits. So, after you setup the ui (presumably somewhere in __init__) you would set

```<code>self.check_boxes = {'country':self.ui.checkbox_Country, 'city':self.ui.checkbox_City,
                    'isp':self.ui.checkbox_ISP, 'regionName':self.ui.checkbox_Rname,
                    'timezone':self.ui.checkbox_Time}
self.line_edits = {'country':self.ui.lineEdit_Country, 'city':self.ui.lineEdit_City,
                   'isp':self.ui.lineEdit_ISP, 'regionName':self.ui.lineEdit_Rname,
                   'timezone':self.ui.lineEdit_Time}
</code>```

In set_params(self,IP) you could then use these dicts according to

```<code>def set_params(self.IP):
    try:
        ....
    except:
        ....
    else:
        # iterate over dict with check boxes to check their state
        values = [key for key, check_box in self.check_boxes.items() if check_box.isChecked()]
        param = {"fields": ','.join(values)}

        r = requests.get("http://ip-api.com/json/{}".format(IP), params=param)

        resdict = r.json()

        # iterate over dict with line edits and set the text of the line edit if the corresponding key is in resdict.
        for key, line_edit in self.line_edits.items():
            line_edit.clear()
            if key in resdict.keys():
                line_edit.setText(resdict[key])
</code>```

Body:
I'm trying to create a simple desktop app that gets an IP address and show it's location using a REST API (including country, city, isp, regionName and timezone). I have 5 checkboxes in my form so that the user can decide what data will be shown (city, country, isp etc).

The way i did it was by using 5 If statements for each checkbox which don't seem a good way of doing it.
Also in order to set the returned values from API to the lineEdits, again i had to use 5 if statements for each lineEdit.

Is there any other way of checking which checkboxes are checked so that i can call the API with the data related to those checkboxes?
My snippet:

def set_params(self,IP):
        try:
            socket.inet_aton("%s" %IP)
        except:
            pass #for now

        else:

            if self.ui.checkBox_City.isChecked():

                city = "city"
            else:
                city = None

            if self.ui.checkBox_Country.isChecked():
                country = "country"
            else:
                country = None

            if self.ui.checkBox_Rname.isChecked():
                Rname = "regionName"
            else:
                Rname = None

            if self.ui.checkBox_ISP.isChecked():
                ISP = "isp"
            else:
                ISP = None

            if self.ui.checkBox_Time.isChecked():
                time = "timezone"
            else:
                time = None

            param = {"fields": "{},{},{},{},{}".format(country,city,ISP,Rname,time)}

            r = requests.get("http://ip-api.com/json/{}".format(IP), params=param)

            resdict = r.json()
            #print(resdict)

            if "country" in resdict.keys():
                self.ui.lineEdit_Country.setText(resdict["country"])

            if "city" in resdict.keys():
                self.ui.lineEdit_City.setText(resdict["city"])

            if "isp" in resdict.keys():
                self.ui.lineEdit_ISP.setText(resdict["isp"])

            if "timezone" in resdict.keys():
                self.ui.lineEdit_Time.setText(resdict["timezone"])

            if "regionName" in resdict.keys():
                self.ui.lineEdit_Country.setText(resdict["regionName"])

Body:
You could store the check boxes and the line edits in a dictionaries using "city", "country", etc. as keys and use these in set_params to check the state of the check boxes and set the text of the line edits. So, after you setup the ui (presumably somewhere in __init__) you would set

self.check_boxes = {'country':self.ui.checkbox_Country, 'city':self.ui.checkbox_City,
                    'isp':self.ui.checkbox_ISP, 'regionName':self.ui.checkbox_Rname,
                    'timezone':self.ui.checkbox_Time}
self.line_edits = {'country':self.ui.lineEdit_Country, 'city':self.ui.lineEdit_City,
                   'isp':self.ui.lineEdit_ISP, 'regionName':self.ui.lineEdit_Rname,
                   'timezone':self.ui.lineEdit_Time}

In set_params(self,IP) you could then use these dicts according to

def set_params(self.IP):
    try:
        ....
    except:
        ....
    else:
        # iterate over dict with check boxes to check their state
        values = [key for key, check_box in self.check_boxes.items() if check_box.isChecked()]
        param = {"fields": ','.join(values)}

        r = requests.get("http://ip-api.com/json/{}".format(IP), params=param)

        resdict = r.json()

        # iterate over dict with line edits and set the text of the line edit if the corresponding key is in resdict.
        for key, line_edit in self.line_edits.items():
            line_edit.clear()
            if key in resdict.keys():
                line_edit.setText(resdict[key])


问:
Is there a way to read and write on multiple text files in a folder using Python?
I am trying to retrieve several text files from a folder. Afterwards, I am trying to read all of the files within the directory to which I then append a blank line at the top of each file.

However, once I run the program it does not execute what I desire. This is the code:

```<code>import os

folderPath = "./textFiles"

def myFilesAddEmptyLine():
    for file in os.listdir(folderPath):
        if file.endswith(".txt"):
            with open(file, "r+") as myFile:
                # print(myFile)
                # ^ This returns "<_io.TextIOWrapper name='test.txt' mode='r+' encoding='cp1252'>" in the console.
                fileContent = myFile.read()
                myFile.seek(0, 0)
                myFile.write("\n" + fileContent)

myFilesAddEmptyLine()
</code>```

On the other hand, if I read the file directly without trying to automate the process using os, it executes what I am trying to achieve flawlessly. Therefore, the following piece of code opens the file and appends a blank line at the top of the file.

```<code>def myFilesAddEmptyLine():
    with open("test.txt", "r+") as myFile:
        fileContent = myFile.read()
        myFile.seek(0, 0)
        myFile.write("\n" + fileContent)

myFilesAddEmptyLine()
</code>```

Could anyone kindly outline what the issue with the first piece of code is? Thanks in advance!

答:
As user @asylumax pointed out in the comments, this:

```<code>import os

folderPath = "./textFiles"

def myFilesAddEmptyLine():
    for file in os.listdir(folderPath):
        if file.endswith(".txt"):
            with open(file, "r+") as myFile:
                fileContent = myFile.read()
                myFile.seek(0, 0)
                myFile.write("\n" + fileContent)

myFilesAddEmptyLine()
</code>```

Needed to be changed to this:

```<code>import os

folderPath = "./textFiles"

def myFilesAddEmptyLine():
    for file in os.listdir(folderPath):
        if file.endswith(".txt"):
            with open(os.path.join(folderPath, file), "r+") as myFile: #This is the line that needed changing.
                fileContent = myFile.read()
                myFile.seek(0, 0)
                myFile.write("\n" + fileContent)
                print(myFile)

myFilesAddEmptyLine()
</code>```

Body:
I am trying to retrieve several text files from a folder. Afterwards, I am trying to read all of the files within the directory to which I then append a blank line at the top of each file.

However, once I run the program it does not execute what I desire. This is the code:

import os

folderPath = "./textFiles"

def myFilesAddEmptyLine():
    for file in os.listdir(folderPath):
        if file.endswith(".txt"):
            with open(file, "r+") as myFile:
                # print(myFile)
                # ^ This returns "<_io.TextIOWrapper name='test.txt' mode='r+' encoding='cp1252'>" in the console.
                fileContent = myFile.read()
                myFile.seek(0, 0)
                myFile.write("\n" + fileContent)

myFilesAddEmptyLine()

On the other hand, if I read the file directly without trying to automate the process using os, it executes what I am trying to achieve flawlessly. Therefore, the following piece of code opens the file and appends a blank line at the top of the file.

def myFilesAddEmptyLine():
    with open("test.txt", "r+") as myFile:
        fileContent = myFile.read()
        myFile.seek(0, 0)
        myFile.write("\n" + fileContent)

myFilesAddEmptyLine()

Could anyone kindly outline what the issue with the first piece of code is? Thanks in advance!

Body:
As user @asylumax pointed out in the comments, this:

import os

folderPath = "./textFiles"

def myFilesAddEmptyLine():
    for file in os.listdir(folderPath):
        if file.endswith(".txt"):
            with open(file, "r+") as myFile:
                fileContent = myFile.read()
                myFile.seek(0, 0)
                myFile.write("\n" + fileContent)

myFilesAddEmptyLine()

Needed to be changed to this:

import os

folderPath = "./textFiles"

def myFilesAddEmptyLine():
    for file in os.listdir(folderPath):
        if file.endswith(".txt"):
            with open(os.path.join(folderPath, file), "r+") as myFile: #This is the line that needed changing.
                fileContent = myFile.read()
                myFile.seek(0, 0)
                myFile.write("\n" + fileContent)
                print(myFile)

myFilesAddEmptyLine()


问:
How to turn off logging buffer to get logs in real time with python command line tool?
I have a command line tool which produces plenty of logs. I want these logs to be sent to stdout as soon as they're made. Right now, the program finishes everything (which can take several minutes), and then sends everything to stdout all at once. This means that currently, the user is not aware of whats going on internally, and I want to change that.

So far I've tried passing the -u flag as a command line argument, but that doesn't change anything. I have a feeling I need to use logging.handlers.BufferingHandler with flush() in some capacity, but I haven't been able to figure it out through tinkering.

def some_func(flag: bool):
    if flag:
        logging.info('flag is truthy')
        return
    logging.warning('flag is falsy')
```

I'd like the above function to show the user one of those logs as soon as the log is created.
Note: currently I set the logging level with logging.root.setLevel(logging.INFO).

Thanks!

答: you have to set environmental variable PYTHONUNBUFFERED=1.</p>

Body:
I have a command line tool which produces plenty of logs. I want these logs to be sent to stdout as soon as they're made. Right now, the program finishes everything (which can take several minutes), and then sends everything to stdout all at once. This means that currently, the user is not aware of whats going on internally, and I want to change that.

So far I've tried passing the -u flag as a command line argument, but that doesn't change anything. I have a feeling I need to use logging.handlers.BufferingHandler with flush() in some capacity, but I haven't been able to figure it out through tinkering.

def some_func(flag: bool):
    if flag:
        logging.info('flag is truthy')
        return
    logging.warning('flag is falsy')

I'd like the above function to show the user one of those logs as soon as the log is created.
Note: currently I set the logging level with logging.root.setLevel(logging.INFO).

Thanks!


问:
How to pass correlated value in next request in Gatling script
How can I replace "details1" in "request_2" with correlated value "SynchToken" from "request_1". I am trying to replace with ${SynchToken} but it is not reflecting the correlated value.</p>

```<code>val Transaction_Name_1 = group("Transaction_Name_1") {
  exec(http("request_1")
    .get(session => "/abc/details1?_=" + System.currentTimeMillis())
    .check(regex("""name="SYNCHRONIZER_TOKEN" value="(.*?)"""").saveAs("SynchToken")))
  .pause(5)
  .exec(http("request_2")
    .get(session => "/abc/details1?_=" + System.currentTimeMillis()))
}
</code>```

答:
You should really spend some time reading the documentation.
Here, you need to use the Session API.

exec(http("request_2")
    .get(session => "/abc/" + session("SynchToken").as[String] + "?_=" + System.currentTimeMillis()))
```

Body:
How can I replace "details1" in "request_2" with correlated value "SynchToken" from "request_1". I am trying to replace with ${SynchToken} but it is not reflecting the correlated value.

val Transaction_Name_1 = group("Transaction_Name_1") {
  exec(http("request_1")
    .get(session => "/abc/details1?_=" + System.currentTimeMillis())
    .check(regex("""name="SYNCHRONIZER_TOKEN" value="(.*?)"""").saveAs("SynchToken")))
  .pause(5)
  .exec(http("request_2")
    .get(session => "/abc/details1?_=" + System.currentTimeMillis()))
}


问:
Comparing Objects Realm Swift
I'm trying to compare 2 Realm Objects in Swift.

```<code>// Object 1 Prints:

currentObject:  Optional(ObjectClass {
    order = 0;
    number = 010;
    temp = 903;
    state = 6;

})

// Object 2 Prints:

 lastObject:  Optional(ObjectClass {
        order = 0;
        number = 010;
        temp = 903;
        state = 6;

    })
</code>```

Obviously the values are equal. But the Objects are not.

```<code>print(lastObject?.number == currentObject?.number) // Prints True
print(lastObject == currentObject) // Prints False
</code>```

I tried to implement equatable in the object class. But Xcode isn't liking it due to Realm.

Redundant conformance of 'ObjectClass' to protocol 'Equatable'

How can I compare the variables of lastObject to currentObject? I imagine theres a better way than checking each object's variable against each other. But I don't know what it is.

Object Class:

```<code>import UIKit
import RealmSwift

class ObjectClass: Object {

    @objc dynamic var order = 0
    @objc dynamic var number = ""
    @objc dynamic var temp = 0
    @objc dynamic var state = 1

}
</code>```

答:
tl;dr

Change your object class to include a primary key and == will work to see if they are the same object. If they are the same object then their property variables will always be the same

```<code>class ObjectClass: Object {
    @objc dynamic var object_id = UUID().uuidString
    @objc dynamic var order = 0
    @objc dynamic var number = ""
    @objc dynamic var temp = 0
    @objc dynamic var state = 1

    override static func primaryKey() -> String? {
       return "object_id"
    }
}
</code>```

If you want to just compare the objects properties, then it's a straightforward property to property comparison (or implement isEqual and use == per the other answer)

Discussion

When comparing Realm objects we need to understand what we're comparing; are you looking too see if the objects properties have the same values or are you looking to see if they are the same objects?

If other words take a Realm object

```<code>class RealmObject: Object {
   @objc dynamic var text = ""
}
</code>```

if two objects are created

```<code>let o0 = RealmObject()
o0.text = "Hello"

let o1 = RealmObject()
o1.text = "Hello"
</code>```

and we compare the objects

```<code>print( o1 == o0 )
</code>```

will print false because o0 and o1 are two separate objects.

Whereas if we compare a property

```<code>print( o0.text == o1.text )
</code>```

would produce true because those properties are equal.

Along those same lines, after Realm 3.8 I believe you cannot test to see if two objects are the same using Equatable without a primary key. Check this out

```<code>let o0 = ObjectClass()
o0.order = 1

try! realm.write {
   realm.add(o0)
}

let o1 = realm.objects(ObjectClass.self).first!
print( o1 == o0 ) //prints false
print( o1.isSameObject(as: o0) ) //prints true
</code>```

However, if we add a primary key to the ObjectClass

```<code>class ObjectClass: Object {
    @objc dynamic var object_id = UUID().uuidString
    @objc dynamic var order = 0

    override static func primaryKey() -> String? {
        return "object_id"
    }
}
</code>```

and run the code again, they both print true

```<code>print( o1 == o0 ) //prints true
print( o1.isSameObject(as: o0) ) //prints true
</code>```

Title: Comparing Objects Realm Swift

Body:
I'm trying to compare 2 Realm Objects in Swift.

// Object 1 Prints:

currentObject:  Optional(ObjectClass {
    order = 0;
    number = 010;
    temp = 903;
    state = 6;

})

// Object 2 Prints:

 lastObject:  Optional(ObjectClass {
        order = 0;
        number = 010;
        temp = 903;
        state = 6;

    })

Obviously the values are equal. But the Objects are not.

print(lastObject?.number == currentObject?.number) // Prints True
print(lastObject == currentObject) // Prints False

I tried to implement equatable in the object class. But Xcode isn't liking it due to Realm.

Redundant conformance of 'ObjectClass' to protocol 'Equatable'

How can I compare the variables of lastObject to currentObject? I imagine theres a better way than checking each object's variable against each other. But I don't know what it is.

Object Class:

import UIKit
import RealmSwift

class ObjectClass: Object {

    @objc dynamic var order = 0
    @objc dynamic var number = ""
    @objc dynamic var temp = 0
    @objc dynamic var state = 1

}

Body:
tl;dr

Change your object class to include a primary key and == will work to see if they are the same object. If they are the same object then their property variables will always be the same

class ObjectClass: Object {
    @objc dynamic var object_id = UUID().uuidString
    @objc dynamic var order = 0
    @objc dynamic var number = ""
    @objc dynamic var temp = 0
    @objc dynamic var state = 1

    override static func primaryKey() -> String? {
       return "object_id"
    }
}

If you want to just compare the objects properties, then it's a straightforward property to property comparison (or implement isEqual and use == per the other answer)

Discussion

When comparing Realm objects we need to understand what we're comparing; are you looking too see if the objects properties have the same values or are you looking to see if they are the same objects?

If other words take a Realm object

class RealmObject: Object {
   @objc dynamic var text = ""
}

if two objects are created

let o0 = RealmObject()
o0.text = "Hello"

let o1 = RealmObject()
o1.text = "Hello"

and we compare the objects

print( o1 == o0 )

will print false because o0 and o1 are two separate objects.

Whereas if we compare a property

print( o0.text == o1.text )

would produce true because those properties are equal.

Along those same lines, after Realm 3.8 I believe you cannot test to see if two objects are the same using Equatable without a primary key. Check this out

let o0 = ObjectClass()
o0.order = 1

try! realm.write {
   realm.add(o0)
}

let o1 = realm.objects(ObjectClass.self).first!
print( o1 == o0 ) //prints false
print( o1.isSameObject(as: o0) ) //prints true

However, if we add a primary key to the ObjectClass

class ObjectClass: Object {
    @objc dynamic var object_id = UUID().uuidString
    @objc dynamic var order = 0

    override static func primaryKey() -> String? {
        return "object_id"
    }
}

and run the code again, they both print true

print( o1 == o0 ) //prints true
print( o1.isSameObject(as: o0) ) //prints true


问:
How can I automatically register 'controllers as services' in other directories in Symfony 5

Background

I want to use functional cohesion to organise my controllers.

This means that I will not have a Controllers/ directory, which makes it easy for the framework, but I will organise my code by use-case. An arbitrary example:

src/FetchLatestNews/Controller.php

src/FetchLatestNews/News.php

src/FetchLatestNews/NewsRepository.php

...etc

However, Symfony is set up by default to require all controllers in one place. See services.yaml:

    # controllers are imported separately to make sure services can be injected
    # as action arguments even if you don't extend any base controller class
    App\Controller\:
        resource: '../src/Controller'
        tags: ['controller.service_arguments']
```

Following the above template, I could just place the new src/FetchLatestNews/Controller in there and then add each new controller each time. However, I don't want to, nor should I have to, manually update this file every time I create a new use-case.

Question

How can I avoid this error:

maybe you forgot to register the controller as a service or missed tagging it with the "controller.service_arguments"

As a user I should not have to care about manually adding service_arguments or any other configuration. When I specify a route, the thing it's pointing to is therefore a controller.

The ideal workflow would be:

Create a controller wherever I like.

Add a route to routes.yaml referencing the controller.

That's it!

Is it possible to achieve this workflow in Symfony? It should be, because anything from a route --> some class will be a controller. Is there a way to use a regex, or some other solution?

Note: this answer suggests an empty interface sort of 'hack'. This is not ideal, either. Any alternatives?

答:
Please note, this answer has been updated again with new information.

The controller.service_arguments tag is only required to allow action injection. Stick with constructor injection and __invoke() and that's all you need.

The public addition below was a requirement, but it turns out you don't need a compiler pass for this and it can be all done at the services.yaml level. Therefore the only thing you need is the following:

```<code>services:
    _defaults:
        autowire: true
        autoconfigure: true
        public: true         // <---- This is the new additional config.
</code>```

Then, any class can be used in routes.yaml as a controller and construct injection works just fine.

Note: The original answer is below. Thanks to Jakumi for pointing me in the right direction.

You need to add a compiler pass to do two things. On booting and registering things for automatic dependency injection, if a class has Controller in the name:

Add the tag controller.service_arguments, which is the tag you'd normally need to add yourself manually in services.yaml to allow setter injection (you can ignore this if you don't care about setter injection)

Set the class to public, because Symfony had this weird idea that the concept of public or private anything is not to be inferred from the class access modifier (seriously?) - This is the important thing as Symfony will complain that the controller is private otherwise

Don't forget you don't have to use the logic for "Controller in name". It can be "Controller" is at the end of the class name which is probably better.

Anyway, first create a CompilerPass. Put it anywhere you want. I put mine next to Kernel.php.

use Symfony\Component\DependencyInjection\{Compiler\CompilerPassInterface, ContainerBuilder};

class ControllersAsServices implements CompilerPassInterface
{
    public function process(ContainerBuilder $container)
    {
        foreach ($container->getDefinitions() as $definition) {
            if (strpos($definition->getClass(), "Controller") === false) {
                continue;
            }

            $definition->addTag("controller.service_arguments");
            $definition->setPublic(true);
        }
    }
}
```

<p>Then in your <code>Kernel.php</code>, you need to tell it to use this new one. Override the protected function <code>build</code> and add your compiler passes as the documentation shows:</p>

<pre class="lang-php prettyprint-override"><code>protected function build(ContainerBuilder $container)
{
    $container->addCompilerPass(new ControllersAsServices, PassConfig::TYPE_BEFORE_OPTIMIZATION, -1);

    parent::build($container);
}
</code>```

Clear your dev cache. Nothing changed for me until I did this.

Now, any class with Controller in the name can be autowired as it should have been originally.

Original anser from Jakumi below:

I believe the best approach in your case would be to implement a CompilerPass, to add classes to the container:

https://symfony.com/doc/current/bundles/extension.html#adding-classes-to-compile

in the process there's probably a way to also add the tags.

Symfony caters to the controller.service_arguments tag via the RegisterControllerArgumentLocatorsPass, which resolves the constructor arguments and checks for some traits. If you get your compiler pass' priority higher, you could probably solve this problem easily then ...

Body:
Background

I want to use functional cohesion to organise my controllers.

This means that I will not have a Controllers/ directory, which makes it easy for the framework, but I will organise my code by use-case. An arbitrary example:

src/FetchLatestNews/Controller.php

src/FetchLatestNews/News.php

src/FetchLatestNews/NewsRepository.php

...etc

However, Symfony is set up by default to require all controllers in one place. See services.yaml:

    # controllers are imported separately to make sure services can be injected
    # as action arguments even if you don't extend any base controller class
    App\Controller\:
        resource: '../src/Controller'
        tags: ['controller.service_arguments']

Following the above template, I could just place the new src/FetchLatestNews/Controller in there and then add each new controller each time. However, I don't want to, nor should I have to, manually update this file every time I create a new use-case.

Question

How can I avoid this error:

maybe you forgot to register the controller as a service or missed tagging it with the "controller.service_arguments"

As a user I should not have to care about manually adding service_arguments or any other configuration. When I specify a route, the thing it's pointing to is therefore a controller.

The ideal workflow would be:

Create a controller wherever I like.

Add a route to routes.yaml referencing the controller.

That's it!

Is it possible to achieve this workflow in Symfony? It should be, because anything from a route --> some class will be a controller. Is there a way to use a regex, or some other solution?

Note: this answer suggests an empty interface sort of 'hack'. This is not ideal, either. Any alternatives?

Body:
Please note, this answer has been updated again with new information.

The controller.service_arguments tag is only required to allow action injection. Stick with constructor injection and __invoke() and that's all you need.

The public addition below was a requirement, but it turns out you don't need a compiler pass for this and it can be all done at the services.yaml level. Therefore the only thing you need is the following:

services:
    _defaults:
        autowire: true
        autoconfigure: true
        public: true         // <---- This is the new additional config.

Then, any class can be used in routes.yaml as a controller and construct injection works just fine.

Note: The original answer is below. Thanks to Jakumi for pointing me in the right direction.

You need to add a compiler pass to do two things. On booting and registering things for automatic dependency injection, if a class has Controller in the name:

Add the tag controller.service_arguments, which is the tag you'd normally need to add yourself manually in services.yaml to allow setter injection (you can ignore this if you don't care about setter injection)

Set the class to public, because Symfony had this weird idea that the concept of public or private anything is not to be inferred from the class access modifier (seriously?) - This is the important thing as Symfony will complain that the controller is private otherwise

Don't forget you don't have to use the logic for "Controller in name". It can be "Controller" is at the end of the class name which is probably better.

Anyway, first create a CompilerPass. Put it anywhere you want. I put mine next to Kernel.php.

use Symfony\Component\DependencyInjection\{Compiler\CompilerPassInterface, ContainerBuilder};

class ControllersAsServices implements CompilerPassInterface
{
    public function process(ContainerBuilder $container)
    {
        foreach ($container->getDefinitions() as $definition) {
            if (strpos($definition->getClass(), "Controller") === false) {
                continue;
            }

            $definition->addTag("controller.service_arguments");
            $definition->setPublic(true);
        }
    }
}

Then in your Kernel.php, you need to tell it to use this new one. Override the protected function build and add your compiler passes as the documentation shows:

protected function build(ContainerBuilder $container)
{
    $container->addCompilerPass(new ControllersAsServices, PassConfig::TYPE_BEFORE_OPTIMIZATION, -1);

    parent::build($container);
}

Clear your dev cache. Nothing changed for me until I did this.

Now, any class with Controller in the name can be autowired as it should have been originally.

Original anser from Jakumi below:

I believe the best approach in your case would be to implement a CompilerPass, to add classes to the container:

https://symfony.com/doc/current/bundles/extension.html#adding-classes-to-compile

in the process there's probably a way to also add the tags.

Symfony caters to the controller.service_arguments tag via the RegisterControllerArgumentLocatorsPass, which resolves the constructor arguments and checks for some traits. If you get your compiler pass' priority higher, you could probably solve this problem easily then ...


问:
Calculate first number in a list like BlackJack card game
I am just a newbie to python and my teacher tell me to create BlackJack game.And i stuck at the stage is count the total number of card.Here is what i got now, i need general solution for this one so i create a new python for this stage(just for testing)

```<code>list=["20","10","30"]
###I want to check first character of the number and add it together so i do this.

i = 0
while i < len(list):
      first_letter=list[i][0]
      i=i+1
      second_letter=list[i][0]
      total = first_letter+second_letter
      print(total)
####This is just an example for testing.
</code>```

And when i run the code it work somehow but also have this message :

```<code>
Traceback (most recent call last):

  File "D:\PYTHON BLACKJACK\00.py", line 9, in <module>

    second_letter=int(movie[i][0])

IndexError: list index out of range
</code>```

i can not understand this one. can someone help me with this???

答:
When you want to process all the elements of a list it is (arguably) considered more pythonic to iterate using a for statement rather than a while loop, like this:

numbers = ["20", "10", "30"]

total = 0
for number in numbers:
    first, second = number
    total += int(first) + int(second)
print(total)
```

<p>Please be aware that all the strings in <code>numbers</code> must have exactly two characters. Otherwise this code will fail.</p>

<p>This one-liner is more robust as the strings in <code>numbers</code> can have any number of digits:</p>

<pre class="lang-py prettyprint-override"><code>total = sum(sum(int(digit) for digit in number) for number in numbers)
</code>```

The solution above can be made a bit less verbose by using the built-in function map:

total = sum(sum(map(int, number)) for number in numbers)
```

Body:
I am just a newbie to python and my teacher tell me to create BlackJack game.And i stuck at the stage is count the total number of card.Here is what i got now, i need general solution for this one so i create a new python for this stage(just for testing)

list=["20","10","30"]
###I want to check first character of the number and add it together so i do this.

i = 0
while i < len(list):
      first_letter=list[i][0]
      i=i+1
      second_letter=list[i][0]
      total = first_letter+second_letter
      print(total)
####This is just an example for testing.

And when i run the code it work somehow but also have this message :

Traceback (most recent call last):

  File "D:\PYTHON BLACKJACK\00.py", line 9, in <module>

    second_letter=int(movie[i][0])

IndexError: list index out of range

i can not understand this one. can someone help me with this???

Body:
When you want to process all the elements of a list it is (arguably) considered more pythonic to iterate using a for statement rather than a while loop, like this:

numbers = ["20", "10", "30"]

total = 0
for number in numbers:
    first, second = number
    total += int(first) + int(second)
print(total)

Please be aware that all the strings in numbers must have exactly two characters. Otherwise this code will fail.

This one-liner is more robust as the strings in numbers can have any number of digits:

total = sum(sum(int(digit) for digit in number) for number in numbers)

The solution above can be made a bit less verbose by using the built-in function map:

total = sum(sum(map(int, number)) for number in numbers)


问:
Create a grid on top of an image
I hope you are all well and safe.

In NodeJS, I wanted to create a grid on top of an image. Like this:

Image without grid

Image with grid

Can someone tell me, please, how can I achieve this (some library or something)?

After creating the grid, I would like to go square by square and check the information for each square. Does anyone have any ideas?

Thank you very much for your time!

答:
I would use Canvas. You can use it for all sorts of image jobs and editing. For example, you could get a transparent PNG image of the grid and lay it on:

```<code>const Canvas = require("canvas");
const canvas = Canvas.createCanvas(619, 319);
const ctx = canvas.getContext("2d");

let img = await Canvas.loadImage("./path/to/image.png");
ctx.drawImage(img, 0, 0, img.width, img.height);

let grid = await Canvas.loadImage("./path/to/grid.png");
ctx.drawImage(grid, 0, 0, canvas.width, canvas.height);

console.log(canvas.toDataURL());
</code>```

I myself managed to get something like this.

Title: Create a grid on top of an image

Body:
I would use Canvas. You can use it for all sorts of image jobs and editing. For example, you could get a transparent PNG image of the grid and lay it on:

const Canvas = require("canvas");
const canvas = Canvas.createCanvas(619, 319);
const ctx = canvas.getContext("2d");

let img = await Canvas.loadImage("./path/to/image.png");
ctx.drawImage(img, 0, 0, img.width, img.height);

let grid = await Canvas.loadImage("./path/to/grid.png");
ctx.drawImage(grid, 0, 0, canvas.width, canvas.height);

console.log(canvas.toDataURL());

I myself managed to get something like this.


问:
Angular9/Typescript3.8/Babylon4.1.0 - Typescript compilation error - Cannot find module ‘react’/Cannot find namespace ‘JSX’
I'm currently facing compilation issues with Babylon4.1.0 in the context of an angular9 app. It seems like the inspector cannot import the internally used "react" module. The issue can be reproduced by
* Creating a bootstrap angular9 app with the CLI
* Adding @babylon/* dependencies to package.json
* Adding import '@babylonjs/inspector'; to app.component.ts

I played with several module and target settings in the tsconfig.json but without luck. Frankly I'm also kind of clueless here as i'd assume that npm should have downloaded the needed dependencies (like react). Any ideas what could cause the issues?

Here are the relevant files, but as mentioned, this is basically just a newly bootstrapped,  barebones angular9 app. for reproduction of the issue. Settings are pretty much all factory defaults.

Error log

```<code>$ npm run start

> angular9-babylon41@0.0.0 start D:\repos\angular9-babylon41
> ng serve

chunk {main} main.js, main.js.map (main) 1.99 kB [initial] [rendered]
chunk {polyfills} polyfills.js, polyfills.js.map (polyfills) 673 bytes [initial] [rendered]
chunk {runtime} runtime.js, runtime.js.map (runtime) 6.15 kB [entry] [rendered]
chunk {styles} styles.js, styles.js.map (styles) 12.4 kB [initial] [rendered]
chunk {vendor} vendor.js, vendor.js.map (vendor) 340 kB [initial] [rendered]
Date: 2020-05-31T11:09:34.586Z - Hash: e370845231b8941feaea - Time: 13568ms

ERROR in node_modules/@babylonjs/inspector/babylon.inspector.module.d.ts:77:28 - error TS2307: Cannot find module 'react'.

77     import * as React from "react";
                              ~~~~~~~
node_modules/@babylonjs/inspector/babylon.inspector.module.d.ts:94:19 - error TS2503: Cannot find namespace 'JSX'.

94         render(): JSX.Element | null;
                     ~~~
node_modules/@babylonjs/inspector/babylon.inspector.module.d.ts:98:28 - error TS2307: Cannot find module 'react'.

98     import * as React from "react";
                              ~~~~~~~
node_modules/@babylonjs/inspector/babylon.inspector.module.d.ts:108:59 - error TS2503: Cannot find namespace 'JSX'.

108         renderLabel(child: PaneComponent, index: number): JSX.Element;
                                                              ~~~
node_modules/@babylonjs/inspector/babylon.inspector.module.d.ts:109:19 - error TS2503: Cannot find namespace 'JSX'.

109         render(): JSX.Element;
                      ~~~
node_modules/@babylonjs/inspector/babylon.inspector.module.d.ts:113:28 - error TS2307: Cannot find module 'react'.

113     import * as React from "react";
                               ~~~~~~~
node_modules/@babylonjs/inspector/babylon.inspector.module.d.ts:125:26 - error TS2503: Cannot find namespace 'JSX'.

125         renderContent(): JSX.Element | null;
                             ~~~
node_modules/@babylonjs/inspector/babylon.inspector.module.d.ts:126:19 - error TS2503: Cannot find namespace 'JSX'.

126         render(): JSX.Element;
                      ~~~
node_modules/@babylonjs/inspector/babylon.inspector.module.d.ts:130:28 - error TS2307: Cannot find module 'react'.

130     import * as React from "react";
                               ~~~~~~~
...
</code>```

package.json:

```<code>{
  "name": "angular9-babylon41",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~9.1.9",
    "@angular/common": "~9.1.9",
    "@angular/compiler": "~9.1.9",
    "@angular/core": "~9.1.9",
    "@angular/forms": "~9.1.9",
    "@angular/platform-browser": "~9.1.9",
    "@angular/platform-browser-dynamic": "~9.1.9",
    "@angular/router": "~9.1.9",
    "@babylonjs/core": "^4.1.0",
    "@babylonjs/gui": "^4.1.0",
    "@babylonjs/inspector": "^4.1.0",
    "@babylonjs/loaders": "^4.1.0",
    "@babylonjs/materials": "^4.1.0",
    "rxjs": "~6.5.4",
    "tslib": "^1.10.0",
    "zone.js": "~0.10.2"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.901.7",
    "@angular/cli": "~9.1.7",
    "@angular/compiler-cli": "~9.1.9",
    "@types/node": "^12.11.1",
    "@types/jasmine": "~3.5.0",
    "@types/jasminewd2": "~2.0.3",
    "codelyzer": "^5.1.2",
    "jasmine-core": "~3.5.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~5.0.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage-istanbul-reporter": "~2.1.0",
    "karma-jasmine": "~3.0.1",
    "karma-jasmine-html-reporter": "^1.4.2",
    "protractor": "~7.0.0",
    "ts-node": "~8.3.0",
    "tslint": "~6.1.0",
    "typescript": "~3.8.3"
  }
}
</code>```

tsconfig.json:

```<code>{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "module": "esnext",
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "es2015",
    "lib": [
      "es2018",
      "dom"
    ]
  },
  "angularCompilerOptions": {
    "fullTemplateTypeCheck": true,
    "strictInjectionParameters": true
  }
}
</code>```

tsconfig.app.json:

```<code>{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/app",
    "types": []
  },
  "files": [
    "src/main.ts",
    "src/polyfills.ts"
  ],
  "include": [
    "src/**/*.d.ts"
  ]
}
</code>```

angular.json:

```<code>{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "angular9-babylon41": {
      "projectType": "application",
      "schematics": {},
      "root": "",
      "sourceRoot": "src",
      "prefix": "app",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "preserveSymlinks": true,
            "outputPath": "dist/angular9-babylon41",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.app.json",
            "aot": true,
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.css"
            ],
            "scripts": []
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "2mb",
                  "maximumError": "5mb"
                },
                {
                  "type": "anyComponentStyle",
                  "maximumWarning": "6kb",
                  "maximumError": "10kb"
                }
              ]
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "angular9-babylon41:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "angular9-babylon41:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "angular9-babylon41:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.spec.json",
            "karmaConfig": "karma.conf.js",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.css"
            ],
            "scripts": []
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "tsconfig.app.json",
              "tsconfig.spec.json",
              "e2e/tsconfig.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        },
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "e2e/protractor.conf.js",
            "devServerTarget": "angular9-babylon41:serve"
          },
          "configurations": {
            "production": {
              "devServerTarget": "angular9-babylon41:serve:production"
            }
          }
        }
      }
    }},
  "defaultProject": "angular9-babylon41"
}
</code>```

app.component.ts:

```<code>import { Component } from '@angular/core';
import { OnInit } from '@angular/core';

import '@babylonjs/inspector';  // causes compilation error

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
  title = 'angular9-babylon41';

  ngOnInit() {
    console.log(`Test`);
  }
}
</code>```

答:
When using Babylon version 4.0.3 the error is different, everything else is the same as above: (Opposed to this, the combination Babylon4.0.3, Angular8 & TS 3.5 has been working so far in the past).

```<code>$ npm run start

> angular9-babylon41@0.0.0 start D:\repos\angular9-babylon41
> ng serve

chunk {main} main.js, main.js.map (main) 1.99 kB [initial] [rendered]
chunk {polyfills} polyfills.js, polyfills.js.map (polyfills) 673 bytes [initial] [rendered]
chunk {runtime} runtime.js, runtime.js.map (runtime) 6.15 kB [entry] [rendered]
chunk {styles} styles.js, styles.js.map (styles) 12.4 kB [initial] [rendered]
chunk {vendor} vendor.js, vendor.js.map (vendor) 340 kB [initial] [rendered]
Date: 2020-05-31T12:17:13.978Z - Hash: e4a4da1571609f68f746 - Time: 14364ms

ERROR in node_modules/@babylonjs/core/Engines/engine.d.ts:8:10 - error TS2303: Circular definition of import alias 'IDisplayChangedEventArgs'.

8 import { IDisplayChangedEventArgs } from "../Engines/engine";
           ~~~~~~~~~~~~~~~~~~~~~~~~
node_modules/@babylonjs/core/Engines/engine.d.ts:8:10 - error TS2459: Module '"../Engines/engine"' declares 'IDisplayChangedEventArgs' locally, but it is not exported.

8 import { IDisplayChangedEventArgs } from "../Engines/engine";
           ~~~~~~~~~~~~~~~~~~~~~~~~

  node_modules/@babylonjs/core/Engines/engine.d.ts:8:10
    8 import { IDisplayChangedEventArgs } from "../Engines/engine";
               ~~~~~~~~~~~~~~~~~~~~~~~~
    'IDisplayChangedEventArgs' is declared here.
</code>```

Body:
I'm currently facing compilation issues with Babylon4.1.0 in the context of an angular9 app. It seems like the inspector cannot import the internally used "react" module. The issue can be reproduced by
* Creating a bootstrap angular9 app with the CLI
* Adding @babylon/* dependencies to package.json
* Adding import '@babylonjs/inspector'; to app.component.ts

I played with several module and target settings in the tsconfig.json but without luck. Frankly I'm also kind of clueless here as i'd assume that npm should have downloaded the needed dependencies (like react). Any ideas what could cause the issues?

Here are the relevant files, but as mentioned, this is basically just a newly bootstrapped,  barebones angular9 app. for reproduction of the issue. Settings are pretty much all factory defaults.

Error log

$ npm run start

> angular9-babylon41@0.0.0 start D:\repos\angular9-babylon41
> ng serve

chunk {main} main.js, main.js.map (main) 1.99 kB [initial] [rendered]
chunk {polyfills} polyfills.js, polyfills.js.map (polyfills) 673 bytes [initial] [rendered]
chunk {runtime} runtime.js, runtime.js.map (runtime) 6.15 kB [entry] [rendered]
chunk {styles} styles.js, styles.js.map (styles) 12.4 kB [initial] [rendered]
chunk {vendor} vendor.js, vendor.js.map (vendor) 340 kB [initial] [rendered]
Date: 2020-05-31T11:09:34.586Z - Hash: e370845231b8941feaea - Time: 13568ms

ERROR in node_modules/@babylonjs/inspector/babylon.inspector.module.d.ts:77:28 - error TS2307: Cannot find module 'react'.

77     import * as React from "react";
                              ~~~~~~~
node_modules/@babylonjs/inspector/babylon.inspector.module.d.ts:94:19 - error TS2503: Cannot find namespace 'JSX'.

94         render(): JSX.Element | null;
                     ~~~
node_modules/@babylonjs/inspector/babylon.inspector.module.d.ts:98:28 - error TS2307: Cannot find module 'react'.

98     import * as React from "react";
                              ~~~~~~~
node_modules/@babylonjs/inspector/babylon.inspector.module.d.ts:108:59 - error TS2503: Cannot find namespace 'JSX'.

108         renderLabel(child: PaneComponent, index: number): JSX.Element;
                                                              ~~~
node_modules/@babylonjs/inspector/babylon.inspector.module.d.ts:109:19 - error TS2503: Cannot find namespace 'JSX'.

109         render(): JSX.Element;
                      ~~~
node_modules/@babylonjs/inspector/babylon.inspector.module.d.ts:113:28 - error TS2307: Cannot find module 'react'.

113     import * as React from "react";
                               ~~~~~~~
node_modules/@babylonjs/inspector/babylon.inspector.module.d.ts:125:26 - error TS2503: Cannot find namespace 'JSX'.

125         renderContent(): JSX.Element | null;
                             ~~~
node_modules/@babylonjs/inspector/babylon.inspector.module.d.ts:126:19 - error TS2503: Cannot find namespace 'JSX'.

126         render(): JSX.Element;
                      ~~~
node_modules/@babylonjs/inspector/babylon.inspector.module.d.ts:130:28 - error TS2307: Cannot find module 'react'.

130     import * as React from "react";
                               ~~~~~~~
...

package.json:

{
  "name": "angular9-babylon41",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~9.1.9",
    "@angular/common": "~9.1.9",
    "@angular/compiler": "~9.1.9",
    "@angular/core": "~9.1.9",
    "@angular/forms": "~9.1.9",
    "@angular/platform-browser": "~9.1.9",
    "@angular/platform-browser-dynamic": "~9.1.9",
    "@angular/router": "~9.1.9",
    "@babylonjs/core": "^4.1.0",
    "@babylonjs/gui": "^4.1.0",
    "@babylonjs/inspector": "^4.1.0",
    "@babylonjs/loaders": "^4.1.0",
    "@babylonjs/materials": "^4.1.0",
    "rxjs": "~6.5.4",
    "tslib": "^1.10.0",
    "zone.js": "~0.10.2"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.901.7",
    "@angular/cli": "~9.1.7",
    "@angular/compiler-cli": "~9.1.9",
    "@types/node": "^12.11.1",
    "@types/jasmine": "~3.5.0",
    "@types/jasminewd2": "~2.0.3",
    "codelyzer": "^5.1.2",
    "jasmine-core": "~3.5.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~5.0.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage-istanbul-reporter": "~2.1.0",
    "karma-jasmine": "~3.0.1",
    "karma-jasmine-html-reporter": "^1.4.2",
    "protractor": "~7.0.0",
    "ts-node": "~8.3.0",
    "tslint": "~6.1.0",
    "typescript": "~3.8.3"
  }
}

tsconfig.json:

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "module": "esnext",
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "es2015",
    "lib": [
      "es2018",
      "dom"
    ]
  },
  "angularCompilerOptions": {
    "fullTemplateTypeCheck": true,
    "strictInjectionParameters": true
  }
}

tsconfig.app.json:

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/app",
    "types": []
  },
  "files": [
    "src/main.ts",
    "src/polyfills.ts"
  ],
  "include": [
    "src/**/*.d.ts"
  ]
}

angular.json:

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "angular9-babylon41": {
      "projectType": "application",
      "schematics": {},
      "root": "",
      "sourceRoot": "src",
      "prefix": "app",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "preserveSymlinks": true,
            "outputPath": "dist/angular9-babylon41",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.app.json",
            "aot": true,
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.css"
            ],
            "scripts": []
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "2mb",
                  "maximumError": "5mb"
                },
                {
                  "type": "anyComponentStyle",
                  "maximumWarning": "6kb",
                  "maximumError": "10kb"
                }
              ]
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "angular9-babylon41:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "angular9-babylon41:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "angular9-babylon41:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.spec.json",
            "karmaConfig": "karma.conf.js",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.css"
            ],
            "scripts": []
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "tsconfig.app.json",
              "tsconfig.spec.json",
              "e2e/tsconfig.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        },
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "e2e/protractor.conf.js",
            "devServerTarget": "angular9-babylon41:serve"
          },
          "configurations": {
            "production": {
              "devServerTarget": "angular9-babylon41:serve:production"
            }
          }
        }
      }
    }},
  "defaultProject": "angular9-babylon41"
}

app.component.ts:

import { Component } from '@angular/core';
import { OnInit } from '@angular/core';

import '@babylonjs/inspector';  // causes compilation error

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
  title = 'angular9-babylon41';

  ngOnInit() {
    console.log(`Test`);
  }
}

Body:
When using Babylon version 4.0.3 the error is different, everything else is the same as above: (Opposed to this, the combination Babylon4.0.3, Angular8 & TS 3.5 has been working so far in the past).

$ npm run start

> angular9-babylon41@0.0.0 start D:\repos\angular9-babylon41
> ng serve

chunk {main} main.js, main.js.map (main) 1.99 kB [initial] [rendered]
chunk {polyfills} polyfills.js, polyfills.js.map (polyfills) 673 bytes [initial] [rendered]
chunk {runtime} runtime.js, runtime.js.map (runtime) 6.15 kB [entry] [rendered]
chunk {styles} styles.js, styles.js.map (styles) 12.4 kB [initial] [rendered]
chunk {vendor} vendor.js, vendor.js.map (vendor) 340 kB [initial] [rendered]
Date: 2020-05-31T12:17:13.978Z - Hash: e4a4da1571609f68f746 - Time: 14364ms

ERROR in node_modules/@babylonjs/core/Engines/engine.d.ts:8:10 - error TS2303: Circular definition of import alias 'IDisplayChangedEventArgs'.

8 import { IDisplayChangedEventArgs } from "../Engines/engine";
           ~~~~~~~~~~~~~~~~~~~~~~~~
node_modules/@babylonjs/core/Engines/engine.d.ts:8:10 - error TS2459: Module '"../Engines/engine"' declares 'IDisplayChangedEventArgs' locally, but it is not exported.

8 import { IDisplayChangedEventArgs } from "../Engines/engine";
           ~~~~~~~~~~~~~~~~~~~~~~~~

  node_modules/@babylonjs/core/Engines/engine.d.ts:8:10
    8 import { IDisplayChangedEventArgs } from "../Engines/engine";
               ~~~~~~~~~~~~~~~~~~~~~~~~
    'IDisplayChangedEventArgs' is declared here.


问:
Permission error when creating Flutter project
I am new to Flutter, and after installing it, I got this error when I tried to create a project.

```<code>[hello_world] flutter create --ios-language swift --android-language kotlin .
Failed to open or create the artifact cache lockfile: "FileSystemException: Cannot open file, path = '/home/raphael/flutter/flutter/bin/cache/lockfile' (OS Error: Permission denied, errno = 13)"
Please ensure you have permissions to create or open /home/raphael/flutter/flutter/bin/cache/lockfile
Failed to open or create the lockfile
exit code 1
</code>```

I can't find any way to fix this, so I'd be glad if someone helps me :)

Thank you!

答:
Try this:

```<code>sudo chown -R [user]:root /opt/flutter
</code>```

It worked for me on Manjaro Linux.

Body:
I am new to Flutter, and after installing it, I got this error when I tried to create a project.

[hello_world] flutter create --ios-language swift --android-language kotlin .
Failed to open or create the artifact cache lockfile: "FileSystemException: Cannot open file, path = '/home/raphael/flutter/flutter/bin/cache/lockfile' (OS Error: Permission denied, errno = 13)"
Please ensure you have permissions to create or open /home/raphael/flutter/flutter/bin/cache/lockfile
Failed to open or create the lockfile
exit code 1

I can't find any way to fix this, so I'd be glad if someone helps me :)

Thank you!

Body:
Try this:

sudo chown -R [user]:root /opt/flutter

It worked for me on Manjaro Linux.


问:
Selecting rows with groupby, summing columns and creating new column with the sum for all groupby elements
I have this dataframe:

```<code>nome       code  tipo   score
Alexandre   AAA  Frads  4000
Alexandre   AAA  Memb   10000
Alexandre   AAA  Memb   20000
Bruno       BBB  Dans   10000
Bruno       BBB  Grap   4000
</code>```

Values available in this Google Sheets

I need to create a new column summing the rows with same nome and code where tipo = 'Memb', in a way that it looks like this:

I tried groupby with transform('sum') however it is getting me the wrong result.

```<code>df['score'].loc[df['tipo'] == "Memb"]=df[['nome','code','score']].groupby(['nome','code'])['score'].transform('sum')
</code>```

What am I missing?

答:
You can try this.

Set 'tipo' as index using df.set_index, then group values with similar nome and code using df.groupby and use df.transform and sum of those indices which are equal to Memb

```<code>df['Memb_sum'] =  (df.set_index('tipo').
                     groupby(['nome','code']).score.
                     transform(lambda x:x.loc[x.index=='Memb'].sum()).
                     values)
</code>```

Output:

```<code>        nome code   tipo  score  Memb_sum
0  Alexandre  AAA  Frads   4000     30000
1  Alexandre  AAA   Memb  10000     30000
2  Alexandre  AAA   Memb  20000     30000
3      Bruno  BBB   Dans  10000         0
4      Bruno  BBB   Grap   4000         0
</code>```

Body:
I have this dataframe:

nome       code  tipo   score
Alexandre   AAA  Frads  4000
Alexandre   AAA  Memb   10000
Alexandre   AAA  Memb   20000
Bruno       BBB  Dans   10000
Bruno       BBB  Grap   4000

Values available in this Google Sheets

I need to create a new column summing the rows with same nome and code where tipo = 'Memb', in a way that it looks like this:

I tried groupby with transform('sum') however it is getting me the wrong result.

df['score'].loc[df['tipo'] == "Memb"]=df[['nome','code','score']].groupby(['nome','code'])['score'].transform('sum')

What am I missing?

Body:
You can try this.

Set 'tipo' as index using df.set_index, then group values with similar nome and code using df.groupby and use df.transform and sum of those indices which are equal to Memb

df['Memb_sum'] =  (df.set_index('tipo').
                     groupby(['nome','code']).score.
                     transform(lambda x:x.loc[x.index=='Memb'].sum()).
                     values)

Output:

        nome code   tipo  score  Memb_sum
0  Alexandre  AAA  Frads   4000     30000
1  Alexandre  AAA   Memb  10000     30000
2  Alexandre  AAA   Memb  20000     30000
3      Bruno  BBB   Dans  10000         0
4      Bruno  BBB   Grap   4000         0


问:
How to run CQL in Zeppelin by taking input in user input format?
I was trying to run CQL query by taking in user input format in Zeppelin tool:-

```<code>%cassandra

SELECT  ${Select Fields Type=uuid ,uuid | created_by |  email_verify| username} FROM
${Select Table=keyspace.table_name}
${WHERE email_verify="true" } ${ORDER BY='updated_date' }LIMIT ${limit = 10};
</code>```

while running this query I was getting this error:

```<code>line 4:0 mismatched input 'true' expecting EOF
   (SELECT uuid FROM keyspace.table_name ["true"]...)
</code>```

答:
You need to move WHERE and ORDER BY out of the dynamic form declaration.

The input field declaration is looks as following: ${field_name=default_value}. In your case, instead of WHERE ..., you've got the field name of WHERE email_verify.

It should be as following (didn't tested):

```<code>%cassandra

SELECT ${Select Fields Type=uuid ,uuid | created_by |  email_verify| username} FROM
${Select Table=keyspace.table_name}
WHERE ${where_cond=email_verify='true'} ORDER BY ${order_by='updated_date'} LIMIT ${limit = 10};
</code>```

Update:

here is the working example for table with following structure:

```<code>CREATE TABLE test.scala_test2 (
    id int,
    c int,
    t text,
    tm timestamp,
    PRIMARY KEY (id, c)
) WITH CLUSTERING ORDER BY (c ASC)
</code>```

Body:
I was trying to run CQL query by taking in user input format in Zeppelin tool:-

%cassandra

SELECT  ${Select Fields Type=uuid ,uuid | created_by |  email_verify| username} FROM
${Select Table=keyspace.table_name}
${WHERE email_verify="true" } ${ORDER BY='updated_date' }LIMIT ${limit = 10};

while running this query I was getting this error:

line 4:0 mismatched input 'true' expecting EOF
   (SELECT uuid FROM keyspace.table_name ["true"]...)

Body:
You need to move WHERE and ORDER BY out of the dynamic form declaration.

The input field declaration is looks as following: ${field_name=default_value}. In your case, instead of WHERE ..., you've got the field name of WHERE email_verify.

It should be as following (didn't tested):

%cassandra

SELECT ${Select Fields Type=uuid ,uuid | created_by |  email_verify| username} FROM
${Select Table=keyspace.table_name}
WHERE ${where_cond=email_verify='true'} ORDER BY ${order_by='updated_date'} LIMIT ${limit = 10};

Update:

here is the working example for table with following structure:

CREATE TABLE test.scala_test2 (
    id int,
    c int,
    t text,
    tm timestamp,
    PRIMARY KEY (id, c)
) WITH CLUSTERING ORDER BY (c ASC)


问:
Unity 3D UI Buttons not working on mobile device
For few days I'm encountering a strange problem that my buttons don't work when I build and run my game on the mobile device even though they work just fine in the editor. What's even more surprising is only the buttons that are placed for the actual gameplay level don't work. All buttons prior to that level on the menu screens and work.

This problem only started occurring a couple of days ago before that there was no such thing. I worked around this problem by first building the game with Orientation 'Landscape Left' and then again building it with 'Auto Rotation' and checking the 'Landscape Left' checkbox in the player settings or vice versa. That will make buttons work again on the mobile device. But today when I build a second level I found that this problem also occur on Second level even though I made it to work on first level.

It's driving me crazy, I don't know what to do. The only difference between Menu and gameplay level is that on the gameplay level I'm placing objects using some objects using Instantiate.

Yes, I have checked I have placed the EventSYstem on the level and GraphicsRaycaster script on the canvas.
Any ideas?

答: In case this helps someone, I ran into a similar issue. I was implementing a tabbed UI by using a parent transform representing each tab (so I could easily activate/deactivate by tab). Any buttons that were not an immediate child of the canvas (e.g. one under a tab) were not clickable when running on Android.</p>


问:
How to use Backpack for Laravel on existing project?
I'm building a small app with Laravel and I just discovered Backpack that looks very nice !

I downloaded it (I have a license), but I really don't know how to use it with my existing files (so far 3 controllers, 3 models and a few blade files)

Maybe the answer is somewhere in the documentation, but I could not find it..

A detailed explanation would help.

答:
suppose you have model called Person ...

```<code>php artisan backpack:crud Person
</code>```

the generated command will tell you that the model is existed... and it will generate the routes and Crud Controller for you ...

then you go to your model ... in 'use' section add:

```<code>use Backpack\CRUD\app\Models\Traits\CrudTrait;
</code>```

and in your model body ... add

```<code> use CrudTrait;
</code>```

you can also override the views ... witch i do not recommend unless you have good reason for that

https://backpackforlaravel.com/docs/4.1/upgrade-guide#views

Body:
suppose you have model called Person ...

php artisan backpack:crud Person

the generated command will tell you that the model is existed... and it will generate the routes and Crud Controller for you ...

then you go to your model ... in 'use' section add:

use Backpack\CRUD\app\Models\Traits\CrudTrait;

and in your model body ... add

 use CrudTrait;

you can also override the views ... witch i do not recommend unless you have good reason for that

https://backpackforlaravel.com/docs/4.1/upgrade-guide#views


问:
For a large project, what planning should be done before coding and how should it be approached?
What is your method of "mapping out" an idea before creating it?

Say I wanted to take on a big project, for example at the scale of a site like Facebook or MySpace.  What planning/design steps should I take before I start the actual work?

For example, should I map everything out page by page (their functionalities, data, etc.)?

答: If you work for the same company as this person, start by getting everything in writing so you aren't the one to take the fall when the inevitable happens...</p>

OwnerDisplayName: sarmenhb

LastEditorDisplayName: Hanno Fietz

ContentLicense: CC BY-SA 2.5


问:
No output on the screen word-cloud with matplotlib
```<code>from wordcloud import WordCloud
import matplotlib.pyplot as plt

text = '''python python python python python
big data big dat big data big data big data big data big data big data big data big data
crawling crawling crawling crawling
analysis analysis analysis analysis
visualization visualization visualization visualization
machine learning machine learning machine learning machine learning machine learning
deep learning deep learning deep learning deep learning deep learning deep learning
'''

wc = WordCloud(width=1000, height=600, background_color="white", random_state=0, font_path=r'NanumBarunGothic.otf')
plt.imshow(wc.generate(text))
plt.axis("off")
plt.show()

image = wc.to_image()
image.show()
</code>```

This is the code that creates the word cloud. Word Cloud is not visible on the screen in pycharm. What should i do. I would really appreciate it if you can tell me how to fix it.

答:
I have used your code with the modification using IPython and it works:

```<code>wc = WordCloud(width=1000, height=600, background_color="white")
plt.imshow(wc.generate(text))

plt.axis("off")
plt.show()

image = wc.to_image()
image.show()
</code>```

The attached picture is:

Body:
from wordcloud import WordCloud
import matplotlib.pyplot as plt

text = '''python python python python python
big data big dat big data big data big data big data big data big data big data big data
crawling crawling crawling crawling
analysis analysis analysis analysis
visualization visualization visualization visualization
machine learning machine learning machine learning machine learning machine learning
deep learning deep learning deep learning deep learning deep learning deep learning
'''

wc = WordCloud(width=1000, height=600, background_color="white", random_state=0, font_path=r'NanumBarunGothic.otf')
plt.imshow(wc.generate(text))
plt.axis("off")
plt.show()

image = wc.to_image()
image.show()

This is the code that creates the word cloud. Word Cloud is not visible on the screen in pycharm. What should i do. I would really appreciate it if you can tell me how to fix it.

Body:
I have used your code with the modification using IPython and it works:

wc = WordCloud(width=1000, height=600, background_color="white")
plt.imshow(wc.generate(text))

plt.axis("off")
plt.show()

image = wc.to_image()
image.show()

The attached picture is:


问:
Python-docx and ElemetTree: how to find where hyperlinks lie within a paragraph
I'm using python-docx and ElementTree to convert Word documents to XML, and it's working well except for hyperlinks.

I'm able to find which python-docx paragraphs have a hyperlink, however if the hyperlink is in the middle of the paragraph text, I don't know where to render the hyperlink when writing the output to XML.

Is there a way to iterate through all elements in a paragraph?
If I understand correctly, iterating through the runs will only consider the <w:r> elements, so I expect my hyperlink element will be in between 2 of the runs. How can I figure out which two?

答:
I know I'm a bit late but maybe someone will find that answer useful.
Let's say you have a paragraph in a MS Word document that has a hyperlink inside it, like this:

It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. https://www.google.com/ The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English.

You can check how it looks like in xml when you 1) change the extension of your .docx file to .docx.zip or 2) by printing the xml => print(paragraph._p.xml)
!)When you look at the document.xml file, you will see something like this:

```<code><w:hyperlink w:history="1" r:id="rId9">
  <w:r w:rsidR="000D6596" w:rsidRPr="00302570">
   <w:rPr>
    <w:rStyle w:val="Hipercze"/>
    <w:rFonts w:cs="Arial"/>
    <w:spacing w:val="-4"/>
   </w:rPr>
  <w:t>https/google.com</w:t>
 </w:r>
</w:hyperlink>
</code>```

Then you could find the relationship ids of all the hyperlinks that you have in your document (if you have more than one hyperlink, you probably want to save the rIds to a list):

```<code>import docx
from docx.oxml.ns import qn

for paragraph in document.paragraphs:
        hyperlink = paragraph._p.xpath("./w:hyperlink")
        if len(hyperlink) > 0:
            hyperlink = hyperlink[0]
            hyperlink_rel_id = hyperlink.get(qn("r:id"))
</code>```

Once you have the rId you can get to that link, delete, modify, etc. Another way to get the rIds here:

```<code>        from docx.opc.constants import RELATIONSHIP_TYPE as RT

        link_text = 'https://www.google.pl/'
        document = docx.Document(path)
        rels = document.part.rels
        for rel in rels:
            if rels[rel].reltype == RT.HYPERLINK:
                if rels[rel]._target == link_text:
                  # if the text of the link is the same as the one you are looking for
                  # do something
</code>```

Body:
I know I'm a bit late but maybe someone will find that answer useful.
Let's say you have a paragraph in a MS Word document that has a hyperlink inside it, like this:

It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. https://www.google.com/ The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English.

You can check how it looks like in xml when you 1) change the extension of your .docx file to .docx.zip or 2) by printing the xml => print(paragraph._p.xml)
!)When you look at the document.xml file, you will see something like this:

<w:hyperlink w:history="1" r:id="rId9">
  <w:r w:rsidR="000D6596" w:rsidRPr="00302570">
   <w:rPr>
    <w:rStyle w:val="Hipercze"/>
    <w:rFonts w:cs="Arial"/>
    <w:spacing w:val="-4"/>
   </w:rPr>
  <w:t>https/google.com</w:t>
 </w:r>
</w:hyperlink>

Then you could find the relationship ids of all the hyperlinks that you have in your document (if you have more than one hyperlink, you probably want to save the rIds to a list):

import docx
from docx.oxml.ns import qn

for paragraph in document.paragraphs:
        hyperlink = paragraph._p.xpath("./w:hyperlink")
        if len(hyperlink) > 0:
            hyperlink = hyperlink[0]
            hyperlink_rel_id = hyperlink.get(qn("r:id"))

Once you have the rId you can get to that link, delete, modify, etc. Another way to get the rIds here:

        from docx.opc.constants import RELATIONSHIP_TYPE as RT

        link_text = 'https://www.google.pl/'
        document = docx.Document(path)
        rels = document.part.rels
        for rel in rels:
            if rels[rel].reltype == RT.HYPERLINK:
                if rels[rel]._target == link_text:
                  # if the text of the link is the same as the one you are looking for
                  # do something