问:
Adding multiple buttons to JFrame, text+color not showing up
I'm trying to add 10 buttons to a JPanel one by one, and then adding them all to a JFrame. I need to have my for loop because it has to be easy changing the number of buttons. All the buttons also need to have different colors and texts (I know that they CAN get the same color with the code below, but that's OK for now).

My output from the code below is just a frame with 10 white buttons and no text/color. Why is the colors, text and the actionlistener not getting connected to my buttons?

I've read on other questions that I have to be careful of my placements regarding frame.add(panel, frame.pack() and frame.setVisible(true), but I think these are correctly placed outside of my forloop. I also tried using frame.setContentPane(panel), but this gave the same result - a frame with 10 white buttons and no text/color.

CMain class:

```<code>public class CMain extends MyButton {
public static void main(String[] args) {

    Random randomGenerator = new Random();
    int numberofbuttons = 10;

    JPanel panel = new JPanel();
    JFrame frame = new JFrame("MyButton testing");

    for (int i = 0; i < numberofbuttons; i++) {

        float r = randomGenerator.nextFloat();float g = randomGenerator.nextFloat();float b = randomGenerator.nextFloat();float r2 = randomGenerator.nextFloat();float g2 = randomGenerator.nextFloat();float b2 = randomGenerator.nextFloat();

        String theText = "SWITCH ME BACK";
        String theOtherText = "button nr: " + i;
        Color theColor = new Color(r, g, b);
        Color theOtherColor = new Color(r2, g2, b2);

        MyButton myb = new MyButton(theColor, theOtherColor, theText, theOtherText);
        panel.add(myb);
    }
    frame.add(panel);
    frame.pack();
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
</code>```

MyButton class:

```<code>public class MyButton extends JButton implements ActionListener {

private JButton button;
private Color col1;
private Color col2;
private String text1;
private String text2;

public MyButton(Color col1, Color col2, String text1, String text2) {
    this.col1 = col1;
    this.col2 = col2;
    this.text1 = text1;
    this.text2 = text2;
    button = new JButton(text1);
    button.setOpaque(true);
    button.setBackground(col1);
    button.addActionListener(this);
}

public MyButton() {
    this(Color.blue, Color.red, "click = make red", "click = reset to blue");
}

public void ToggleState() {
    Color initialBackground = button.getBackground();

    if (initialBackground == col1) {
        button.setBackground(col2);
        button.setText(text2);
    } else if (initialBackground == col2) {
        button.setBackground(col1);
        button.setText(text1);
    }
}

public void actionPerformed(ActionEvent e) {
    if (e.getSource() == button) {
        this.ToggleState();
    }
}
}
</code>```

答:
You're creating two JButtons with your class, one the object of the class itself (the this if you will) and the second, the button JButton variable within the class:

```<code>public class MyButton extends JButton implements ActionListener {  // **** this is a JButton

    private JButton button; // ***** and so is THIS!
</code>```

Get rid of the button variable and only work with this and your problems will likely be fixed.

```<code>public class MyButton extends JButton implements ActionListener {  // this is a JButton

    // private JButton button; // get rid of this
    // and then change all code where you try to use button to this.
</code>```

e.g.,

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

public class MyButton extends JButton implements ActionListener {

    // private JButton button;
    private Color col1;
    private Color col2;
    private String text1;
    private String text2;

    public MyButton(Color col1, Color col2, String text1, String text2) {

        super(text1);   // *********** also add this **********

        this.col1 = col1;
        this.col2 = col2;
        this.text1 = text1;
        this.text2 = text2;
        // button = new JButton(text1);
        this.setOpaque(true);
        this.setBackground(col1);
        this.addActionListener(this);
    }

    public MyButton() {
        this(Color.blue, Color.red, "click = make red", "click = reset to blue");
    }

    public void ToggleState() {
        Color initialBackground = this.getBackground();

        if (initialBackground == col1) {
            this.setBackground(col2);
            this.setText(text2);
        } else if (initialBackground == col2) {
            this.setBackground(col1);
            this.setText(text1);
        }
    }

    public void actionPerformed(ActionEvent e) {
        // if (e.getSource() == button) {
        this.ToggleState();
        // }
    }
}
</code>```

Body:
I'm trying to add 10 buttons to a JPanel one by one, and then adding them all to a JFrame. I need to have my for loop because it has to be easy changing the number of buttons. All the buttons also need to have different colors and texts (I know that they CAN get the same color with the code below, but that's OK for now).

My output from the code below is just a frame with 10 white buttons and no text/color. Why is the colors, text and the actionlistener not getting connected to my buttons?

I've read on other questions that I have to be careful of my placements regarding frame.add(panel, frame.pack() and frame.setVisible(true), but I think these are correctly placed outside of my forloop. I also tried using frame.setContentPane(panel), but this gave the same result - a frame with 10 white buttons and no text/color.

CMain class:

public class CMain extends MyButton {
public static void main(String[] args) {

    Random randomGenerator = new Random();
    int numberofbuttons = 10;

    JPanel panel = new JPanel();
    JFrame frame = new JFrame("MyButton testing");

    for (int i = 0; i < numberofbuttons; i++) {

        float r = randomGenerator.nextFloat();float g = randomGenerator.nextFloat();float b = randomGenerator.nextFloat();float r2 = randomGenerator.nextFloat();float g2 = randomGenerator.nextFloat();float b2 = randomGenerator.nextFloat();

        String theText = "SWITCH ME BACK";
        String theOtherText = "button nr: " + i;
        Color theColor = new Color(r, g, b);
        Color theOtherColor = new Color(r2, g2, b2);

        MyButton myb = new MyButton(theColor, theOtherColor, theText, theOtherText);
        panel.add(myb);
    }
    frame.add(panel);
    frame.pack();
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

MyButton class:

public class MyButton extends JButton implements ActionListener {

private JButton button;
private Color col1;
private Color col2;
private String text1;
private String text2;

public MyButton(Color col1, Color col2, String text1, String text2) {
    this.col1 = col1;
    this.col2 = col2;
    this.text1 = text1;
    this.text2 = text2;
    button = new JButton(text1);
    button.setOpaque(true);
    button.setBackground(col1);
    button.addActionListener(this);
}

public MyButton() {
    this(Color.blue, Color.red, "click = make red", "click = reset to blue");
}

public void ToggleState() {
    Color initialBackground = button.getBackground();

    if (initialBackground == col1) {
        button.setBackground(col2);
        button.setText(text2);
    } else if (initialBackground == col2) {
        button.setBackground(col1);
        button.setText(text1);
    }
}

public void actionPerformed(ActionEvent e) {
    if (e.getSource() == button) {
        this.ToggleState();
    }
}
}

Body:
You're creating two JButtons with your class, one the object of the class itself (the this if you will) and the second, the button JButton variable within the class:

public class MyButton extends JButton implements ActionListener {  // **** this is a JButton

    private JButton button; // ***** and so is THIS!

Get rid of the button variable and only work with this and your problems will likely be fixed.

public class MyButton extends JButton implements ActionListener {  // this is a JButton

    // private JButton button; // get rid of this
    // and then change all code where you try to use button to this.

e.g.,

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class MyButton extends JButton implements ActionListener {

    // private JButton button;
    private Color col1;
    private Color col2;
    private String text1;
    private String text2;

    public MyButton(Color col1, Color col2, String text1, String text2) {

        super(text1);   // *********** also add this **********

        this.col1 = col1;
        this.col2 = col2;
        this.text1 = text1;
        this.text2 = text2;
        // button = new JButton(text1);
        this.setOpaque(true);
        this.setBackground(col1);
        this.addActionListener(this);
    }

    public MyButton() {
        this(Color.blue, Color.red, "click = make red", "click = reset to blue");
    }

    public void ToggleState() {
        Color initialBackground = this.getBackground();

        if (initialBackground == col1) {
            this.setBackground(col2);
            this.setText(text2);
        } else if (initialBackground == col2) {
            this.setBackground(col1);
            this.setText(text1);
        }
    }

    public void actionPerformed(ActionEvent e) {
        // if (e.getSource() == button) {
        this.ToggleState();
        // }
    }
}


来源: stackexchange

问:
Amazon CLI won't allow me to list objects
I'm trying to copy contents of an S3 bucket to another bucket on another account, and I wanted to use the CLI to do this. So I set up a bucket policy on the source bucket, allowing a IAM user in the destination account to perform all S3 actions, but it keeps complaining that the ListObjects operation is denied.

I've tried Google, but I can't tell what would be the problem with my policy compared to the solutions I find. Even if I make the source bucket public (and can list it in a browser), it still gives me access denied.

What to do, what to do? Here's my bucket policy:

```<code>{
"Version": "2012-10-17",
"Statement": [
    {
        "Sid": "AllowAll",
        "Effect": "Allow",
        "Principal": {
            "AWS": "arn:aws:iam::123123123123:user/USER"
        },
        "Action": [
            "s3:*"
        ],
        "Resource": [
            "arn:aws:s3:::SOURCE",
            "arn:aws:s3:::SOURCE/*"
        ]
    }
]
</code>```

}

答:
Please try using below policy,

{
    "Version": "2008-10-17",
    "Id": "Policy1357935677554",
    "Statement": [
        {
            "Sid": "CrossAccountList",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::111111111111:root"
            },
            "Action": "s3:ListBucket",
            "Resource": "arn:aws:s3:::examplebucket"
        },
        {
            "Sid": "CrossAccountS3",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::111111111111:root"
            },
            "Action": "s3:*",
            "Resource": "arn:aws:s3:::examplebucket/*"
        }
    ]
}```

You can read the full steps here

Another read here

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to copy contents of an S3 bucket to another bucket on another account, and I wanted to use the CLI to do this. So I set up a bucket policy on the source bucket, allowing a IAM user in the destination account to perform all S3 actions, but it keeps complaining that the ListObjects operation is denied.

I've tried Google, but I can't tell what would be the problem with my policy compared to the solutions I find. Even if I make the source bucket public (and can list it in a browser), it still gives me access denied.

What to do, what to do? Here's my bucket policy:

{
"Version": "2012-10-17",
"Statement": [
    {
        "Sid": "AllowAll",
        "Effect": "Allow",
        "Principal": {
            "AWS": "arn:aws:iam::123123123123:user/USER"
        },
        "Action": [
            "s3:*"
        ],
        "Resource": [
            "arn:aws:s3:::SOURCE",
            "arn:aws:s3:::SOURCE/*"
        ]
    }
]

}

Body:
Please try using below policy,

{
    "Version": "2008-10-17",
    "Id": "Policy1357935677554",
    "Statement": [
        {
            "Sid": "CrossAccountList",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::111111111111:root"
            },
            "Action": "s3:ListBucket",
            "Resource": "arn:aws:s3:::examplebucket"
        },
        {
            "Sid": "CrossAccountS3",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::111111111111:root"
            },
            "Action": "s3:*",
            "Resource": "arn:aws:s3:::examplebucket/*"
        }
    ]
}

You can read the full steps here

Another read here


