问:
Trying to do a JTable which adds data from a JTextField
I'm trying to do code that adds a row to a JTable. I type but nothing shows up. My showMessageDialog also has an error.

Does anyone know how I can rewrite the code?

```<code>import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;

import static javax.swing.JOptionPane.showMessageDialog;

public class JTABEL extends Component {
private JPanel panel1;
private JLabel Name;
private JLabel Age;
private JLabel Class;
private JTextField enterNameTextField;
private JTextField Agefield;
private JTextField EnterClassField;
private JTable Table;
private JButton saveButton;

public JTABEL() {
    saveButton.addActionListener(this::actionPerformed);
}

public static void main(String[] args) {
        JFrame frame = new JFrame("Jtable");
        frame.setContentPane(new JTABEL().panel1);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

private void actionPerformed(ActionEvent e) {
    if (enterNameTextField.getText().equals("") || Agefield.getText().equals("") ||
EnterClassField.getText().equals("")) {
        showMessageDialog(this, "please Enter all Data");
    } else {
        String data[] = {enterNameTextField.getText(), Agefield.getText(),
EnterClassField.getText()};

        DefaultTableModel tableModel = (DefaultTableModel) Table.getModel();
        tableModel.addRow(new Object[]{enterNameTextField.getText(), Agefield.getText(),
EnterClassField.getText()});
        showMessageDialog(this, "Add Data Successfully");
        enterNameTextField.setText("");
        Agefield.setText("");
        EnterClassField.setText("");
    }
}
}
</code>```

答:
Introduction

Oracle has a helpful tutorial, Creating a GUI With Swing.  Skip the Learning Swing with the NetBeans IDE section.

I created the following GUI.

Here's the same GUI after adding a couple of students.

Explanation

The model–view–controller (MVC) pattern is useful when creating a Swing application.  The name implies that you create the model first, then the view, then the controller.

An application model is made up of one or more plain Java getter/setter classes.

A Swing view is one JFrame with one or more JPanels.  The view displays the contents of the model.  The view does not modify the model.

Each Swing ActionListener is a controller.  The controllers update the model.

Model

I created two model classes.  The Student class holds a name, age, and class.

The JTableModel class holds the DefaultTableModel for the JTable.

View

All Swing applications must start with a call to the SwingUtilities invokeLater method.  This method ensures that all Swing components are created and executed on the Event Dispatch Thread.

I created a JFrame and two JPanels.  One JPanel holds the JTable and the other JPanel holds the add student form.  The JFrame has a default BorderLayout.  I placed the table JPanel in the center and the form JPanel on the east side.

The table JPanel uses a BorderLayout.  The JTable is placed inside of a JScrollPane.  The JScrollPane is placed inside of the table JPanel in the center.

The form JPanel uses a GridBagLayout to create a form structure JPanel.

Complete explanations of all the Swing layout managers can be found in the Oracle tutorial.

Controller

The anonymous JButton ActionListener checks to see if the fields have been typed.  If so, a Student instance is created and passed to the application model.  If not, an error display pops up.

Code

Here's the complete runnable code.  I made the additional classes inner classes so I could post the code as one block.

```<code>import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;

public class JTableExample implements Runnable {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new JTableExample());
    }

    private final JTableModel model;

    private JFrame frame;

    private JTextField nameField, ageField, classField;

    public JTableExample() {
        this.model = new JTableModel();
    }

    @Override
    public void run() {
        frame = new JFrame("JTable Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.add(createTablePanel(), BorderLayout.CENTER);
        frame.add(createAddPanel(), BorderLayout.EAST);

        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    private JPanel createTablePanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

        JTable table = new JTable(model.getTableModel());
        JScrollPane scrollPane = new JScrollPane(table);

        panel.add(scrollPane, BorderLayout.CENTER);

        return panel;
    }

    private JPanel createAddPanel() {
        JPanel panel = new JPanel(new GridBagLayout());
        panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.anchor = GridBagConstraints.LINE_START;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.insets = new Insets(0, 5, 5, 5);
        gbc.gridwidth = 1;
        gbc.gridx = 0;
        gbc.gridy = 0;

        JLabel label = new JLabel("Name:");
        panel.add(label, gbc);

        gbc.gridx++;
        nameField = new JTextField(20);
        panel.add(nameField, gbc);

        gbc.gridx = 0;
        gbc.gridy++;
        label = new JLabel("Age:");
        panel.add(label, gbc);

        gbc.gridx++;
        ageField = new JTextField(20);
        panel.add(ageField, gbc);

        gbc.gridx = 0;
        gbc.gridy++;
        label = new JLabel("Class:");
        panel.add(label, gbc);

        gbc.gridx++;
        classField = new JTextField(20);
        panel.add(classField, gbc);

        gbc.gridwidth = 2;
        gbc.gridx = 0;
        gbc.gridy++;
        JButton button = new JButton("Add Student");
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                String name = nameField.getText().trim();
                String ageString = ageField.getText().trim();
                String level = classField.getText().trim();

                if (name.isEmpty() || ageString.isEmpty() || level.isEmpty()) {
                    JOptionPane.showMessageDialog(
                            frame, "Please enter all information");
                    return;
                }

                int age = getAge(ageString);
                if (age > 0) {
                    model.addStudent(new Student(name, age, level));
                    clearInputFields();
                }
            }

            private int getAge(String ageString) {
                int age = -1;
                try {
                    age = Integer.valueOf(ageString);
                } catch (NumberFormatException e) {
                    JOptionPane.showMessageDialog(
                            frame, "Please enter a numeric age");
                }
                return age;
            }

            private void clearInputFields() {
                nameField.setText("");
                ageField.setText("");
                classField.setText("");

                nameField.requestFocus();
            }
        });

        panel.add(button, gbc);
        frame.getRootPane().setDefaultButton(button);

        return panel;
    }

    public class JTableModel {

        private final DefaultTableModel tableModel;

        public JTableModel() {
            this.tableModel = new DefaultTableModel();
            tableModel.addColumn("Name");
            tableModel.addColumn("Age");
            tableModel.addColumn("Class");
        }

        public void addStudent(Student student) {
            Object[] rowData = new Object[3];
            rowData[0] = student.getName();
            rowData[1] = student.getAge();
            rowData[2] = student.getLevel();
            tableModel.addRow(rowData);
        }

        public DefaultTableModel getTableModel() {
            return tableModel;
        }

    }

    public class Student {

        private final int age;

        private final String level, name;

        public Student(String name, int age, String level) {
            this.name = name;
            this.age = age;
            this.level = level;
        }

        public int getAge() {
            return age;
        }

        public String getLevel() {
            return level;
        }

        public String getName() {
            return name;
        }

    }

}
</code>```

Body:
I'm trying to do code that adds a row to a JTable. I type but nothing shows up. My showMessageDialog also has an error.

Does anyone know how I can rewrite the code?

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;

import static javax.swing.JOptionPane.showMessageDialog;

public class JTABEL extends Component {
private JPanel panel1;
private JLabel Name;
private JLabel Age;
private JLabel Class;
private JTextField enterNameTextField;
private JTextField Agefield;
private JTextField EnterClassField;
private JTable Table;
private JButton saveButton;

public JTABEL() {
    saveButton.addActionListener(this::actionPerformed);
}

public static void main(String[] args) {
        JFrame frame = new JFrame("Jtable");
        frame.setContentPane(new JTABEL().panel1);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

private void actionPerformed(ActionEvent e) {
    if (enterNameTextField.getText().equals("") || Agefield.getText().equals("") ||
EnterClassField.getText().equals("")) {
        showMessageDialog(this, "please Enter all Data");
    } else {
        String data[] = {enterNameTextField.getText(), Agefield.getText(),
EnterClassField.getText()};

        DefaultTableModel tableModel = (DefaultTableModel) Table.getModel();
        tableModel.addRow(new Object[]{enterNameTextField.getText(), Agefield.getText(),
EnterClassField.getText()});
        showMessageDialog(this, "Add Data Successfully");
        enterNameTextField.setText("");
        Agefield.setText("");
        EnterClassField.setText("");
    }
}
}

Body:
Introduction

Oracle has a helpful tutorial, Creating a GUI With Swing.  Skip the Learning Swing with the NetBeans IDE section.

I created the following GUI.

Here's the same GUI after adding a couple of students.

Explanation

The model–view–controller (MVC) pattern is useful when creating a Swing application.  The name implies that you create the model first, then the view, then the controller.

An application model is made up of one or more plain Java getter/setter classes.

A Swing view is one JFrame with one or more JPanels.  The view displays the contents of the model.  The view does not modify the model.

Each Swing ActionListener is a controller.  The controllers update the model.

Model

I created two model classes.  The Student class holds a name, age, and class.

The JTableModel class holds the DefaultTableModel for the JTable.

View

All Swing applications must start with a call to the SwingUtilities invokeLater method.  This method ensures that all Swing components are created and executed on the Event Dispatch Thread.

I created a JFrame and two JPanels.  One JPanel holds the JTable and the other JPanel holds the add student form.  The JFrame has a default BorderLayout.  I placed the table JPanel in the center and the form JPanel on the east side.

The table JPanel uses a BorderLayout.  The JTable is placed inside of a JScrollPane.  The JScrollPane is placed inside of the table JPanel in the center.

The form JPanel uses a GridBagLayout to create a form structure JPanel.

Complete explanations of all the Swing layout managers can be found in the Oracle tutorial.

Controller

The anonymous JButton ActionListener checks to see if the fields have been typed.  If so, a Student instance is created and passed to the application model.  If not, an error display pops up.

Code

Here's the complete runnable code.  I made the additional classes inner classes so I could post the code as one block.

import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;

public class JTableExample implements Runnable {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new JTableExample());
    }

    private final JTableModel model;

    private JFrame frame;

    private JTextField nameField, ageField, classField;

    public JTableExample() {
        this.model = new JTableModel();
    }

    @Override
    public void run() {
        frame = new JFrame("JTable Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.add(createTablePanel(), BorderLayout.CENTER);
        frame.add(createAddPanel(), BorderLayout.EAST);

        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    private JPanel createTablePanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

        JTable table = new JTable(model.getTableModel());
        JScrollPane scrollPane = new JScrollPane(table);

        panel.add(scrollPane, BorderLayout.CENTER);

        return panel;
    }

    private JPanel createAddPanel() {
        JPanel panel = new JPanel(new GridBagLayout());
        panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.anchor = GridBagConstraints.LINE_START;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.insets = new Insets(0, 5, 5, 5);
        gbc.gridwidth = 1;
        gbc.gridx = 0;
        gbc.gridy = 0;

        JLabel label = new JLabel("Name:");
        panel.add(label, gbc);

        gbc.gridx++;
        nameField = new JTextField(20);
        panel.add(nameField, gbc);

        gbc.gridx = 0;
        gbc.gridy++;
        label = new JLabel("Age:");
        panel.add(label, gbc);

        gbc.gridx++;
        ageField = new JTextField(20);
        panel.add(ageField, gbc);

        gbc.gridx = 0;
        gbc.gridy++;
        label = new JLabel("Class:");
        panel.add(label, gbc);

        gbc.gridx++;
        classField = new JTextField(20);
        panel.add(classField, gbc);

        gbc.gridwidth = 2;
        gbc.gridx = 0;
        gbc.gridy++;
        JButton button = new JButton("Add Student");
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                String name = nameField.getText().trim();
                String ageString = ageField.getText().trim();
                String level = classField.getText().trim();

                if (name.isEmpty() || ageString.isEmpty() || level.isEmpty()) {
                    JOptionPane.showMessageDialog(
                            frame, "Please enter all information");
                    return;
                }

                int age = getAge(ageString);
                if (age > 0) {
                    model.addStudent(new Student(name, age, level));
                    clearInputFields();
                }
            }

            private int getAge(String ageString) {
                int age = -1;
                try {
                    age = Integer.valueOf(ageString);
                } catch (NumberFormatException e) {
                    JOptionPane.showMessageDialog(
                            frame, "Please enter a numeric age");
                }
                return age;
            }

            private void clearInputFields() {
                nameField.setText("");
                ageField.setText("");
                classField.setText("");

                nameField.requestFocus();
            }
        });

        panel.add(button, gbc);
        frame.getRootPane().setDefaultButton(button);

        return panel;
    }

    public class JTableModel {

        private final DefaultTableModel tableModel;

        public JTableModel() {
            this.tableModel = new DefaultTableModel();
            tableModel.addColumn("Name");
            tableModel.addColumn("Age");
            tableModel.addColumn("Class");
        }

        public void addStudent(Student student) {
            Object[] rowData = new Object[3];
            rowData[0] = student.getName();
            rowData[1] = student.getAge();
            rowData[2] = student.getLevel();
            tableModel.addRow(rowData);
        }

        public DefaultTableModel getTableModel() {
            return tableModel;
        }

    }

    public class Student {

        private final int age;

        private final String level, name;

        public Student(String name, int age, String level) {
            this.name = name;
            this.age = age;
            this.level = level;
        }

        public int getAge() {
            return age;
        }

        public String getLevel() {
            return level;
        }

        public String getName() {
            return name;
        }

    }

}


