问:
Is there a way to override inline CSS for `overflow`?
If I want override inline css i must use !important or javascript.

But if I want to override, for example, inline width without important I can use max-width or min-width

Is there some way to override inline

```<code>  overflow:hidden
</code>```

答:
Using CSS

You can override the inline style using !important keyword like below. The inline style background green is override with other color through the class style using !important keyword.

.test {
 background-color:#ff00ff !important;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="test" style="background-color:green">
<h1>
Sample
</h1>
</div></code>```

Using Javascript

The same you can achieve using JavaScript also.

document.getElementById('test').style.backgroundColor = '#fff000';```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="test" style="background-color:green">
<h1>
Sample
</h1>
</div></code>```

Body:
If I want override inline css i must use !important or javascript.

But if I want to override, for example, inline width without important I can use max-width or min-width

Is there some way to override inline

  overflow:hidden

Body:
Using CSS

You can override the inline style using !important keyword like below. The inline style background green is override with other color through the class style using !important keyword.

.test {
 background-color:#ff00ff !important;
}

<div class="test" style="background-color:green">
<h1>
Sample
</h1>
</div>

Using Javascript

The same you can achieve using JavaScript also.

document.getElementById('test').style.backgroundColor = '#fff000';

<div id="test" style="background-color:green">
<h1>
Sample
</h1>
</div>


来源: stackexchange

问:
is nested choice state possible in spring state machine
Can we define multiple choice sequentially(nested if) with in a spring state machine like below

```<code>.withStates()
            .initial(States.READY)
            .fork(States.FORK)
            .state(States.TASKS)
            .join(States.JOIN)
            .choice(States.CHOICE1)
            .choice(States.CHOICE2)
            .state(States.ERROR)
</code>```

How can i define choice state for below flowchart section

答: Simple answer yes. Might be that this is not mentioned in docs but there is a test for this testSubsequentChoiceStates. </p>

ContentLicense: CC BY-SA 3.0

Body:
Can we define multiple choice sequentially(nested if) with in a spring state machine like below

.withStates()
            .initial(States.READY)
            .fork(States.FORK)
            .state(States.TASKS)
            .join(States.JOIN)
            .choice(States.CHOICE1)
            .choice(States.CHOICE2)
            .state(States.ERROR)

How can i define choice state for below flowchart section


问:
Sleep breaks the script
I want simply to set a sleep in a loop. But it doesn't work as expected

```<code>for ($i = 1; $i <= 6; $i++) {
    echo $i;
    sleep(1);
}
</code>```

if the loop takes more than 5 seconds. It doesn't work (don't print at all).

I tested it in Teh Playground, and this error appears :

Execution took longer than 5 seconds, sent SIGTERM and terminated

Edit : Modifying set_time_limit doesn't change anything...

It seems it's related to my server's config...

答: This works fine when I ran it in my local machine. I think your script execution getting timed out at Teh Playground when it takes more than 5 seconds to execute. </p>

Title: Sleep breaks the script

Body:
I want simply to set a sleep in a loop. But it doesn't work as expected

for ($i = 1; $i <= 6; $i++) {
    echo $i;
    sleep(1);
}

if the loop takes more than 5 seconds. It doesn't work (don't print at all).

I tested it in Teh Playground, and this error appears :

Execution took longer than 5 seconds, sent SIGTERM and terminated

Edit : Modifying set_time_limit doesn't change anything...

It seems it's related to my server's config...


问:
Python: Solving knapsack optimization with a genetic algorithm?
currently I am trying to wrap my head around the best way to accomplish what I am doing. I have the following pandas df.

```<code>    Player  Pos Salary  My Proj
0   James Harden    PG/SG   10600   51.94472302
1   Jose Juan Barea PG/SG   4200    22.20823452
2   Stephen Curry   PG/SG   8700    42.95809374
3   Eric Gordon     SG      5400    27.45218158
4   Nikola Vucevic  C       7400    37.00103015
5   Wilson Chandler SF/PF   4900    24.83866589
</code>```

This goes on for roughly 200 players every day. I need to run an optimization to fill up to 20 lineups on draftkings that follow the following constraints:

Under $50,000
Using 1 PG, 1 SG, 1 SF, 1 PF, 1 C, 1 G, 1 F, and 1 UTIL

As you can see most players can fill multiple positions in a single lineup denoted by the "/" character in the position column. The G position can be filled with either a PG or a SG and the F position can be filled with a SF or PF with the UTIL position accepting all positions.

At first I looked into using a knapsack brute force approach which seemed to be the simplest but there are literally trillions of combinations, so this would take an outrageous amount of time without ever really doing what I truly want.

Instead I decided to try using a genetics approach as I have been watching many lecture videos on this and think it is a great idea for this problem. However, I don't know how to set this problem up in a general 1/0 knapsack approach as there are numerous things I need to include. In a typical knapsack approach you just have a weight and a value. My weight and values are the players salary and their projected score. However I have to include the position of the player in here as well, which can be 1 or sometimes 2 different possibilities for one player.

Hopefully this makes sense, and I am basically looking for some sort of insight on how to begin tackling this task within Python 3. Thanks ahead of time for anything you can provide!

答:
Here is a good start:

Fully understand the basics of a Genetic Algorithm, good example here.

The beauty of genetic algorithms are that once you define how to evaluate fitness, everything else falls into place on its own.  You could start with completely random items and over successive generations it will become orderly.  The lineup and knapsack problem are very, very similar if you approach it the right way.  You already know how many items can fit (head-start); you now just have to select which ones and that is where the GA comes in.

Think of these steps:

Create your population(random lineups)

Check the fitness of the population, are the positions filled, salary less than the maximum, etc

Evolve the population while grading the lineups

Continue with new generations until you are satisfied.

Body:
currently I am trying to wrap my head around the best way to accomplish what I am doing. I have the following pandas df.

    Player  Pos Salary  My Proj
0   James Harden    PG/SG   10600   51.94472302
1   Jose Juan Barea PG/SG   4200    22.20823452
2   Stephen Curry   PG/SG   8700    42.95809374
3   Eric Gordon     SG      5400    27.45218158
4   Nikola Vucevic  C       7400    37.00103015
5   Wilson Chandler SF/PF   4900    24.83866589

This goes on for roughly 200 players every day. I need to run an optimization to fill up to 20 lineups on draftkings that follow the following constraints:

Under $50,000
Using 1 PG, 1 SG, 1 SF, 1 PF, 1 C, 1 G, 1 F, and 1 UTIL

As you can see most players can fill multiple positions in a single lineup denoted by the "/" character in the position column. The G position can be filled with either a PG or a SG and the F position can be filled with a SF or PF with the UTIL position accepting all positions.

At first I looked into using a knapsack brute force approach which seemed to be the simplest but there are literally trillions of combinations, so this would take an outrageous amount of time without ever really doing what I truly want.

Instead I decided to try using a genetics approach as I have been watching many lecture videos on this and think it is a great idea for this problem. However, I don't know how to set this problem up in a general 1/0 knapsack approach as there are numerous things I need to include. In a typical knapsack approach you just have a weight and a value. My weight and values are the players salary and their projected score. However I have to include the position of the player in here as well, which can be 1 or sometimes 2 different possibilities for one player.

Hopefully this makes sense, and I am basically looking for some sort of insight on how to begin tackling this task within Python 3. Thanks ahead of time for anything you can provide!


问:
Installing Laravel homestead on a virtual machine in windows 10 - after I created a VM box do I need to install virtualbox again within this box?
Trying to install laravel homestead in windows but inside a virtualbox. So first I installed VirtualBox which then allows me to install a VM which I called LaravelBox (so this is an empty machine) - which means I need to install ubuntu 16.04, then vagrant (as the documents on the laravel homestead site (https://laravel.com/docs/5.5/homestead#installation-and-setup) - which instruct me to install the homestead vagrant box, then configure, etc. When I get to he final step to run vagrant up, I get the error:

```<code>**Vagrant could not detect VirtualBox! Make sure VirtualBox is properly installed.
</code>```

Vagrant uses the VBoxManage binary that ships with VirtualBox, and requires
this to be available on the PATH. If VirtualBox is installed, please find the
VBoxManage binary and add it to the PATH environmental variable.**

Does this mean then I now need to install virtualbox inside the VM I just created called LaravelBox? - so it's the case of a VM that contains the laravel homestead vagrant box is inside a a VM? Any help is appreciated, thanks.

答:
The first question why you try to install homestead in a VM instead of installing it in Windows directly?

Yes, the problem is that your VM can't find any Virtualbox installation, then you have to install it there and it will be working.

Body:
Trying to install laravel homestead in windows but inside a virtualbox. So first I installed VirtualBox which then allows me to install a VM which I called LaravelBox (so this is an empty machine) - which means I need to install ubuntu 16.04, then vagrant (as the documents on the laravel homestead site (https://laravel.com/docs/5.5/homestead#installation-and-setup) - which instruct me to install the homestead vagrant box, then configure, etc. When I get to he final step to run vagrant up, I get the error:

**Vagrant could not detect VirtualBox! Make sure VirtualBox is properly installed.

Vagrant uses the VBoxManage binary that ships with VirtualBox, and requires
this to be available on the PATH. If VirtualBox is installed, please find the
VBoxManage binary and add it to the PATH environmental variable.**

Does this mean then I now need to install virtualbox inside the VM I just created called LaravelBox? - so it's the case of a VM that contains the laravel homestead vagrant box is inside a a VM? Any help is appreciated, thanks.


问:
How to break a line of chained methods in Python?
I have a line of the following code (don't blame for naming conventions, they are not mine):

```<code>subkeyword = Session.query(
    Subkeyword.subkeyword_id, Subkeyword.subkeyword_word
).filter_by(
    subkeyword_company_id=self.e_company_id
).filter_by(
    subkeyword_word=subkeyword_word
).filter_by(
    subkeyword_active=True
).one()
</code>```

I don't like how it looks like (not too readable) but I don't have any better idea to limit lines to 79 characters in this situation. Is there a better way of breaking it (preferably without backslashes)?

答:
You could use additional parentheses:</p>
```<code>subkeyword = (
        Session.query(Subkeyword.subkeyword_id, Subkeyword.subkeyword_word)
        .filter_by(subkeyword_company_id=self.e_company_id)
        .filter_by(subkeyword_word=subkeyword_word)
        .filter_by(subkeyword_active=True)
        .one()
    )
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a line of the following code (don't blame for naming conventions, they are not mine):

subkeyword = Session.query(
    Subkeyword.subkeyword_id, Subkeyword.subkeyword_word
).filter_by(
    subkeyword_company_id=self.e_company_id
).filter_by(
    subkeyword_word=subkeyword_word
).filter_by(
    subkeyword_active=True
).one()

I don't like how it looks like (not too readable) but I don't have any better idea to limit lines to 79 characters in this situation. Is there a better way of breaking it (preferably without backslashes)?

Body:
You could use additional parentheses:

subkeyword = (
        Session.query(Subkeyword.subkeyword_id, Subkeyword.subkeyword_word)
        .filter_by(subkeyword_company_id=self.e_company_id)
        .filter_by(subkeyword_word=subkeyword_word)
        .filter_by(subkeyword_active=True)
        .one()
    )

ContentLicense: CC BY-SA 4.0


问:
How to consistently set EditText Selected Underline Color Programmatically
I'm trying to build a renderer for Xamarin Forms. The renderer needs to set the EditText underline color to "Active Color" when selected and "Hint Color" when deselected. My initial setup looks something like this.

note: here's the path to the full source file

https://github.com/XamFormsExtended/Xfx.Controls/blob/issue-%236/src/Xfx.Controls.Droid/Renderers/XfxEntryRendererDroid.cs

```<code>// called when control is created or when Colors are changed.
protected virtual void SetLabelAndUnderlineColor()
{
    var defaultColor = GetPlaceholderColor();
    var activeColor = GetActivePlaceholderColor();

    SetHintLabelDefaultColor(defaultColor);
    SetHintLabelActiveColor(activeColor);
    SetUnderlineColor(_hasFocus ? activeColor : defaultColor);
}

private void SetUnderlineColor(AColor color)
{
    var bg = ColorStateList.ValueOf(color);
    ViewCompat.SetBackgroundTintList(EditText,bg);
}

private void SetHintLabelActiveColor(AColor color)
{
    var hintText = Control.Class.GetDeclaredField("mFocusedTextColor");
    hintText.Accessible = true;
    hintText.Set(Control, new ColorStateList(new int[][] { new[] { 0 } }, new int[] { color }));
}

private void SetHintLabelDefaultColor(AColor color)
{
    var hint = Control.Class.GetDeclaredField("mDefaultTextColor");
    hint.Accessible = true;
    hint.Set(Control, new ColorStateList(new int[][] { new[] { 0 } }, new int[] { color }));
}
</code>```

Outside of this, I also have an OnClickListener that updates the underline only when the state changes

```<code>private void ControlOnFocusChange(object sender, FocusChangeEventArgs args)
{
    _hasFocus = args.HasFocus;
    SetUnderlineColor(args.HasFocus ? GetPlaceholderColor() : GetActivePlaceholderColor());
}
</code>```

The problem is that when I tap into the EditText, it's hit or miss as to what I'm going to see for an underline color.
I can pretty much guarantee that it'll be the default android:colorAccent the very first time. Then after that it switches between the "Hint Color" and the "Placeholder Color".

note: if I change the SetUnderlineColor method to this (below), it no longer uses the "Hint Color" in the mix, but I still get the android:colorAccent color as the initial underline color, after that it behaves as expected.

```<code>private void SetUnderlineColor(AColor color)
{
    var bg = EditText.Background;
    DrawableCompat.SetTint(bg,color);
    EditText.SetBackground(bg);
}
</code>```

What do I need to do to set the INITIAL selected color of the EditText to my chosen activeColor / 'focused color' (purple)?

In this animation I am simply selecting and deselecting the EditText

答:
Why don't you change the tint colour at runtime using this (May be in your text changed event):

```<code>ViewCompat.SetBackgroundTintList(_YourView , ColorStateList.ValueOf(Color.ParseColor(Resources.GetString(Resource.Color.blueLine))));
</code>```

Anyways Goodluck!

Body:
I'm trying to build a renderer for Xamarin Forms. The renderer needs to set the EditText underline color to "Active Color" when selected and "Hint Color" when deselected. My initial setup looks something like this.

note: here's the path to the full source file

https://github.com/XamFormsExtended/Xfx.Controls/blob/issue-%236/src/Xfx.Controls.Droid/Renderers/XfxEntryRendererDroid.cs

// called when control is created or when Colors are changed.
protected virtual void SetLabelAndUnderlineColor()
{
    var defaultColor = GetPlaceholderColor();
    var activeColor = GetActivePlaceholderColor();

    SetHintLabelDefaultColor(defaultColor);
    SetHintLabelActiveColor(activeColor);
    SetUnderlineColor(_hasFocus ? activeColor : defaultColor);
}

private void SetUnderlineColor(AColor color)
{
    var bg = ColorStateList.ValueOf(color);
    ViewCompat.SetBackgroundTintList(EditText,bg);
}

private void SetHintLabelActiveColor(AColor color)
{
    var hintText = Control.Class.GetDeclaredField("mFocusedTextColor");
    hintText.Accessible = true;
    hintText.Set(Control, new ColorStateList(new int[][] { new[] { 0 } }, new int[] { color }));
}

private void SetHintLabelDefaultColor(AColor color)
{
    var hint = Control.Class.GetDeclaredField("mDefaultTextColor");
    hint.Accessible = true;
    hint.Set(Control, new ColorStateList(new int[][] { new[] { 0 } }, new int[] { color }));
}

Outside of this, I also have an OnClickListener that updates the underline only when the state changes

private void ControlOnFocusChange(object sender, FocusChangeEventArgs args)
{
    _hasFocus = args.HasFocus;
    SetUnderlineColor(args.HasFocus ? GetPlaceholderColor() : GetActivePlaceholderColor());
}

The problem is that when I tap into the EditText, it's hit or miss as to what I'm going to see for an underline color.
I can pretty much guarantee that it'll be the default android:colorAccent the very first time. Then after that it switches between the "Hint Color" and the "Placeholder Color".

note: if I change the SetUnderlineColor method to this (below), it no longer uses the "Hint Color" in the mix, but I still get the android:colorAccent color as the initial underline color, after that it behaves as expected.

private void SetUnderlineColor(AColor color)
{
    var bg = EditText.Background;
    DrawableCompat.SetTint(bg,color);
    EditText.SetBackground(bg);
}

What do I need to do to set the INITIAL selected color of the EditText to my chosen activeColor / 'focused color' (purple)?

In this animation I am simply selecting and deselecting the EditText

Body:
Why don't you change the tint colour at runtime using this (May be in your text changed event):

ViewCompat.SetBackgroundTintList(_YourView , ColorStateList.ValueOf(Color.ParseColor(Resources.GetString(Resource.Color.blueLine))));

Anyways Goodluck!


问:
JavaFX Login hide buttons
I made a function in my program which alllows employees to login in an application I made. The code for that looks like this:

LoginController:

```<code>//Login for employee
@FXML
private TextField textUsername;

@FXML
private PasswordField textPassword;

@FXML
private ChoiceBox<String> EmpSelect;

Stage dialogStage = new Stage();
Scene scene;

Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;

public LoginController() {
    connection = sqlDatabaseConnection.connectdb();
}

//Login for employee
@FXML
private void handleButtonAction(ActionEvent event) {
    String username = textUsername.getText().toString();
    String password = textPassword.getText().toString();
    String function = EmpSelect.getValue().toString();
    String sql = "SELECT * FROM Employee WHERE username = ? and password = ? and function = ?";

    try {
        preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1, username);
        preparedStatement.setString(2, password);
        preparedStatement.setString(3, function);
        resultSet = preparedStatement.executeQuery();

        if (!resultSet.next()) {
            infoBox("Enter Correct Username and Password", "Failed", null);
        } else {

            if ("Employee".equals(function)) {
                infoBox("Login Successfull", "Success", null);
                FXMLDocumentController controller = new FXMLDocumentController();
                controller.newAnchorpane("WorkerHomescreen", paneLogin);
            } else if ("Manager".equals(function)) {
                infoBox("Login Successfull", "Success", null);
                FXMLDocumentController controller = new FXMLDocumentController();
                controller.newAnchorpane("WorkerHomescreen", paneLogin);
            }
        }

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

public static void infoBox(String infoMessage, String titleBar, String headerMessage) {
    Alert alert = new Alert(AlertType.INFORMATION);
    alert.setTitle(titleBar);
    alert.setHeaderText(headerMessage);
    alert.setContentText(infoMessage);
    alert.showAndWait();
}
</code>```

With this piece of code employees are able to login.
This works all fine and dandy.
As you can see with this code it checks in the choiceBox if you want to login as a employee or a manager, and than it redirects you to the correct page.

The thing is that if you login as a manager you will be able to see all the buttons and labels.
And when you login as a employee you will be able to see only a few buttons and labels.

I want this to happen when the page loads after the login. And seeing as I want to login to the page called: WorkerHomescreen.fxml I thought it would be handy to put some code in this class.

WorkerHomescreen class:

```<code>Connection connection = null;
public WorkerHomescreenController() {
    connection = sqlDatabaseConnection.connectdb();
}

@Override
public void initialize(URL url, ResourceBundle rb) {
    String Check = "SELECT * FROM Employee WHERE function = 'employee'";
    but4.setVisible(false);
}
</code>```

So basically with this piece of code I want to make it so that the query checks if you logged in as a employee. And if that is the case the button called "but4" will become invisible.
I tried this and it doesn't work. It hides the button even if you are logged in as a manager.

So I was wondering what I am doing wrong here and if someone can help me with this.

If I missed something please let me know and I will post it in the comments below.

答:
Hiding and displaying controls depending on the role of the user is a solution, but perhaps not the most appropriate.
You have the option to take advantage of the principles of object-oriented programming.

Make two different views, one for workers and one for managers, using common identifiers for general controls. Do two different controllers, like the one for managers, to be the successor to the controller for the workers. This will give you a logical separation of both views and allowed features for each user group.

Here is a sample implementation.

These are the two controllers: worker_homescreen.fxml

```<code><VBox xmlns="http://javafx.com/javafx" xmlns:fx="http://javafx.com/fxml" fx:controller="sample.WorkerController">
    <children>
        <Label text="Worker"/>
        <Button text="Different Action Button" onAction="#handleDifferentActionButton"/>
        <Button text="General Action Button" onAction="#handleGeneralActionButton"/>
    </children>
</VBox>
</code>```

and manager_homescreen.fxml

```<code><VBox xmlns="http://javafx.com/javafx" xmlns:fx="http://javafx.com/fxml" fx:controller="sample.ManagerController">
    <children>
        <Label text="Manager"/>
        <Button text="Manager Only Button" onAction="#handleManagerButton"/>
        <Button text="Different Action Button" onAction="#handleDifferentActionButton"/>
        <Button text="General Action Button" onAction="#handleGeneralActionButton"/>
    </children>
</VBox>
</code>```

The General Action Button is a control available in both views, which performs the same function. Different Action Button is also available in both views but performs different things depending on which view is loaded. And, of course, Manager Only Button is only available in the Mannard view and performs a specific feature available only for Managers.

All this "magic" comes from the inheritance of the controllers used.

```<code>public class WorkerController {

    @FXML
    protected void initialize() {

    }

    @FXML
    protected void handleDifferentActionButton(ActionEvent event) {

    }

    @FXML
    protected void handleGeneralActionButton(ActionEvent event) {

    }
}

public class ManagerController extends WorkerController {

    @FXML
    @Override
    protected void initialize() {
        super.initialize();
    }

    @FXML
    protected void handleManagerButton(ActionEvent event) {

    }

    @FXML
    @Override
    protected void handleDifferentActionButton(ActionEvent event) {

    }
}
</code>```

As you can see, logic is cleared and you do not have to constantly hide and show controls. You can concentrate on implementing business logic because you will not have to constantly check the role of the user. This is done once when logging in.

```<code>public class Controller {
    private static final String WORKER = "/sample/worker_homescreen.fxml";
    private static final String MANAGER = "/sample/manager_homescreen.fxml";

    @FXML
    private void handleLoginButton() {
        ...

        if (!resultSet.next()) {
            infoBox("Enter Correct Username and Password", "Failed", null);
        } else {
            if ("Employee".equals(function)) {
                infoBox("Login Successfull", "Success", null);
                showMainView(getClass().getResource(WORKER));

            } else if ("Manager".equals(function)) {
                infoBox("Login Successfull", "Success", null);
                showMainView(getClass().getResource(MANAGER));
            }
        }
    }

    private void showMainView(URL url) {
        try {
            Parent parent = FXMLLoader.load(url);

            Stage stage = new Stage();
            stage.setScene(new Scene(parent, 800, 600));
            stage.show();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}
</code>```

The best thing about this approach is that you can easily add roles without affecting the existing logic.

Title: JavaFX Login hide buttons

Body:
I made a function in my program which alllows employees to login in an application I made. The code for that looks like this:

LoginController:

//Login for employee
@FXML
private TextField textUsername;

@FXML
private PasswordField textPassword;

@FXML
private ChoiceBox<String> EmpSelect;

Stage dialogStage = new Stage();
Scene scene;

Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;

public LoginController() {
    connection = sqlDatabaseConnection.connectdb();
}

//Login for employee
@FXML
private void handleButtonAction(ActionEvent event) {
    String username = textUsername.getText().toString();
    String password = textPassword.getText().toString();
    String function = EmpSelect.getValue().toString();
    String sql = "SELECT * FROM Employee WHERE username = ? and password = ? and function = ?";

    try {
        preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1, username);
        preparedStatement.setString(2, password);
        preparedStatement.setString(3, function);
        resultSet = preparedStatement.executeQuery();

        if (!resultSet.next()) {
            infoBox("Enter Correct Username and Password", "Failed", null);
        } else {

            if ("Employee".equals(function)) {
                infoBox("Login Successfull", "Success", null);
                FXMLDocumentController controller = new FXMLDocumentController();
                controller.newAnchorpane("WorkerHomescreen", paneLogin);
            } else if ("Manager".equals(function)) {
                infoBox("Login Successfull", "Success", null);
                FXMLDocumentController controller = new FXMLDocumentController();
                controller.newAnchorpane("WorkerHomescreen", paneLogin);
            }
        }

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

public static void infoBox(String infoMessage, String titleBar, String headerMessage) {
    Alert alert = new Alert(AlertType.INFORMATION);
    alert.setTitle(titleBar);
    alert.setHeaderText(headerMessage);
    alert.setContentText(infoMessage);
    alert.showAndWait();
}

With this piece of code employees are able to login.
This works all fine and dandy.
As you can see with this code it checks in the choiceBox if you want to login as a employee or a manager, and than it redirects you to the correct page.

The thing is that if you login as a manager you will be able to see all the buttons and labels.
And when you login as a employee you will be able to see only a few buttons and labels.

I want this to happen when the page loads after the login. And seeing as I want to login to the page called: WorkerHomescreen.fxml I thought it would be handy to put some code in this class.

WorkerHomescreen class:

Connection connection = null;
public WorkerHomescreenController() {
    connection = sqlDatabaseConnection.connectdb();
}

@Override
public void initialize(URL url, ResourceBundle rb) {
    String Check = "SELECT * FROM Employee WHERE function = 'employee'";
    but4.setVisible(false);
}

So basically with this piece of code I want to make it so that the query checks if you logged in as a employee. And if that is the case the button called "but4" will become invisible.
I tried this and it doesn't work. It hides the button even if you are logged in as a manager.

So I was wondering what I am doing wrong here and if someone can help me with this.

If I missed something please let me know and I will post it in the comments below.

Body:
Hiding and displaying controls depending on the role of the user is a solution, but perhaps not the most appropriate.
You have the option to take advantage of the principles of object-oriented programming.

Make two different views, one for workers and one for managers, using common identifiers for general controls. Do two different controllers, like the one for managers, to be the successor to the controller for the workers. This will give you a logical separation of both views and allowed features for each user group.

Here is a sample implementation.

These are the two controllers: worker_homescreen.fxml

<VBox xmlns="http://javafx.com/javafx" xmlns:fx="http://javafx.com/fxml" fx:controller="sample.WorkerController">
    <children>
        <Label text="Worker"/>
        <Button text="Different Action Button" onAction="#handleDifferentActionButton"/>
        <Button text="General Action Button" onAction="#handleGeneralActionButton"/>
    </children>
</VBox>

and manager_homescreen.fxml

<VBox xmlns="http://javafx.com/javafx" xmlns:fx="http://javafx.com/fxml" fx:controller="sample.ManagerController">
    <children>
        <Label text="Manager"/>
        <Button text="Manager Only Button" onAction="#handleManagerButton"/>
        <Button text="Different Action Button" onAction="#handleDifferentActionButton"/>
        <Button text="General Action Button" onAction="#handleGeneralActionButton"/>
    </children>
</VBox>

The General Action Button is a control available in both views, which performs the same function. Different Action Button is also available in both views but performs different things depending on which view is loaded. And, of course, Manager Only Button is only available in the Mannard view and performs a specific feature available only for Managers.

All this "magic" comes from the inheritance of the controllers used.

public class WorkerController {

    @FXML
    protected void initialize() {

    }

    @FXML
    protected void handleDifferentActionButton(ActionEvent event) {

    }

    @FXML
    protected void handleGeneralActionButton(ActionEvent event) {

    }
}

public class ManagerController extends WorkerController {

    @FXML
    @Override
    protected void initialize() {
        super.initialize();
    }

    @FXML
    protected void handleManagerButton(ActionEvent event) {

    }

    @FXML
    @Override
    protected void handleDifferentActionButton(ActionEvent event) {

    }
}

As you can see, logic is cleared and you do not have to constantly hide and show controls. You can concentrate on implementing business logic because you will not have to constantly check the role of the user. This is done once when logging in.

public class Controller {
    private static final String WORKER = "/sample/worker_homescreen.fxml";
    private static final String MANAGER = "/sample/manager_homescreen.fxml";

    @FXML
    private void handleLoginButton() {
        ...

        if (!resultSet.next()) {
            infoBox("Enter Correct Username and Password", "Failed", null);
        } else {
            if ("Employee".equals(function)) {
                infoBox("Login Successfull", "Success", null);
                showMainView(getClass().getResource(WORKER));

            } else if ("Manager".equals(function)) {
                infoBox("Login Successfull", "Success", null);
                showMainView(getClass().getResource(MANAGER));
            }
        }
    }

    private void showMainView(URL url) {
        try {
            Parent parent = FXMLLoader.load(url);

            Stage stage = new Stage();
            stage.setScene(new Scene(parent, 800, 600));
            stage.show();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}

The best thing about this approach is that you can easily add roles without affecting the existing logic.


问:
Why doesn't my DISTINCT ON expression work?
Query:

```<code>SELECT DISTINCT ON (geom_line),gid
FROM edge_table;
</code>```

I have a edge table which contains duplicates and I want to remove duplicate edges keeping one of them, but the syntax itself is wrong?

答:
The comma is the problem.

If you want geom_line included in the result, use

```<code>SELECT DISTINCT ON (geom_line) geom_line, gid FROM edge_table;
</code>```

Else use

```<code>SELECT DISTINCT ON (geom_line) gid FROM edge_table;
</code>```

But if your objective is just to remove duplicates, I'd say that you should use

```<code>SELECT DISTINCT geom_line, gid FROM edge_table;
</code>```

DISTINCT guarantees uniqueness over the whole result set, while DISTINCT ON guarantees uniqueness over the expression in parentheses. If there are several rows where the expression in parentheses is identical, one of these rows is picked. If you have an ORDER BY clause, the first row will be picked.

DISTINCT a, b is the same as DISTINCT ON (a, b) a, b.

Body:
Query:

SELECT DISTINCT ON (geom_line),gid
FROM edge_table;

I have a edge table which contains duplicates and I want to remove duplicate edges keeping one of them, but the syntax itself is wrong?

Body:
The comma is the problem.

If you want geom_line included in the result, use

SELECT DISTINCT ON (geom_line) geom_line, gid FROM edge_table;

Else use

SELECT DISTINCT ON (geom_line) gid FROM edge_table;

But if your objective is just to remove duplicates, I'd say that you should use

SELECT DISTINCT geom_line, gid FROM edge_table;

DISTINCT guarantees uniqueness over the whole result set, while DISTINCT ON guarantees uniqueness over the expression in parentheses. If there are several rows where the expression in parentheses is identical, one of these rows is picked. If you have an ORDER BY clause, the first row will be picked.

DISTINCT a, b is the same as DISTINCT ON (a, b) a, b.


问:
Regex Generation Assistance
I need some hopefully easy and quick help. I am getting a string of data from a barcode and I need to splice it to obtain three different values - Account Number, Date, and Invoice Number.

The regex has to be written for .Net Framework.

An example of what the barcode will return looks like this –

```<code>000295934009000306511302017001
</code>```

The first 9 digits is the Account Number. I’ve got that figured out by using this - ^\d{9}

The next 10 digits is the Invoice Number. I am not sure what regex expression would give me that.

Then, the 8 digits following the Invoice Number is the date (in this example it is 11302017). I need to pull that and put it into a MM/DD/YYYY format.

I will be creating a named group pattern for this too.

```<code>(?<account>^\d{9})(?<date>XXXXXXX)(?<invoice>XXXXXXX) - the X's are what I need to figure out.
</code>```

Any help is greatly appreciated!

答:
This is the regex:

```<code>(\d{9})(\d{10})([0-1][0-2][0-3][0-9]\d{4})
</code>```

accountNumber - Group1

invoiceNumber - Group2

date - Groups3

Title: Regex Generation Assistance

Body:
I need some hopefully easy and quick help. I am getting a string of data from a barcode and I need to splice it to obtain three different values - Account Number, Date, and Invoice Number.

The regex has to be written for .Net Framework.

An example of what the barcode will return looks like this –

000295934009000306511302017001

The first 9 digits is the Account Number. I’ve got that figured out by using this - ^\d{9}

The next 10 digits is the Invoice Number. I am not sure what regex expression would give me that.

Then, the 8 digits following the Invoice Number is the date (in this example it is 11302017). I need to pull that and put it into a MM/DD/YYYY format.

I will be creating a named group pattern for this too.

(?<account>^\d{9})(?<date>XXXXXXX)(?<invoice>XXXXXXX) - the X's are what I need to figure out.

Any help is greatly appreciated!

Body:
This is the regex:

(\d{9})(\d{10})([0-1][0-2][0-3][0-9]\d{4})

accountNumber - Group1

invoiceNumber - Group2

date - Groups3


问:
Install PEAR on project local?
How to install pear on project local?
Only install system global (and copy manually to project local) ?</p>

答:
The Answers @greg0ire provided (+1) should work out.

If you are using PHP 5.3 you can also look into "the next version of the pear installer" pyrus.

It can make it easier mainting different configurations

Title: Install PEAR on project local?


问:
Django Rest Framework, using multiple model queries
I am quite new in using the REST Framework and I did not find in the tutorial how to achieve what I am looking for;

In my serialiser.py I have a class that is used to serialized MyUser models

```<code>class MyUserSerializer(ModelSerializer):
    class Meta:
        model = MyUser
        fields = (
            'email',
            'first_name',
            'last_name'
        )
</code>```

and in my view I am serializing a query that retrieve the user member in a team:

```<code>class EmployeeChartData(APIView):
    #import pdb; pdb.set_trace()
    authentication_classes = []
    permission_classes = []
    serializer_class = MyUserSerializer

    def get_serializer_class(self):
        return self.serializer_class

    def get(self, request, format=None, *args, **kwargs):

        team_name_list2 = Project.objects.get(id=kwargs['pk1']).team_id.members.all()
        serializer=self.serializer_class
        team_name_data = serializer(team_name_list2, many=True)
        team_name_data = team_name_data.data

        data = {
        "team_name_list2":team_name_data,
        }
</code>```

Which give me an output for example:

```<code>"team_name_list2": [
        {
            "email": "johndoe@gmail.com",
            "first_name": "John",
            "last_name": "Doe"
        },
</code>```

My question is how can I add to that dict custom data and data from other models that are linked to MyUser Model.

For example I have a Team Model

```<code>class Team(models.Model):
    team_name = models.CharField(max_length=100, default = '')
    team_hr_admin = models.ForeignKey(MyUser, blank=True, null=True)
    members = models.ManyToManyField(MyUser, related_name="members")
</code>```

How can I add all the team that the specific user is linked to ?

Thx you very much

答:
1- Read about Nested Serializer to give you clean code http://www.django-rest-framework.org/api-guide/relations/#nested-relationships

2- Or Try this:

```<code>class MyUserSerializer(ModelSerializer):
    team = serializers.SerializerMethodField()
    class Meta:
        model = MyUser
        fields = (
            'email',
            'first_name',
            'last_name',
            'team',
        )
    def get_team(self, obj):
        print(obj) # for you to understand what's happening
        teams = Team.objects.filter(member=obj)
        serialized_teams = TeamSerializer(teams,many=True)
        return serialized_teams.data
</code>```

For your Team Serializer as follows

```<code>class TeamSerializer(ModelSerializer):
    class Meta:
        model = Team
        fields = (
            'team_name',
            'team_hr_admin',
            'members',  # you can exclude this field since it may seem duplicate
        )
</code>```

For your view

```<code>class EmployeeChartData(viewsets.ModelViewSet):
    queryset = MyUser.objects.all()
    serializer_class = MyUserSerializer
    permission_classes = []
    http_method_names = ['get',]
</code>```

Body:
I am quite new in using the REST Framework and I did not find in the tutorial how to achieve what I am looking for;

In my serialiser.py I have a class that is used to serialized MyUser models

class MyUserSerializer(ModelSerializer):
    class Meta:
        model = MyUser
        fields = (
            'email',
            'first_name',
            'last_name'
        )

and in my view I am serializing a query that retrieve the user member in a team:

class EmployeeChartData(APIView):
    #import pdb; pdb.set_trace()
    authentication_classes = []
    permission_classes = []
    serializer_class = MyUserSerializer

    def get_serializer_class(self):
        return self.serializer_class

    def get(self, request, format=None, *args, **kwargs):

        team_name_list2 = Project.objects.get(id=kwargs['pk1']).team_id.members.all()
        serializer=self.serializer_class
        team_name_data = serializer(team_name_list2, many=True)
        team_name_data = team_name_data.data

        data = {
        "team_name_list2":team_name_data,
        }

Which give me an output for example:

"team_name_list2": [
        {
            "email": "johndoe@gmail.com",
            "first_name": "John",
            "last_name": "Doe"
        },

My question is how can I add to that dict custom data and data from other models that are linked to MyUser Model.

For example I have a Team Model

class Team(models.Model):
    team_name = models.CharField(max_length=100, default = '')
    team_hr_admin = models.ForeignKey(MyUser, blank=True, null=True)
    members = models.ManyToManyField(MyUser, related_name="members")

How can I add all the team that the specific user is linked to ?

Thx you very much

Body:
1- Read about Nested Serializer to give you clean code http://www.django-rest-framework.org/api-guide/relations/#nested-relationships

2- Or Try this:

class MyUserSerializer(ModelSerializer):
    team = serializers.SerializerMethodField()
    class Meta:
        model = MyUser
        fields = (
            'email',
            'first_name',
            'last_name',
            'team',
        )
    def get_team(self, obj):
        print(obj) # for you to understand what's happening
        teams = Team.objects.filter(member=obj)
        serialized_teams = TeamSerializer(teams,many=True)
        return serialized_teams.data

For your Team Serializer as follows

class TeamSerializer(ModelSerializer):
    class Meta:
        model = Team
        fields = (
            'team_name',
            'team_hr_admin',
            'members',  # you can exclude this field since it may seem duplicate
        )

For your view

class EmployeeChartData(viewsets.ModelViewSet):
    queryset = MyUser.objects.all()
    serializer_class = MyUserSerializer
    permission_classes = []
    http_method_names = ['get',]


问:
How to completely uninstall VS Code on Windows?
What is the way to totally uninstall Visual Studio Code and its extensions, including all configurations, etc.) on Windows 10?

I tried uninstalling and installing but it remembered its previous settings.

答:
Turns out the extensions are stored under %USER%.vscode\extensions. Deleting that gets rid of them.
%USER%\\.vscode\extensions (or) %USERPROFILE%\.vscode\extensions


问:
How to convert this code from VB to Delphi
```<code>Public Function GetChecksum(AsciText As String) As Integer
    Dim i As Integer

    For i = 1 To Len(AsciText)
        GetChecksum = GetChecksum Xor Asc(Mid$(AsciText, i, 1))
    Next i
End Function
</code>```

I no have idea for "Mid$" on Delphi.

答:
```<code>Private Sub RadioButton1_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadioButton1.CheckedChanged
    ListBox1.Items.Clear()
    Try
        Dim wc As New Net.WebClient
        wc.Encoding = System.Text.Encoding.Default
        Dim wb As New System.Net.WebClient
        Dim sr As String = wb.DownloadString("")
        Dim regex As New Regex("")
        Dim matches As MatchCollection = regex.Matches(sr)
        For Each element As Match In matches
            ListBox1.Items.Add(element.Value)
        Next
    Catch ex As Exception

    End Try
End Sub
</code>```

Body:
Public Function GetChecksum(AsciText As String) As Integer
    Dim i As Integer

    For i = 1 To Len(AsciText)
        GetChecksum = GetChecksum Xor Asc(Mid$(AsciText, i, 1))
    Next i
End Function

I no have idea for "Mid$" on Delphi.


问:
Angular 2 ng-template not rendering in dom inside component
I have a component like so

```<code>import {Component, OnInit} from '@angular/core';
import {NgbModal, ModalDismissReasons} from '@ng-bootstrap/ng-bootstrap';

@Component({
    selector: 'details',
    templateUrl: 'details.component.html',
    styleUrls: ["./details.component.scss"],
})
export class DetailsComponent {

    constructor(
        private modalService: NgbModal
    ) {
    }

    open(content) {
        this.modalService.open(content).result.then((result) => {
            console.log("closed");
        }, (reason) => {
            console.log("dismissed");
        });
    }

}
</code>```

the html is, notice the popover component at the very top

```<code><popover></popover>
<div class="row">
    <div class="col">
        <table class="table">
            <thead>
                <th>Action</th>
            </thead>
            <tbody>
                <tr>
                    <td>
                        <button (click)="open(popover)"> open </button>
                    </td>
                </tr>

            </tbody>
        </table>
    </div>
</div>
</code>```

The open component is just a component to display html

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

@Component({
    selector: 'popover',
    templateUrl: 'popover.component.html',
    styleUrls: ["./popover.component.scss"],
})
export class PopOverComponent {

    constructor(
    ) {
    }

}
</code>```

and the html for the popover component

```<code><ng-template #popover let-c="close" let-d="dismiss">
    <div class="modal-header">
    <h4 class="modal-title">Modal title</h4>
        <button type="button" class="close" aria-label="Close" (click)="d('Cross click')">
            <span aria-hidden="true">×</span>
        </button>
    </div>
    <div class="modal-body">
      <p>One fine body…</p>
    </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-secondary" (click)="c('Close click')">Close</button>
    </div>
</ng-template>
</code>```

My issue is when I have ng-template wrapped around test, the h1 test element doesn't render in the dom. More explicitly, ng-template doesn't render which is what I need to pass the #popover to the open function to open the popover.

When I remove the ng-template, I can see h1 test. I need the ng-template to render in the dom and I'm putting i in a component because there's a lot of html in the popover component.

Any idea why this is behaving this way?

答:
use <ng-container> instead

https://angular.io/guide/structural-directives#!#ng-container

Body:
I have a component like so

import {Component, OnInit} from '@angular/core';
import {NgbModal, ModalDismissReasons} from '@ng-bootstrap/ng-bootstrap';

@Component({
    selector: 'details',
    templateUrl: 'details.component.html',
    styleUrls: ["./details.component.scss"],
})
export class DetailsComponent {

    constructor(
        private modalService: NgbModal
    ) {
    }

    open(content) {
        this.modalService.open(content).result.then((result) => {
            console.log("closed");
        }, (reason) => {
            console.log("dismissed");
        });
    }

}

the html is, notice the popover component at the very top

<popover></popover>

                Action

                        <button (click)="open(popover)"> open </button>

The open component is just a component to display html

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

@Component({
    selector: 'popover',
    templateUrl: 'popover.component.html',
    styleUrls: ["./popover.component.scss"],
})
export class PopOverComponent {

    constructor(
    ) {
    }

}

and the html for the popover component

<ng-template #popover let-c="close" let-d="dismiss">

Modal title

        <button type="button" class="close" aria-label="Close" (click)="d('Cross click')">
            ×
        </button>

One fine body…

        <button type="button" class="btn btn-secondary" (click)="c('Close click')">Close</button>

</ng-template>

My issue is when I have ng-template wrapped around test, the h1 test element doesn't render in the dom. More explicitly, ng-template doesn't render which is what I need to pass the #popover to the open function to open the popover.

When I remove the ng-template, I can see h1 test. I need the ng-template to render in the dom and I'm putting i in a component because there's a lot of html in the popover component.

Any idea why this is behaving this way?


答:
SIGTERM is the signal that is typically used to administratively terminate a process and its triggered by tehplayground's some server settings which is not related to PHP

Because your program executes amount of time allowed on tehplayground, There is nothing wrong with your code.

I ran it on my server it works fine.

To increase the time limit on your server

For runtime

```<code>ini_set('max_execution_time', 60); //60 secs
</code>```

Change this on php.ini for permanent change

```<code>; Maximum execution time of each script, in seconds
; http://php.net/max-execution-time
; Note: This directive is hardcoded to 0 for the CLI SAPI
max_execution_time = 300
</code>```

Setting it to 0 means there's no time limit.

Title: Sleep breaks the script

Body:
I want simply to set a sleep in a loop. But it doesn't work as expected

for ($i = 1; $i <= 6; $i++) {
    echo $i;
    sleep(1);
}

if the loop takes more than 5 seconds. It doesn't work (don't print at all).

I tested it in Teh Playground, and this error appears :

Execution took longer than 5 seconds, sent SIGTERM and terminated

Edit : Modifying set_time_limit doesn't change anything...

It seems it's related to my server's config...

Body:
SIGTERM is the signal that is typically used to administratively terminate a process and its triggered by tehplayground's some server settings which is not related to PHP

Because your program executes amount of time allowed on tehplayground, There is nothing wrong with your code.

I ran it on my server it works fine.

To increase the time limit on your server

For runtime

ini_set('max_execution_time', 60); //60 secs

Change this on php.ini for permanent change

; Maximum execution time of each script, in seconds
; http://php.net/max-execution-time
; Note: This directive is hardcoded to 0 for the CLI SAPI
max_execution_time = 300

Setting it to 0 means there's no time limit.


问:
I need someone who explain me these lines of code
I need someone who explain me this code, line by line. I specially don't understand this line:

```<code>operator std::map<T, U>()
</code>```

Thank you very much.

```<code>template <typename T, typename U>
class create_map
{
    std::map<T, U> m_map;
public:
    create_map(const T& key, const U& val)
    {
        m_map[key] = val;
    }
    create_map<T, U>& operator()(const T& key, const U& val)
    {
        m_map[key] = val;
        return *this;
    }
    operator std::map<T, U>()
    {
        return m_map;
    }
};
</code>```

答:
```<code>operator std::map<T, U>()
{
         return m_map;
}
</code>```

This is user-defined conversion function.

That means, you can write this:

```<code>//obj is an object of type create_map
create_map<int,std::string> obj(1,"Nawaz");

//obj implicitly converts into std::map type!
std::map<int,std::string> map_inst=obj;
</code>```

See this topic to know more about user-defined conversion function:

User Defined Conversions in C++

You can see this as well: Implicit conversion sequences (C++ only)

```<code>create_map<T, U>& operator()(const T& key, const U& val)
{
      m_map[key] = val;
      return *this;
}
</code>```

This actually overloads the operator(), which internally inserts or updates (key,val) pair into the m_map; just see the function definition as to what it does.

So using this function you can write code like this,

```<code>obj(2,"Sarfaraz"); //this inserts the pair into the underlying m_map;
</code>```

I would also suggest you to explore std::map a bit more, especially the overloaded operator[] in std::map.

Body:
I need someone who explain me this code, line by line. I specially don't understand this line:

operator std::map<T, U>()

Thank you very much.

template <typename T, typename U>
class create_map
{
    std::map<T, U> m_map;
public:
    create_map(const T& key, const U& val)
    {
        m_map[key] = val;
    }
    create_map<T, U>& operator()(const T& key, const U& val)
    {
        m_map[key] = val;
        return *this;
    }
    operator std::map<T, U>()
    {
        return m_map;
    }
};

Body:
operator std::map<T, U>()
{
         return m_map;
}

This is user-defined conversion function.

That means, you can write this:

//obj is an object of type create_map
create_map<int,std::string> obj(1,"Nawaz");

//obj implicitly converts into std::map type!
std::map<int,std::string> map_inst=obj;

See this topic to know more about user-defined conversion function:

User Defined Conversions in C++

You can see this as well: Implicit conversion sequences (C++ only)

create_map<T, U>& operator()(const T& key, const U& val)
{
      m_map[key] = val;
      return *this;
}

This actually overloads the operator(), which internally inserts or updates (key,val) pair into the m_map; just see the function definition as to what it does.

So using this function you can write code like this,

obj(2,"Sarfaraz"); //this inserts the pair into the underlying m_map;

I would also suggest you to explore std::map a bit more, especially the overloaded operator[] in std::map.


问:
Cannot logout and login as a different Facebook user in ionic 3?
I implemented social media logins like Facebook,google,twitter  using fire-base and ionic 3 with the following link reference.

https://firebase.google.com/docs/auth/web/cordova.

first time i successfully log in with my Facebook account credentials and when i logged out using firebase.auth().signOut() and try to login with different Facebook account, instead of showing login screen in the browser it automatically logged in with previous Facebook account details that I just logged out.

same issue for the all the social media logins. I want the browser to show the login page every time for Facebook instead of automatic login.
Please help me out to solve the problem.

答:
The issue is that once the user logs in with Facebook, they remain logged in with that same Facebook account. firebase.auth().signOut() will sign out the user from the current app using Firebase but not from Facebook. This is normally OK as users usually have one Facebook account on a device but if you insist, here is one option:

Allow the user to re-authenticate by passing the custom parameter to Facebook: firebase.auth().signInWithRedirect(new firebase.auth.FacebookAuthProvider().setCustomParameters({auth_type: 'reauthenticate'}) This will show the user the current Facebook account and ask them to enter their password again. This gives them the ability to change the account if they want to.


问:
Magento 2 Rest API, PUT catalog request doesn't work
I am using Symfony application to send requests to Magento 2 Rest Api. When I send a PUT request to update a catalog, it doesn't change catalog information in Magento, but changes the name and other parameters except parentId on Symfony side.

Here is the code with request:

```<code>public function updateCategory($id, $name, $parentId, $isActive = true)
{
    $pageSuffix = "rest/V1/categories/" . $id;
    $headers = ['content-type' => "application/json", 'Authorization' => "Bearer " . $this->adminToken];
    $content = ["category" => ["id" => (int)$id, "name" => $name, "parentId" => (int)$parentId, "isActive" => (bool)$isActive]];
    $response = $this->buzz->put($this->urlBase . $pageSuffix, $headers, json_encode($content));
    print_r(json_decode($response));
    print_r($this->buzz->getLastRequest());
}
</code>```

category tree before I send a request:

```<code>[id] => 1
[parent_id] => 0
[name] => Root Catalog
[is_active] =>
[position] => 0
[level] => 0
[product_count] => 0
[children_data] => Array
    (
        [0] => stdClass Object
            (
                [id] => 2
                [parent_id] => 1
                [name] => root_test_category_1
                [is_active] => 1
                [position] => 1
                [level] => 1
                [product_count] => 0
                [children_data] => Array
                    (
                        [0] => stdClass Object
                            (
                                [id] => 3
                                [parent_id] => 2
                                [name] => test_category_1
                                [is_active] => 1
                                [position] => 1
                                [level] => 2
                                [product_count] => 0
                                [children_data] => Array
                                    (
                                        [0] => stdClass Object
                                            (
                                                [id] => 8
                                                [parent_id] => 3
                                                [name] => test_category_1_1
                                                [is_active] => 1
                                                [position] => 1
                                                [level] => 3
                                                [product_count] => 0
                                                [children_data] => Array
                                                    (
                                                        [0] => stdClass Object
                                                            (
                                                                [id] => 9
                                                                [parent_id] => 8
                                                                [name] => test_category_1_1_1
                                                                [is_active] => 1
                                                                [position] => 1
                                                                [level] => 4
                                                                [product_count] => 0
                                                                [children_data] => Array
                                                                    (
                                                                    )

                                                            )

                                                        [1] => stdClass Object
                                                            (
                                                                [id] => 10
                                                                [parent_id] => 8
                                                                [name] => test_category_1_1_2
                                                                [is_active] => 1
                                                                [position] => 2
                                                                [level] => 4
                                                                [product_count] => 0
                                                                [children_data] => Array
                                                                    (
                                                                    )

                                                            )

                                                        [2] => stdClass Object
                                                            (
                                                                [id] => 16
                                                                [parent_id] => 8
                                                                [name] => test_category_1_1_3
                                                                [is_active] => 1
                                                                [position] => 3
                                                                [level] => 4
                                                                [product_count] => 0
                                                                [children_data] => Array
                                                                    (
                                                                    )

                                                            )

                                                    )

                                            )

                                    )

                            )

                    )

            )

        [1] => stdClass Object
            (
                [id] => 5
                [parent_id] => 1
                [name] => root_test_category_2
                [is_active] => 1
                [position] => 2
                [level] => 1
                [product_count] => 0
                [children_data] => Array
                    (
                        [0] => stdClass Object
                            (
                                [id] => 6
                                [parent_id] => 5
                                [name] => test_category_2_1
                                [is_active] => 1
                                [position] => 1
                                [level] => 2
                                [product_count] => 0
                                [children_data] => Array
                                    (
                                    )

                            )

                    )

            )

    )
</code>```

Then I send a request to change test_category_1_1_3, id 16. The command below sends parameters as in function updateCategory() listed above. So it should fetch catalog with id 16 and change it's name and parentId.

```<code>app/console magento:test 16 test_category_1_1_3_test 6 1 -vvv
</code>```

After running the command and sending request I check this catalog by getting it from Magento Rest API. As the result, it changes it's name but everything else remains the same.

```<code>[id] => 16
[parent_id] => 8
[name] => test_category_1_1_3_test
[is_active] => 1
[position] => 3
[level] => 4
[product_count] => 0
[children_data] => Array
    (
    )
</code>```

Response from the request:

```<code>Buzz\Message\Response Object
(
    [protocolVersion:Buzz\Message\Response:private] =>
    [statusCode:Buzz\Message\Response:private] =>
    [reasonPhrase:Buzz\Message\Response:private] =>
    [headers:Buzz\Message\AbstractMessage:private] => Array
        (
            [0] => HTTP/1.1 200 OK
            [1] => Date: Wed, 17 May 2017 12:56:23 GMT
            [2] => Server: Apache/2.4.18 (Ubuntu)
            [3] => Set-Cookie: PHPSESSID=56hrlb8nejsnrduk05npemd3n3; expires=Wed, 17-May-2017 13:56:23 GMT; Max-Age=3600; path=/; domain=magento-project.nikolay.localdev; HttpOnly
            [4] => Expires: Thu, 19 Nov 1981 08:52:00 GMT
            [5] => Cache-Control: no-store, no-cache, must-revalidate
            [6] => Pragma: no-cache
            [7] => X-Frame-Options: SAMEORIGIN
            [8] => Content-Length: 739
            [9] => Content-Type: application/json; charset=utf-8
        )

    [content:Buzz\Message\AbstractMessage:private] => {"id":16,"parent_id":8,"name":"test_category_1_1_3_test","is_active":true,"position":3,"level":4,"children":"","created_at":"2017-05-17 10:51:17","updated_at":"2017-05-17 10:51:17","path":"1\/2\/3\/8\/16","available_sort_by":[],"include_in_menu":true,"custom_attributes":[{"attribute_code":"display_mode","value":"PRODUCTS"},{"attribute_code":"is_anchor","value":"1"},{"attribute_code":"path","value":"1\/2\/3\/8\/16"},{"attribute_code":"children_count","value":"0"},{"attribute_code":"custom_use_parent_settings","value":"0"},{"attribute_code":"custom_apply_to_products","value":"0"},{"attribute_code":"url_key","value":"test-category-1-1-3"},{"attribute_code":"url_path","value":"test-category\/test-category-1-1\/test-category-1-1-3"}]}
)
Buzz\Message\Request Object
(
    [method:Buzz\Message\Request:private] => PUT
    [resource:Buzz\Message\Request:private] => /rest/V1/categories/16
    [host:Buzz\Message\Request:private] => http://magento-project.nikolay.localdev
    [protocolVersion:Buzz\Message\Request:private] => 1.1
    [headers:Buzz\Message\AbstractMessage:private] => Array
        (
            [0] => content-type: application/json
            [1] => Authorization: Bearer mcq2i97t0t3b15hdmwwhoolp6ma0lyuy
        )

    [content:Buzz\Message\AbstractMessage:private] => {"category":{"id":16,"name":"test_category_1_1_3_test","parentId":6,"isActive":true}}
)
</code>```

Moreover, nothing at all changes in Magento itself.

I tried to debug save() function in (vendor/magento/module-catalog/Model/CategoryRepository.php) but it didn't show me anything that would help. I've been trying to clear cache both on Magento and Symfony sides but that doesn't help as well.

答:
Acknowledged as a bug. Possibly related to the store scope in Magento 2.

https://github.com/magento/magento2/issues/9949

Body:
I am using Symfony application to send requests to Magento 2 Rest Api. When I send a PUT request to update a catalog, it doesn't change catalog information in Magento, but changes the name and other parameters except parentId on Symfony side.

Here is the code with request:

public function updateCategory($id, $name, $parentId, $isActive = true)
{
    $pageSuffix = "rest/V1/categories/" . $id;
    $headers = ['content-type' => "application/json", 'Authorization' => "Bearer " . $this->adminToken];
    $content = ["category" => ["id" => (int)$id, "name" => $name, "parentId" => (int)$parentId, "isActive" => (bool)$isActive]];
    $response = $this->buzz->put($this->urlBase . $pageSuffix, $headers, json_encode($content));
    print_r(json_decode($response));
    print_r($this->buzz->getLastRequest());
}

category tree before I send a request:

[id] => 1
[parent_id] => 0
[name] => Root Catalog
[is_active] =>
[position] => 0
[level] => 0
[product_count] => 0
[children_data] => Array
    (
        [0] => stdClass Object
            (
                [id] => 2
                [parent_id] => 1
                [name] => root_test_category_1
                [is_active] => 1
                [position] => 1
                [level] => 1
                [product_count] => 0
                [children_data] => Array
                    (
                        [0] => stdClass Object
                            (
                                [id] => 3
                                [parent_id] => 2
                                [name] => test_category_1
                                [is_active] => 1
                                [position] => 1
                                [level] => 2
                                [product_count] => 0
                                [children_data] => Array
                                    (
                                        [0] => stdClass Object
                                            (
                                                [id] => 8
                                                [parent_id] => 3
                                                [name] => test_category_1_1
                                                [is_active] => 1
                                                [position] => 1
                                                [level] => 3
                                                [product_count] => 0
                                                [children_data] => Array
                                                    (
                                                        [0] => stdClass Object
                                                            (
                                                                [id] => 9
                                                                [parent_id] => 8
                                                                [name] => test_category_1_1_1
                                                                [is_active] => 1
                                                                [position] => 1
                                                                [level] => 4
                                                                [product_count] => 0
                                                                [children_data] => Array
                                                                    (
                                                                    )

                                                            )

                                                        [1] => stdClass Object
                                                            (
                                                                [id] => 10
                                                                [parent_id] => 8
                                                                [name] => test_category_1_1_2
                                                                [is_active] => 1
                                                                [position] => 2
                                                                [level] => 4
                                                                [product_count] => 0
                                                                [children_data] => Array
                                                                    (
                                                                    )

                                                            )

                                                        [2] => stdClass Object
                                                            (
                                                                [id] => 16
                                                                [parent_id] => 8
                                                                [name] => test_category_1_1_3
                                                                [is_active] => 1
                                                                [position] => 3
                                                                [level] => 4
                                                                [product_count] => 0
                                                                [children_data] => Array
                                                                    (
                                                                    )

                                                            )

                                                    )

                                            )

                                    )

                            )

                    )

            )

        [1] => stdClass Object
            (
                [id] => 5
                [parent_id] => 1
                [name] => root_test_category_2
                [is_active] => 1
                [position] => 2
                [level] => 1
                [product_count] => 0
                [children_data] => Array
                    (
                        [0] => stdClass Object
                            (
                                [id] => 6
                                [parent_id] => 5
                                [name] => test_category_2_1
                                [is_active] => 1
                                [position] => 1
                                [level] => 2
                                [product_count] => 0
                                [children_data] => Array
                                    (
                                    )

                            )

                    )

            )

    )

Then I send a request to change test_category_1_1_3, id 16. The command below sends parameters as in function updateCategory() listed above. So it should fetch catalog with id 16 and change it's name and parentId.

app/console magento:test 16 test_category_1_1_3_test 6 1 -vvv

After running the command and sending request I check this catalog by getting it from Magento Rest API. As the result, it changes it's name but everything else remains the same.

[id] => 16
[parent_id] => 8
[name] => test_category_1_1_3_test
[is_active] => 1
[position] => 3
[level] => 4
[product_count] => 0
[children_data] => Array
    (
    )

Response from the request:

Buzz\Message\Response Object
(
    [protocolVersion:Buzz\Message\Response:private] =>
    [statusCode:Buzz\Message\Response:private] =>
    [reasonPhrase:Buzz\Message\Response:private] =>
    [headers:Buzz\Message\AbstractMessage:private] => Array
        (
            [0] => HTTP/1.1 200 OK
            [1] => Date: Wed, 17 May 2017 12:56:23 GMT
            [2] => Server: Apache/2.4.18 (Ubuntu)
            [3] => Set-Cookie: PHPSESSID=56hrlb8nejsnrduk05npemd3n3; expires=Wed, 17-May-2017 13:56:23 GMT; Max-Age=3600; path=/; domain=magento-project.nikolay.localdev; HttpOnly
            [4] => Expires: Thu, 19 Nov 1981 08:52:00 GMT
            [5] => Cache-Control: no-store, no-cache, must-revalidate
            [6] => Pragma: no-cache
            [7] => X-Frame-Options: SAMEORIGIN
            [8] => Content-Length: 739
            [9] => Content-Type: application/json; charset=utf-8
        )

    [content:Buzz\Message\AbstractMessage:private] => {"id":16,"parent_id":8,"name":"test_category_1_1_3_test","is_active":true,"position":3,"level":4,"children":"","created_at":"2017-05-17 10:51:17","updated_at":"2017-05-17 10:51:17","path":"1\/2\/3\/8\/16","available_sort_by":[],"include_in_menu":true,"custom_attributes":[{"attribute_code":"display_mode","value":"PRODUCTS"},{"attribute_code":"is_anchor","value":"1"},{"attribute_code":"path","value":"1\/2\/3\/8\/16"},{"attribute_code":"children_count","value":"0"},{"attribute_code":"custom_use_parent_settings","value":"0"},{"attribute_code":"custom_apply_to_products","value":"0"},{"attribute_code":"url_key","value":"test-category-1-1-3"},{"attribute_code":"url_path","value":"test-category\/test-category-1-1\/test-category-1-1-3"}]}
)
Buzz\Message\Request Object
(
    [method:Buzz\Message\Request:private] => PUT
    [resource:Buzz\Message\Request:private] => /rest/V1/categories/16
    [host:Buzz\Message\Request:private] => http://magento-project.nikolay.localdev
    [protocolVersion:Buzz\Message\Request:private] => 1.1
    [headers:Buzz\Message\AbstractMessage:private] => Array
        (
            [0] => content-type: application/json
            [1] => Authorization: Bearer mcq2i97t0t3b15hdmwwhoolp6ma0lyuy
        )

    [content:Buzz\Message\AbstractMessage:private] => {"category":{"id":16,"name":"test_category_1_1_3_test","parentId":6,"isActive":true}}
)

Moreover, nothing at all changes in Magento itself.

I tried to debug save() function in (vendor/magento/module-catalog/Model/CategoryRepository.php) but it didn't show me anything that would help. I've been trying to clear cache both on Magento and Symfony sides but that doesn't help as well.


问:
How to trim string from right in PHP?
I have a string example

```<code>this-is-the-example/exa
</code>```

I want to trim /exa from the above line

```<code>$string1 = "this-is-the-example/exa";
$string2 = "/exa";
</code>```

I am using rtrim($string1, $sting2)

But the output is this-is-the-exampl

I want to this-is-the-example as output.

Both string are dynamic and may have multiple occurrences within the string. But I only want to remove the last part. Also its not compulsory that the string2 has / in it. this may be normal string too. like a, abc too..

答:
There are various approaches you can use for this:

With substr(DEMO):

```<code>function removeFromEnd($haystack, $needle)
{
    $length = strlen($needle);

    if(substr($haystack, -$length) === $needle)
    {
        $haystack = substr($haystack, 0, -$length);
    }
    return $haystack;
}

$trim = '/exa';
$str = 'this-is-the-example/exa';

var_dump(removeFromEnd($str, $trim));
</code>```

With regex(DEMO):

```<code>$trim = '/exa';
$str = 'this-is-the-example/exa';

function removeFromEnd($haystack, $needle)
{
    $needle = preg_quote($needle, '/');
    $haystack = preg_replace("/$needle$/", '', $haystack);
    return $haystack;
}
var_dump(removeFromEnd($str, $trim));
</code>```

Title: How to trim string from right in PHP?

Body:
I have a string example

this-is-the-example/exa

I want to trim /exa from the above line

$string1 = "this-is-the-example/exa";
$string2 = "/exa";

I am using rtrim($string1, $sting2)

But the output is this-is-the-exampl

I want to this-is-the-example as output.

Both string are dynamic and may have multiple occurrences within the string. But I only want to remove the last part. Also its not compulsory that the string2 has / in it. this may be normal string too. like a, abc too..

Body:
There are various approaches you can use for this:

With substr(DEMO):

function removeFromEnd($haystack, $needle)
{
    $length = strlen($needle);

    if(substr($haystack, -$length) === $needle)
    {
        $haystack = substr($haystack, 0, -$length);
    }
    return $haystack;
}

$trim = '/exa';
$str = 'this-is-the-example/exa';

var_dump(removeFromEnd($str, $trim));

With regex(DEMO):

$trim = '/exa';
$str = 'this-is-the-example/exa';

function removeFromEnd($haystack, $needle)
{
    $needle = preg_quote($needle, '/');
    $haystack = preg_replace("/$needle$/", '', $haystack);
    return $haystack;
}
var_dump(removeFromEnd($str, $trim));


问:
how to release a lock automatically in mysql
My question is similar to this questionMySQL rollback on transaction with lost/disconnected connection ,but it was 5 years ago.

If a client(like jdbc or something else) lock one row in table, execute some statements then network is down, so mysql would never receive commit or rollback command from client, does mysql support to rollback this transaction(unlock row) automatically?

I refer innodb_rollback_on_timeout it says If --innodb_rollback_on_timeout is specified, a transaction timeout causes InnoDB to abort and roll back the entire transaction, but how long is the transaction timeout and where to set it?

The accepted answer in similar question is to use wait_timeout, if wait_timeout is set to a small number like 10 seconds, so the idle connections in pool(if used) need to test connection every 10 seconds before they are disconnected by mysql sever, is the cost too high? or is there other ways(configuration will be best) to solve my question?

答: Actually there's no settings for transaction timeout, still wait_timeout or interactive_timeout applies. What --innodb_rollback_on_timeout affected is the behavior of rollback(whole transaction or statements in the transation).


问:
How to extract files in uImage?
Here is my problem:

I have a uImage file, which has kernel + dtb + initramfs in it. The initramfs has some proprietary binaries, hence I cannot rebuild it from source. But I need to change the Linux kernel for different reasons.

Hence I thought if following steps would solve my problem:

extract the above uImage file,

replace kernel and dtb files with newly built files,

recreate a newer version of uImage file with new-kernel, new-dtb but old-initramfs.

Is there a tool available to do this? If not, I appreciate any inputs to develop the same.

答:
Try this command:

```<code>mkimage -l kernel.uImage
</code>```

For details have a look at this link.

Title: How to extract files in uImage?

Body:
Try this command:

mkimage -l kernel.uImage

For details have a look at this link.


问:
Regular expression to match all digits of unknown length except the last 4 digits
There is a number with unknown length and the idea is to build a regular expression which matches all digits except last 4 digits.

I have tried a lot to achieve this but no luck yet.

Currently I have this regex: "^(\d*)\d{0}\d{0}\d{0}\d{0}.*$"

Input: 123456789089775

Expected output: XXXXXXXXXXX9775

which I am using as follows(and this doesn't work):

```<code>String accountNumber ="123456789089775";
String pattern = "^(\\d*)\\d{1}\\d{1}\\d{1}\\d{1}.*$";
String result = accountNumber.replaceAll(pattern, "X");
</code>```

Please suggest how I should approach this problem or give me the solution.
In this case my whole point is to negate the regex : "\d{4}$"

答:
You may use

```<code>\G\d(?=\d{4,}$)
</code>```

See the regex demo.

Details

\G - start of string or end of the previous match

\d - a digit

(?=\d{4,}$) - a positive lookahead that requires 4 or more digits up to the end of the string immediately to the right of the current location.

Java demo:

```<code>String accountNumber ="123456789089775";
String pattern = "\\G\\d(?=\\d{4,}$)"; // Or \\G.(?=.{4,}$)
String result = accountNumber.replaceAll(pattern, "X");
System.out.println(result); // => XXXXXXXXXXX9775
</code>```

Body:
There is a number with unknown length and the idea is to build a regular expression which matches all digits except last 4 digits.

I have tried a lot to achieve this but no luck yet.

Currently I have this regex: "^(\d*)\d{0}\d{0}\d{0}\d{0}.*$"

Input: 123456789089775

Expected output: XXXXXXXXXXX9775

which I am using as follows(and this doesn't work):

String accountNumber ="123456789089775";
String pattern = "^(\\d*)\\d{1}\\d{1}\\d{1}\\d{1}.*$";
String result = accountNumber.replaceAll(pattern, "X");

Please suggest how I should approach this problem or give me the solution.
In this case my whole point is to negate the regex : "\d{4}$"

Body:
You may use

\G\d(?=\d{4,}$)

See the regex demo.

Details

\G - start of string or end of the previous match

\d - a digit

(?=\d{4,}$) - a positive lookahead that requires 4 or more digits up to the end of the string immediately to the right of the current location.

Java demo:

String accountNumber ="123456789089775";
String pattern = "\\G\\d(?=\\d{4,}$)"; // Or \\G.(?=.{4,}$)
String result = accountNumber.replaceAll(pattern, "X");
System.out.println(result); // => XXXXXXXXXXX9775


问:
Python regex: How to make a group of words/character optional?
I am trying to make regex that can match all of them:

word

word-hyphen

word-hyphen-again

that is -\w+could be many depends on words in a term. How can I make it optional

Thing I made so far is given here:- https://regex101.com/r/Atpwze/1

答:
To catch all of your examples, I think you could use:

^\w+(?:\w+\-?|\-\w+)+$

Beginning of the string ^

Match a word character one or more times \w+

Start a non capturing group (?:

Match a word character one or more times with an optional hyphen \w+\-?

Or |

A hyphen with one or more word characters \-\w+

Close the non capturing group )

End of the string $


问:
What is the difference between a Rule and a Policy
in the context of a database, we sometimes need to check values against some statements like "the customer name is non-empty" or "the customer number of purchases is positive"...

But do such statements constitute rules or policies ?

In general how would you define these concepts, their differences and relations ?

Thanks in advance.

答:
In the context of a database, I would argue that it's a rule to have a username, while it's a policy (potentially overridden by administrative or other approval) to allow customers to have a lower assigned discount if they have less than a set number of purchases.

```<code>Rule: All users must have a username.
Rule: All users must have a password.
Rule: All users must have a valid email address.
Rule: All users must have a valid credit card on file.
Policy: All users begin with a 0% discount rate on purchases.
Policy: All users are required to pay for shipping.
</code>```

Rules are outward-facing statements backed by validation. Policies are internal rules backed by consequence.

It could be a policy that later on down the road, a user can change a username (depending on how the software was written), or that the discount and shipping rates assigned on signup may be adjusted to create customer opportunities.

In my estimation then, a rule requires hard validation, while a policy by nature is subject to intervention and/or manipulation.

HTH

Jared

Body:
In the context of a database, I would argue that it's a rule to have a username, while it's a policy (potentially overridden by administrative or other approval) to allow customers to have a lower assigned discount if they have less than a set number of purchases.

Rule: All users must have a username.
Rule: All users must have a password.
Rule: All users must have a valid email address.
Rule: All users must have a valid credit card on file.
Policy: All users begin with a 0% discount rate on purchases.
Policy: All users are required to pay for shipping.

Rules are outward-facing statements backed by validation. Policies are internal rules backed by consequence.

It could be a policy that later on down the road, a user can change a username (depending on how the software was written), or that the discount and shipping rates assigned on signup may be adjusted to create customer opportunities.

In my estimation then, a rule requires hard validation, while a policy by nature is subject to intervention and/or manipulation.

HTH

Jared


问:
Passing argument in a Subset using function in R
I want to make a function that will accept a argument and use it into subset and then plot a graph with multiple line. I wrote following code

```<code>plot.new( )
rest_o_noise <- function(noise_level, color) {
    rest_o_noise_level = subset(yelp_flat, attributes.RestaurantsPriceRange2!= "NA", eval(parse(text=noise_level)))
    rest_o_noise_level <- rest_o_noise_level %>%
    group_by(attributes.RestaurantsPriceRange2) %>%
    summarise(n=mean(stars))
    lines(rest_o_noise_level, stars, col=color)
}

rest_o_noise("attributes.NoiseLevel=='loud'", "green")
rest_o_noise("attributes.NoiseLevel=='low'", "green")
</code>```

I am getting a error:

Error in grouped_df_impl(data, unname(vars), drop) : Column attributes.RestaurantsPriceRange2 is unknown

Just to be clear attributes.RestaurantsPriceRange2 is present in csv.

final output should look like:

Is this correct way to plot?
Please help!!

答:
Getting a subset of rows from iris data using a conditional in a string

```<code>Species <- as.character(iris$Species)
noise_level <- "Species == \"setosa\""

subset(iris, Sepal.Length == 5.1 &
       eval(parse(text=noise_level)))

#      Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1           5.1         3.5          1.4         0.2  setosa
# 18          5.1         3.5          1.4         0.3  setosa
# 20          5.1         3.8          1.5         0.3  setosa
# 22          5.1         3.7          1.5         0.4  setosa
# 24          5.1         3.3          1.7         0.5  setosa
# 40          5.1         3.4          1.5         0.2  setosa
# 45          5.1         3.8          1.9         0.4  setosa
# 47          5.1         3.8          1.6         0.2  setosa
</code>```

In your case, it would be something like what is below which conditions on the
columns attributes.RestaurantsPriceRange2 and  attributes.NoiseLevel to select subset of rows.

```<code>plot.new( )
rest_o_noise <- function(noise_level, color) {
  rest_o_noise_level = subset(yelp_flat,
   (attributes.RestaurantsPriceRange2!= "NA") &
                              eval(parse(text=noise_level)))
  rest_o_noise_level <- rest_o_noise_level %>%
    group_by(attributes.RestaurantsPriceRange2) %>%
    summarise(n=mean(stars))
  lines(rest_o_noise_level, stars, col=color)
}

rest_o_noise("attributes.NoiseLevel==\"loud\"", "green")
</code>```

You can, of course,  select a single column, as below. However, why you would use the "==" for that is not clear, hence I assumed you are trying to select a subset of rows.

```<code>noise_level <- "Petal.Width"
subset(iris, Sepal.Length == 5.1,
         eval(parse(text=noise_level)))

#      Petal.Width
# 1          0.2
# 18         0.3
# 20         0.3
# 22         0.4
# 24         0.5
# 40         0.2
# 45         0.4
# 47         0.2
# 99         1.1
</code>```

Body:
I want to make a function that will accept a argument and use it into subset and then plot a graph with multiple line. I wrote following code

plot.new( )
rest_o_noise <- function(noise_level, color) {
    rest_o_noise_level = subset(yelp_flat, attributes.RestaurantsPriceRange2!= "NA", eval(parse(text=noise_level)))
    rest_o_noise_level <- rest_o_noise_level %>%
    group_by(attributes.RestaurantsPriceRange2) %>%
    summarise(n=mean(stars))
    lines(rest_o_noise_level, stars, col=color)
}

rest_o_noise("attributes.NoiseLevel=='loud'", "green")
rest_o_noise("attributes.NoiseLevel=='low'", "green")

I am getting a error:

Error in grouped_df_impl(data, unname(vars), drop) : Column attributes.RestaurantsPriceRange2 is unknown

Just to be clear attributes.RestaurantsPriceRange2 is present in csv.

final output should look like:

Is this correct way to plot?
Please help!!

Body:
Getting a subset of rows from iris data using a conditional in a string

Species <- as.character(iris$Species)
noise_level <- "Species == \"setosa\""

subset(iris, Sepal.Length == 5.1 &
       eval(parse(text=noise_level)))

#      Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1           5.1         3.5          1.4         0.2  setosa
# 18          5.1         3.5          1.4         0.3  setosa
# 20          5.1         3.8          1.5         0.3  setosa
# 22          5.1         3.7          1.5         0.4  setosa
# 24          5.1         3.3          1.7         0.5  setosa
# 40          5.1         3.4          1.5         0.2  setosa
# 45          5.1         3.8          1.9         0.4  setosa
# 47          5.1         3.8          1.6         0.2  setosa

In your case, it would be something like what is below which conditions on the
columns attributes.RestaurantsPriceRange2 and  attributes.NoiseLevel to select subset of rows.

plot.new( )
rest_o_noise <- function(noise_level, color) {
  rest_o_noise_level = subset(yelp_flat,
   (attributes.RestaurantsPriceRange2!= "NA") &
                              eval(parse(text=noise_level)))
  rest_o_noise_level <- rest_o_noise_level %>%
    group_by(attributes.RestaurantsPriceRange2) %>%
    summarise(n=mean(stars))
  lines(rest_o_noise_level, stars, col=color)
}

rest_o_noise("attributes.NoiseLevel==\"loud\"", "green")

You can, of course,  select a single column, as below. However, why you would use the "==" for that is not clear, hence I assumed you are trying to select a subset of rows.

noise_level <- "Petal.Width"
subset(iris, Sepal.Length == 5.1,
         eval(parse(text=noise_level)))

#      Petal.Width
# 1          0.2
# 18         0.3
# 20         0.3
# 22         0.4
# 24         0.5
# 40         0.2
# 45         0.4
# 47         0.2
# 99         1.1


问:
how to pass event and variable as argument
In the following code, When I click anywhere on the document I am removing particular div's highlights class.

I have different class names for different div's for that, I am writing different functions for each and every div.

I want to write it using only one function by passing as arguments to a function parameter. But here I am facing the real problem. I have 'e'(event) on document.click and the variable 'clicked'.

I don't know how to pass the 'e' and the variable 'clicked' as an argument. Please help me with solving this.

```<code> $(document).click(function(e) {
      var clicked = $(e.target);
        if(!clicked.parents().hasClass("highlight"))
        {
            $(".highlight").removeClass("highlights");
        }
 });
</code>```

I want to do it as something like this:

```<code>function clickFun(parameters to be passed)
{

}
$(document).click(function()
{
  clickFun(args to be passed);
}
</code>```

As you can see I wanna pass arguments to a function parameter. Please help me with solving this.

答:
Do like this way:

$(document).ready(function(){
    $(document).click(function(){
        clickFun($(this)); //Function calling
    });
    function clickFun(event){
         console.log(event);// Your code
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

Body:
In the following code, When I click anywhere on the document I am removing particular div's highlights class.

I have different class names for different div's for that, I am writing different functions for each and every div.

I want to write it using only one function by passing as arguments to a function parameter. But here I am facing the real problem. I have 'e'(event) on document.click and the variable 'clicked'.

I don't know how to pass the 'e' and the variable 'clicked' as an argument. Please help me with solving this.

 $(document).click(function(e) {
      var clicked = $(e.target);
        if(!clicked.parents().hasClass("highlight"))
        {
            $(".highlight").removeClass("highlights");
        }
 });

I want to do it as something like this:

function clickFun(parameters to be passed)
{

}
$(document).click(function()
{
  clickFun(args to be passed);
}

As you can see I wanna pass arguments to a function parameter. Please help me with solving this.

Body:
Do like this way:

$(document).ready(function(){
    $(document).click(function(){
        clickFun($(this)); //Function calling
    });
    function clickFun(event){
         console.log(event);// Your code
    }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>