问:
"TypeError: 'Tensor' object is not iterable" error with tensorflow Estimator
I have a procedurally generated (infinite) data source and am trying to use this as input to the high-level Tensorflow Estimator to train a image-based 3D object detector.

I set up the Dataset just as in the Tensorflor Estimator Quickstart, and my dataset_input_fn returns a tuple of features and labels Tensor's, just as the Estimator.train function specifies, and how this tutorial shows, but I am getting an error when trying to call the train function:

TypeError: 'Tensor' object is not iterable.

What am I doing wrong?

```<code>    def data_generator():
        """
        Generator for image (features) and ground truth object positions (labels)

        Sample an image and object positions from a procedurally generated data source
        """
        while True:
            source.step()  # generate next data point

            object_ground_truth = source.get_ground_truth() # list of 9 floats
            cam_img = source.get_cam_frame()  # image (224, 224, 3)
            yield (cam_img, object_ground_truth)

    def dataset_input_fn():
        """
        Tensorflow `Dataset` object from generator
        """

        dataset = tf.data.Dataset.from_generator(data_generator, (tf.uint8, tf.float32), \
            (tf.TensorShape([224, 224, 3]), tf.TensorShape([9])))
        dataset = dataset.batch(16)

        iterator = dataset.make_one_shot_iterator()

        features, labels = iterator.get_next()
        return features, labels

    def main():
        """
        Estimator [from Keras model](https://www.tensorflow.org/programmers_guide/estimators#creating_estimators_from_keras_models)

        Try to call `est_vgg.train()` leads to the error
        """
        ....
        est_vgg16 = tf.keras.estimator.model_to_estimator(keras_model=keras_vgg16)
        est_vgg16.train(input_fn=dataset_input_fn, steps=10)
        ....
</code>```

Here is the full code

(note: things are named differently from this question)

Here is the stack trace:

```<code>Traceback (most recent call last):
  File "./rock_detector.py", line 155, in <module>
    main()
  File "./rock_detector.py", line 117, in main
    est_vgg16.train(input_fn=dataset_input_fn, steps=10)
  File "/usr/local/lib/python3.6/site-packages/tensorflow/python/estimator/estimator.py", line 302, in train
    loss = self._train_model(input_fn, hooks, saving_listeners)
  File "/usr/local/lib/python3.6/site-packages/tensorflow/python/estimator/estimator.py", line 711, in _train_model
    features, labels, model_fn_lib.ModeKeys.TRAIN, self.config)
  File "/usr/local/lib/python3.6/site-packages/tensorflow/python/estimator/estimator.py", line 694, in _call_model_fn
    model_fn_results = self._model_fn(features=features, **kwargs)
  File "/usr/local/lib/python3.6/site-packages/tensorflow/python/keras/_impl/keras/estimator.py", line 145, in model_fn
    labels)
  File "/usr/local/lib/python3.6/site-packages/tensorflow/python/keras/_impl/keras/estimator.py", line 92, in _clone_and_build_model
    keras_model, features)
  File "/usr/local/lib/python3.6/site-packages/tensorflow/python/keras/_impl/keras/estimator.py", line 58, in _create_ordered_io
    for key in estimator_io_dict:
  File "/usr/local/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 505, in __iter__
    raise TypeError("'Tensor' object is not iterable.")
TypeError: 'Tensor' object is not iterable.
</code>```

答:
Make your input function return a dictionary of features like this:

def dataset_input_fn():
  ...
  features, labels = iterator.get_next()
  return {'image': features}, labels
```

Body:
I have a procedurally generated (infinite) data source and am trying to use this as input to the high-level Tensorflow Estimator to train a image-based 3D object detector.

I set up the Dataset just as in the Tensorflor Estimator Quickstart, and my dataset_input_fn returns a tuple of features and labels Tensor's, just as the Estimator.train function specifies, and how this tutorial shows, but I am getting an error when trying to call the train function:

TypeError: 'Tensor' object is not iterable.

What am I doing wrong?

    def data_generator():
        """
        Generator for image (features) and ground truth object positions (labels)

        Sample an image and object positions from a procedurally generated data source
        """
        while True:
            source.step()  # generate next data point

            object_ground_truth = source.get_ground_truth() # list of 9 floats
            cam_img = source.get_cam_frame()  # image (224, 224, 3)
            yield (cam_img, object_ground_truth)

    def dataset_input_fn():
        """
        Tensorflow `Dataset` object from generator
        """

        dataset = tf.data.Dataset.from_generator(data_generator, (tf.uint8, tf.float32), \
            (tf.TensorShape([224, 224, 3]), tf.TensorShape([9])))
        dataset = dataset.batch(16)

        iterator = dataset.make_one_shot_iterator()

        features, labels = iterator.get_next()
        return features, labels

    def main():
        """
        Estimator [from Keras model](https://www.tensorflow.org/programmers_guide/estimators#creating_estimators_from_keras_models)

        Try to call `est_vgg.train()` leads to the error
        """
        ....
        est_vgg16 = tf.keras.estimator.model_to_estimator(keras_model=keras_vgg16)
        est_vgg16.train(input_fn=dataset_input_fn, steps=10)
        ....

Here is the full code

(note: things are named differently from this question)

Here is the stack trace:

Traceback (most recent call last):
  File "./rock_detector.py", line 155, in <module>
    main()
  File "./rock_detector.py", line 117, in main
    est_vgg16.train(input_fn=dataset_input_fn, steps=10)
  File "/usr/local/lib/python3.6/site-packages/tensorflow/python/estimator/estimator.py", line 302, in train
    loss = self._train_model(input_fn, hooks, saving_listeners)
  File "/usr/local/lib/python3.6/site-packages/tensorflow/python/estimator/estimator.py", line 711, in _train_model
    features, labels, model_fn_lib.ModeKeys.TRAIN, self.config)
  File "/usr/local/lib/python3.6/site-packages/tensorflow/python/estimator/estimator.py", line 694, in _call_model_fn
    model_fn_results = self._model_fn(features=features, **kwargs)
  File "/usr/local/lib/python3.6/site-packages/tensorflow/python/keras/_impl/keras/estimator.py", line 145, in model_fn
    labels)
  File "/usr/local/lib/python3.6/site-packages/tensorflow/python/keras/_impl/keras/estimator.py", line 92, in _clone_and_build_model
    keras_model, features)
  File "/usr/local/lib/python3.6/site-packages/tensorflow/python/keras/_impl/keras/estimator.py", line 58, in _create_ordered_io
    for key in estimator_io_dict:
  File "/usr/local/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 505, in __iter__
    raise TypeError("'Tensor' object is not iterable.")
TypeError: 'Tensor' object is not iterable.


问:
Select of 2 related tables in MySQL
I have these 2 tables:

Table Users:

```<code>id | name
---------
1  | Joe
2  | Sara
3  | Michael
</code>```

Table Sales:

```<code>id |  product  | user_id
------------------------
1  |    Car    | 2
2  |   Truck   | 3
3  | motorcycle| 1
4  |    Car    | 2
5  |   Truck   | 1
6  |    Car    | 3
7  |    Car    | 2
8  |   Truck   | 3
9  |    Car    | 2
10 |    Car    | 3
</code>```

I want the following:

```<code>User Name  | Car | Truck | Motorcycle
Joe        |  0  |   1   |     1
Sara       |  4  |   0   |     0
Michael    |  2  |   2   |     0
</code>```

Any help would be appreciated

答:
--For a small number of products this works,</p>

```<code>Select username
, Sum(case when product = 'Car' then 1 else 0 End) Cars
, Sum(case when product = 'Truck' then 1 else 0 End) Truck
, Sum(case when product = 'motorcycle' then 1 else 0 End) motorcycle
From Sales s join users u on s.userid = u.userid
group by username
</code>```

Title: Select of 2 related tables in MySQL

Body:
I have these 2 tables:

Table Users:

id | name
---------
1  | Joe
2  | Sara
3  | Michael

Table Sales:

id |  product  | user_id
------------------------
1  |    Car    | 2
2  |   Truck   | 3
3  | motorcycle| 1
4  |    Car    | 2
5  |   Truck   | 1
6  |    Car    | 3
7  |    Car    | 2
8  |   Truck   | 3
9  |    Car    | 2
10 |    Car    | 3

I want the following:

User Name  | Car | Truck | Motorcycle
Joe        |  0  |   1   |     1
Sara       |  4  |   0   |     0
Michael    |  2  |   2   |     0

Any help would be appreciated

Body:
--For a small number of products this works,

Select username
, Sum(case when product = 'Car' then 1 else 0 End) Cars
, Sum(case when product = 'Truck' then 1 else 0 End) Truck
, Sum(case when product = 'motorcycle' then 1 else 0 End) motorcycle
From Sales s join users u on s.userid = u.userid
group by username


问:
Updating variable in react
I have what seems to be a very simple question. In the following code I can not update a variable reference but I can set it directly, can you tell me why?

This updates the HTML element correctly:

```<code>startTimer() {
    let timerOutput = this.timerOutput.innerHTML = this.state.timer.toLocaleTimeString();
}
</code>```

Using this code however nothing happens in the DOM:

```<code>startTimer() {
        let timerOutput = this.timerOutput.innerHTML;
        timerOutput = this.state.timer.toLocaleTimeString();
    }
</code>```

Printout of the entire Timer container component:

```<code>export class Timer extends React.PureComponent {
    constructor(props) {
        super(props);
        this.state = {timer: new Date()};
      }

    startTimer() {
        let timerOutput = this.timerOutput.innerHTML;
        timerOutput = this.state.timer.toLocaleTimeString();
        // timerOutput = this.state.timer.toLocaleTimeString();
        console.log(this.state.timer);
    }

    handleClick(e) {
        this.startTimer(e);
    }

  componentDidMount() {

  }

  render() {

    return (
      <section>
        <div id="timerOut"
        ref={(output) => {this.timerOutput = output }}
        ></div>
        <button onClick={this.handleClick.bind(this)} value="Click me" />;
        <h2>It is {this.state.timer.toLocaleTimeString()}.</h2>
      </section>
    );
  }
}