来源: stackexchange

问:
How to ignore a Task in F#?
If we have a function f that returns Async<something>, we can ignore the return value with do! f() |> Async.Ignore. Is there a similar construct for ignoring Tasks? Right now, I'm having to do something like this:

task {
    let! result = SomeOperation()
    result |> ignore
}
```

Technically I could do |> Async.AwaitTask |> Async.Ignore, but I'm not sure how wasteful it is to convert a task to async just to ignore it...

If it matters, I'm using task{} computation expressions from Ply.

答:
If your function returns Async, then simply ignoring it won't work because unlike Tasks, an Async operation does not execute unless you explicitly start it.

If you just want to make it run, but don't care about waiting until it is done you can do

```<code>f() |> Async.RunAsTask |> ignore
</code>```

if you do want to wait for the result, you can do

```<code>f() |> Async.RunSynchronously |> ignore
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to ignore a Task in F#?

Body:
If we have a function f that returns Async<something>, we can ignore the return value with do! f() |> Async.Ignore. Is there a similar construct for ignoring Tasks? Right now, I'm having to do something like this:

task {
    let! result = SomeOperation()
    result |> ignore
}

Technically I could do |> Async.AwaitTask |> Async.Ignore, but I'm not sure how wasteful it is to convert a task to async just to ignore it...

If it matters, I'm using task{} computation expressions from Ply.

Body:
If your function returns Async, then simply ignoring it won't work because unlike Tasks, an Async operation does not execute unless you explicitly start it.

If you just want to make it run, but don't care about waiting until it is done you can do

f() |> Async.RunAsTask |> ignore

if you do want to wait for the result, you can do

f() |> Async.RunSynchronously |> ignore


问:
javascript hashmap one line modify or create
I want to know if there is a clean way to modify a value in a hashmap or create it if it doesn't exist without doing an if block.  Example of what i'm currently doing

```<code>let dict = {}
if(dict['key']){
 dict['key'] += 1
} else {
 dict['key'] = 1
}
</code>```

Want to know if there is a cleaner way to do what I did above.

答:
Use dot notation, because the property isn't dynamic, and alternate dict.key with 0 before adding 1.

```<code>dict.key = (dict.key || 0) + 1;
</code>```

Body:
I want to know if there is a clean way to modify a value in a hashmap or create it if it doesn't exist without doing an if block.  Example of what i'm currently doing

let dict = {}
if(dict['key']){
 dict['key'] += 1
} else {
 dict['key'] = 1
}

Want to know if there is a cleaner way to do what I did above.

Body:
Use dot notation, because the property isn't dynamic, and alternate dict.key with 0 before adding 1.

dict.key = (dict.key || 0) + 1;


问:
HASKELL --- Is there any function to remove an element in a list?
My problem is I have a list and want to remove some strings in it. but when I remove the first time it's OK. but the second time, it removes the string but bring back the first one.
do you know how I can avoid this?
thank you

```<code>Prelude Data.List Data.Char> x = ["ab","cd","ef","gh"]

Prelude Data.List Data.Char> delete "ab" x

["cd","ef","gh"]

Prelude Data.List Data.Char> delete "cd" x

["ab","ef","gh"]
</code>```

!!Here the "ab" came back and I don't want this!! thanks

答:
See ''How to "think functional"'' here. In short, x is the same x; delete "abc" x returns new value, it does not change the existing x.

If you want to refer to this new value, give it a new name, like this:

```<code>> x = ["ab","cd","ef","gh"]

> x2 = delete "ab" x

> delete "cd" x2
["ef","gh"]
</code>```

Body:
My problem is I have a list and want to remove some strings in it. but when I remove the first time it's OK. but the second time, it removes the string but bring back the first one.
do you know how I can avoid this?
thank you

Prelude Data.List Data.Char> x = ["ab","cd","ef","gh"]

Prelude Data.List Data.Char> delete "ab" x

["cd","ef","gh"]

Prelude Data.List Data.Char> delete "cd" x

["ab","ef","gh"]

!!Here the "ab" came back and I don't want this!! thanks

Body:
See ''How to "think functional"'' here. In short, x is the same x; delete "abc" x returns new value, it does not change the existing x.

If you want to refer to this new value, give it a new name, like this:

> x = ["ab","cd","ef","gh"]

> x2 = delete "ab" x

> delete "cd" x2
["ef","gh"]


问:
How do I write a Prometheus query that returns the value of a label?
I'm making a Grafana dashboard and want a panel that reports the latest version of our app. The version is reported as a label in the app_version (say) metric like so:

```<code>app_version_updated{instance="eu99",version="1.5.0-abcdefg"}
</code>```

I've tried a number of Prometheus queries to extract the version label as a string from the latest member of this time series, to no effect.

For example, the query

```<code>count(app_version_updated) by (version)
</code>```

returns a {version="1.5.0-abcdefg"} element with a value of 1. When put in a Grafana dashboard in a single value panel, this doesn't display the version string but instead the count value (1).

How can I construct a Prometheus query that returns the version string?

答: With Stat visualization in Grafana 8+, you can set the legend to the intended label name and then change the Stat Styles -> Text Mode to Name

ContentLicense: CC BY-SA 3.0

Body:
I'm making a Grafana dashboard and want a panel that reports the latest version of our app. The version is reported as a label in the app_version (say) metric like so:

app_version_updated{instance="eu99",version="1.5.0-abcdefg"}

I've tried a number of Prometheus queries to extract the version label as a string from the latest member of this time series, to no effect.

For example, the query

count(app_version_updated) by (version)

returns a {version="1.5.0-abcdefg"} element with a value of 1. When put in a Grafana dashboard in a single value panel, this doesn't display the version string but instead the count value (1).

How can I construct a Prometheus query that returns the version string?


问:
Why would people use `$a = $b = 2;` in PHP?
Why would people use this format? Whats different between this and $a=2; $b=2;?

答:
Functionally? nothing. They both do the same thing "set variables $a and $b to 2". But, it does communicate something to your fellow programmers and it is faster/easier in some circumstances. For example

```<code>for($i = $j = 0; $i < 5; $i++, $j--) echo "$i $j \n";
</code>```

Outputs:

```<code>0 0
1 -1
2 -2
3 -3
4 -4
</code>```

Of course, if you need $i and $j to initialize to something more useful, say, floor( count( $myArr ) / 2 ), it can also be useful that way.

Then there are other, similar uses:

```<code>$j = ( $i = 1 ) - 1; // $i = 1, $j = 0;
</code>```

Body:
Functionally? nothing. They both do the same thing "set variables $a and $b to 2". But, it does communicate something to your fellow programmers and it is faster/easier in some circumstances. For example

for($i = $j = 0; $i < 5; $i++, $j--) echo "$i $j \n";

Outputs:

0 0
1 -1
2 -2
3 -3
4 -4

Of course, if you need $i and $j to initialize to something more useful, say, floor( count( $myArr ) / 2 ), it can also be useful that way.

Then there are other, similar uses:

$j = ( $i = 1 ) - 1; // $i = 1, $j = 0;


问:
How to check username availability using Ajax in Struts 2
I am trying to check username available or not when a user tries to create his account.
when a user types it's username there should be an instant check that username is available or not and it will show a message in just below the username box.

I was tried to achieve it by calling an Ajax but not able to understand what to return basically and how will it work, actually I am very new in Struts 2 , I am able to check the username but did not under what to return.

My Ajax Call

```<code><script>
            $(document).ready(function () {
                $("input").blur(function () {
                    var input = $(this).val();
                    alert(input);
                    $.ajax({
                        url:'checkUsername',
                        method:"POST",
                        data:{username:input},
                        success:function(data)
                        {
                            if(data!='0'){
                                $('#availability').html('<span>not available</span>')
                                $('#update').attr("disabled",true);
                            }
                            else{
                                $('#availability').html('<span>available</span>')
                                $('#update').attr("disabled",false);
                            }
                        }
                    })
                });
            });
        </script>
</code>```

checkUsername Action

```<code>public String checkUsername() {
        try {
            setCtr(admin.checkUsername(username));
            if (ctr > 0) {
                System.out.println(ctr);
                setNoData(false);
            } else {
                setNoData(true);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "CHECKUSER";
    }
</code>```

method to check username in dao

```<code>public int checkUsername(String username) throws Exception {
        ResultSet rs = null;
        Connection con = null;
        try {
            con = ConnectionManager.getConnection();
            System.out.println(username);
            String sql = "SELECT * FROM userinfo WHERE username =?";
            PreparedStatement ps = con.prepareStatement(sql);
            ps.setString(1, username);
            rs = ps.executeQuery();
            if (rs.next()) {
                return 1;
            }

        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            if (con != null) {
                con.close();
            }
        }
        return 0;
    }
}
</code>```

This method in dao is able to check the username but what to return in that ajax data which i am trying to check that the if rows > 0 it should print not available. How to return and how to check?

struts.xml

```<code> <action name="checkUsername" class="com.redress.actions.AdminAction" method = "checkUsername"> </action>
</code>```

Can anyone please correct me, how to achieve this?

答:
Simply return a json result. You should define it in the action config. I've already explained how you can return a json result without struts2-json-plugin. Now you will use it to return an JSON object to the success callback function via jQuery ajax.

First you need to add it to the project build path. Then make package of your action config to extend json-default package. It will add JSON result type to the Struts config.

Make the property noData (whatever) you want to access having getter and setter.

Add result of type JSON to the action config.

 <action name="checkUsername" class="com.redress.actions.AdminAction" method = "checkUsername">
    <result type="json">
        <param name="root">action</param>
    </result>
</action>
```
<p>The action method should return <code>ActionSupport.SUCCESS</code> result code.</p>
<p>In the success callback function you should get JSON object which you can check</p>
<pre class="lang-js prettyprint-override"><code>success:function(data){
  if(!data.noData){
    $('#availability').html('<span>not available</span>');
    $('#update').attr("disabled",true);
   }
   else{
     $('#availability').html('<span>available</span>');
     $('#update').attr("disabled",false);
  }
}
</code>```

Body:
I am trying to check username available or not when a user tries to create his account.
when a user types it's username there should be an instant check that username is available or not and it will show a message in just below the username box.

I was tried to achieve it by calling an Ajax but not able to understand what to return basically and how will it work, actually I am very new in Struts 2 , I am able to check the username but did not under what to return.

My Ajax Call

checkUsername Action

public String checkUsername() {
        try {
            setCtr(admin.checkUsername(username));
            if (ctr > 0) {
                System.out.println(ctr);
                setNoData(false);
            } else {
                setNoData(true);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "CHECKUSER";
    }

method to check username in dao

public int checkUsername(String username) throws Exception {
        ResultSet rs = null;
        Connection con = null;
        try {
            con = ConnectionManager.getConnection();
            System.out.println(username);
            String sql = "SELECT * FROM userinfo WHERE username =?";
            PreparedStatement ps = con.prepareStatement(sql);
            ps.setString(1, username);
            rs = ps.executeQuery();
            if (rs.next()) {
                return 1;
            }

        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            if (con != null) {
                con.close();
            }
        }
        return 0;
    }
}

This method in dao is able to check the username but what to return in that ajax data which i am trying to check that the if rows > 0 it should print not available. How to return and how to check?

struts.xml

 <action name="checkUsername" class="com.redress.actions.AdminAction" method = "checkUsername"> </action>

Can anyone please correct me, how to achieve this?

Body:
Simply return a json result. You should define it in the action config. I've already explained how you can return a json result without struts2-json-plugin. Now you will use it to return an JSON object to the success callback function via jQuery ajax.

First you need to add it to the project build path. Then make package of your action config to extend json-default package. It will add JSON result type to the Struts config.

Make the property noData (whatever) you want to access having getter and setter.

Add result of type JSON to the action config.

 <action name="checkUsername" class="com.redress.actions.AdminAction" method = "checkUsername">
    <result type="json">
        <param name="root">action</param>
    </result>
</action>

The action method should return ActionSupport.SUCCESS result code.

In the success callback function you should get JSON object which you can check

success:function(data){
  if(!data.noData){
    $('#availability').html('<span>not available</span>');
    $('#update').attr("disabled",true);
   }
   else{
     $('#availability').html('<span>available</span>');
     $('#update').attr("disabled",false);
  }
}


问:
I'm having trouble fetching from my API, every time I get an HTTP2 Error
I have a PHP API that sends JSON.

Whenever I try to fetch that JSON I get:

My .htaccess file looks like this:

I'm completely stumped on how to allow the fetch to actually fetch, any suggestions?

答:
Problems

Your 2nd and 3rd screenshots indicate that you're adding an Access-Control-Allow-Origin header to the request. However, that header is a response header, not a request header; adding it to a request is pointless and counterproductive. Moreover, because it isn't listed in the value of your Access-Control-Allow-Headers header. Therefore, CORS preflight fails.

Besides, your 4th screenshot indicates that you're explicitly allowing the Origin header, but there's never a need for that, because that header is special and automatically added by the browser.

Solution

Stop sending an Access-Control-Allow-Origin header with your requests.
You can also drop Origin from the Access-Control-Allow-Headers header in your CORS configuration.


问:
Sum of a list 2 elements by 2 elements
I have a 25 elements list like

```<code>tab=[6, 5, 5, 6, 3, 3, 2, 3, 2, 5, 6, 3, 2, 4, 5, 6, 4, 2, 1, 3, 1, 1, 4, 1, 5]
</code>```

And I want to create a new list tab1 which display the sum of the elements of the list two by two, if the list is odd I don't have to calculate the sum on the last element.
And it has to be done with a for loop for... any ideas?
Any help would be appreciated.
I tried on my side but without success.

i tried this :

```<code>for i in tab:
print(sum(i:len(tab))
</code>```

it gives me a syntax error and i tried some of others things but didn't work...

i tried this too

```<code>for i in tab:
print(sum(i,i+1))
</code>```

didn't work too

and when i do this

```<code>sum=0
for i in tab:
print(sum(tab[i]+tab[i+1]))
</code>```

it gives me back : TypeError: 'int' object is not callable

答:
You could iterate over the list with steps of 2.

orig_len = len(tab)  # List length
tab1 = []
for i in range(0, orig_len - orig_len%2, 2):
  tab1.append(tab[i] + tab[i+1])
print(tab1)
```

You have to round down the number to first smaller even number, which is that orig_len - orig_len%2 does.

Title: Sum of a list 2 elements by 2 elements

Body:
I have a 25 elements list like

tab=[6, 5, 5, 6, 3, 3, 2, 3, 2, 5, 6, 3, 2, 4, 5, 6, 4, 2, 1, 3, 1, 1, 4, 1, 5]

And I want to create a new list tab1 which display the sum of the elements of the list two by two, if the list is odd I don't have to calculate the sum on the last element.
And it has to be done with a for loop for... any ideas?
Any help would be appreciated.
I tried on my side but without success.

i tried this :

for i in tab:
print(sum(i:len(tab))

it gives me a syntax error and i tried some of others things but didn't work...

i tried this too

for i in tab:
print(sum(i,i+1))

didn't work too

and when i do this

sum=0
for i in tab:
print(sum(tab[i]+tab[i+1]))

it gives me back : TypeError: 'int' object is not callable

Body:
You could iterate over the list with steps of 2.

orig_len = len(tab)  # List length
tab1 = []
for i in range(0, orig_len - orig_len%2, 2):
  tab1.append(tab[i] + tab[i+1])
print(tab1)

You have to round down the number to first smaller even number, which is that orig_len - orig_len%2 does.


问:
The difference between two dates
I have been writing some queries about SQL Server in order to learn.

I wonder that how can I get the difference of today between 90 days ago in a SQL query?

答:
```<code>DATEDIFF
</code>```

http://msdn.microsoft.com/en-us/library/ms189794.aspx

```<code>DECLARE @90DaysAgo datetime
        ,@Today datetime

SET @90DaysAgo = DATEADD(d, -90, GETDATE())
SET @Today = GETDATE()

SELECT DATEDIFF(d, @90DaysAgo, @Today) --Returns 90
</code>```

Title: The difference between two dates

Body:
DATEDIFF

http://msdn.microsoft.com/en-us/library/ms189794.aspx

DECLARE @90DaysAgo datetime
        ,@Today datetime

SET @90DaysAgo = DATEADD(d, -90, GETDATE())
SET @Today = GETDATE()

SELECT DATEDIFF(d, @90DaysAgo, @Today) --Returns 90


问:
Add character variable to dataframe designating the portion of a timeseries each row falls within over a grouped variable
I have a dataframe of annual values at multiple sites for two species. I need to add a character variable (we'll call this position) that designates the position of each row in the timeseries. The issue is that I have a number of sites (grouping variable), and the lengths of the timeseries of each site differ. If it helps, I would like to split each timeseries into thirds, so that the resulting data looks something like this (simplified):

```<code>Species  Site Year Position
   1       1  2000  Early
   1       1  2001  Mid
   1       1  2002  Late
   1       2  2000  Early
   1       2  2001  Early
   1       2  2002  Mid
   1       2  2003  Mid
   1       2  2004  Late
   1       2  2005  Late
   2       1  2000  Early
   2       1  2001  Mid
   2       1  2002  Late
   2       2  2000  Early
   2       2  2001  Early
   2       2  2002  Mid
   2       2  2003  Mid
   2       2  2004  Late
   2       2  2005  Late
</code>```

Where:

Early = Position (or year) <= 1/3 of total timeseries (or number of rows)

Mid = Position >= 1/3 and <= 2/3

Late = Position >= 2/3 and <= 3/3

Here is a sample of my data (cols 1-3 of first 200 of 5,000 rows):

```<code>structure(list(Site = c("CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW",
"CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW",
"CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW",
"CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW",
"CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW",
"CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW",
"CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW",
"CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW",
"CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW",
"CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW",
"CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW",
"CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW",
"CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW",
"CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW",
"CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW",
"CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW",
"CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW",
"CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW",
"CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW",
"CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW",
"CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW",
"CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW",
"CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW",
"CT_CW", "CT_CW", "CT_CW", "IN_PM", "IN_PM", "IN_PM", "IN_PM",
"IN_PM", "IN_PM", "IN_PM", "IN_PM", "IN_PM", "IN_PM", "IN_PM",
"IN_PM", "IN_PM", "IN_PM", "IN_PM", "IN_PM", "IN_PM", "IN_PM",
"IN_PM", "IN_PM", "IN_PM", "IN_PM", "IN_PM", "IN_PM", "IN_PM",
"IN_PM", "IN_PM", "IN_PM", "IN_PM", "IN_PM", "IN_PM", "IN_PM",
"IN_PM", "IN_PM", "IN_PM", "IN_PM", "IN_PM", "IN_PM"), Year = c(1901L,
1901L, 1902L, 1902L, 1903L, 1903L, 1904L, 1904L, 1905L, 1905L,
1906L, 1906L, 1907L, 1907L, 1908L, 1908L, 1909L, 1909L, 1910L,
1910L, 1911L, 1911L, 1912L, 1912L, 1913L, 1913L, 1914L, 1914L,
1915L, 1915L, 1916L, 1916L, 1917L, 1917L, 1918L, 1918L, 1919L,
1919L, 1920L, 1920L, 1921L, 1921L, 1922L, 1922L, 1923L, 1923L,
1924L, 1924L, 1925L, 1925L, 1926L, 1926L, 1927L, 1927L, 1928L,
1928L, 1929L, 1929L, 1930L, 1930L, 1931L, 1931L, 1932L, 1932L,
1933L, 1933L, 1934L, 1934L, 1935L, 1935L, 1936L, 1936L, 1937L,
1937L, 1938L, 1938L, 1939L, 1939L, 1940L, 1940L, 1941L, 1941L,
1942L, 1942L, 1943L, 1943L, 1944L, 1944L, 1945L, 1945L, 1946L,
1946L, 1947L, 1947L, 1948L, 1948L, 1949L, 1949L, 1950L, 1950L,
1951L, 1951L, 1952L, 1952L, 1953L, 1953L, 1954L, 1954L, 1955L,
1955L, 1956L, 1956L, 1957L, 1957L, 1958L, 1958L, 1959L, 1959L,
1960L, 1960L, 1961L, 1961L, 1962L, 1962L, 1963L, 1963L, 1964L,
1964L, 1965L, 1965L, 1966L, 1966L, 1967L, 1967L, 1968L, 1968L,
1969L, 1969L, 1970L, 1970L, 1971L, 1971L, 1972L, 1972L, 1973L,
1973L, 1974L, 1974L, 1975L, 1975L, 1976L, 1976L, 1977L, 1977L,
1978L, 1978L, 1979L, 1979L, 1980L, 1980L, 1981L, 1981L, 1901L,
1901L, 1902L, 1902L, 1903L, 1903L, 1904L, 1904L, 1905L, 1905L,
1906L, 1906L, 1907L, 1907L, 1908L, 1908L, 1909L, 1909L, 1910L,
1910L, 1911L, 1911L, 1912L, 1912L, 1913L, 1913L, 1914L, 1914L,
1915L, 1915L, 1916L, 1916L, 1917L, 1917L, 1918L, 1918L, 1919L,
1919L), Species = c("QA", "QR", "QA", "QR", "QA", "QR", "QA",
"QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR",
"QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA",
"QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR",
"QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA",
"QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR",
"QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA",
"QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR",
"QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA",
"QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR",
"QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA",
"QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR",
"QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA",
"QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR",
"QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA",
"QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR",
"QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA",
"QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR",
"QA", "QR", "QA", "QR", "QA", "QR")), row.names = c(NA, 200L), class = "data.frame")
</code>```

答:
We could group by 'Species', 'Site' and then create the Position (either with quantile/cut) or use case_when (for custom cuts) to create the values based on logical expression

```<code>library(dplyr)
df1 %>%
 arrange(Species, Site, Year) %>%
 select(Species, Site, Year) %>%
 group_by(Species, Site) %>%
 mutate(Position =
    case_when(row_number() <= n()/3 ~ 'Early',
              between(row_number(), n()/3, 2*n()/3) ~ "Mid",
             TRUE ~ "Late")) %>%
 ungroup
</code>```

Body:
I have a dataframe of annual values at multiple sites for two species. I need to add a character variable (we'll call this position) that designates the position of each row in the timeseries. The issue is that I have a number of sites (grouping variable), and the lengths of the timeseries of each site differ. If it helps, I would like to split each timeseries into thirds, so that the resulting data looks something like this (simplified):

Species  Site Year Position
   1       1  2000  Early
   1       1  2001  Mid
   1       1  2002  Late
   1       2  2000  Early
   1       2  2001  Early
   1       2  2002  Mid
   1       2  2003  Mid
   1       2  2004  Late
   1       2  2005  Late
   2       1  2000  Early
   2       1  2001  Mid
   2       1  2002  Late
   2       2  2000  Early
   2       2  2001  Early
   2       2  2002  Mid
   2       2  2003  Mid
   2       2  2004  Late
   2       2  2005  Late

Where:

Early = Position (or year) <= 1/3 of total timeseries (or number of rows)

Mid = Position >= 1/3 and <= 2/3

Late = Position >= 2/3 and <= 3/3

Here is a sample of my data (cols 1-3 of first 200 of 5,000 rows):

structure(list(Site = c("CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW",
"CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW",
"CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW",
"CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW",
"CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW",
"CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW",
"CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW",
"CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW",
"CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW",
"CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW",
"CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW",
"CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW",
"CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW",
"CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW",
"CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW",
"CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW",
"CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW",
"CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW",
"CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW",
"CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW",
"CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW",
"CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW",
"CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW", "CT_CW",
"CT_CW", "CT_CW", "CT_CW", "IN_PM", "IN_PM", "IN_PM", "IN_PM",
"IN_PM", "IN_PM", "IN_PM", "IN_PM", "IN_PM", "IN_PM", "IN_PM",
"IN_PM", "IN_PM", "IN_PM", "IN_PM", "IN_PM", "IN_PM", "IN_PM",
"IN_PM", "IN_PM", "IN_PM", "IN_PM", "IN_PM", "IN_PM", "IN_PM",
"IN_PM", "IN_PM", "IN_PM", "IN_PM", "IN_PM", "IN_PM", "IN_PM",
"IN_PM", "IN_PM", "IN_PM", "IN_PM", "IN_PM", "IN_PM"), Year = c(1901L,
1901L, 1902L, 1902L, 1903L, 1903L, 1904L, 1904L, 1905L, 1905L,
1906L, 1906L, 1907L, 1907L, 1908L, 1908L, 1909L, 1909L, 1910L,
1910L, 1911L, 1911L, 1912L, 1912L, 1913L, 1913L, 1914L, 1914L,
1915L, 1915L, 1916L, 1916L, 1917L, 1917L, 1918L, 1918L, 1919L,
1919L, 1920L, 1920L, 1921L, 1921L, 1922L, 1922L, 1923L, 1923L,
1924L, 1924L, 1925L, 1925L, 1926L, 1926L, 1927L, 1927L, 1928L,
1928L, 1929L, 1929L, 1930L, 1930L, 1931L, 1931L, 1932L, 1932L,
1933L, 1933L, 1934L, 1934L, 1935L, 1935L, 1936L, 1936L, 1937L,
1937L, 1938L, 1938L, 1939L, 1939L, 1940L, 1940L, 1941L, 1941L,
1942L, 1942L, 1943L, 1943L, 1944L, 1944L, 1945L, 1945L, 1946L,
1946L, 1947L, 1947L, 1948L, 1948L, 1949L, 1949L, 1950L, 1950L,
1951L, 1951L, 1952L, 1952L, 1953L, 1953L, 1954L, 1954L, 1955L,
1955L, 1956L, 1956L, 1957L, 1957L, 1958L, 1958L, 1959L, 1959L,
1960L, 1960L, 1961L, 1961L, 1962L, 1962L, 1963L, 1963L, 1964L,
1964L, 1965L, 1965L, 1966L, 1966L, 1967L, 1967L, 1968L, 1968L,
1969L, 1969L, 1970L, 1970L, 1971L, 1971L, 1972L, 1972L, 1973L,
1973L, 1974L, 1974L, 1975L, 1975L, 1976L, 1976L, 1977L, 1977L,
1978L, 1978L, 1979L, 1979L, 1980L, 1980L, 1981L, 1981L, 1901L,
1901L, 1902L, 1902L, 1903L, 1903L, 1904L, 1904L, 1905L, 1905L,
1906L, 1906L, 1907L, 1907L, 1908L, 1908L, 1909L, 1909L, 1910L,
1910L, 1911L, 1911L, 1912L, 1912L, 1913L, 1913L, 1914L, 1914L,
1915L, 1915L, 1916L, 1916L, 1917L, 1917L, 1918L, 1918L, 1919L,
1919L), Species = c("QA", "QR", "QA", "QR", "QA", "QR", "QA",
"QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR",
"QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA",
"QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR",
"QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA",
"QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR",
"QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA",
"QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR",
"QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA",
"QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR",
"QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA",
"QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR",
"QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA",
"QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR",
"QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA",
"QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR",
"QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA",
"QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR", "QA", "QR",
"QA", "QR", "QA", "QR", "QA", "QR")), row.names = c(NA, 200L), class = "data.frame")

Body:
We could group by 'Species', 'Site' and then create the Position (either with quantile/cut) or use case_when (for custom cuts) to create the values based on logical expression

library(dplyr)
df1 %>%
 arrange(Species, Site, Year) %>%
 select(Species, Site, Year) %>%
 group_by(Species, Site) %>%
 mutate(Position =
    case_when(row_number() <= n()/3 ~ 'Early',
              between(row_number(), n()/3, 2*n()/3) ~ "Mid",
             TRUE ~ "Late")) %>%
 ungroup


Title: Sum of a list 2 elements by 2 elements

Body:
Try this:

tab=[6, 5, 5, 6, 3, 3, 2, 3, 2, 5, 6, 3, 2, 4, 5, 6, 4, 2, 1, 3, 1, 1, 4, 1, 5]
print([sum(tab[i:i+2]) for i in range(0, len(tab),2)])

The output will be:

[11, 11, 6, 5, 7, 9, 6, 11, 6, 4, 2, 5, 5]


问:
Does the computer erase the values which have been reserved for variables in the RAM after the program is finished?
We have learned that the information in the hard disk are never erased, only the links to it are erased. Does this apply to RAM as well (as long as the computer is on of course)?

For example, When I declare a variable before I give it a value, the value can be 0 or some other value that was previously in that place.

Can I say that the computer doesn't know how to delete something it just replaces it with another?

答:
When a process (program/app) starts, it asks the operating system for some memory. The operating system keeps track of the address/size of the memory each process uses. A process can't access a region of memory it doesn't own (virtual address mapping). When the process ends the operating system may choose to write a value (like 0x00) to all the memory a process had. I believe most existing operating systems don't overwrite memory.

Take a look at this question for a further insight about this subject.


问:
ModuleNotFoundError: No module named 'gpiozero'
I tried to use gpiozero on my raspberry pi 4, when i try to run the code it doesn't find the module.

Any suggestions?

I tried downloading it by several different ways as stated on the gpiozero documentation page. Don't know what to do now.

答:
you should try

```<code>pip install gpiozero
</code>```

if u have python with two or more versions, please consider an environment

Body:
you should try

pip install gpiozero

if u have python with two or more versions, please consider an environment


问:
VideoPlayer/AVQueuePlayer does not seek to time
The AVQueuePlayer does not seek to the given time. Video always starts playing at the beginning.
Using the default controls, I can seek manually to a desired point.
I am using a m3u8 HLS stream.

```<code>import SwiftUI
import AVKit

struct ChannelPlayerView: View {
  @ObservedObject var channelViewModel: ChannelViewModel
  @State private var player: AVQueuePlayer?
  @State private var videoLooper: AVPlayerLooper?

// VideoPlayer example from https://www.raywenderlich.com/19074315-swiftui-on-tvos
  var body: some View {
    VideoPlayer(player: player)
      .onAppear {
        if player == nil {
          let videoURL = self.channelViewModel.currentVideo().masterUrl // example.com/video/master.m3u8

          // Will be used after seeking works
          //let currentTimesamp = Date() - video.startingTime
          //let cmTime = CMTime(seconds: currentTimesamp, preferredTimescale: 1000000)

          let templateItem = AVPlayerItem(url: URL(string: videoURL)!)
          player = AVQueuePlayer(playerItem: templateItem)
          videoLooper = AVPlayerLooper(player: player!, templateItem: templateItem)¡
        }

        if player?.isPlaying == false {
          let playerTimescale = self.player!.currentItem?.asset.duration.timescale ?? 1
          let time =  CMTime(seconds: 77.000000, preferredTimescale: playerTimescale)
          player?.seek(to: time)
          player?.play() // Tried with play() and without
        }
      }
      .edgesIgnoringSafeArea(.all)
  }
}
</code>```

Here is the m3u8 File that is given to the player.

```<code>#EXTM3U
# Created with Bento4 mp4-hls.py version 1.2.0r637

#EXT-X-VERSION:4

# Media Playlists
#EXT-X-STREAM-INF:AVERAGE-BANDWIDTH=3072204,BANDWIDTH=4633702,CODECS="avc1.4D402A,mp4a.40.2",RESOLUTION=1920x1080
media-1/stream.m3u8
#EXT-X-STREAM-INF:AVERAGE-BANDWIDTH=1576056,BANDWIDTH=2443812,CODECS="avc1.4D402A,mp4a.40.2",RESOLUTION=1280x720
media-2/stream.m3u8
#EXT-X-STREAM-INF:AVERAGE-BANDWIDTH=896410,BANDWIDTH=1351872,CODECS="avc1.4D402A,mp4a.40.2",RESOLUTION=852x480
media-3/stream.m3u8
#EXT-X-STREAM-INF:AVERAGE-BANDWIDTH=637434,BANDWIDTH=940939,CODECS="avc1.4D402A,mp4a.40.2",RESOLUTION=640x360
media-4/stream.m3u8
#EXT-X-STREAM-INF:AVERAGE-BANDWIDTH=418851,BANDWIDTH=579212,CODECS="avc1.4D402A,mp4a.40.2",RESOLUTION=426x240
media-5/stream.m3u8

# I-Frame Playlists
#EXT-X-I-FRAME-STREAM-INF:AVERAGE-BANDWIDTH=226870,BANDWIDTH=4053137,CODECS="avc1.4D402A",RESOLUTION=1920x1080,URI="media-1/iframes.m3u8"
#EXT-X-I-FRAME-STREAM-INF:AVERAGE-BANDWIDTH=132899,BANDWIDTH=2336684,CODECS="avc1.4D402A",RESOLUTION=1280x720,URI="media-2/iframes.m3u8"
#EXT-X-I-FRAME-STREAM-INF:AVERAGE-BANDWIDTH=83388,BANDWIDTH=1363065,CODECS="avc1.4D402A",RESOLUTION=852x480,URI="media-3/iframes.m3u8"
#EXT-X-I-FRAME-STREAM-INF:AVERAGE-BANDWIDTH=57207,BANDWIDTH=908710,CODECS="avc1.4D402A",RESOLUTION=640x360,URI="media-4/iframes.m3u8"
#EXT-X-I-FRAME-STREAM-INF:AVERAGE-BANDWIDTH=31981,BANDWIDTH=490415,CODECS="avc1.4D402A",RESOLUTION=426x240,URI="media-5/iframes.m3u8"
</code>```

答:
Found out the problem.

I need to seek on the currentItem, not on the AVQueuePlayer. Did not found a  clue on why in the documentation.

```<code>          player?.currentItem!.seek(to: cmTime, toleranceBefore: .zero, toleranceAfter: .zero, completionHandler: nil)
</code>```

Body:
The AVQueuePlayer does not seek to the given time. Video always starts playing at the beginning.
Using the default controls, I can seek manually to a desired point.
I am using a m3u8 HLS stream.

import SwiftUI
import AVKit

struct ChannelPlayerView: View {
  @ObservedObject var channelViewModel: ChannelViewModel
  @State private var player: AVQueuePlayer?
  @State private var videoLooper: AVPlayerLooper?

// VideoPlayer example from https://www.raywenderlich.com/19074315-swiftui-on-tvos
  var body: some View {
    VideoPlayer(player: player)
      .onAppear {
        if player == nil {
          let videoURL = self.channelViewModel.currentVideo().masterUrl // example.com/video/master.m3u8

          // Will be used after seeking works
          //let currentTimesamp = Date() - video.startingTime
          //let cmTime = CMTime(seconds: currentTimesamp, preferredTimescale: 1000000)

          let templateItem = AVPlayerItem(url: URL(string: videoURL)!)
          player = AVQueuePlayer(playerItem: templateItem)
          videoLooper = AVPlayerLooper(player: player!, templateItem: templateItem)¡
        }

        if player?.isPlaying == false {
          let playerTimescale = self.player!.currentItem?.asset.duration.timescale ?? 1
          let time =  CMTime(seconds: 77.000000, preferredTimescale: playerTimescale)
          player?.seek(to: time)
          player?.play() // Tried with play() and without
        }
      }
      .edgesIgnoringSafeArea(.all)
  }
}

Here is the m3u8 File that is given to the player.

#EXTM3U
# Created with Bento4 mp4-hls.py version 1.2.0r637

#EXT-X-VERSION:4

# Media Playlists
#EXT-X-STREAM-INF:AVERAGE-BANDWIDTH=3072204,BANDWIDTH=4633702,CODECS="avc1.4D402A,mp4a.40.2",RESOLUTION=1920x1080
media-1/stream.m3u8
#EXT-X-STREAM-INF:AVERAGE-BANDWIDTH=1576056,BANDWIDTH=2443812,CODECS="avc1.4D402A,mp4a.40.2",RESOLUTION=1280x720
media-2/stream.m3u8
#EXT-X-STREAM-INF:AVERAGE-BANDWIDTH=896410,BANDWIDTH=1351872,CODECS="avc1.4D402A,mp4a.40.2",RESOLUTION=852x480
media-3/stream.m3u8
#EXT-X-STREAM-INF:AVERAGE-BANDWIDTH=637434,BANDWIDTH=940939,CODECS="avc1.4D402A,mp4a.40.2",RESOLUTION=640x360
media-4/stream.m3u8
#EXT-X-STREAM-INF:AVERAGE-BANDWIDTH=418851,BANDWIDTH=579212,CODECS="avc1.4D402A,mp4a.40.2",RESOLUTION=426x240
media-5/stream.m3u8

# I-Frame Playlists
#EXT-X-I-FRAME-STREAM-INF:AVERAGE-BANDWIDTH=226870,BANDWIDTH=4053137,CODECS="avc1.4D402A",RESOLUTION=1920x1080,URI="media-1/iframes.m3u8"
#EXT-X-I-FRAME-STREAM-INF:AVERAGE-BANDWIDTH=132899,BANDWIDTH=2336684,CODECS="avc1.4D402A",RESOLUTION=1280x720,URI="media-2/iframes.m3u8"
#EXT-X-I-FRAME-STREAM-INF:AVERAGE-BANDWIDTH=83388,BANDWIDTH=1363065,CODECS="avc1.4D402A",RESOLUTION=852x480,URI="media-3/iframes.m3u8"
#EXT-X-I-FRAME-STREAM-INF:AVERAGE-BANDWIDTH=57207,BANDWIDTH=908710,CODECS="avc1.4D402A",RESOLUTION=640x360,URI="media-4/iframes.m3u8"
#EXT-X-I-FRAME-STREAM-INF:AVERAGE-BANDWIDTH=31981,BANDWIDTH=490415,CODECS="avc1.4D402A",RESOLUTION=426x240,URI="media-5/iframes.m3u8"

Body:
Found out the problem.

I need to seek on the currentItem, not on the AVQueuePlayer. Did not found a  clue on why in the documentation.

          player?.currentItem!.seek(to: cmTime, toleranceBefore: .zero, toleranceAfter: .zero, completionHandler: nil)


问:
How to get rolling median on pandas dataframe?
```<code>Data:

              vix      s_0000     s_0001     s_0002     s_0003  s_0004
Date
1990-01-02  17.24         NaN  13.389421        NaN        NaN     NaN
1990-01-03  18.19         NaN  13.588601        NaN        NaN     NaN
1990-01-04  19.22         NaN  13.610730        NaN        NaN     NaN
1990-01-05  20.11         NaN  13.477942        NaN        NaN     NaN
1990-01-08  20.26         NaN  13.477942        NaN        NaN     NaN
...           ...         ...        ...        ...        ...     ...
2020-12-23  23.31  116.631310  22.171579  15.890000  16.577030    9.00
2020-12-24  21.53  116.641243  21.912146  15.660000  16.606722    8.77
2020-12-28  21.70  117.158287  22.191536  16.059999  16.200956    8.93
2020-12-29  23.08  116.561714  21.991972  15.860000  16.745275    8.80
2020-12-30  22.77  116.720795  22.899990  16.150000  17.932884    8.60
</code>```

I would like to add a new column "HVM" showing a 12-month rolling median (n=12) of vix.
For instance, the HVM for January 1991 will be the median of Jan 1990 to Dec 1990. The HVM for February 1991 will be the median of Feb 1990 to Jan 1991. There will be no HVM for Year 1990. I've only managed the code below:

```<code>import pandas as pd
md = pd.read_csv('ADJ_CLOSE.zip')
md.Date = pd.to_datetime(md.Date)
md.set_index('Date', inplace=True)
md['HVM'] = md.groupby(md.Date.dt.year)['vix'].transform('median')
</code>```

However this code applies the 12m median starting from 1990, which gives the same HVM for the entire year, instead of calculating from the past 12 months. Any help would be appreciated!

答:
The problem is 12M is considered as a non-fixed frequency. The best you can do is to compute the median over 365 days:

```<code>md = pd.read_csv('ADJ_CLOSE.zip', index_col='Date', parse_dates=['Date'])
md['HVM'] = md.rolling('365D')['vix'].median()
</code>```

Body:
Data:

              vix      s_0000     s_0001     s_0002     s_0003  s_0004
Date
1990-01-02  17.24         NaN  13.389421        NaN        NaN     NaN
1990-01-03  18.19         NaN  13.588601        NaN        NaN     NaN
1990-01-04  19.22         NaN  13.610730        NaN        NaN     NaN
1990-01-05  20.11         NaN  13.477942        NaN        NaN     NaN
1990-01-08  20.26         NaN  13.477942        NaN        NaN     NaN
...           ...         ...        ...        ...        ...     ...
2020-12-23  23.31  116.631310  22.171579  15.890000  16.577030    9.00
2020-12-24  21.53  116.641243  21.912146  15.660000  16.606722    8.77
2020-12-28  21.70  117.158287  22.191536  16.059999  16.200956    8.93
2020-12-29  23.08  116.561714  21.991972  15.860000  16.745275    8.80
2020-12-30  22.77  116.720795  22.899990  16.150000  17.932884    8.60

I would like to add a new column "HVM" showing a 12-month rolling median (n=12) of vix.
For instance, the HVM for January 1991 will be the median of Jan 1990 to Dec 1990. The HVM for February 1991 will be the median of Feb 1990 to Jan 1991. There will be no HVM for Year 1990. I've only managed the code below:

import pandas as pd
md = pd.read_csv('ADJ_CLOSE.zip')
md.Date = pd.to_datetime(md.Date)
md.set_index('Date', inplace=True)
md['HVM'] = md.groupby(md.Date.dt.year)['vix'].transform('median')

However this code applies the 12m median starting from 1990, which gives the same HVM for the entire year, instead of calculating from the past 12 months. Any help would be appreciated!

Body:
The problem is 12M is considered as a non-fixed frequency. The best you can do is to compute the median over 365 days:

md = pd.read_csv('ADJ_CLOSE.zip', index_col='Date', parse_dates=['Date'])
md['HVM'] = md.rolling('365D')['vix'].median()


问:
Prevent user to insert cells in sheet but allow him to insert whole rows or columns
I use Excel 2010. Is there a way to prevent a user to insert cells in sheet (and shift the cell down or somewhere else) but allow him to insert whole rows or columns (in Excel 2010). A solution in VBA is also welcome.
I have tried all the possible ways in Excel 2010 (and VBA) but could not find any solution.
Thanks in advance.</p>

答:
Please, copy the next code in the sheet code module where insertion of cells is not allowed, but entire rows or columns is:

```<code>Option Explicit

Private rowsNo As Long, colsNo As Long

Private Sub Worksheet_Change(ByVal Target As Range)
   Dim lastR As Long, lastCol As Long
   lastR = Me.UsedRange.Rows.count
   lastCol = Me.UsedRange.Columns.count

   If Target.cells.count <> Me.Columns.count And Target.cells.count <> Me.Rows.count Then
        If rowsNo < Me.UsedRange.Rows.count Or _
                 colsNo < Me.UsedRange.Columns.count Then
            Application.EnableEvents = False
               Application.Undo                    'UnDo the inserting
            Application.EnableEvents = True
        End If
   Else
        If rowsNo < lastR Then
            rowsNo = rowsNo + Target.Rows.count    'increment rowsNo with the number of inserted rows
        End If
        If colsNo < lastCol Then
            colsNo = colsNo + Target.Columns.count 'increment colsNo with the number of inserted columns
        End If
   End If
End Sub

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    rowsNo = Me.UsedRange.Rows.count
    colsNo = Me.UsedRange.Columns.count
End Sub
</code>```

It will work only if (at least) a selection has been changed before making the insertion. The code can be adapted to also handle such a situation, but it will become much more complicated...

Body:
Please, copy the next code in the sheet code module where insertion of cells is not allowed, but entire rows or columns is:

Option Explicit

Private rowsNo As Long, colsNo As Long

Private Sub Worksheet_Change(ByVal Target As Range)
   Dim lastR As Long, lastCol As Long
   lastR = Me.UsedRange.Rows.count
   lastCol = Me.UsedRange.Columns.count

   If Target.cells.count <> Me.Columns.count And Target.cells.count <> Me.Rows.count Then
        If rowsNo < Me.UsedRange.Rows.count Or _
                 colsNo < Me.UsedRange.Columns.count Then
            Application.EnableEvents = False
               Application.Undo                    'UnDo the inserting
            Application.EnableEvents = True
        End If
   Else
        If rowsNo < lastR Then
            rowsNo = rowsNo + Target.Rows.count    'increment rowsNo with the number of inserted rows
        End If
        If colsNo < lastCol Then
            colsNo = colsNo + Target.Columns.count 'increment colsNo with the number of inserted columns
        End If
   End If
End Sub

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    rowsNo = Me.UsedRange.Rows.count
    colsNo = Me.UsedRange.Columns.count
End Sub

It will work only if (at least) a selection has been changed before making the insertion. The code can be adapted to also handle such a situation, but it will become much more complicated...


问:
sed Extract unique characters within each line
I want to get unique chars within each line using regular expressions in a Shell Script (sh).
In other words, I want to remove any further occurrence of a char within each line.

I'm trying to answer this question:
"What characters do appears in each line?"

For example, I'm trying to do something like this:

echo '1.Hi
2.This is
3.a huge file
4.with repeated chars
5.per
6.line' | sed 's/MYSTERIOUS_REGEX/MYSTERIOUS_REPLACE/g'
```
<p>And the expected output is:</p>
```1.Hi
2.This
3.a hugefil
4.with repadcs
5.per
6.line
```
<p>This is the explanation:</p>
<ul>
<li>Line 1: <strong>there isn't any repeated chars</strong></li>
<li>Line 2: '<code>i</code>', '<code>s</code>' <strong>repeated</strong></li>
<li>Line 3: '<code> </code>', '<code>e</code>' <strong>repeated</strong></li>
<li>Line 4: '<code>e</code>', '<code>a</code>', '<code>t</code>', '<code>e</code>', '<code>d</code>', '<code> </code>', '<code>c</code>', '<code>h</code>', '<code>a</code>', '<code>r</code>' <strong>repeated</strong></li>
<li>Line 5: <strong>there isn't any repeated chars</strong></li>
<li>Line 6: <strong>there isn't any repeated chars</strong></li>
</ul>
<p><strong>OBS</strong>:</p>
<ul>
<li>If you achieve this using <code>sh</code> and <code>sed</code> you obtain 5⭐s</li>
<li>If you achieve this using  other tools (<code>bash</code>, <code>awk</code> etc), you obtain 3⭐s</li>
</ul>
<hr />
<p>̶D̶i̶s̶t̶r̶a̶c̶t̶o̶r̶ ̶ <strong>HINT</strong>:</p>
<p>The following regex matches lines which don't have repeated chars: <strong><code>^(?:([A-Za-z])(?!.*\1))*$</code></strong></p>
<pre class="lang-sh prettyprint-override"><code>echo "bleh" | grep -P '^(?:([A-Za-z])(?!.*\1))*$'
</code>```

ble

echo "fooo" | grep -P '^(?:([A-Za-z])(?!.*\1))*$'
```

(empty)

答:
You may use this gnu-sed solution:

sed -E ':a;s/((.).*)\2/\1/;ta' file

1.Hi
2.This
3.a hugefil
4.with repadcs
5.per
6.line
```
<p>Alternative <code>awk</code> non-regex solution (should work in any awk version):</p>
<pre class="lang-sh prettyprint-override"><code>awk '{
   delete seen
   for (i=1; i<=length(); ++i) {
      ch = substr($0,i,1)
      if (!seen[ch]++) printf "%s", ch
   }
   print ""
}' file

1.Hi
2.This
3.a hugefil
4.with repadcs
5.per
6.line
</code>```

Body:
I want to get unique chars within each line using regular expressions in a Shell Script (sh).
In other words, I want to remove any further occurrence of a char within each line.

I'm trying to answer this question:
"What characters do appears in each line?"

For example, I'm trying to do something like this:

echo '1.Hi
2.This is
3.a huge file
4.with repeated chars
5.per
6.line' | sed 's/MYSTERIOUS_REGEX/MYSTERIOUS_REPLACE/g'

And the expected output is:

1.Hi
2.This
3.a hugefil
4.with repadcs
5.per
6.line

This is the explanation:

Line 1: there isn't any repeated chars

Line 2: 'i', 's' repeated

Line 3: ' ', 'e' repeated

Line 4: 'e', 'a', 't', 'e', 'd', ' ', 'c', 'h', 'a', 'r' repeated

Line 5: there isn't any repeated chars

Line 6: there isn't any repeated chars

OBS:

If you achieve this using sh and sed you obtain 5⭐s

If you achieve this using  other tools (bash, awk etc), you obtain 3⭐s

̶D̶i̶s̶t̶r̶a̶c̶t̶o̶r̶ ̶ HINT:

The following regex matches lines which don't have repeated chars: ^(?:([A-Za-z])(?!.*\1))*$

echo "bleh" | grep -P '^(?:([A-Za-z])(?!.*\1))*$'

ble

echo "fooo" | grep -P '^(?:([A-Za-z])(?!.*\1))*$'

(empty)

Body:
You may use this gnu-sed solution:

sed -E ':a;s/((.).*)\2/\1/;ta' file

1.Hi
2.This
3.a hugefil
4.with repadcs
5.per
6.line

Alternative awk non-regex solution (should work in any awk version):

awk '{
   delete seen
   for (i=1; i<=length(); ++i) {
      ch = substr($0,i,1)
      if (!seen[ch]++) printf "%s", ch
   }
   print ""
}' file