export default Timer;
</code>```

答:
When you are doing this:

```<code>let timerOutput = this.timerOutput.innerHTML;
timerOutput = this.state.timer.toLocaleTimeString();
</code>```

You are not changing the element's innerHTML but just a copy of that. In order to change the DOM you have to do:

```<code>this.timerOutput.innerHTML = this.state.timer.toLocaleTimeString();
</code>```

Edit: to be clear, it does answer your question but it's not the "React way" of doing this. You should manage state with setState().

Title: Updating variable in react

Body:
I have what seems to be a very simple question. In the following code I can not update a variable reference but I can set it directly, can you tell me why?

This updates the HTML element correctly:

startTimer() {
    let timerOutput = this.timerOutput.innerHTML = this.state.timer.toLocaleTimeString();
}

Using this code however nothing happens in the DOM:

startTimer() {
        let timerOutput = this.timerOutput.innerHTML;
        timerOutput = this.state.timer.toLocaleTimeString();
    }

Printout of the entire Timer container component:

export class Timer extends React.PureComponent {
    constructor(props) {
        super(props);
        this.state = {timer: new Date()};
      }

    startTimer() {
        let timerOutput = this.timerOutput.innerHTML;
        timerOutput = this.state.timer.toLocaleTimeString();
        // timerOutput = this.state.timer.toLocaleTimeString();
        console.log(this.state.timer);
    }

    handleClick(e) {
        this.startTimer(e);
    }

  componentDidMount() {

  }

  render() {

    return (

 {this.timerOutput = output }}
        >

        <button onClick={this.handleClick.bind(this)} value="Click me" />;

It is {this.state.timer.toLocaleTimeString()}.

    );
  }
}

export default Timer;

Body:
When you are doing this:

let timerOutput = this.timerOutput.innerHTML;
timerOutput = this.state.timer.toLocaleTimeString();

You are not changing the element's innerHTML but just a copy of that. In order to change the DOM you have to do:

this.timerOutput.innerHTML = this.state.timer.toLocaleTimeString();

Edit: to be clear, it does answer your question but it's not the "React way" of doing this. You should manage state with setState().


问:
Form still posting even after canceling
I've read all the posts on this but can't seem to work out why my form is still posting even after I press cancel on the confirm popup. Any help appreciated. I'm returning the the result of the confirm, so i was expecting the dialog to just disappear and the form to not post.  Im sure its something simple.

Here is my code:

```<code><form action='/auth/deleteUserCascade' method='post' onsubmit='return confirm(\"Are you sure you want to delete this user?\");'>
    <button type='submit' class='btn-link'>
        <i class='fa fa-trash' aria-hidden='true'></i>
    </button>";
</form>
</code>```

答:
It seems like you had written a wrong syntax. Next variant works as well(I used double quotes instead of single ones):</p>

```<code><form action="/auth/deleteUserCascade" method="post" onsubmit="return confirm('Are you sure you want to delete this user?');">
  <button type="submit" class="btn-link">
    Submit
  </button>
</form>
</code>```

Title: Form still posting even after canceling

Body:
I've read all the posts on this but can't seem to work out why my form is still posting even after I press cancel on the confirm popup. Any help appreciated. I'm returning the the result of the confirm, so i was expecting the dialog to just disappear and the form to not post.  Im sure its something simple.

Here is my code:

<form action='/auth/deleteUserCascade' method='post' onsubmit='return confirm(\"Are you sure you want to delete this user?\");'>
    <button type='submit' class='btn-link'>

    </button>";
</form>

Body:
It seems like you had written a wrong syntax. Next variant works as well(I used double quotes instead of single ones):

<form action="/auth/deleteUserCascade" method="post" onsubmit="return confirm('Are you sure you want to delete this user?');">
  <button type="submit" class="btn-link">
    Submit
  </button>
</form>


问:
JDT Compiler Exception
```<code>java.lang.NoSuchMethodError: org.eclipse.jdt.internal.compiler.CompilationResult.getProblems()[Lorg/eclipse/jdt/core/compiler/IProblem;
 at org.apache.jasper.compiler.JDTCompiler$2.acceptResult(JDTCompiler.java:329)
 at org.eclipse.jdt.internal.compiler.Compiler.handleInternalException(Compiler.java:502)
 at org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:430)
 at org.apache.jasper.compiler.JDTCompiler.generateClass(JDTCompiler.java:387)
 at org.apache.jasper.compiler.Compiler.compile(Compiler.java:288)
 at org.apache.jasper.compiler.Compiler.compile(Compiler.java:267)
 at org.apache.jasper.compiler.Compiler.compile(Compiler.java:255)
</code>```

I am getting the above exception... any ideas?

JBoss (MX MicroKernel) [4.2.3.GA

JDK 1.6

Icefaces 1.8.2

答:
here is your solution

JBoss Rules uses the Apache JCI to interface to compilers which means we can switch to other compilers or versions.

There are several ways to enable the Janino compiler instead of JDT for Java semantics.

ContentLicense: CC BY-SA 2.5

Title: JDT Compiler Exception

Body:
java.lang.NoSuchMethodError: org.eclipse.jdt.internal.compiler.CompilationResult.getProblems()[Lorg/eclipse/jdt/core/compiler/IProblem;
 at org.apache.jasper.compiler.JDTCompiler$2.acceptResult(JDTCompiler.java:329)
 at org.eclipse.jdt.internal.compiler.Compiler.handleInternalException(Compiler.java:502)
 at org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:430)
 at org.apache.jasper.compiler.JDTCompiler.generateClass(JDTCompiler.java:387)
 at org.apache.jasper.compiler.Compiler.compile(Compiler.java:288)
 at org.apache.jasper.compiler.Compiler.compile(Compiler.java:267)
 at org.apache.jasper.compiler.Compiler.compile(Compiler.java:255)

I am getting the above exception... any ideas?

JBoss (MX MicroKernel) [4.2.3.GA

JDK 1.6

Icefaces 1.8.2


问:
Nested list using React
I am trying to create nested lists in separate div's using different input data. I am having a problem printing a nested list: List 2 here. I printing the name attribute of object and then checking if there are any childNodes print the name attribute of those too, nested that is. Here's the Parent class.

```<code>export default class Parent extends Component {
  render() {
    return (

    <div>
      <h4>List 1</h4>
      <ul>
        {this.props.jsonData1.map(item => {
          return <Child name={item.name}/>
        })}
      </ul>
    </div>

    <div>
      <h4>List 2</h4>
      <ul>
        {this.props.jsonData2.map(item1 => {
          return <Child name={item1.name}/>
         if(item1.childNodes){
           <ul>
           {item1.jsonData2.map(item2=>{
             return <Child name={item2.name}/>
           })}
         }</ul>
        })}
      </ul>
    </div>
    );
  }
}
</code>```

My Child class is pretty simple. It only returns a single list element.

```<code>export default class Child extends Component {
  render() {
    let {name}=this.props;
    return (
      <li>{name}</li>
    );
  }
}
</code>```

I would appreciate some guidance about what I am doing wrong here. I am trying to keep the recursion as simple as possible but apparently I am doing it wrong.

答:
A few things just looking at the code. In the return for your Parent class, make sure you've encapsulating everything in one div: </p>

```<code>export default class Parent extends Component {
   render() {
      return(
         <div>
           //other code
         </div>
      );
   }
}
</code>```

Title: Nested list using React

Body:
I am trying to create nested lists in separate div's using different input data. I am having a problem printing a nested list: List 2 here. I printing the name attribute of object and then checking if there are any childNodes print the name attribute of those too, nested that is. Here's the Parent class.

export default class Parent extends Component {
  render() {
    return (

List 1

        {this.props.jsonData1.map(item => {
          return <Child name={item.name}/>
        })}

List 2

        {this.props.jsonData2.map(item1 => {
          return <Child name={item1.name}/>
         if(item1.childNodes){

           {item1.jsonData2.map(item2=>{
             return <Child name={item2.name}/>
           })}
         }

        })}

    );
  }
}

My Child class is pretty simple. It only returns a single list element.

export default class Child extends Component {
  render() {
    let {name}=this.props;
    return (

{name}

    );
  }
}

I would appreciate some guidance about what I am doing wrong here. I am trying to keep the recursion as simple as possible but apparently I am doing it wrong.

Body:
A few things just looking at the code. In the return for your Parent class, make sure you've encapsulating everything in one div:

export default class Parent extends Component {
   render() {
      return(
         <div>
           //other code
         </div>
      );
   }
}


问:
How can i handle native crash in my app due to Google Ocr lib, during instantiation on TextReconiger?
I am using Google's OCR library to detect text from image in my App. Earlier It was working fine but suddenly it has started giving error. I am getting crash during instantiation on TextReconiger. I am getting this crash on some devices like Samsung S6 edge, Samsung S7 etc and on some devices it is working fine.

I am getting crash on this line in my code

```<code>TextRecognizer textRecognizer = new TextRecognizer.Builder(context).build();
</code>```

crash log :

```<code>  native: pc 000000000006f9fc  /system/lib64/libc.so (tgkill+8)
  native: pc 000000000006cd10  /system/lib64/libc.so (pthread_kill+64)
  native: pc 0000000000025078  /system/lib64/libc.so (raise+24)
  native: pc 000000000001cc04  /system/lib64/libc.so (abort+52)
  native: pc 00000000004750d0
  /data/data/com.google.android.gms/app_vision/ocr/libs/arm64-
  v8a/libocr.so
  native: pc 0000000000475770
  /data/data/com.google.android.gms/app_vision/ocr/libs/arm64-
  v8a/libocr.so
  native: pc 0000000000475814
  /data/data/com.google.android.gms/app_vision/ocr/libs/arm64-
  v8a/libocr.so
  native: pc 0000000000474830
  /data/data/com.google.android.gms/app_vision/ocr/libs/arm64-
  v8a/libocr.so
  native: pc 000000000026cee4
  /data/data/com.google.android.gms/app_vision/ocr/libs/arm64-
  v8a/libocr.so
  native: pc 0000000000271190
  /data/data/com.google.android.gms/app_vision/ocr/libs/arm64-
  v8a/libocr.so
  native: pc 0000000000065794
  /data/data/com.google.android.gms/app_vision/ocr/libs/arm64-
  v8a/libocr.so
  native: pc 0000000000065488
  /data/data/com.google.android.gms/app_vision/ocr/libs/arm64-
  v8a/libocr.so
  native: pc 000000000027caf4
  /data/data/com.google.android.gms/app_vision/ocr/libs/arm64-
  v8a/libocr.so
  native: pc 0000000000280274
  /data/data/com.google.android.gms/app_vision/ocr/libs/arm64-
  v8a/libocr.so
  native: pc 0000000000067c84
  /data/data/com.google.android.gms/app_vision/ocr/libs/arm64-
  v8a/libocr.so
  native: pc 0000000000067f64
  /data/data/com.google.android.gms/app_vision/ocr/libs/arm64-
  v8a/libocr.so
  native: pc 0000000000063dec
  /data/data/com.google.android.gms/app_vision/ocr/libs/arm64-
  v8a/libocr.so
  native: pc 0000000000387e60
/data/user_de/0/com.google.android.gms/app_chimera/m/00000027/oat/arm64
/DynamiteModulesA_GmsCore_prodmnc_xxhdpi_release.odex
</code>```

This crash is affecting rating of my App on Google play store. From this crash log i am not getting any idea how to fix this. If someone knows the solution for this issue please help me out.

答:
I have the same problem and the same error trace.

I read that the new Google Play Service version with OCR fix is currently in Beta channel. I've just tested it and is working!

https://play.google.com/apps/testing/com.google.android.gms

Body:
I am using Google's OCR library to detect text from image in my App. Earlier It was working fine but suddenly it has started giving error. I am getting crash during instantiation on TextReconiger. I am getting this crash on some devices like Samsung S6 edge, Samsung S7 etc and on some devices it is working fine.

I am getting crash on this line in my code

TextRecognizer textRecognizer = new TextRecognizer.Builder(context).build();

crash log :

  native: pc 000000000006f9fc  /system/lib64/libc.so (tgkill+8)
  native: pc 000000000006cd10  /system/lib64/libc.so (pthread_kill+64)
  native: pc 0000000000025078  /system/lib64/libc.so (raise+24)
  native: pc 000000000001cc04  /system/lib64/libc.so (abort+52)
  native: pc 00000000004750d0
  /data/data/com.google.android.gms/app_vision/ocr/libs/arm64-
  v8a/libocr.so
  native: pc 0000000000475770
  /data/data/com.google.android.gms/app_vision/ocr/libs/arm64-
  v8a/libocr.so
  native: pc 0000000000475814
  /data/data/com.google.android.gms/app_vision/ocr/libs/arm64-
  v8a/libocr.so
  native: pc 0000000000474830
  /data/data/com.google.android.gms/app_vision/ocr/libs/arm64-
  v8a/libocr.so
  native: pc 000000000026cee4
  /data/data/com.google.android.gms/app_vision/ocr/libs/arm64-
  v8a/libocr.so
  native: pc 0000000000271190
  /data/data/com.google.android.gms/app_vision/ocr/libs/arm64-
  v8a/libocr.so
  native: pc 0000000000065794
  /data/data/com.google.android.gms/app_vision/ocr/libs/arm64-
  v8a/libocr.so
  native: pc 0000000000065488
  /data/data/com.google.android.gms/app_vision/ocr/libs/arm64-
  v8a/libocr.so
  native: pc 000000000027caf4
  /data/data/com.google.android.gms/app_vision/ocr/libs/arm64-
  v8a/libocr.so
  native: pc 0000000000280274
  /data/data/com.google.android.gms/app_vision/ocr/libs/arm64-
  v8a/libocr.so
  native: pc 0000000000067c84
  /data/data/com.google.android.gms/app_vision/ocr/libs/arm64-
  v8a/libocr.so
  native: pc 0000000000067f64
  /data/data/com.google.android.gms/app_vision/ocr/libs/arm64-
  v8a/libocr.so
  native: pc 0000000000063dec
  /data/data/com.google.android.gms/app_vision/ocr/libs/arm64-
  v8a/libocr.so
  native: pc 0000000000387e60
/data/user_de/0/com.google.android.gms/app_chimera/m/00000027/oat/arm64
/DynamiteModulesA_GmsCore_prodmnc_xxhdpi_release.odex

This crash is affecting rating of my App on Google play store. From this crash log i am not getting any idea how to fix this. If someone knows the solution for this issue please help me out.


问:
ld: framework not found Pods
I'm trying to add a framework to my IOS project but when I build I always got the same message :

ld: framework not found Pods

clang: error: linker command failed with exit code 1 (use -v to see invocation)

I tried to remove my Pods directory and then run pod install
I open the .xcworkspace like it is written in the logs on the pod install, I clean the project on xcode and then try to build but it won't works..

My podfile looks like this :

```<code>xcodeproj '/Users/guillaume/project/Mobile/iOS/FoodPin/FoodPin.xcodeproj'
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!
pod 'SwiftHTTP', '~> 0.9.2'
</code>```

My version of xcode is 6.3.1

Thank you,

答:
I had a similar issue as

```<code>framework not found Pods_OneSignalNotificationServiceExtension
</code>```

It was resolved by removing the following. Go to target OneSignalNotificationServiceExtension > Build Phases > Link Binary with Libraries and deleting Pods_OneSignalNotificationServiceExtension.framework

Hope this helps. Cheers.

Title: ld: framework not found Pods

Body:
I'm trying to add a framework to my IOS project but when I build I always got the same message :

ld: framework not found Pods

clang: error: linker command failed with exit code 1 (use -v to see invocation)

I tried to remove my Pods directory and then run pod install
I open the .xcworkspace like it is written in the logs on the pod install, I clean the project on xcode and then try to build but it won't works..

My podfile looks like this :

xcodeproj '/Users/guillaume/project/Mobile/iOS/FoodPin/FoodPin.xcodeproj'
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!
pod 'SwiftHTTP', '~> 0.9.2'

My version of xcode is 6.3.1

Thank you,

Body:
I had a similar issue as

framework not found Pods_OneSignalNotificationServiceExtension

It was resolved by removing the following. Go to target OneSignalNotificationServiceExtension > Build Phases > Link Binary with Libraries and deleting Pods_OneSignalNotificationServiceExtension.framework

Hope this helps. Cheers.


问:
Subclipse: Updating Change Sets for SVNStatusSubscriber (UPDATED - clock sync issue)
I see this when digging into the error logs of Eclipse - I keep getting an error:

An internal error occurred during:
  "Updating Change Sets for
  SVNStatusSubscriber"

It happens a few times when trying to update or commit, and eventually hoses my local copy of SVN, and I'm forced to rebuild it.

Has anyone every encountered either of these or have any thoughts on fixing?  It's a huge annoyance to have to rebuild SVN each time.  I'm using Subclipse with Helios.  Also I'm connected via FUSE/SSHfs to the project on a VM.

答:
Okay, so this is still not 100% certain, but it would appear that what's happened is that the date goes out of sync on the VM on occassion.  During svn updates or commits, this causes inconsistent synchronization data and the client in Eclipse, confused, ends up throwing errors.

Because the errors cause an abort of the update or commit process, this leaves the repository in a very unstable state, my guess is that it tries to retrieve a name of a file but gets back null, and ends up writing this back to the .svn/entries somehow.

As I said I can't confirm that this is the only thing causing the problems, but it makes sense as after my clock went out of sync, pretty much all of svn was broken on the next svn up call.


问:
Null Reference exception using ADAL for acquiringtokenasync with resource and clientkey
I am hitting this null reference exception using ADAL with version:3.13.1.846, this doesn’t repro every time. Any ideas?

I have made sure that when calling AcquireTokenAsync on the AuthenticationContext as recommended in many MS samples, for example. Here's a link to the docs for that method and the SecureClientSecret which is causing errors.

I am not passing in a null value

```<code>System.NullReferenceException: Object reference not set to an instance of an object.
   at Microsoft.IdentityModel.Clients.ActiveDirectory.SecureClientSecret.ApplyTo(IDictionary`2 parameters)
   at Microsoft.IdentityModel.Clients.ActiveDirectory.AcquireTokenHandlerBase.<SendTokenRequestAsync>d__65.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
   at Microsoft.IdentityModel.Clients.ActiveDirectory.AcquireTokenHandlerBase.<RunAsync>d__55.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext.<AcquireTokenForClientCommonAsync>d__49.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext.<AcquireTokenAsync>d__26.MoveNext()
</code>```

Thanks,
Sara

答:
I've had a look over the source code for the SecureClientSecret

SecureClientSecret

I'm a bit confused as to what Microsoft are trying to do with their ApplyTo method, it looks a bit like the kind of pattern you see with TryParse and out params, populating a dictionary by reference.

More explicity, populating the dictionary value at OAuthParameter.ClientSecret ('client_secret'as that translates to), with the decrypted value of the SecureString stashed away inside SecureClientSecret.

Microsoft then clear down the private SecureString member, which means any further calls to ApplyTo are going to be met with an unhandled exception when we hit the first line:

```<code>var output = new char[secureString.Length];
</code>```

'secureString.Length' is going to blow, the exception you'd expect, calling null.Length... System.NullReferenceException, something that we see happening in the stack trace.

If MS really need to clear away that member field after a single use for some reason that I don't understand at the moment, maybe they should consider making the class more robust.

Add an IsApplied method/property to the interface:

```<code>public interface ISecureClientSecret
{
    /// <summary>
    /// Writes SecureString to the dictionary.
    /// </summary>
    /// <param name="parameters"></param>
    void ApplyTo(IDictionary<string, string> parameters);

    /// <summary>
    /// Indicates whether this <see cref="ISecureClientSecret"/> has already been applied.
    /// </summary>
    /// <returns><c>true</c> if applied, otherwise <c>false</c></returns>
    bool IsApplied { get; };
}
</code>```

Which could easily be implemented in the concrete class with:

```<code>public bool IsApplied => secureString == null;
</code>```

Also, the ApplyTo method could make use of locking to prevent bad things happening with lots of calls:

```<code>public void ApplyTo(IDictionary<string, string> parameters)
{
    secureLock.WaitOne();

    // We don't want to blow up if ApplyTo is called multiple times.
    if (IsApplied)
        return;

    IntPtr ptr = IntPtr.Zero;

    try
    {
        ptr = Marshal.SecureStringToCoTaskMemUnicode(secureString);
        parameters[OAuthParameter.ClientSecret] = Marshal.PtrToStringUni(ptr);
    }
    finally
    {
        if (ptr != IntPtr.Zero)
            Marshal.ZeroFreeCoTaskMemUnicode(ptr);

        if (secureString != null && !secureString.IsReadOnly())
            secureString.Clear();

        secureString = null;

        secureLock.Set();
    }
}
</code>```

Sticking a AutoResetEvent in as a member for the class.

```<code>private AutoResetEvent secureLock = new AutoResetEvent(true);
</code>```

It would be great if one of the devs on this project could explain what they're trying to do as things seem a little convoluted as a newbie looking in.

UPDATE

As @Nan Yu previously said, I'd like to see the poster's calling code for the delegate that provides the auth. After playing around with my own version I'm wondering if making sure the vars related to the SecureClientSecret are scoped as low down as possible would get around the potential issues I discussed above.

I.e. Don't have any member/field references to the SecureClientSecret. Don't have any vars scoped outside the delegate itself either, as I think the underlying SecureString inside the SecureClientSecret object gets nulled and things don't work out well when you try to get another token passing in the original SecureString.

I believe this is essentially what @'Kevin ssssssss' was suggesting in their answer!

```<code>var delegateAuthProvider = new DelegateAuthenticationProvider(async (requestMessage) =>
{
    var authContext = new AuthenticationContext($"https://login.microsoftonline.com/{tenant}/oauth2/token");
    var result = await authContext.AcquireTokenAsync(Resource, new ClientCredential(appClientId, new SecureClientSecret(appSecretSecure)));

    requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", result.AccessToken);
});
</code>```

MS samples seem to recommend calling for a new token every time before making a Graph request, which personally seems like a waste to me, also if you end up making a lot of async calls (i.e await Task.WhenAll(someTasks);) you might end up with a race-like condition where every task wants to call for a token, and you'll get a lot of open sockets as the tasks get scheduled. Here's a snippet of some code I'd use when trying to deal with the token/delegate etc.

```<code>namespace GraphTestConsole
{
    using Microsoft.Graph;
    using Microsoft.IdentityModel.Clients.ActiveDirectory;
    using Nito.AsyncEx;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net.Http.Headers;
    using System.Security;
    using System.Threading.Tasks;

    public class Program
    {
        private const string Resource = "https://graph.microsoft.com";

        private const string AppClientId = "YOUR_CLIENT_ID";

        private static readonly SecureString AppClientSecretSecure = ToSecureString("YOUR_CLIENT_SECRET");

        private const string Tenant = "YOUR_TENANT.onmicrosoft.com";

        private static IGraphServiceClient _graphClient;

        private static string _token;

        private static DateTimeOffset _tokenExpiresOn = DateTime.Now;

        private static readonly AsyncLock _mutex = new AsyncLock();

        public static void Main(string[] args)
        {
            AsyncContext.Run(() => AsyncMain(AppClientId, AppClientSecretSecure, Tenant));
        }

        private static async Task AsyncMain(string appId, SecureString appSecretSecure, string tenant)
        {
            try
            {
                var upn = "YOUR_USER_UPN";
                _graphClient = GetGraphClient(appId, appSecretSecure, tenant);
                var user = await _graphClient.Users[upn].Request().Select("id").GetAsync();
            }
            catch (Exception ex)
            {
                // Handle the exception...
                Console.WriteLine(DateTime.Now.ToString());
                Console.WriteLine(ex);
            }
        }

        private static bool IsTokenInvalid => string.IsNullOrEmpty(_token) || (_tokenExpiresOn - DateTime.Now).TotalSeconds <= 0;

        private static GraphServiceClient GetGraphClient(string appClientId, SecureString appSecretSecure, string tenant)
        {
            var delegateAuthProvider = new DelegateAuthenticationProvider(async (requestMessage) =>
            {
                using (await _mutex.LockAsync())
                {
                    if (IsTokenInvalid)
                    {
                        var authContext = new AuthenticationContext($"https://login.microsoftonline.com/{tenant}/oauth2/token");
                        var result = await authContext.AcquireTokenAsync(Resource, new ClientCredential(appClientId, new SecureClientSecret(appSecretSecure)));

                        _token = result.AccessToken;
                        _tokenExpiresOn = result.ExpiresOn;
                    }

                    requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", _token);
                }
            });

            return new GraphServiceClient(delegateAuthProvider);
        }

        private static SecureString ToSecureString(IEnumerable<char> value)
        {
            if (value == null)
                throw new ArgumentNullException(nameof(value));

            var secured = new SecureString();
            var charArray = value.ToArray();

            for (int i = 0; i < charArray.Length; i++)
            {
                secured.AppendChar(charArray[i]);
            }

            secured.MakeReadOnly();
            return secured;
        }
    }
}
</code>```

P.S. I still think the MS ADAL code is poorly written. :)