1.Hi
2.This
3.a hugefil
4.with repadcs
5.per
6.line


问:
why I am getting empty list when I use split()?
I have a textfile as:

```<code>-- Generated ]
FILEUNIT
  METRIC /

Hello
-- timestep: Jan 01,2017 00:00:00
  3*2 344.0392 343.4564 343.7741
  343.9302 343.3884 343.7685 0.0000 341.0843
  342.2441 342.5899 343.0728 343.4850 342.8882
  342.0056 342.0564 341.9619 341.8840 342.0447 /
</code>```

I have written a code to read the file and remove the words, characters and empty lines, and do some other processes on that and finally return those numbers in the last four lines. I cannot understand how to put all the numbers of the text file properly in a list. Right now the new_line generates a string of those lines with numbers

```<code>import string

def expand(chunk):
    l = chunk.split("*")
    chunk = [str(float(l[1]))] * int(l[0])

    return chunk

with open('old_textfile.txt', 'r') as infile1:
    for line in infile1:
        if set(string.ascii_letters.replace("e","")) & set(line):
            continue

        chunks = line.split(" ")
        #Get rid of newlines
        chunks = list(map(lambda chunk: chunk.strip(), chunks))
        if "/" in chunks:
            chunks.remove("/")

        new_chunks = []
        for i in range(len(chunks)):
            if '*' in chunks[i]:
                new_chunks += expand(chunks[i])
            else:
                new_chunks.append(chunks[i])
        new_chunks[len(new_chunks)-1] = new_chunks[len(new_chunks)-1]+"\n"
        new_line = " ".join(new_chunks)
</code>```