Body:
I am hitting this null reference exception using ADAL with version:3.13.1.846, this doesn’t repro every time. Any ideas?

I have made sure that when calling AcquireTokenAsync on the AuthenticationContext as recommended in many MS samples, for example. Here's a link to the docs for that method and the SecureClientSecret which is causing errors.

I am not passing in a null value

System.NullReferenceException: Object reference not set to an instance of an object.
   at Microsoft.IdentityModel.Clients.ActiveDirectory.SecureClientSecret.ApplyTo(IDictionary`2 parameters)
   at Microsoft.IdentityModel.Clients.ActiveDirectory.AcquireTokenHandlerBase.<SendTokenRequestAsync>d__65.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
   at Microsoft.IdentityModel.Clients.ActiveDirectory.AcquireTokenHandlerBase.<RunAsync>d__55.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext.<AcquireTokenForClientCommonAsync>d__49.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext.<AcquireTokenAsync>d__26.MoveNext()

Thanks,
Sara

Body:
I've had a look over the source code for the SecureClientSecret

SecureClientSecret

I'm a bit confused as to what Microsoft are trying to do with their ApplyTo method, it looks a bit like the kind of pattern you see with TryParse and out params, populating a dictionary by reference.

More explicity, populating the dictionary value at OAuthParameter.ClientSecret ('client_secret'as that translates to), with the decrypted value of the SecureString stashed away inside SecureClientSecret.

Microsoft then clear down the private SecureString member, which means any further calls to ApplyTo are going to be met with an unhandled exception when we hit the first line:

var output = new char[secureString.Length];

'secureString.Length' is going to blow, the exception you'd expect, calling null.Length... System.NullReferenceException, something that we see happening in the stack trace.

If MS really need to clear away that member field after a single use for some reason that I don't understand at the moment, maybe they should consider making the class more robust.

Add an IsApplied method/property to the interface:

public interface ISecureClientSecret
{
    /// <summary>
    /// Writes SecureString to the dictionary.
    /// </summary>
    /// <param name="parameters"></param>
    void ApplyTo(IDictionary<string, string> parameters);

    /// <summary>
    /// Indicates whether this <see cref="ISecureClientSecret"/> has already been applied.
    /// </summary>
    /// <returns><c>true</c> if applied, otherwise <c>false</c></returns>
    bool IsApplied { get; };
}

Which could easily be implemented in the concrete class with:

public bool IsApplied => secureString == null;

Also, the ApplyTo method could make use of locking to prevent bad things happening with lots of calls:

public void ApplyTo(IDictionary<string, string> parameters)
{
    secureLock.WaitOne();

    // We don't want to blow up if ApplyTo is called multiple times.
    if (IsApplied)
        return;

    IntPtr ptr = IntPtr.Zero;

    try
    {
        ptr = Marshal.SecureStringToCoTaskMemUnicode(secureString);
        parameters[OAuthParameter.ClientSecret] = Marshal.PtrToStringUni(ptr);
    }
    finally
    {
        if (ptr != IntPtr.Zero)
            Marshal.ZeroFreeCoTaskMemUnicode(ptr);

        if (secureString != null && !secureString.IsReadOnly())
            secureString.Clear();

        secureString = null;

        secureLock.Set();
    }
}

Sticking a AutoResetEvent in as a member for the class.

private AutoResetEvent secureLock = new AutoResetEvent(true);

It would be great if one of the devs on this project could explain what they're trying to do as things seem a little convoluted as a newbie looking in.

UPDATE

As @Nan Yu previously said, I'd like to see the poster's calling code for the delegate that provides the auth. After playing around with my own version I'm wondering if making sure the vars related to the SecureClientSecret are scoped as low down as possible would get around the potential issues I discussed above.

I.e. Don't have any member/field references to the SecureClientSecret. Don't have any vars scoped outside the delegate itself either, as I think the underlying SecureString inside the SecureClientSecret object gets nulled and things don't work out well when you try to get another token passing in the original SecureString.

I believe this is essentially what @'Kevin ssssssss' was suggesting in their answer!

var delegateAuthProvider = new DelegateAuthenticationProvider(async (requestMessage) =>
{
    var authContext = new AuthenticationContext($"https://login.microsoftonline.com/{tenant}/oauth2/token");
    var result = await authContext.AcquireTokenAsync(Resource, new ClientCredential(appClientId, new SecureClientSecret(appSecretSecure)));

    requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", result.AccessToken);
});

MS samples seem to recommend calling for a new token every time before making a Graph request, which personally seems like a waste to me, also if you end up making a lot of async calls (i.e await Task.WhenAll(someTasks);) you might end up with a race-like condition where every task wants to call for a token, and you'll get a lot of open sockets as the tasks get scheduled. Here's a snippet of some code I'd use when trying to deal with the token/delegate etc.

namespace GraphTestConsole
{
    using Microsoft.Graph;
    using Microsoft.IdentityModel.Clients.ActiveDirectory;
    using Nito.AsyncEx;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net.Http.Headers;
    using System.Security;
    using System.Threading.Tasks;

    public class Program
    {
        private const string Resource = "https://graph.microsoft.com";

        private const string AppClientId = "YOUR_CLIENT_ID";

        private static readonly SecureString AppClientSecretSecure = ToSecureString("YOUR_CLIENT_SECRET");

        private const string Tenant = "YOUR_TENANT.onmicrosoft.com";

        private static IGraphServiceClient _graphClient;

        private static string _token;

        private static DateTimeOffset _tokenExpiresOn = DateTime.Now;

        private static readonly AsyncLock _mutex = new AsyncLock();

        public static void Main(string[] args)
        {
            AsyncContext.Run(() => AsyncMain(AppClientId, AppClientSecretSecure, Tenant));
        }

        private static async Task AsyncMain(string appId, SecureString appSecretSecure, string tenant)
        {
            try
            {
                var upn = "YOUR_USER_UPN";
                _graphClient = GetGraphClient(appId, appSecretSecure, tenant);
                var user = await _graphClient.Users[upn].Request().Select("id").GetAsync();
            }
            catch (Exception ex)
            {
                // Handle the exception...
                Console.WriteLine(DateTime.Now.ToString());
                Console.WriteLine(ex);
            }
        }

        private static bool IsTokenInvalid => string.IsNullOrEmpty(_token) || (_tokenExpiresOn - DateTime.Now).TotalSeconds <= 0;

        private static GraphServiceClient GetGraphClient(string appClientId, SecureString appSecretSecure, string tenant)
        {
            var delegateAuthProvider = new DelegateAuthenticationProvider(async (requestMessage) =>
            {
                using (await _mutex.LockAsync())
                {
                    if (IsTokenInvalid)
                    {
                        var authContext = new AuthenticationContext($"https://login.microsoftonline.com/{tenant}/oauth2/token");
                        var result = await authContext.AcquireTokenAsync(Resource, new ClientCredential(appClientId, new SecureClientSecret(appSecretSecure)));

                        _token = result.AccessToken;
                        _tokenExpiresOn = result.ExpiresOn;
                    }

                    requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", _token);
                }
            });

            return new GraphServiceClient(delegateAuthProvider);
        }

        private static SecureString ToSecureString(IEnumerable<char> value)
        {
            if (value == null)
                throw new ArgumentNullException(nameof(value));

            var secured = new SecureString();
            var charArray = value.ToArray();

            for (int i = 0; i < charArray.Length; i++)
            {
                secured.AppendChar(charArray[i]);
            }

            secured.MakeReadOnly();
            return secured;
        }
    }
}

P.S. I still think the MS ADAL code is poorly written. :)


问:
Ansible sx su - impersonation
Does anybody have an idea how to execute a playbook on a RHEL machine with sx su - impersonation?

Ansible only provides sudo out of the box but we cannot use sudo as we are using Boks ssh.
Does anybody have an idea how to tackle this?

答:
Actually you can!
Ansible.cfg has a flax where you can use sx su as a become method</p>

ContentLicense: CC BY-SA 4.0

Title: Ansible sx su - impersonation


问:
Trigger GitLab Build with Python Requests
I'm trying to trigger a GitLab build using Python Requests.  Normally one can kick off a build with a curl command.

Example curl command:

```<code>curl -X POST \
  -F token=TOKEN \
  -F ref=master \
  -F "variables[UPLOAD_TO_S3]=true" \
  https://gitlab.example.com/api/v4/projects/9/trigger/pipeline
</code>```

I can get this working using the sh module but I'd prefer using requests.  I've tried variations with the following:

```<code>data = {
    'token': token,
    'ref': master,
    'variables[UPLOAD_TO_S3]': str(uploadS3),
}

headers = {'Content-Type': 'application/json'}
result = requests.post(_trigger_url, headers=headers, json=data)
</code>```

I tried with and without the headers param.  I've also tried passing the data dict using params, json, files, and data. All keep coming back with 400 or 404 errors.  Any suggestions?

答:
You shouldn't send the Content-Type: "application/json" header as part of your request, and you should only need form encoding, so just pass your data dict as the data argument.

Here's a request to my Gitlab instance that succeeds and triggers a build of my project's master branch.

```<code>rsp = requests.post('https://gitlab.instance/api/v4/projects/PROJECT_ID/trigger/pipeline',
          data={'token': '125fdsfdf1ab3631d2423434347643', 'ref': 'master'})
</code>```

Here's the output if I inspect my rsp object in `ipython:

```<code>In [3]: rsp
Out[3]: <Response [201]>
</code>```

You should also be able to trigger the pipeline by sending a POST and including the token and ref in the URL itself.

```<code>rsp = requests.post('https://gitlab.instance/api/v4/projects/PROJECT_ID/trigger/pipeline?token=TOKEN&ref=master')
</code>```

If I pass the Content-Type: "application/json" header, Gitlab responds with an HTTP/400 error.

Body:
I'm trying to trigger a GitLab build using Python Requests.  Normally one can kick off a build with a curl command.

Example curl command:

curl -X POST \
  -F token=TOKEN \
  -F ref=master \
  -F "variables[UPLOAD_TO_S3]=true" \
  https://gitlab.example.com/api/v4/projects/9/trigger/pipeline

I can get this working using the sh module but I'd prefer using requests.  I've tried variations with the following:

data = {
    'token': token,
    'ref': master,
    'variables[UPLOAD_TO_S3]': str(uploadS3),
}

headers = {'Content-Type': 'application/json'}
result = requests.post(_trigger_url, headers=headers, json=data)

I tried with and without the headers param.  I've also tried passing the data dict using params, json, files, and data. All keep coming back with 400 or 404 errors.  Any suggestions?

Body:
You shouldn't send the Content-Type: "application/json" header as part of your request, and you should only need form encoding, so just pass your data dict as the data argument.

Here's a request to my Gitlab instance that succeeds and triggers a build of my project's master branch.

rsp = requests.post('https://gitlab.instance/api/v4/projects/PROJECT_ID/trigger/pipeline',
          data={'token': '125fdsfdf1ab3631d2423434347643', 'ref': 'master'})

Here's the output if I inspect my rsp object in `ipython:

In [3]: rsp
Out[3]: <Response [201]>

You should also be able to trigger the pipeline by sending a POST and including the token and ref in the URL itself.

rsp = requests.post('https://gitlab.instance/api/v4/projects/PROJECT_ID/trigger/pipeline?token=TOKEN&ref=master')

If I pass the Content-Type: "application/json" header, Gitlab responds with an HTTP/400 error.


问:
R Functions: how to pass a response variable as a parameter?
When I use functions such as glm I need to specify the explicit formula, for example:

```<code>glm(sales ~ ., data = database)
</code>```

However, when I use this inside of a function, the response variable isn't always "sales". Is there any way I can make the formula parameter of the glm function "dynamic" in order to address this issue?

答:
Something like the following?

```<code>dynamic <- function(database, response){
    fmla <- as.formula(paste(response, ".", sep = "~"))
    glm(fmla, data = database)
}
</code>```

Then call with the data.frame and response variable of your choice.

Body:
When I use functions such as glm I need to specify the explicit formula, for example:

glm(sales ~ ., data = database)

However, when I use this inside of a function, the response variable isn't always "sales". Is there any way I can make the formula parameter of the glm function "dynamic" in order to address this issue?

Body:
Something like the following?

dynamic <- function(database, response){
    fmla <- as.formula(paste(response, ".", sep = "~"))
    glm(fmla, data = database)
}

Then call with the data.frame and response variable of your choice.


问:
error: anachronistic old-style base class initializer [-fpermissive]
I have this constructor which give an error on compilation :-

```<code>Time::Time(short y,short m,short d,short h,short mi,short s):
        (*this).y(y);
        (*this).m(m);
        (*this).d(d);
        (*this).h(h);
        (*this).mi(mi);
        (*this).s(s);   {};
</code>```

here is full error:-

```<code>Time.cpp: In constructor ‘Time::Time(short int, short int, short int, short int, short int, short int)’:
Time.cpp:22:2: error: anachronistic old-style base class initializer [-fpermissive]
  (*this).y(y);
  ^
Time.cpp:21:61: error: unnamed initializer for ‘Time’, which has no base classes
 Time::Time(short y,short m,short d,short h,short mi,short s):
                                                             ^
Time.cpp:22:9: error: expected ‘{’ before ‘.’ token
  (*this).y(y);
         ^
Time.cpp: At global scope:
Time.cpp:22:9: error: expected unqualified-id before ‘.’ token
Time.cpp:23:4: error: expected unqualified-id before ‘this’
  (*this).m(m);
    ^~~~
Time.cpp:23:4: error: expected ‘)’ before ‘this’
Time.cpp:24:4: error: expected unqualified-id before ‘this’
  (*this).d(d);
    ^~~~
Time.cpp:24:4: error: expected ‘)’ before ‘this’
Time.cpp:25:4: error: expected unqualified-id before ‘this’
  (*this).h(h);
    ^~~~
Time.cpp:25:4: error: expected ‘)’ before ‘this’
Time.cpp:26:4: error: expected unqualified-id before ‘this’
  (*this).mi(mi);
    ^~~~
Time.cpp:26:4: error: expected ‘)’ before ‘this’
Time.cpp:27:4: error: expected unqualified-id before ‘this’
  (*this).s(s);  {};
    ^~~~
Time.cpp:27:4: error: expected ‘)’ before ‘this’
Time.cpp:27:17: error: expected unqualified-id before ‘{’ token
  (*this).s(s);  {};
                 ^
</code>```

As a noob I have no idea what is going on. On googling ,I only find one stackoverflow link which also doesn't help.

答:
You are not allowed to use this to specify the class member you want to initialize in the constructor initializer list. Get rid of this entirely. It is not a matter of preference or style, it is just an error.

The error message about "old-style base class" is just a syntactic confusion: seeing nonsensical syntax in member initializer list the compiler gets confused.

Body:
I have this constructor which give an error on compilation :-

Time::Time(short y,short m,short d,short h,short mi,short s):
        (*this).y(y);
        (*this).m(m);
        (*this).d(d);
        (*this).h(h);
        (*this).mi(mi);
        (*this).s(s);   {};

here is full error:-

Time.cpp: In constructor ‘Time::Time(short int, short int, short int, short int, short int, short int)’:
Time.cpp:22:2: error: anachronistic old-style base class initializer [-fpermissive]
  (*this).y(y);
  ^
Time.cpp:21:61: error: unnamed initializer for ‘Time’, which has no base classes
 Time::Time(short y,short m,short d,short h,short mi,short s):
                                                             ^
Time.cpp:22:9: error: expected ‘{’ before ‘.’ token
  (*this).y(y);
         ^
Time.cpp: At global scope:
Time.cpp:22:9: error: expected unqualified-id before ‘.’ token
Time.cpp:23:4: error: expected unqualified-id before ‘this’
  (*this).m(m);
    ^~~~
Time.cpp:23:4: error: expected ‘)’ before ‘this’
Time.cpp:24:4: error: expected unqualified-id before ‘this’
  (*this).d(d);
    ^~~~
Time.cpp:24:4: error: expected ‘)’ before ‘this’
Time.cpp:25:4: error: expected unqualified-id before ‘this’
  (*this).h(h);
    ^~~~
Time.cpp:25:4: error: expected ‘)’ before ‘this’
Time.cpp:26:4: error: expected unqualified-id before ‘this’
  (*this).mi(mi);
    ^~~~
Time.cpp:26:4: error: expected ‘)’ before ‘this’
Time.cpp:27:4: error: expected unqualified-id before ‘this’
  (*this).s(s);  {};
    ^~~~
Time.cpp:27:4: error: expected ‘)’ before ‘this’
Time.cpp:27:17: error: expected unqualified-id before ‘{’ token
  (*this).s(s);  {};
                 ^

As a noob I have no idea what is going on. On googling ,I only find one stackoverflow link which also doesn't help.


问:
How to use jQuery Plugin with Angular 4?
I want to use a range slider in an angular project and I tried using one available module for angular 4.

It works fine during compilation but when I try to build it for deployment, it throws the below error.

I checked for the option of using jQuery plugin directly in the angular project and I'm only getting options for doing it in Angular 2.

Is there any way we can use jQuery plugins in Angular 4?

Please let me know.

答:
Try this:

```<code>import * as $ from 'jquery/dist/jquery.min.js';
</code>```

Or add scripts to angular-cli.json:

```<code>"scripts": [
    "../node_modules/jquery/dist/jquery.min.js",
  ]
</code>```

and in your .ts file:

```<code>declare var $: any;
</code>```

Body:
Try this:

import * as $ from 'jquery/dist/jquery.min.js';

Or add scripts to angular-cli.json:

"scripts": [
    "../node_modules/jquery/dist/jquery.min.js",
  ]

and in your .ts file:

declare var $: any;


问:
Python put a triangle inside another one
I’m trying to print a triangle inside of another one so I have the code

```<code>w = int(input(“Input width of first triangle: “)
c1 = input(“Pick a character: “)
c2 = input(“Pick another character: “)

print(“One: “)
for i in range(“width, 0, -2):
    print(‘{:^{str_len}}’.format(c1 * i, str_len = w * 2))
</code>```

If c1 was * and w was 5 it would print:

```<code>*****
 ***
  *
</code>```

And now I want it to be like so if c2 was + it would also print:

```<code>     +
    +++
   +++++
  +*****+
 +++***+++
+++++*+++++
</code>```

Like a triangle with the first one inside it but I don’t know how that would work

Body:
I’m trying to print a triangle inside of another one so I have the code

w = int(input(“Input width of first triangle: “)
c1 = input(“Pick a character: “)
c2 = input(“Pick another character: “)

print(“One: “)
for i in range(“width, 0, -2):
    print(‘{:^{str_len}}’.format(c1 * i, str_len = w * 2))

If c1 was * and w was 5 it would print:

*****
 ***
  *

And now I want it to be like so if c2 was + it would also print:

     +
    +++
   +++++
  +*****+
 +++***+++
+++++*+++++

Like a triangle with the first one inside it but I don’t know how that would work

Body:
h = 10
h2 = 5
assert(2*h >= h2)

for i in range(h):
    if i >= h2 and i <= 2*h2: #start printing second triangle as well
        s ='%s%s%s' % ('+'*(i-h2),  '*'*(2*h2 - i ), '+'*(i-h2))
        s = " ".join(s)
        print('%s%s' % (' ' * (h - i), s))
    else:
        s = " ".join('+'*i)
        print('%s%s' % (' '*(h-i),s))

yields:

         +
        + +
       + + +
      + + + +
     * * * * *
    + * * * * +
   + + * * * + +
  + + + * * + + +
 + + + + * + + + +


问:
Invalid floating point operation Delphi
I have a problem in a Delphi program that i'm writing. The problem is this piece of code:

```<code>type
  TRobot = class(TObject)
  private
  public
    fAcceso: Boolean;
    fOra: TTime;
    fCode: Integer;
    mex: string;
    constructor Create;
  end;

// ...

myrobot.mex:= ('Acceso: '+  BoolToStr(myrobot.fAcceso) +
               ',Tempo:' +  TimeToStr(myrobot.fOra) +
               ',Codice:' + IntToStr(myrobot.fCode));
memo.Lines.add(myrobot.mex);
</code>```

precisely with TimeToStr(myrobot.fOra).

The problem occurs is

"Invalid floating point operation".

Can someone help me??

答:
This error message means division by zero, square root of negative value and similar issues. It looks like something wrong either with myrobot.fOra or with format settings.

Set breakpoint at this line and check fOra value. If it looks good, use F7 to step into TimeToStr (yes, you can debug system library routines... maybe you'll need to install VCL sources and/or set up 'use debug dcu(s)' option of your project). Using it you'll be able to reach exact place of error and check what's wrong.

Title: Invalid floating point operation Delphi

Body:
I have a problem in a Delphi program that i'm writing. The problem is this piece of code:

type
  TRobot = class(TObject)
  private
  public
    fAcceso: Boolean;
    fOra: TTime;
    fCode: Integer;
    mex: string;
    constructor Create;
  end;

// ...

myrobot.mex:= ('Acceso: '+  BoolToStr(myrobot.fAcceso) +
               ',Tempo:' +  TimeToStr(myrobot.fOra) +
               ',Codice:' + IntToStr(myrobot.fCode));
memo.Lines.add(myrobot.mex);

precisely with TimeToStr(myrobot.fOra).

The problem occurs is

"Invalid floating point operation".

Can someone help me??


答:
You need to use setState to re-render the component. Try changing the startTimer() method as follows. If all you are trying is to show the current time each time you click on the button.

```<code>startTimer() {
    this.setState({timer: new Date()})
}
</code>```

Title: Updating variable in react

Body:
I have what seems to be a very simple question. In the following code I can not update a variable reference but I can set it directly, can you tell me why?

This updates the HTML element correctly:

startTimer() {
    let timerOutput = this.timerOutput.innerHTML = this.state.timer.toLocaleTimeString();
}

Using this code however nothing happens in the DOM:

startTimer() {
        let timerOutput = this.timerOutput.innerHTML;
        timerOutput = this.state.timer.toLocaleTimeString();
    }

Printout of the entire Timer container component:

export class Timer extends React.PureComponent {
    constructor(props) {
        super(props);
        this.state = {timer: new Date()};
      }

    startTimer() {
        let timerOutput = this.timerOutput.innerHTML;
        timerOutput = this.state.timer.toLocaleTimeString();
        // timerOutput = this.state.timer.toLocaleTimeString();
        console.log(this.state.timer);
    }

    handleClick(e) {
        this.startTimer(e);
    }

  componentDidMount() {

  }

  render() {

    return (

 {this.timerOutput = output }}
        >

        <button onClick={this.handleClick.bind(this)} value="Click me" />;

It is {this.state.timer.toLocaleTimeString()}.

    );
  }
}

export default Timer;

Body:
You need to use setState to re-render the component. Try changing the startTimer() method as follows. If all you are trying is to show the current time each time you click on the button.

startTimer() {
    this.setState({timer: new Date()})
}


问:
Can I set a variable in the build time before the installation process in Install4j?
For each installation I would like to introduce the current version on the welcome screen. For that, I create a "Read a properties file" action which reads my application manifest.properties which exists under the distribution tree. A step later I have a "Run script" action which extracts the properties I need for the version and set it into installer variables.

My problem is that when trying to install the installer on a clean computer it throws an error since it has no distribution tree nor the manifest.properties.

Is there any elegant way to set the variables before the installation process begins, like in the build time for example?

答:
The version of your application is configured on the "General Settings->Application Info" step. You can use it in all text properties with this syntax:</p>

```<code>${compiler:sys.version}
</code>```

Body:
The version of your application is configured on the "General Settings->Application Info" step. You can use it in all text properties with this syntax:

${compiler:sys.version}


问:
How to "clear" an object?
What's the better way to clear an object:

Write a method inside the class that clears all the members of the class: MyObject.Clear();

Inside my code, in the business logic, null the object: MyObject = null;

答:
The answer to your question is, "it depends."  It depends on what you're trying to do with it.  If you want to keep a reference to that particular instance (i.e. others have a reference to it, or constructing it is expensive), then you're probably best off with a Clear method.  But only if you're going to continue to use that particular object instance.

If you don't care about an object anymore, then just stop referring to it.  In general, you don't have to set it to null, since the code generator can determine the object lifetime and make the object available for garbage collection.  But if you want to make sure that the object is collected as soon as possible (i.e. during the next garbage collection cycle), then setting MyObject = null is the way to go.  Again, that's not normally necessary, but it won't hurt anything.

Title: How to "clear" an object?


问:
Differences between ConstraintLayout and RelativeLayout
What is the difference between ConstraintLayout and RelativeLayout?

答:
Officially, ConstraintLayout is much faster

In the N release of Android, the ConstraintLayout class provides similar functionality to RelativeLayout, but at a significantly lower cost.


问:
Bash - Running multiple commands using string evaluation
I'm trying to create a shell script that concatenates multiple commands to a string and then execute the commands.

The following succeeds (Creates the 'y' and 'z' files and prints ls output):

```<code>$ /bin/touch /z && ls && /bin/touch /y
</code>```

But the following fails (Creates the 'y' and 'z' files, but also a '&&' and 'ls' files)

```<code>$ A="/bin/touch /z && ls && /bin/touch /y"
$ $A
</code>```

It seems that by executing the line using $A the binary touch gets the rest of the string as parameters and the && operator does not execute as intended.
(I also tried switching && with ;, || and such but got the same result)

I found out the eval $A does the trick, but I'm still curious as to why this happens. (And possibly want to skip the need to eval)

Thanks!

答:
Broadly speaking, there are two stages to evaluating a command line: parsing and expansion.

When you enter

```<code>/bin/touch /z && ls && /bin/touch /y
</code>```

the string is first parsed into a preliminary series of words separated by whitespace:

/bin/touch

/z

&&

ls

&&

/bin/touch

/y

At this points, it recognizes the &&s as separating a list of simple commands consisting of the following words:

/bin/touch, /z

ls

/bin/touch, /y

Now, it applies a set of expansions to each word in an attempt to produce more words. In this case, there is nothing to expand, and each simple command is examined again to identify the command itself and its arguments:

Command /bin/touch, argument /z

Command ls, no arguments

Command /bin/touch, argument /y

In the case of $A, parsing is simple: there is a single word $A in the preliminary series. That word next undergoes expansion; the only relevant one is parameter expansion, which produces the same list of words as identified in the parsing step of the first example. The difference here is that list does not undergo further expansion; it's not time to identify the command name and its arguments.

Command /bin/touch, with arguments...

/z

&&

ls

&&

/bin/touch

/y

A string is practically never the correct way to bundle up a set of commands. What you want to do is define a function

```<code>a () {
  /bin/touch /z && ls && /bin/touch /y
}
</code>```

which you then use as an ordinary command:

```<code>$ a
/z
$ ls
/z
/y
</code>```

Body:
I'm trying to create a shell script that concatenates multiple commands to a string and then execute the commands.

The following succeeds (Creates the 'y' and 'z' files and prints ls output):

$ /bin/touch /z && ls && /bin/touch /y

But the following fails (Creates the 'y' and 'z' files, but also a '&&' and 'ls' files)

$ A="/bin/touch /z && ls && /bin/touch /y"
$ $A

It seems that by executing the line using $A the binary touch gets the rest of the string as parameters and the && operator does not execute as intended.
(I also tried switching && with ;, || and such but got the same result)

I found out the eval $A does the trick, but I'm still curious as to why this happens. (And possibly want to skip the need to eval)

Thanks!

Body:
Broadly speaking, there are two stages to evaluating a command line: parsing and expansion.

When you enter

/bin/touch /z && ls && /bin/touch /y

the string is first parsed into a preliminary series of words separated by whitespace:

/bin/touch

/z

&&

ls

&&

/bin/touch

/y

At this points, it recognizes the &&s as separating a list of simple commands consisting of the following words:

/bin/touch, /z

ls

/bin/touch, /y

Now, it applies a set of expansions to each word in an attempt to produce more words. In this case, there is nothing to expand, and each simple command is examined again to identify the command itself and its arguments:

Command /bin/touch, argument /z

Command ls, no arguments

Command /bin/touch, argument /y

In the case of $A, parsing is simple: there is a single word $A in the preliminary series. That word next undergoes expansion; the only relevant one is parameter expansion, which produces the same list of words as identified in the parsing step of the first example. The difference here is that list does not undergo further expansion; it's not time to identify the command name and its arguments.

Command /bin/touch, with arguments...

/z

&&

ls

&&

/bin/touch

/y

A string is practically never the correct way to bundle up a set of commands. What you want to do is define a function

a () {
  /bin/touch /z && ls && /bin/touch /y
}

which you then use as an ordinary command:

$ a
/z
$ ls
/z
/y


问:
Look for specific special characters SQL Server 2008 R2
I need to look for mention of below special characters in a description field string/rows.  Some of these are straightforward, but there are some I can't figure out how to look for:

```<code>Special characters:  < > { } [ ] " ' * = @ ~ | <Tab> (tab key) <Enter> (extra line (carriage return))
</code>```

what I have so far:

```<code>select * from
table
where [Account description] like '[<>{}[]*=@~|]'
</code>```

Not sure how to identify following special characters:

```<code>" (double quote)
' (single quote)
<Tab> (tab key)
<Enter> (extra line (carriage return))
</code>```

答:
May be you could try something like this:

```<code>select * from table
where [Account description] like '[<>{}[]*=@~|]'
and [Account description] like '%''%'
and [Account description] like '%'+CAST(X'09' AS TEXT)+'%'
and ([Account description] like '%'+char(13)+'%'
or [Account description] like '%'+char(10)+'%)
</code>```

but I think is gonna be slow.

Body:
I need to look for mention of below special characters in a description field string/rows.  Some of these are straightforward, but there are some I can't figure out how to look for:

Special characters:  < > { } [ ] " ' * = @ ~ | <Tab> (tab key) <Enter> (extra line (carriage return))

what I have so far:

select * from
table
where [Account description] like '[<>{}[]*=@~|]'

Not sure how to identify following special characters:

" (double quote)
' (single quote)
<Tab> (tab key)
<Enter> (extra line (carriage return))

Body:
May be you could try something like this:

select * from table
where [Account description] like '[<>{}[]*=@~|]'
and [Account description] like '%''%'
and [Account description] like '%'+CAST(X'09' AS TEXT)+'%'
and ([Account description] like '%'+char(13)+'%'
or [Account description] like '%'+char(10)+'%)

but I think is gonna be slow.


问:
How to check which relative layout is selected?
I am developing a reminder app. Here user click on a Relative layout which has a TextView and a button. After clicking layout user can set the time. I have set same Relative layout thrice in an activity. Now I want to set the user's selected time on the TextView with different layout clicking.

SetReminder.java

```<code>public void setTime(View v){

    switch (v.getId()) {
        case R.id.time:
            //mTimeTextHour.setText(mTime);
           setTimePicker();

            break;
        case R.id.time2:
            //mTimeTextHour.setText(mTime);
            setTimePicker();

            break;
        case R.id.time3:
            setTimePicker();
            break;

        case R.id.time4:
            setTimePicker();
            break;

    }

}

public void setTimePicker()
{
    Calendar now = Calendar.getInstance();
    TimePickerDialog tpd = TimePickerDialog.newInstance(
            this,
            now.get(Calendar.HOUR_OF_DAY),
            now.get(Calendar.MINUTE),
            false
    );
    tpd.setThemeDark(false);
    tpd.show(getFragmentManager(), "Timepickerdialog");
}
@Override
    public void onTimeSet(RadialPickerLayout view, int hourOfDay, int minute) {
        mHour = hourOfDay;
        mMinute = minute;
        if (minute < 10) {
            mTime = hourOfDay + ":" + "0" + minute;
        } else {
            mTime = hourOfDay + ":" + minute;
        }

}
</code>```

Three TextViews are TextView1 is in Relative_layout time ,TextView2 is in time2,TextView3 is in time3,TextView4 is in time4.

I want to set user's selected time for different layouts.

答: Simplest you can do is to create variable for example int selectedLayout, and on click on TextView set this variable, for example if first TextView selected set selectedLayout = 0. Then in onTimeSet check if (selectedLayout == 0) then you know that first layout is selected.

Body:
I am developing a reminder app. Here user click on a Relative layout which has a TextView and a button. After clicking layout user can set the time. I have set same Relative layout thrice in an activity. Now I want to set the user's selected time on the TextView with different layout clicking.

SetReminder.java

public void setTime(View v){

    switch (v.getId()) {
        case R.id.time:
            //mTimeTextHour.setText(mTime);
           setTimePicker();

            break;
        case R.id.time2:
            //mTimeTextHour.setText(mTime);
            setTimePicker();

            break;
        case R.id.time3:
            setTimePicker();
            break;

        case R.id.time4:
            setTimePicker();
            break;

    }

}

public void setTimePicker()
{
    Calendar now = Calendar.getInstance();
    TimePickerDialog tpd = TimePickerDialog.newInstance(
            this,
            now.get(Calendar.HOUR_OF_DAY),
            now.get(Calendar.MINUTE),
            false
    );
    tpd.setThemeDark(false);
    tpd.show(getFragmentManager(), "Timepickerdialog");
}
@Override
    public void onTimeSet(RadialPickerLayout view, int hourOfDay, int minute) {
        mHour = hourOfDay;
        mMinute = minute;
        if (minute < 10) {
            mTime = hourOfDay + ":" + "0" + minute;
        } else {
            mTime = hourOfDay + ":" + minute;
        }

}

Three TextViews are TextView1 is in Relative_layout time ,TextView2 is in time2,TextView3 is in time3,TextView4 is in time4.

I want to set user's selected time for different layouts.


答:
Sounds like you want all non-alphanumeric characters? if so, you can use

```<code>declare @table table (id int identity (1,1), column1 nvarchar(64))
insert into @table
values
('<'),
('>'),
('{'),
('}'),
('['),
(']'),
('"'),
(''''),
('*'),
('='),
('@'),
('~'),
('|'),
('a' + char(10)),
('b' + char(13)),
('c' + char(9)),
('a'),
('A'),
('1')

select *
from @table
where [Account description] like '%[^0-9a-zA-Z]%'
</code>```

Otherwise, you'll need to list them explicit and use an escape value for the special cases...

```<code>select *
from @table
where column1 like '%[<>{}![!]"''''*=@~|]%' ESCAPE '!'
or column1 like '%' + char(10) + '%'
or column1 like '%' + char(9) + '%'
or column1 like '%' + char(13) + '%'
</code>```

Title: Look for specific special characters SQL Server 2008 R2

Body:
Sounds like you want all non-alphanumeric characters? if so, you can use

declare @table table (id int identity (1,1), column1 nvarchar(64))
insert into @table
values
('<'),
('>'),
('{'),
('}'),
('['),
(']'),
('"'),
(''''),
('*'),
('='),
('@'),
('~'),
('|'),
('a' + char(10)),
('b' + char(13)),
('c' + char(9)),
('a'),
('A'),
('1')

select *
from @table
where [Account description] like '%[^0-9a-zA-Z]%'

Otherwise, you'll need to list them explicit and use an escape value for the special cases...

select *
from @table
where column1 like '%[<>{}![!]"''''*=@~|]%' ESCAPE '!'
or column1 like '%' + char(10) + '%'
or column1 like '%' + char(9) + '%'
or column1 like '%' + char(13) + '%'


问:
Dynamic Slicer Selection
I have this table that is feeding into a PowerBI report

```<code>select *
from
    (
        values
            (1,0),
            (2,0),
            (3,1),
            (4,0),
            (5,0),
            (6,0),
            (7,0),
            (8,0)
    ) as x(num, active)
</code>```

Then in the report I have a slicer for num:

So - what I am trying to do is have 3 selected in the slicer - because it is marked 1 in the active column of the data BUT all other options in the num slicer should still be visible.

Then tomorrow if the data changes and 4 is marked 1 in the active column then it should be selected rather than 3

.... is this possible?

答:
I don't believe that this is currently possible, but you can vote for a similar idea here:

https://ideas.powerbi.com/forums/265200-power-bi-ideas/suggestions/7162004-default-selected-slicer-or-tile-by-value-configura

Title: Dynamic Slicer Selection

Body:
I have this table that is feeding into a PowerBI report

select *
from
    (
        values
            (1,0),
            (2,0),
            (3,1),
            (4,0),
            (5,0),
            (6,0),
            (7,0),
            (8,0)
    ) as x(num, active)

Then in the report I have a slicer for num:

So - what I am trying to do is have 3 selected in the slicer - because it is marked 1 in the active column of the data BUT all other options in the num slicer should still be visible.

Then tomorrow if the data changes and 4 is marked 1 in the active column then it should be selected rather than 3

.... is this possible?


问:
How to remove duplicated scrollbar in Angular Covalent templates?
I am super new to Angular 4. I've onlçy created few projects with AngularJS.

I started using Teradata Covalent Framework to build front-end structure and focus on building the menu content and card lists for a Catalog Web App.

I downloaded this full template in https://stackblitz.com/edit/covalent-dashboard-ynyp1w?file=main.ts which you can see in the image below:

As you can see, the problem is those two scrollbars in the right side of the page. I think that only the inner scroll should exist there because it is not interfering with the gray toolbar.

```<code><td-layout>
  <td-navigation-drawer flex [sidenavTitle]="name" logo="assets:covalent">
    Top level navigation drawer
  </td-navigation-drawer>
  <td-layout-nav [toolbarTitle]="(media.registerQuery('gt-xs') | async) ? 'Dashboard' : ''" logo="assets:covalent" navigationRoute="/">
    <button mat-icon-button td-menu-button tdLayoutToggle>
      <mat-icon>menu</mat-icon>
    </button>
    <div td-toolbar-content>
      Top toolbar
    </div>
    <td-layout-manage-list #manageList>
      <div td-sidenav-content layout="column" layout-fill>
        Inner sidenav listing dashboards
      </div>

      <mat-sidenav-container flex>
        <mat-sidenav #sidenav align="end">
          Right Sidenav
        </mat-sidenav>
        <td-layout-nav>
          <div td-toolbar-content>
            Second toolbar
          </div>

          <div flex layout-gt-sm="row">
            <div flex-gt-sm="50">
              <mat-card>
                ...
              </mat-card>
            </div>
          </div>

        </td-layout-nav>
      </mat-sidenav-container>
    </td-layout-manage-list>
    <td-layout-footer>Footer content</td-layout-footer>
  </td-layout-nav>
</td-layout>
</code>```

Anyone who already worked with this template or is very good at CSS could tell me how to remove this creep extra scrollbar from the site? And (Bonus) How could I replace those old scrollbar style for those new skinny scrollbars from Facebook?

答: Just add overflow:hidden; to the css class of the inner content

Body:
I am super new to Angular 4. I've onlçy created few projects with AngularJS.

I started using Teradata Covalent Framework to build front-end structure and focus on building the menu content and card lists for a Catalog Web App.

I downloaded this full template in https://stackblitz.com/edit/covalent-dashboard-ynyp1w?file=main.ts which you can see in the image below:

As you can see, the problem is those two scrollbars in the right side of the page. I think that only the inner scroll should exist there because it is not interfering with the gray toolbar.

    Top level navigation drawer

    <button mat-icon-button td-menu-button tdLayoutToggle>
      <mat-icon>menu</mat-icon>
    </button>

      Top toolbar

        Inner sidenav listing dashboards

      <mat-sidenav-container flex>
        <mat-sidenav #sidenav align="end">
          Right Sidenav
        </mat-sidenav>

            Second toolbar

              <mat-card>
                ...
              </mat-card>

      </mat-sidenav-container>

    Footer content

Anyone who already worked with this template or is very good at CSS could tell me how to remove this creep extra scrollbar from the site? And (Bonus) How could I replace those old scrollbar style for those new skinny scrollbars from Facebook?


问:
Vue Object is Empty
I'm using Vuejs to display data from an API to a template. I'm trying to figure out why I am not returning data for the team so I can display in for the template. Right now when I use the VueJS Chrome Extention it shows that the team is an empty object.</p>

```<code><div v-if="team">
    <div class="row">
       <div class="col-12 col-sm-12">
          <div class="fw-700 pb3 mb5" style="border-bottom: 1px solid #333;">Name:</div>
       <div class="mb10" style="font-size: 20px;">{{ team.name }}</div>
   </div>
</div>

<script>

    module.exports = {
        http: {
            headers: {
               'X-CSRF-TOKEN': window.Laravel.csrfToken
            }
        },
        props: [ 'id', 'editable' ],
        data: function(){
            return {
                modalName: 'additionalInfo',
                team:{

                }
            }
        };
     },
     methods: {
         fetchInfo: function(){
             this.$http.get('/api/teams/info', { params: { id: this.id } }).then((response) => {
             this.team = response.data;
         });
      },
    },
  }
}
</script>
</code>```

答:
It is empty because your method fetchInfo isn't being called, so you need to do something like this:

```<code>created () {
 this.fetchInfo()
}
</code>```

This will call the function fetchInfo which in turn will fetch and fill this.team

Title: Vue Object is Empty

Body:
I'm using Vuejs to display data from an API to a template. I'm trying to figure out why I am not returning data for the team so I can display in for the template. Right now when I use the VueJS Chrome Extention it shows that the team is an empty object.

Name:

{{ team.name }}

Body:
It is empty because your method fetchInfo isn't being called, so you need to do something like this:

created () {
 this.fetchInfo()
}

This will call the function fetchInfo which in turn will fetch and fill this.team