when I use the

```<code>A = new_line.split()
B = list(map(float, A))
</code>```

it returns an empty list. Do you have any idea how I can put all these numbers in one single list?
currently, I am writing the new_line as a textfile and reading it again, but it increase my runtime which is not good.

```<code>f = open('new_textfile.txt').read()
A = f.split()
B = list(map(float, A))
list_1.extend(B)
</code>```

There was another solution to use Regex, but it deletes 3*2. I want to process that as 2 2 2

```<code>import re

with open('old_textfile.txt', 'r') as infile1:
    lines = infile1.read()

nums = re.findall(r'\d+\.\d+', lines)
print(nums)
</code>```

答:
I'm not quite sure if I entirely understand what you are trying to do, but as I understand it you want to extract all numbers which either are in a decimal form \d+\.\d+ or an integer which is multiplied by another integer using an asterisk, so \d+\*\d+. You want the results all in a list of floats where the decimals are in the list directly and for the integers the second is repeated by the first.

One way to do this would be:

```<code>lines = """
-- Generated ]
FILEUNIT
  METRIC /

Hello
-- timestep: Jan 01,2017 00:00:00
  3*2 344.0392 343.4564 343.7741
  343.9302 343.3884 343.7685 0.0000 341.0843
  342.2441 342.5899 343.0728 343.4850 342.8882
  342.0056 342.0564 341.9619 341.8840 342.0447 /
"""

nums = []
for n in re.findall(r'(\d+\.\d+|\d+\*\d+)', lines):
    split_by_ast = n.split("*")
    if len(split_by_ast) == 1:
        nums += [float(split_by_ast[0])]
    else:
        nums += [float(split_by_ast[1])] * int(split_by_ast[0])

print(nums)
</code>```

Which returns:

```<code>[2.0, 2.0, 2.0, 344.0392, 343.4564, 343.7741, 343.9302, 343.3884, 343.7685, 0.0, 341.0843, 342.2441, 342.5899, 343.0728, 343.485, 342.8882, 342.0056, 342.0564, 341.9619, 341.884, 342.0447]
</code>```

The regular expression searches for numbers matching one of the formats (decimal or int*int). Then in case of a decimal it is directly appended to the list, in case of int*int it is parsed to a smaller list repeating the second int by first int times, then the lists are concatenated.

Body:
I have a textfile as:

-- Generated ]
FILEUNIT
  METRIC /

Hello
-- timestep: Jan 01,2017 00:00:00
  3*2 344.0392 343.4564 343.7741
  343.9302 343.3884 343.7685 0.0000 341.0843
  342.2441 342.5899 343.0728 343.4850 342.8882
  342.0056 342.0564 341.9619 341.8840 342.0447 /

I have written a code to read the file and remove the words, characters and empty lines, and do some other processes on that and finally return those numbers in the last four lines. I cannot understand how to put all the numbers of the text file properly in a list. Right now the new_line generates a string of those lines with numbers

import string

def expand(chunk):
    l = chunk.split("*")
    chunk = [str(float(l[1]))] * int(l[0])

    return chunk

with open('old_textfile.txt', 'r') as infile1:
    for line in infile1:
        if set(string.ascii_letters.replace("e","")) & set(line):
            continue

        chunks = line.split(" ")
        #Get rid of newlines
        chunks = list(map(lambda chunk: chunk.strip(), chunks))
        if "/" in chunks:
            chunks.remove("/")

        new_chunks = []
        for i in range(len(chunks)):
            if '*' in chunks[i]:
                new_chunks += expand(chunks[i])
            else:
                new_chunks.append(chunks[i])
        new_chunks[len(new_chunks)-1] = new_chunks[len(new_chunks)-1]+"\n"
        new_line = " ".join(new_chunks)

when I use the

A = new_line.split()
B = list(map(float, A))

it returns an empty list. Do you have any idea how I can put all these numbers in one single list?
currently, I am writing the new_line as a textfile and reading it again, but it increase my runtime which is not good.

f = open('new_textfile.txt').read()
A = f.split()
B = list(map(float, A))
list_1.extend(B)

There was another solution to use Regex, but it deletes 3*2. I want to process that as 2 2 2

import re

with open('old_textfile.txt', 'r') as infile1:
    lines = infile1.read()

nums = re.findall(r'\d+\.\d+', lines)
print(nums)

Body:
I'm not quite sure if I entirely understand what you are trying to do, but as I understand it you want to extract all numbers which either are in a decimal form \d+\.\d+ or an integer which is multiplied by another integer using an asterisk, so \d+\*\d+. You want the results all in a list of floats where the decimals are in the list directly and for the integers the second is repeated by the first.

One way to do this would be:

lines = """
-- Generated ]
FILEUNIT
  METRIC /

Hello
-- timestep: Jan 01,2017 00:00:00
  3*2 344.0392 343.4564 343.7741
  343.9302 343.3884 343.7685 0.0000 341.0843
  342.2441 342.5899 343.0728 343.4850 342.8882
  342.0056 342.0564 341.9619 341.8840 342.0447 /
"""

nums = []
for n in re.findall(r'(\d+\.\d+|\d+\*\d+)', lines):
    split_by_ast = n.split("*")
    if len(split_by_ast) == 1:
        nums += [float(split_by_ast[0])]
    else:
        nums += [float(split_by_ast[1])] * int(split_by_ast[0])

print(nums)

Which returns:

[2.0, 2.0, 2.0, 344.0392, 343.4564, 343.7741, 343.9302, 343.3884, 343.7685, 0.0, 341.0843, 342.2441, 342.5899, 343.0728, 343.485, 342.8882, 342.0056, 342.0564, 341.9619, 341.884, 342.0447]

The regular expression searches for numbers matching one of the formats (decimal or int*int). Then in case of a decimal it is directly appended to the list, in case of int*int it is parsed to a smaller list repeating the second int by first int times, then the lists are concatenated.


问:
Check/Resolve cross-references in separate xml files

Starting point

Let's say we have a book in xml format. This book consists of many assets and these can reference each other by a tag ref-asset with attribute path. [Path-Mask: {id}|{version} of target-asset].

Important: Assets are single files and there is no merged, complete file.

Exemplary XML (merged for better visual view)

```<code><book>
    <!-- file a.xml -->
    <asset id="1" version="1.0">
        <name>Prolog</name>
    </asset>
    <!-- file b.xml -->
    <asset id="2" version="2">
        <name>Table of content</name>
        <list>
            <item><ref-asset path="1|1.0">Prolog</ref-asset></item>
            <item><ref-asset path="2|2.0">Table of content</ref-asset></item>
            <item><ref-asset path="3|1.1">FooBar</ref-asset></item>
        </list>
    </asset>
    <!-- file c.xml -->
    <asset id="3" version="1.1">
        <name>FooBar</name>
    </asset>
</book>
</code>```

Request

Check all ref-asset if linked target is in book.

Create report about results [exists, not exists, asset exists but wrong version, ...]

[in addition: Replace the reference with the content of target.]

Settings

Saxon 9.6.x EE XSLT 2.0

Java

100 up to x thousand single documents (combined filesize: upper 3 digit Mb)

How to solve

First attempt function collection() + function document():

Search for all single asset-files on filesystem via collection(), load them into process via document() and search for matching hits.

Second attempt Merged, complete File:

Merge all single assets into book and match via xsl:key or similiar techniques.

Question(s)

Is collection() capable of loading thousands of documents and still perform well with a followed document() to process the asset?

How to "index" run-timed loaded documents [still via xsl:key?] to search efficiently?

Further hints are highly appreciated / No specific stylsheet needed [i will do it on my own, as soon as i know what way to go].

EDITs: collection() returns already a sequence of document nodes, so document() might be unnecessary.

答:
I have written an npm package to resolve references in xml. Hope it serves your purpose
https://www.npmjs.com/package/xml-path-resolver.
This package would take the xml and return JSON with resolved paths

CODE USAGE

```<code>const xmlPathResolver = require("xml-path-resolver");
const xmlString = `
<?xml version="1.0" encoding="utf-8"?>
<note id="1212"  importance="high" logged="true" x_note="23">
    <title>Happy</title>
     <todo>Work</todo>
     <todo>Play</todo>
</note>
<note id="23" importance="high" logged="true">
</note>
<note importance="high" logged="true">
</note>
<person x_note="1212">
</person>
`;
const resolvedJSON = xmlPathResolver(xmlString,{ crossReference: /x_(.*)/ });

</code>```

Example :

```<code><?xml version="1.0" encoding="utf-8"?>
<note id="1212"  importance="high" logged="true" x_note="23">
    <title>Happy</title>
     <todo>Work</todo>
     <todo>Play</todo>
</note>
<note id="23" importance="high" logged="true">
</note>
<note importance="high" logged="true">
</note>
<person x_note="1212">
</person>
</code>```

The above xml has cross reference paths, The resolved JSON output is

```<code>{
  "_declaration": {
    "_attributes": {
      "version": "1.0",
      "encoding": "utf-8"
    }
  },
  "note": [
    {
      "_attributes": {
        "id": "1212",
        "importance": "high",
        "logged": "true",
        "x_note": {
          "_attributes": {
            "id": "23",
            "importance": "high",
            "logged": "true"
          }
        }
      },
      "title": {
        "_text": "Happy"
      },
      "todo": [
        {
          "_text": "Work"
        },
        {
          "_text": "Play"
        }
      ]
    },
    {
      "_attributes": {
        "id": "23",
        "importance": "high",
        "logged": "true"
      }
    },
    {
      "_attributes": {
        "importance": "high",
        "logged": "true"
      }
    }
  ],
  "person": {
    "_attributes": {
      "x_note": {
        "_attributes": {
          "id": "1212",
          "importance": "high",
          "logged": "true",
          "x_note": {
            "_attributes": {
              "id": "23",
              "importance": "high",
              "logged": "true"
            }
          }
        },
        "title": {
          "_text": "Happy"
        },
        "todo": [
          {
            "_text": "Work"
          },
          {
            "_text": "Play"
          }
        ]
      }
    }
  }
}
</code>```

Body:
Starting point

Let's say we have a book in xml format. This book consists of many assets and these can reference each other by a tag ref-asset with attribute path. [Path-Mask: {id}|{version} of target-asset].

Important: Assets are single files and there is no merged, complete file.

Exemplary XML (merged for better visual view)

<book>

    <asset id="1" version="1.0">
        <name>Prolog</name>
    </asset>

    <asset id="2" version="2">
        <name>Table of content</name>
        <list>
            <item><ref-asset path="1|1.0">Prolog</ref-asset></item>
            <item><ref-asset path="2|2.0">Table of content</ref-asset></item>
            <item><ref-asset path="3|1.1">FooBar</ref-asset></item>
        </list>
    </asset>

    <asset id="3" version="1.1">
        <name>FooBar</name>
    </asset>
</book>

Request

Check all ref-asset if linked target is in book.

Create report about results [exists, not exists, asset exists but wrong version, ...]

[in addition: Replace the reference with the content of target.]

Settings

Saxon 9.6.x EE XSLT 2.0

Java

100 up to x thousand single documents (combined filesize: upper 3 digit Mb)

How to solve

First attempt function collection() + function document():

Search for all single asset-files on filesystem via collection(), load them into process via document() and search for matching hits.

Second attempt Merged, complete File:

Merge all single assets into book and match via xsl:key or similiar techniques.

Question(s)

Is collection() capable of loading thousands of documents and still perform well with a followed document() to process the asset?

How to "index" run-timed loaded documents [still via xsl:key?] to search efficiently?

Further hints are highly appreciated / No specific stylsheet needed [i will do it on my own, as soon as i know what way to go].

EDITs: collection() returns already a sequence of document nodes, so document() might be unnecessary.

Body:
I have written an npm package to resolve references in xml. Hope it serves your purpose
https://www.npmjs.com/package/xml-path-resolver.
This package would take the xml and return JSON with resolved paths

CODE USAGE

const xmlPathResolver = require("xml-path-resolver");
const xmlString = `
<?xml version="1.0" encoding="utf-8"?>
<note id="1212"  importance="high" logged="true" x_note="23">
    <title>Happy</title>
     <todo>Work</todo>
     <todo>Play</todo>
</note>
<note id="23" importance="high" logged="true">
</note>
<note importance="high" logged="true">
</note>
<person x_note="1212">
</person>
`;
const resolvedJSON = xmlPathResolver(xmlString,{ crossReference: /x_(.*)/ });

Example :

<?xml version="1.0" encoding="utf-8"?>
<note id="1212"  importance="high" logged="true" x_note="23">
    <title>Happy</title>
     <todo>Work</todo>
     <todo>Play</todo>
</note>
<note id="23" importance="high" logged="true">
</note>
<note importance="high" logged="true">
</note>
<person x_note="1212">
</person>

The above xml has cross reference paths, The resolved JSON output is

{
  "_declaration": {
    "_attributes": {
      "version": "1.0",
      "encoding": "utf-8"
    }
  },
  "note": [
    {
      "_attributes": {
        "id": "1212",
        "importance": "high",
        "logged": "true",
        "x_note": {
          "_attributes": {
            "id": "23",
            "importance": "high",
            "logged": "true"
          }
        }
      },
      "title": {
        "_text": "Happy"
      },
      "todo": [
        {
          "_text": "Work"
        },
        {
          "_text": "Play"
        }
      ]
    },
    {
      "_attributes": {
        "id": "23",
        "importance": "high",
        "logged": "true"
      }
    },
    {
      "_attributes": {
        "importance": "high",
        "logged": "true"
      }
    }
  ],
  "person": {
    "_attributes": {
      "x_note": {
        "_attributes": {
          "id": "1212",
          "importance": "high",
          "logged": "true",
          "x_note": {
            "_attributes": {
              "id": "23",
              "importance": "high",
              "logged": "true"
            }
          }
        },
        "title": {
          "_text": "Happy"
        },
        "todo": [
          {
            "_text": "Work"
          },
          {
            "_text": "Play"
          }
        ]
      }
    }
  }
}


问:
difference between socket programming and Http programming
What is the difference between socket programming and Http programming? can anyone help please?</p>

答: Socket programming is a kind of middleware, residing between the application layer and the TCP layer. It's able to carry anything present in the application layer; even HTTP data.</p>


问:
Is there a R function that allows you to insert a variable inside a command?
For example:
Imagine I have an object named "cors" which contains a string only ("Spain" for example). I would like then for "cors" to be replaced in the expression (1) below by "Spain", resulting in the expression (2):

```<code>#(1)
DF <- DF %>% filter(str_detect(Country, "Germany|cors", negate = TRUE))
</code>```
```<code>#(2)
DF <- DF %>% filter(str_detect(Country, "Germany|Spain", negate = TRUE))
</code>```

P.S: I know that in MATLAB this could be handled with the "eval()" command, though in R it apparently has a completely different applicability.

答:
If you really want eval, you could do:

```<code>cors <- 'Spain'

DF <- DF %>% filter(
  eval(
    parse(text=paste0('str_detect(Country, "Germany|', cors, '", negate=TRUE)'))
  ))
</code>```

Body:
For example:
Imagine I have an object named "cors" which contains a string only ("Spain" for example). I would like then for "cors" to be replaced in the expression (1) below by "Spain", resulting in the expression (2):

#(1)
DF <- DF %>% filter(str_detect(Country, "Germany|cors", negate = TRUE))

#(2)
DF <- DF %>% filter(str_detect(Country, "Germany|Spain", negate = TRUE))

P.S: I know that in MATLAB this could be handled with the "eval()" command, though in R it apparently has a completely different applicability.

Body:
If you really want eval, you could do:

cors <- 'Spain'

DF <- DF %>% filter(
  eval(
    parse(text=paste0('str_detect(Country, "Germany|', cors, '", negate=TRUE)'))
  ))


问:
How to fix php shortcode to show woocommerce download button
I am trying to view the download button belonging to the last order placed by a customer. Basically I have this code. It worked for other things like: displaying the purchase date, order total, product name etc, but it doesn't work with the downlad.

```<code><?php

add_shortcode( 'order_download' , 'last_order_info_08' );
function last_order_info_08(){

// Get the WC_Customer instance Object for the current user
$customer = new WC_Customer( get_current_user_id() );

// Get the last WC_Order Object instance from current customer
$last_order = $customer->get_last_order();

// If this is the last order, then it shows the data from it
  if ( is_a( $last_order, 'WC_Order' ) ) {
     return $last_order->get_downloadable_items();
     }
}
</code>```

return $last_order->get_downloadable_items(); it shows the word array instead of the download button. Could someone tell me where am I wrong? Excuse me, but I am relatively new to php.

// Edit - With probable solution //

Maybe I have found a solution. I modified the code by adding wc_get_template and array. This works well for users who have a download available. Unfortunately, however, users who have not made any purchases and therefore do not have a download available find themselves with a broken layout.

Is there any way to display an error message? or to correct this in any other way?

```<code><?php
add_shortcode( 'order_download' , 'last_order_info_08' );
function last_order_info_08(){

// Get the WC_Customer instance Object for the current user
$customer = new WC_Customer( get_current_user_id() );

// Get the last WC_Order Object instance from current customer
$last_order = $customer->get_last_order();

// Works with array
$downloads = $last_order->get_downloadable_items();

// If this is the last order, then it shows the data from it
    if ( is_a( $last_order, 'WC_Order' ) ) {
        wc_get_template('button-downloads.php',
        array(
            'downloads'  => $downloads,
            'show_title' => true,
         )
     );
     }
}
</code>```

答:
```<code><?php
add_shortcode( 'order_download' , 'last_order_info_08' );
function last_order_info_08(){

// Get the WC_Customer instance Object for the current user
$customer = new WC_Customer( get_current_user_id() );

// Get the last WC_Order Object instance from current customer
$last_order = $customer->get_last_order();

// If this is the last order shows the data from it
  if ( is_a( $last_order, 'WC_Order' ) ) {

     // Works with array below
     $downloads = $last_order->get_downloadable_items();

     if ($downloads){
         wc_get_template(
         'button-downloads.php', // This is a template I placed in wp-content/themes/theme-child/woocommerce
         array(
         'downloads'  => $downloads,
         'show_title' => true,
         ));
         }
     }

//The else part shows the warning message when a user has no order, this does not break the layout.
  else {
        ?><div class="woocommerce-message woocommerce-message--info woocommerce-Message woocommerce-Message--info woocommerce-info">
        <a class="woocommerce-Button button" href="<?php echo esc_url( apply_filters( 'woocommerce_return_to_shop_redirect', wc_get_page_permalink( 'shop' ) ) ); ?>"><?php esc_html_e( 'Browse products', 'woocommerce' ); ?></a>
        <?php esc_html_e( 'No order has been made yet.', 'woocommerce' ); ?>
        </div><?php
    }
}
</code>```

Body:
I am trying to view the download button belonging to the last order placed by a customer. Basically I have this code. It worked for other things like: displaying the purchase date, order total, product name etc, but it doesn't work with the downlad.

<?php

add_shortcode( 'order_download' , 'last_order_info_08' );
function last_order_info_08(){

// Get the WC_Customer instance Object for the current user
$customer = new WC_Customer( get_current_user_id() );

// Get the last WC_Order Object instance from current customer
$last_order = $customer->get_last_order();

// If this is the last order, then it shows the data from it
  if ( is_a( $last_order, 'WC_Order' ) ) {
     return $last_order->get_downloadable_items();
     }
}

return $last_order->get_downloadable_items(); it shows the word array instead of the download button. Could someone tell me where am I wrong? Excuse me, but I am relatively new to php.

// Edit - With probable solution //

Maybe I have found a solution. I modified the code by adding wc_get_template and array. This works well for users who have a download available. Unfortunately, however, users who have not made any purchases and therefore do not have a download available find themselves with a broken layout.

Is there any way to display an error message? or to correct this in any other way?

<?php
add_shortcode( 'order_download' , 'last_order_info_08' );
function last_order_info_08(){

// Get the WC_Customer instance Object for the current user
$customer = new WC_Customer( get_current_user_id() );

// Get the last WC_Order Object instance from current customer
$last_order = $customer->get_last_order();

// Works with array
$downloads = $last_order->get_downloadable_items();

// If this is the last order, then it shows the data from it
    if ( is_a( $last_order, 'WC_Order' ) ) {
        wc_get_template('button-downloads.php',
        array(
            'downloads'  => $downloads,
            'show_title' => true,
         )
     );
     }
}


问:
R portfolio analytics (optimize.portfolio.rebalancing function with random optimizer does not work)
I got an error when running optimize.portfolio.rebalancing, with optimize_method="random". The error is:

"Leverage constraint min_sum and max_sum are restrictive, consider relaxing. e.g. 'full_investment' constraint should be min_sum=0.99 and max_sum=1.01".

I tried to modify the codes with the following:

```<code>port_spec <- portfolio.spec(assets=colnames(asset_returns), weight_seq=generatesequence(min=0, max=1, by=0.002))
port_spec$constraints[[1]]$min_sum=0.99
port_spec$constraints[[1]]$max_sum=1.01
port_spec <- add.constraint(portfolio=port_spec, type="box", min=0, max=0.5)
</code>```

, but the code still couldn't work. Any advice would be grateful!

The original code is the following:

```<code>    library(PortfolioAnalytics)

   data(edhec)

    asset_returns <- edhec

    port_spec <- portfolio.spec(assets=colnames(asset_returns))

# Add a full investment constraint such that the weights sum to 1

    port_spec <- add.constraint(portfolio=port_spec, type="full_investment")

# Add a long only constraint such that the weight of an asset is between 0 and 1

    port_spec <- add.constraint(portfolio=port_spec, type="long_only")

# Add an objective to minimize portfolio standard deviation

    port_spec <- add.objective(portfolio=port_spec, type="risk", name="StdDev")

# Add a risk budget objective

    port_spec <- add.objective(portfolio = port_spec,
                               type = "risk_budget",
                               name = "StdDev",
                               min_prisk = 0.01,
                               max_prisk = 0.4)

# Print the portfolio specification

    print(port_spec)

# Run the optimization

    rp <- 50
    opt_rebal_rb <- optimize.portfolio.rebalancing(R = asset_returns,
                                                   portfolio = port_spec,
                                                   optimize_method = "random", rp =rp,
                                                   trace = TRUE,
                                                   rebalance_on = "quarters",
                                                   training_period = 60,
                                                   rolling_window = 60)
    print(opt_rebal_rb)

# Chart the weights

    chart.Weights(opt_rebal_rb)

# Chart the percentage contribution to risk

    chart.RiskBudget(opt_rebal_rb, match.col = "StdDev", risk.type = "percentage")

# Compute the portfolio returns

    returns_rb <- Return.portfolio(R = asset_returns, weights = extractWeights(opt_rebal_rb))
    colnames(returns_rb) <- "risk_budget"

</code>```

答:
I know it is very very late, but it might serve for future reference.

```<code>port_spec <- add.constraint( portfolio = port_spec,
                             type = "box",
                             min = 0,
                             max= 1 )
</code>```

Adding this constraint solved the issue for me.

Body:
I got an error when running optimize.portfolio.rebalancing, with optimize_method="random". The error is:

"Leverage constraint min_sum and max_sum are restrictive, consider relaxing. e.g. 'full_investment' constraint should be min_sum=0.99 and max_sum=1.01".

I tried to modify the codes with the following:

port_spec <- portfolio.spec(assets=colnames(asset_returns), weight_seq=generatesequence(min=0, max=1, by=0.002))
port_spec$constraints[[1]]$min_sum=0.99
port_spec$constraints[[1]]$max_sum=1.01
port_spec <- add.constraint(portfolio=port_spec, type="box", min=0, max=0.5)

, but the code still couldn't work. Any advice would be grateful!

The original code is the following:

    library(PortfolioAnalytics)

   data(edhec)

    asset_returns <- edhec

    port_spec <- portfolio.spec(assets=colnames(asset_returns))

# Add a full investment constraint such that the weights sum to 1

    port_spec <- add.constraint(portfolio=port_spec, type="full_investment")

# Add a long only constraint such that the weight of an asset is between 0 and 1

    port_spec <- add.constraint(portfolio=port_spec, type="long_only")

# Add an objective to minimize portfolio standard deviation

    port_spec <- add.objective(portfolio=port_spec, type="risk", name="StdDev")

# Add a risk budget objective

    port_spec <- add.objective(portfolio = port_spec,
                               type = "risk_budget",
                               name = "StdDev",
                               min_prisk = 0.01,
                               max_prisk = 0.4)

# Print the portfolio specification

    print(port_spec)

# Run the optimization

    rp <- 50
    opt_rebal_rb <- optimize.portfolio.rebalancing(R = asset_returns,
                                                   portfolio = port_spec,
                                                   optimize_method = "random", rp =rp,
                                                   trace = TRUE,
                                                   rebalance_on = "quarters",
                                                   training_period = 60,
                                                   rolling_window = 60)
    print(opt_rebal_rb)

# Chart the weights

    chart.Weights(opt_rebal_rb)

# Chart the percentage contribution to risk

    chart.RiskBudget(opt_rebal_rb, match.col = "StdDev", risk.type = "percentage")

# Compute the portfolio returns

    returns_rb <- Return.portfolio(R = asset_returns, weights = extractWeights(opt_rebal_rb))
    colnames(returns_rb) <- "risk_budget"

Body:
I know it is very very late, but it might serve for future reference.

port_spec <- add.constraint( portfolio = port_spec,
                             type = "box",
                             min = 0,
                             max= 1 )

Adding this constraint solved the issue for me.