问:
How is InitialTargets chained when doing Import on an msbuild file?
When I have an msbuild file foo.csproj and I want to Import a shared proj/targets file, how is the Project.InitialTargets attribute supposed (i.e. officially) to behave?

What I see with testing MSBUILD 2.0 and 4.x is that, given the following:

```<code><Project InitialTargets="TestMain" ...>
  ...
  <Import Project="Sub.targets"/>
  ...
  <Target Name="TestMain">
    <Message Text="Hello from Main" />
  </Target>
</code>```

and

```<code><Project InitialTargets="TestSubInit" ...>
  ...
  <Target Name="TestSubInit">
    <Message Text="Hello from sub.targets" />
  </Target>
</code>```

then the InitalTargets are chained in order of inclusion, i.e. first the output is:

```<code>TestMain-Target:
    Hello from Main
TestSubInit-Target:
    Hello from sub.targets
</code>```

I want to rely on this chaining behavior - is this documented somehow?

答:
The chaining behaviour for the InitialTargets attribute is documented on the MSDN page for the <Project> element.

From the documentation:

If multiple imported files define InitialTargets, all targets
  mentioned will be run, in the order the imports are encountered.

So, the ordering that you see seems to be documented.

Furthermore, the docs for the Import element state:

If the imported project does not have a DefaultTargets attribute,
  imported projects are inspected in the order that they are imported,
  ... . For example, if ProjectA imports ProjectB and ProjectC (in that
  order), and ProjectB imports ProjectD, MSBuild first looks for
  DefaultTargets specified on ProjectA, then ProjectB, then ProjectD,
  and finally ProjectC.

While this talks about the DefaultTargets attribute, it is a hint that the *Targets Attributes are treated in-order starting at the "main/"importing" project, so

... in the order the imports are encountered

would then mean that the "main" file is just put at the start of the "imports" list. (Which is what is observed.)

Body:
When I have an msbuild file foo.csproj and I want to Import a shared proj/targets file, how is the Project.InitialTargets attribute supposed (i.e. officially) to behave?

What I see with testing MSBUILD 2.0 and 4.x is that, given the following:

<Project InitialTargets="TestMain" ...>
  ...
  <Import Project="Sub.targets"/>
  ...
  <Target Name="TestMain">
    <Message Text="Hello from Main" />
  </Target>

and

<Project InitialTargets="TestSubInit" ...>
  ...
  <Target Name="TestSubInit">
    <Message Text="Hello from sub.targets" />
  </Target>

then the InitalTargets are chained in order of inclusion, i.e. first the output is:

TestMain-Target:
    Hello from Main
TestSubInit-Target:
    Hello from sub.targets

I want to rely on this chaining behavior - is this documented somehow?


来源: stackexchange

问:
How use reduce() to concat an array and delete the items duplicated
I have a problem using the reduce function in JavaScript. My goal is to take an array of arrays and, using reduce, then concat all the values and delete the duplicates:

I have an array like this:
firstArray = [[1, 2],[2, 3, 4],[4, 5, 6]]

I need an array like this after apply reduce():
resultArray = [1, 2, 3, 4, 5, 6]

```<code>const arrayElements = [[1,2],[2,3,4],[5,6]];
const newArray = arrayElements.reduce((total, value) => {
    return total.concat(value);
}, []);
</code>```

This is the fragment that I have, this only concat all the values, this is to say, [1, 2, 2, 3, 4, 5, 6]

答:
```<code>var num = [[1,2],[2,3,4],[5,6]];
var unique_numbers = [].concat(...num);
unique_numbers = Array.from(new Set(unique_numbers ));
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a problem using the reduce function in JavaScript. My goal is to take an array of arrays and, using reduce, then concat all the values and delete the duplicates:

I have an array like this:
firstArray = [[1, 2],[2, 3, 4],[4, 5, 6]]

I need an array like this after apply reduce():
resultArray = [1, 2, 3, 4, 5, 6]

const arrayElements = [[1,2],[2,3,4],[5,6]];
const newArray = arrayElements.reduce((total, value) => {
    return total.concat(value);
}, []);

This is the fragment that I have, this only concat all the values, this is to say, [1, 2, 2, 3, 4, 5, 6]


问:
Android app with off-site processing
I'm wondering what would be a good way to build an Android application with offsite processing.  Essentially I am going to record an input (audio recording or photo), and then send it to a computer I have online (securely - probably using HTTPS).  I then will have the computer process the data and send back a response.

Essentially this is a Shazam like application, except everywhere I look to how Shazam works they talk about the processing algorithm, not the process.  Any help would be appreciated.

答: If your server processing may take time, you can use Push Notification to tell the application that you are done on the server side. The application can then get the result instead of holding up the connection for too long.</p>

ContentLicense: CC BY-SA 3.0

Title: Android app with off-site processing


问:
ReactJS vs NodeJS - Why do I need to create both?
I understand that React is frontend, and NodeJS is the backend that allows Javascript code to function outside of a browser. What I don't understand (and this is after following tutorials online on setting up a React project and a NodeJS project) is why I have to create an instance of each.

For example, in my React project, I managed to create a website. But because I needed a backend, I decided to use NodeJS. But I'm doing NodeJS tutorials, and I can create a website using NodeJS too. I'm confused because right now, it's appearing to be that React and NodeJS do the SAME THING.

I have never worked with NodeJS before so I am a bit confused. I was under the impression that I would just use NodeJS to host the backend, but after seeing that I'm literally having to create an entire website with NodeJS, I don't understand how I'm supposed to use React and NodeJS together.

How do the two, React and NodeJS, integrate together to create a fully-functioning web app? I have yet to see something online that clearly breaks down how the two interact.

答:
React is front-end library. It provides great tooling for creatiing user interfaces. And it creates a single page application. Which means when you open a react app. It does not reload and its really fast.

While you could also use nodejs and something like handlebars to create a website. But that website would be rendered on server and then served to the user. But its alot more than that. There are a lot of things that you want to do on the server. Like authentication. You want that part to be secure. So you keep it on the server.

Now the answer to the final part of your question.

For a fully functional app. You would use react to create user interfaces. And nodejs for creating an API which your react app will call.


问:
Unable to retrieve input text from EditText in Android
I am unable to retrieve the input text from a EditText in Android.
Here's my code:

```<code>package com.example.fragments2

import ...
import com.example.fragments2.databinding.FragmentLoginPageBinding
class LoginPage : Fragment()
{

    lateinit var loginId:EditText
    lateinit var password:EditText
    lateinit var loginButton:Button

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View?

        {
            var binding:FragmentLoginPageBinding = DataBindingUtil.inflate(inflater,R.layout.fragment_login_page,container,false)
            var view  = binding.root
            loginId = view.findViewById(R.id.edittext_userid)
            password = view.findViewById(R.id.edittext_password)
            loginButton = view.findViewById(R.id.button_login)

            val text1: String = loginId.text.toString()
            val text2:String = password.text.toString()

        loginButton.setOnClickListener {
               Navigation.findNavController(it).navigate(LoginPageDirections.actionLoginPageToMainPage(text1,text2))
               Toast.makeText(context,text1,Toast.LENGTH_SHORT).show() //<-- shows empty string
           }

            return view
        }

}

</code>```

The value of Text1, Text2 always remains "" .
What's wrong in this code?

答:
text1 and text2 always remain values you assign them in the beginning.
If you want to get the text of the editText, you can directly request it loginId.text.toString().

Otherwise, you can create val text1: String = "" in the beginning of the class. But to update it, you need to do this inside of TextWatcher.
Take a look at the link

The issue of your code is that onCreateView invokes only when Fragment initialized. But you need to update values every time your text changes.

Body:
I am unable to retrieve the input text from a EditText in Android.
Here's my code:

package com.example.fragments2

import ...
import com.example.fragments2.databinding.FragmentLoginPageBinding
class LoginPage : Fragment()
{

    lateinit var loginId:EditText
    lateinit var password:EditText
    lateinit var loginButton:Button

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View?

        {
            var binding:FragmentLoginPageBinding = DataBindingUtil.inflate(inflater,R.layout.fragment_login_page,container,false)
            var view  = binding.root
            loginId = view.findViewById(R.id.edittext_userid)
            password = view.findViewById(R.id.edittext_password)
            loginButton = view.findViewById(R.id.button_login)

            val text1: String = loginId.text.toString()
            val text2:String = password.text.toString()

        loginButton.setOnClickListener {
               Navigation.findNavController(it).navigate(LoginPageDirections.actionLoginPageToMainPage(text1,text2))
               Toast.makeText(context,text1,Toast.LENGTH_SHORT).show() //<-- shows empty string
           }

            return view
        }

}

The value of Text1, Text2 always remains "" .
What's wrong in this code?


问:
[CORS]:' Access-Control-Allow-Origin' not allowing to get a cross-domain JSON?
Actually, I want to get a JSON object from this url ,
I tried using XMLHttpRequest() in javascript but console logged this error: [CORS] The origin 'http://localhost' did not find 'http://localhost' in the Access-Control-Allow-Origin response header for cross-origin  resource at 'http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-IN'.

But when I typed url in browser address bar, it loaded correctly! See the screenshot!

See my javascript code:

```<code>    <script>
        var url='http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-IN';
        var getJSON = function(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
  var status = xhr.status;
  if (status === 200) {
    callback(null, xhr.response);
  } else {
    callback(status, xhr.response);
  }
};
xhr.send();
};
getJSON('http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-IN',
function(err, data) {
  if (err !== null) {
    alert('Something went wrong: ' + err);
  } else {
    console.log(data);
  }
});

        </script>
</code>```

Note: I can't control the server.

答:
I got this error when playing with AWS serverless using S3 bucket. after adding below in S3/bucketname/permission/CORSconfiguration the following:</p>

```<code><CORSConfiguration>
    <CORSRule>
        <AllowedOrigin>*</AllowedOrigin>
        <AllowedMethod>GET</AllowedMethod>
        <MaxAgeSeconds>3000</MaxAgeSeconds>
        <AllowedHeader>Authorization</AllowedHeader>
    </CORSRule>
</CORSConfiguration>
</code>```

Body:
Actually, I want to get a JSON object from this url ,
I tried using XMLHttpRequest() in javascript but console logged this error: [CORS] The origin 'http://localhost' did not find 'http://localhost' in the Access-Control-Allow-Origin response header for cross-origin  resource at 'http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-IN'.

But when I typed url in browser address bar, it loaded correctly! See the screenshot!

See my javascript code:

Note: I can't control the server.

Body:
I got this error when playing with AWS serverless using S3 bucket. after adding below in S3/bucketname/permission/CORSconfiguration the following:

<CORSConfiguration>
    <CORSRule>
        <AllowedOrigin>*</AllowedOrigin>
        <AllowedMethod>GET</AllowedMethod>
        <MaxAgeSeconds>3000</MaxAgeSeconds>
        <AllowedHeader>Authorization</AllowedHeader>
    </CORSRule>
</CORSConfiguration>


问:
Applying corner radius to a specific UIView corner inside Storyboard does not work for all corners
I made a custom class for this. But it works only for top left corner, not the others:

```<code>@IBDesignable
public class RoundedView: UIView {

    @IBInspectable public var topLeft: Bool = false
    @IBInspectable public var topRight: Bool = false
    @IBInspectable public var bottomLeft: Bool = false
    @IBInspectable public var bottomRight: Bool = false
    @IBInspectable public var cornerRadius: Int = 0

    public override func awakeFromNib() {
        var options = UIRectCorner()

        if topLeft { options =  options.union(.topLeft) }
        if topRight { options =  options.union(.topRight) }
        if bottomLeft { options =  options.union(.bottomLeft) }
        if bottomRight { options =  options.union(.bottomRight) }

        let path = UIBezierPath(roundedRect:self.bounds,
                                byRoundingCorners:options,
                                cornerRadii: CGSize(width: cornerRadius, height: cornerRadius))

        let maskLayer = CAShapeLayer()

        maskLayer.path = path.cgPath
        self.layer.mask = maskLayer
    }
}
</code>```

Here is how it looks when running in simulator and I apply corner radius for all 4 corners:

What's going on here ? TopLeft works, TopRight slightly and bottom corners not at all. I am confused.

答:
You should update the mask in the override of layoutSubviews. As the constraints update the frame of the view, layoutSubviews is called, so that’s the right place to update the mask.

As an aside, I’d discourage the use of awakeFromNib to configure the view. It works fine if you use storyboard, but programmatically created views won’t call this. If you do want to configure the view when it’s created, it’s better to put the code in some private configuration method which is called by init(frame:) and init(coder:). That way it works for both storyboards and programmatically created views.

I might also suggest observers on the inspectable properties, to trigger the update of the corner rounding. You want the corner rounding to update automatically if you change these properties.

Thus:

```<code>@IBDesignable
public class RoundedView: UIView {

    @IBInspectable public var topLeft: Bool = false      { didSet { setNeedsLayout() } }
    @IBInspectable public var topRight: Bool = false     { didSet { setNeedsLayout() } }
    @IBInspectable public var bottomLeft: Bool = false   { didSet { setNeedsLayout() } }
    @IBInspectable public var bottomRight: Bool = false  { didSet { setNeedsLayout() } }
    @IBInspectable public var cornerRadius: CGFloat = 0  { didSet { setNeedsLayout() } }

    public override func layoutSubviews() {
        super.layoutSubviews()

        var options = UIRectCorner()

        if topLeft     { options.formUnion(.topLeft) }
        if topRight    { options.formUnion(.topRight) }
        if bottomLeft  { options.formUnion(.bottomLeft) }
        if bottomRight { options.formUnion(.bottomRight) }

        let path = UIBezierPath(roundedRect: bounds,
                                byRoundingCorners: options,
                                cornerRadii: CGSize(width: cornerRadius, height: cornerRadius))

        let maskLayer = CAShapeLayer()

        maskLayer.path = path.cgPath
        layer.mask = maskLayer
    }
}
</code>```

Or, alternatively, if targeting iOS 11 and later, we can let CoreAnimation do the rounding:

```<code>@IBDesignable
public class RoundedView: UIView {

    @IBInspectable public var topLeft: Bool = false      { didSet { updateCorners() } }
    @IBInspectable public var topRight: Bool = false     { didSet { updateCorners() } }
    @IBInspectable public var bottomLeft: Bool = false   { didSet { updateCorners() } }
    @IBInspectable public var bottomRight: Bool = false  { didSet { updateCorners() } }
    @IBInspectable public var cornerRadius: CGFloat = 0  { didSet { updateCorners() } }

    public override init(frame: CGRect = .zero) {
        super.init(frame: frame)
        updateCorners()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        updateCorners()
    }
}

private extension RoundedView {
    func updateCorners() {
        var corners = CACornerMask()

        if topLeft     { corners.formUnion(.layerMinXMinYCorner) }
        if topRight    { corners.formUnion(.layerMaxXMinYCorner) }
        if bottomLeft  { corners.formUnion(.layerMinXMaxYCorner) }
        if bottomRight { corners.formUnion(.layerMaxXMaxYCorner) }

        layer.maskedCorners = corners
        layer.cornerRadius = cornerRadius
    }
}
</code>```

The nice thing about this latter approach is that CoreAnimation will honor our corner rounding if we happen to be animating the frame of the view:

If you use the aforementioned layoutSubviews approach, then you have to manage the animation manually (e.g. with CADisplayLink).

Body:
I made a custom class for this. But it works only for top left corner, not the others:

@IBDesignable
public class RoundedView: UIView {

    @IBInspectable public var topLeft: Bool = false
    @IBInspectable public var topRight: Bool = false
    @IBInspectable public var bottomLeft: Bool = false
    @IBInspectable public var bottomRight: Bool = false
    @IBInspectable public var cornerRadius: Int = 0

    public override func awakeFromNib() {
        var options = UIRectCorner()

        if topLeft { options =  options.union(.topLeft) }
        if topRight { options =  options.union(.topRight) }
        if bottomLeft { options =  options.union(.bottomLeft) }
        if bottomRight { options =  options.union(.bottomRight) }

        let path = UIBezierPath(roundedRect:self.bounds,
                                byRoundingCorners:options,
                                cornerRadii: CGSize(width: cornerRadius, height: cornerRadius))

        let maskLayer = CAShapeLayer()

        maskLayer.path = path.cgPath
        self.layer.mask = maskLayer
    }
}

Here is how it looks when running in simulator and I apply corner radius for all 4 corners:

What's going on here ? TopLeft works, TopRight slightly and bottom corners not at all. I am confused.

Body:
You should update the mask in the override of layoutSubviews. As the constraints update the frame of the view, layoutSubviews is called, so that’s the right place to update the mask.

As an aside, I’d discourage the use of awakeFromNib to configure the view. It works fine if you use storyboard, but programmatically created views won’t call this. If you do want to configure the view when it’s created, it’s better to put the code in some private configuration method which is called by init(frame:) and init(coder:). That way it works for both storyboards and programmatically created views.

I might also suggest observers on the inspectable properties, to trigger the update of the corner rounding. You want the corner rounding to update automatically if you change these properties.

Thus:

@IBDesignable
public class RoundedView: UIView {

    @IBInspectable public var topLeft: Bool = false      { didSet { setNeedsLayout() } }
    @IBInspectable public var topRight: Bool = false     { didSet { setNeedsLayout() } }
    @IBInspectable public var bottomLeft: Bool = false   { didSet { setNeedsLayout() } }
    @IBInspectable public var bottomRight: Bool = false  { didSet { setNeedsLayout() } }
    @IBInspectable public var cornerRadius: CGFloat = 0  { didSet { setNeedsLayout() } }

    public override func layoutSubviews() {
        super.layoutSubviews()

        var options = UIRectCorner()

        if topLeft     { options.formUnion(.topLeft) }
        if topRight    { options.formUnion(.topRight) }
        if bottomLeft  { options.formUnion(.bottomLeft) }
        if bottomRight { options.formUnion(.bottomRight) }

        let path = UIBezierPath(roundedRect: bounds,
                                byRoundingCorners: options,
                                cornerRadii: CGSize(width: cornerRadius, height: cornerRadius))

        let maskLayer = CAShapeLayer()

        maskLayer.path = path.cgPath
        layer.mask = maskLayer
    }
}

Or, alternatively, if targeting iOS 11 and later, we can let CoreAnimation do the rounding:

@IBDesignable
public class RoundedView: UIView {

    @IBInspectable public var topLeft: Bool = false      { didSet { updateCorners() } }
    @IBInspectable public var topRight: Bool = false     { didSet { updateCorners() } }
    @IBInspectable public var bottomLeft: Bool = false   { didSet { updateCorners() } }
    @IBInspectable public var bottomRight: Bool = false  { didSet { updateCorners() } }
    @IBInspectable public var cornerRadius: CGFloat = 0  { didSet { updateCorners() } }

    public override init(frame: CGRect = .zero) {
        super.init(frame: frame)
        updateCorners()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        updateCorners()
    }
}

private extension RoundedView {
    func updateCorners() {
        var corners = CACornerMask()

        if topLeft     { corners.formUnion(.layerMinXMinYCorner) }
        if topRight    { corners.formUnion(.layerMaxXMinYCorner) }
        if bottomLeft  { corners.formUnion(.layerMinXMaxYCorner) }
        if bottomRight { corners.formUnion(.layerMaxXMaxYCorner) }

        layer.maskedCorners = corners
        layer.cornerRadius = cornerRadius
    }
}

The nice thing about this latter approach is that CoreAnimation will honor our corner rounding if we happen to be animating the frame of the view:

If you use the aforementioned layoutSubviews approach, then you have to manage the animation manually (e.g. with CADisplayLink).


问:
Object "undefined" in Mocha script. Not sure how to pass on value
I am running a mocha test on a bunch of endpoints and I'm not able to pass on results to the next test case
Failing at line    var result = data["results"];
error:data undefined

```<code>
    it('should get series', async () => {
        let data = await legacy.getCategories(config[process.env.TEST_ENV].url, config[process.env.TEST_ENV].origin);
        console.log(data);
        expect(data).to.be.an('array').that.is.not.empty;
        done();
    });

    var unallowedGuids = config[process.env.TEST_ENV].unallowedGuids;
    var result = data["results"];

    for (i = 0; i < result.length; i++) {
        let guid = result[i]["guid"];
        let showName = result[i]["title"];
        if (!unallowedGuids.includes(guid)){
                it('should get colletions guid', async () => {
                let data = await legacy.collectionsGuid(config[process.env.TEST_ENV].url, config[process.env.TEST_ENV].origin, guid);
                expect(data).to.be.an('array').that.is.not.empty;
                done();
    });
                it('should get series guid', async () => {
                let data = await legacy.seriesGuid(config[process.env.TEST_ENV].url, config[process.env.TEST_ENV].origin, guid);
                expect(data).to.be.an('array').that.is.not.empty;
                done();
    });
        }
        else
            console.log("excluded", guid);
    }

});```
```

答:
I think your issue is related to variable scope.

Try modifying your code like so:

```<code>    let data; // initialize "data" outside of the "it" callback function

    it('should get series', async () => {
      data = await legacy.getCategories(config[process.env.TEST_ENV].url, config[process.env.TEST_ENV].origin);
      console.log(data);
      expect(data).to.be.an('array').that.is.not.empty;
      done();
    });

    var unallowedGuids = config[process.env.TEST_ENV].unallowedGuids;
    var result = data["results"]; // data will be defined here
</code>```

Body:
I am running a mocha test on a bunch of endpoints and I'm not able to pass on results to the next test case
Failing at line    var result = data["results"];
error:data undefined

    it('should get series', async () => {
        let data = await legacy.getCategories(config[process.env.TEST_ENV].url, config[process.env.TEST_ENV].origin);
        console.log(data);
        expect(data).to.be.an('array').that.is.not.empty;
        done();
    });

    var unallowedGuids = config[process.env.TEST_ENV].unallowedGuids;
    var result = data["results"];

    for (i = 0; i < result.length; i++) {
        let guid = result[i]["guid"];
        let showName = result[i]["title"];
        if (!unallowedGuids.includes(guid)){
                it('should get colletions guid', async () => {
                let data = await legacy.collectionsGuid(config[process.env.TEST_ENV].url, config[process.env.TEST_ENV].origin, guid);
                expect(data).to.be.an('array').that.is.not.empty;
                done();
    });
                it('should get series guid', async () => {
                let data = await legacy.seriesGuid(config[process.env.TEST_ENV].url, config[process.env.TEST_ENV].origin, guid);
                expect(data).to.be.an('array').that.is.not.empty;
                done();
    });
        }
        else
            console.log("excluded", guid);
    }

});```

Body:
I think your issue is related to variable scope.

Try modifying your code like so:

    let data; // initialize "data" outside of the "it" callback function

    it('should get series', async () => {
      data = await legacy.getCategories(config[process.env.TEST_ENV].url, config[process.env.TEST_ENV].origin);
      console.log(data);
      expect(data).to.be.an('array').that.is.not.empty;
      done();
    });

    var unallowedGuids = config[process.env.TEST_ENV].unallowedGuids;
    var result = data["results"]; // data will be defined here


问:
How do I detect unfocus outside of a certain range?
Solution:

```<code>let focused = false;
document.getElementById('input-comment').addEventListener("focus", ()=>{
  document.getElementById('comment-id').style.display="block";
})

document.getElementById('comment-id').addEventListener("mousedown", ()=>{
  $("#input-comment").focus();
  focused = true;
})

document.getElementById('input-comment').addEventListener("focusout", ()=>{
  if(!focused){
    document.getElementById('comment-id').style.display="none";
  }
  else{
    focused = false;
  }

})
</code>```

I have an input of text and when it gets focused a button bellow it appears.

Furthermore I want it to disappear when It is unfocused but still be able to click in the button that was bellow without it disappearing, which means I want to be able to click the button without the unfocus event getting triggered, but trigger it everywhere else.

Setting button to disappear after unfocused was my first try; after not being able to click it I decided to use a timeout, whcih looked like:

```<code>document.getElementById('input-comment').addEventListener("focusout", ()=>{
 setTimeout(()=>document.getElementById('comment-id').style.display="none", 100);
})
</code>```

The problem with this is that the input doesn't disappear instantly after unfocused when clicked on other elements.

Then I tried

```<code>let clicked = false;
document.body.addEventListener("click", ()=>{
  document.getElementById('comment-id').addEventListener("click", ()=>{
    document.getElementById('comment-id').style.display="block";
    clicked = true;
  })
  setTimeout(()=>{
    if(!clicked){
      document.getElementById('input-comment').addEventListener("focusout", ()=>{
        document.getElementById('comment-id').style.display="none";
      })
    }
  }, 500);
})
</code>```

I was hoping it would block the onfocus event if I clicked the button first, but If I click the button the when unfocused it doesn't hide; if I clicked other elements, I won't be able to click the button.

EDIT: Current code

```<code>document.getElementById('input-comment').addEventListener("focus", ()=>{
  document.getElementById('comment-id').style.display="block";
})

document.getElementById('comment-id').addEventListener("click", ()=>{
  $("#input-comment").focus();
})

document.getElementById('input-comment').addEventListener("focusout", ()=>{
  document.getElementById('comment-id').style.display="none";
})
</code>```

答:
In your button event handler, force focus on the input.

E.g:

$("#button").on("click", () => {
 //code
 $("#input").focus();
});
```

<p>And I suggest you add a listener for <code>onfocus</code> in your input so you can clean the <code>timeout</code>.</p>

<pre class="lang-js prettyprint-override"><code>document.getElementById('input-comment').addEventListener("focusout", () => {
 hideButtonTimeout = setTimeout(()=>document.getElementById('comment-id').style.display="none", 100);
});

document.getElementById('input-comment').addEventListener("onfocus", () => {
 clearInterval(hideButtonTimeout);
});
</code>```

Body:
Solution:

let focused = false;
document.getElementById('input-comment').addEventListener("focus", ()=>{
  document.getElementById('comment-id').style.display="block";
})

document.getElementById('comment-id').addEventListener("mousedown", ()=>{
  $("#input-comment").focus();
  focused = true;
})

document.getElementById('input-comment').addEventListener("focusout", ()=>{
  if(!focused){
    document.getElementById('comment-id').style.display="none";
  }
  else{
    focused = false;
  }

})

I have an input of text and when it gets focused a button bellow it appears.

Furthermore I want it to disappear when It is unfocused but still be able to click in the button that was bellow without it disappearing, which means I want to be able to click the button without the unfocus event getting triggered, but trigger it everywhere else.

Setting button to disappear after unfocused was my first try; after not being able to click it I decided to use a timeout, whcih looked like:

document.getElementById('input-comment').addEventListener("focusout", ()=>{
 setTimeout(()=>document.getElementById('comment-id').style.display="none", 100);
})

The problem with this is that the input doesn't disappear instantly after unfocused when clicked on other elements.

Then I tried

let clicked = false;
document.body.addEventListener("click", ()=>{
  document.getElementById('comment-id').addEventListener("click", ()=>{
    document.getElementById('comment-id').style.display="block";
    clicked = true;
  })
  setTimeout(()=>{
    if(!clicked){
      document.getElementById('input-comment').addEventListener("focusout", ()=>{
        document.getElementById('comment-id').style.display="none";
      })
    }
  }, 500);
})

I was hoping it would block the onfocus event if I clicked the button first, but If I click the button the when unfocused it doesn't hide; if I clicked other elements, I won't be able to click the button.

EDIT: Current code

document.getElementById('input-comment').addEventListener("focus", ()=>{
  document.getElementById('comment-id').style.display="block";
})

document.getElementById('comment-id').addEventListener("click", ()=>{
  $("#input-comment").focus();
})

document.getElementById('input-comment').addEventListener("focusout", ()=>{
  document.getElementById('comment-id').style.display="none";
})

Body:
In your button event handler, force focus on the input.

E.g:

$("#button").on("click", () => {
 //code
 $("#input").focus();
});

And I suggest you add a listener for onfocus in your input so you can clean the timeout.

document.getElementById('input-comment').addEventListener("focusout", () => {
 hideButtonTimeout = setTimeout(()=>document.getElementById('comment-id').style.display="none", 100);
});

document.getElementById('input-comment').addEventListener("onfocus", () => {
 clearInterval(hideButtonTimeout);
});


问:
Initialize repositories protected by Spring authentication
I use Spring Boot Data REST to map Hibernate repositories of entities to REST routes. I also use Spring Security's @PreAuthorize annotation to secure certain methods of those repositories. This works fine during production, but when I want to programmatically initialize the repositories with data (e.g. adding a first user to get started and some other sample data), it complains that "An Authentication object was not found in the SecurityContext". I realize that this is because there is no authenticated user in the security context at the time I configure the database (with an autowired component saving objects to repositories). However, I'd like to temporarily circumvent this authorization during configuration, so that I can initialize the database.

Is there any way to achieve this? And if not, how can I manually log in in the initialization method? I've seen some attempts to the second approach, but they all require access to an AuthenticationManager, which I don't know how to obtain.

答:
An easy solution: Ignore security and focus on an empty repository

```<code>@Component
class InitializeDataIfNoDataPresent {
  private final UserRepo repository;

  public InitializeDataIfNoDataPresent(UserRepo repo) {
      this.repository = repo;
  }

  @EventListener(ApplicationReadyEvent.class)
  public void init() {
    if(0 == repository.count()) {
      setupData();
    }
  }

  @PreAuthorize("hasRole('ADMIN')")
  public void setupData() {
    // your existing setup
  }

}

</code>```

When the application starts and your repository is empty, setupData() will be called even if there is no user present.

ref: stackoverflow-initialization-secured

Body:
An easy solution: Ignore security and focus on an empty repository

@Component
class InitializeDataIfNoDataPresent {
  private final UserRepo repository;

  public InitializeDataIfNoDataPresent(UserRepo repo) {
      this.repository = repo;
  }

  @EventListener(ApplicationReadyEvent.class)
  public void init() {
    if(0 == repository.count()) {
      setupData();
    }
  }

  @PreAuthorize("hasRole('ADMIN')")
  public void setupData() {
    // your existing setup
  }

}

When the application starts and your repository is empty, setupData() will be called even if there is no user present.

ref: stackoverflow-initialization-secured


答:
I think that click callback ins´t take the correct instance of yours TextViews. Try get these values inside click button:

```<code>class LoginPage : Fragment()
{

    lateinit var loginId:EditText
    lateinit var password:EditText
    lateinit var loginButton:Button

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View?

        {
            var binding:FragmentLoginPageBinding = DataBindingUtil.inflate(inflater,R.layout.fragment_login_page,container,false)
            var view  = binding.root
            loginId = view.findViewById(R.id.edittext_userid)
            password = view.findViewById(R.id.edittext_password)
            loginButton = view.findViewById(R.id.button_login)

            loginButton.setOnClickListener {
                val text1: String = loginId.text.toString()
                val text2: String = password.text.toString()
                Navigation.findNavController(it).navigate(LoginPageDirections.actionLoginPageToMainPage(text1,text2))
                Toast.makeText(context,text1,Toast.LENGTH_SHORT).show() //<-- shows empty string
           }

           return view
        }
}
</code>```

Note: Maybe you must call the Toast.makeText with runOnUiMainThread(). It's been some time since I've done this.

```<code>this.runOnUiThread {
     Toast.makeText(context,text1,Toast.LENGTH_SHORT).show() //<-- shows empty string
}
</code>```

Title: Unable to retrieve input text from EditText in Android

Body:
I think that click callback ins´t take the correct instance of yours TextViews. Try get these values inside click button:

class LoginPage : Fragment()
{

    lateinit var loginId:EditText
    lateinit var password:EditText
    lateinit var loginButton:Button

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View?

        {
            var binding:FragmentLoginPageBinding = DataBindingUtil.inflate(inflater,R.layout.fragment_login_page,container,false)
            var view  = binding.root
            loginId = view.findViewById(R.id.edittext_userid)
            password = view.findViewById(R.id.edittext_password)
            loginButton = view.findViewById(R.id.button_login)

            loginButton.setOnClickListener {
                val text1: String = loginId.text.toString()
                val text2: String = password.text.toString()
                Navigation.findNavController(it).navigate(LoginPageDirections.actionLoginPageToMainPage(text1,text2))
                Toast.makeText(context,text1,Toast.LENGTH_SHORT).show() //<-- shows empty string
           }

           return view
        }
}

Note: Maybe you must call the Toast.makeText with runOnUiMainThread(). It's been some time since I've done this.

this.runOnUiThread {
     Toast.makeText(context,text1,Toast.LENGTH_SHORT).show() //<-- shows empty string
}


问:
How to close a tab in vim?
When I use :tabnew myfile in vim it opens a new tab.

When I quit the tab with
:q and I move to another tab with :bn , the tab is still there.

Can someone explain why and how to really close it?

答: :tabclose will need to be coupled with :tabN instead of :bn.  As the original answer suggests tabs and buffers are not the same concept.  If you use tabs using the proper commands will help.

Title: How to close a tab in vim?


问:
How to update the Entity Framework auto-generated code for the results of a stored procedure
What I am trying to achieve is to get the auto-generated code to update for the results of a stored procedure.

What I have done so far is:

Modified the stored procedures in my development database

In Visual Studio:

2.1 Made sure the connection string is set in the Server Explorer

2.2 Right clicked on the EDMX diagram and selected Update Model from database. The update wizard is displayed. I don't add anything, and I check the stored procedure is in the list. After this I click the Finish button.

I then get the "Running this text template can potentially harm your computer" message twice, which I click OK on.

Save the changes

Build the DLL

Right click on the tt (not the context one) under the EDMX and select run custom tool.  I get the same security message as above, so click ok.

Everything seems to be running ok, and there are no obvious errors.

I have also tried the Transform All T4 Templates under the build menu.

I am using Visual Studio 2013 with SQL Server 2014. The Entity Framework runtime version is 4.0.30319.

I have had a look in the EDMX xml file and there is an entry for the FunctionImportMapping for the stored procedure and the class it will create.

If it makes any difference when I try to connect to the database using the SQL Server Object Explorer in Visual Studio, it displays the SQL Server 2012 login, if I click connect it displays the "An incompatible SQL Server version was detected".  That can be cured by installing the latest version of SSDT for Visual Studio 2013.

I am new to Entity Framework, so any help will be appreciated.

How do I get the class to update, or is it that I am overthinking the issue and have to update it manually?

Thank you for your help.

答:
I have found a solution which seems to have done the trick:

Open the EDMX diagram

Update the model from the database

Right click on the diagram and select Model Browser from the menu

Expand the Function Imports folder

Find the stored procedure that has been modified.

Double click on it and the Edit Function Import form will be displayed

Click Get Column Information

Ensure the correct complex type is selected, and click update.

Click OK

The new columns should now be added to the auto-generated code.


问:
How to exclude trailing slash on source URL when redirecting?
I have to make a 301 redirect from a domain to another (example-a.com to example-b.com).

This is the code I put in .htaccess of example-a.com:

```<code>RewriteEngine on
RewriteRule ^(.*)$ https://www.example-b.com/$1 [R=301,L]
</code>```

All URLs are the same, except pages of example-a.com all have a / (slash) at the end of the URL, but example-b.com does not. So how to redirect without the ending / if the URL contains one?

答:
```<code>RewriteRule ^(.*)$ https://www.example-b.com/$1 [R=301,L]
</code>```

To exclude the slash from the redirected URL, then exclude the slash from the captured group in the RewriteRule pattern. eg. ^(.*)/$.

However, assuming you also want the document root to redirect, where there is no slash in the URL-path, then you need to make the trailing slash optional (or create an entirely separate rule). But in that case you need to also make the capturing group non-greedy, otherwise the trailing slash will always be included in the captured group (since regex is greedy by default).

So, try the following instead:

```<code>RewriteRule ^(.*?)/?$ https://www.example-b.com/$1 [R=302,L]
</code>```

You will need to clear your browser cache before testing. Since the earlier 301s will have likely been cached.

Note that this is a 302 (temporary) redirect. Only change this to a 301 (permanent) redirect - if that is the intention - once you have confirmed that it works OK. This is to avoid the browser caching erroneous redirects whilst testing.

Body:
I have to make a 301 redirect from a domain to another (example-a.com to example-b.com).

This is the code I put in .htaccess of example-a.com:

RewriteEngine on
RewriteRule ^(.*)$ https://www.example-b.com/$1 [R=301,L]

All URLs are the same, except pages of example-a.com all have a / (slash) at the end of the URL, but example-b.com does not. So how to redirect without the ending / if the URL contains one?

Body:
RewriteRule ^(.*)$ https://www.example-b.com/$1 [R=301,L]

To exclude the slash from the redirected URL, then exclude the slash from the captured group in the RewriteRule pattern. eg. ^(.*)/$.

However, assuming you also want the document root to redirect, where there is no slash in the URL-path, then you need to make the trailing slash optional (or create an entirely separate rule). But in that case you need to also make the capturing group non-greedy, otherwise the trailing slash will always be included in the captured group (since regex is greedy by default).

So, try the following instead:

RewriteRule ^(.*?)/?$ https://www.example-b.com/$1 [R=302,L]

You will need to clear your browser cache before testing. Since the earlier 301s will have likely been cached.

Note that this is a 302 (temporary) redirect. Only change this to a 301 (permanent) redirect - if that is the intention - once you have confirmed that it works OK. This is to avoid the browser caching erroneous redirects whilst testing.


问:
Controlling dynamic properties in Shady according to video frames not time
I am trying to use Shady to present a sequence of image frames. I'm controlling the flow from another machine, so that I first instruct the machine running Shady to present the first frame, and later on to run the rest of the frames.
I create a World instance, and attach to it an animation callback function. Within this callback I listen for communications from the other machine (using UDP).
First I receive a command to load a given sequence (stored as a numpy array), and I do

```<code>def loadSequence(self, fname):
    yy = np.load(fname)
    pages = []
    sz = yy.shape[0]
    for j in range(yy.shape[1]/yy.shape[0]):
         pages.append(yy[:, j*sz:(j+1)*sz])
    deltax, deltay = (self.screen_px[0] - sz) / 2, (self.screen_px[1] - sz) / 2
    if (self.sequence is None):
        self.sequence = self.wind.Stimulus(pages, 'sequence', multipage=True, anchor=Shady.LOCATION.UPPER_LEFT, position=[deltax, deltay], visible=False)
    else:
        self.sequence.LoadPages(pages, visible=False)
</code>```

When I receive the command to show the first frame, I then do:

```<code>def showFirstFrame(self, pars):
    self.sequence.page = 0 if (pars[0] == 0) else (len(self.sequence.pages) - 1)
    self.sequence.visible = True
</code>```

But what do I do now to get the other frames to be be displayed? In the examples I see, s.page is set as a function of time, but I need to show all frames, regardless of time. So I was thinking of doing something along these lines:

```<code>def showOtherFrames(self, pars, ackClient):
    direction, ack = pars[0], pars[2]
    self.sequence.page = range(1, len(self.sequence.pages)) if (direction == 0) else range(len(self.sequence.pages)-2, -1, -1)
</code>```

But this won't work. Alternatively I thought of defining a function that takes t as argument, but ignores it and uses instead a counter kept in a global variable, but I'd like to understand what is the proper way of doing this.

答:
Your global-variable idea is one perfectly valid way to do this.  Or, since it looks like you're defining things as methods of an instance of your own custom class, you could use instance methods as your animation callbacks and/or dynamic property values—then, instead of truly global variables, it makes sense to use attributes of self:

```<code>import Shady

class Foo(object):

    def __init__(self, stimSources):
        self.wind = Shady.World()
        self.stim = self.wind.Stimulus(stimSources, multipage=True)
        self.stim.page = self.determinePage  # dynamic property assignment

    def determinePage(self, t):
        # Your logic here.
        # Ignore `t` if you think that's appropriate.
        # Use `self.wind.framesCompleted` if it's helpful.
        # And/or use custom attributes of `self` if that's
        # helpful (or, similarly, global variables if you must).
        # But since this is called once per frame (whenever the
        # frame happens to be) it could be as simple as:
        return self.stim.page + 1
        # ...which is indefinitely sustainable since page lookup
        # will wrap around to the number of available pages.

# Let's demo this idea:
foo = Foo(Shady.PackagePath('examples/media/alien1/*.png'))
Shady.AutoFinish(foo.wind)
</code>```

Equivalent to that simple example, you could have the statement self.stim.page += 1 (and whatever other logic) inside a more-general animation callback.

Another useful tool for frame-by-frame animation is support for python's generator functions, i.e. functions that include a yield statement. Worked examples are included in python -m Shady demo precision and python -m Shady demo dithering.

It can also be done in a StateMachine which is always my preferred answer to such things:

```<code>import Shady

class Foo(object):
    def __init__(self, stimSources):
        self.wind = Shady.World()
        self.stim = self.wind.Stimulus(stimSources, multipage=True)

foo = Foo(Shady.PackagePath('examples/media/alien1/*.png'))

sm = Shady.StateMachine()
@sm.AddState
class PresentTenFrames(sm.State):
    def ongoing(self): # called on every frame while the state is active
        foo.stim.page += 1
        if foo.stim.page > 9:
            self.ChangeState()

@sm.AddState
class SelfDestruct(sm.State):
    onset = foo.wind.Close

foo.wind.SetAnimationCallback(sm)

Shady.AutoFinish(foo.wind)
</code>```

Body:
I am trying to use Shady to present a sequence of image frames. I'm controlling the flow from another machine, so that I first instruct the machine running Shady to present the first frame, and later on to run the rest of the frames.
I create a World instance, and attach to it an animation callback function. Within this callback I listen for communications from the other machine (using UDP).
First I receive a command to load a given sequence (stored as a numpy array), and I do

def loadSequence(self, fname):
    yy = np.load(fname)
    pages = []
    sz = yy.shape[0]
    for j in range(yy.shape[1]/yy.shape[0]):
         pages.append(yy[:, j*sz:(j+1)*sz])
    deltax, deltay = (self.screen_px[0] - sz) / 2, (self.screen_px[1] - sz) / 2
    if (self.sequence is None):
        self.sequence = self.wind.Stimulus(pages, 'sequence', multipage=True, anchor=Shady.LOCATION.UPPER_LEFT, position=[deltax, deltay], visible=False)
    else:
        self.sequence.LoadPages(pages, visible=False)

When I receive the command to show the first frame, I then do:

def showFirstFrame(self, pars):
    self.sequence.page = 0 if (pars[0] == 0) else (len(self.sequence.pages) - 1)
    self.sequence.visible = True

But what do I do now to get the other frames to be be displayed? In the examples I see, s.page is set as a function of time, but I need to show all frames, regardless of time. So I was thinking of doing something along these lines:

def showOtherFrames(self, pars, ackClient):
    direction, ack = pars[0], pars[2]
    self.sequence.page = range(1, len(self.sequence.pages)) if (direction == 0) else range(len(self.sequence.pages)-2, -1, -1)

But this won't work. Alternatively I thought of defining a function that takes t as argument, but ignores it and uses instead a counter kept in a global variable, but I'd like to understand what is the proper way of doing this.

Body:
Your global-variable idea is one perfectly valid way to do this.  Or, since it looks like you're defining things as methods of an instance of your own custom class, you could use instance methods as your animation callbacks and/or dynamic property values—then, instead of truly global variables, it makes sense to use attributes of self:

import Shady

class Foo(object):

    def __init__(self, stimSources):
        self.wind = Shady.World()
        self.stim = self.wind.Stimulus(stimSources, multipage=True)
        self.stim.page = self.determinePage  # dynamic property assignment

    def determinePage(self, t):
        # Your logic here.
        # Ignore `t` if you think that's appropriate.
        # Use `self.wind.framesCompleted` if it's helpful.
        # And/or use custom attributes of `self` if that's
        # helpful (or, similarly, global variables if you must).
        # But since this is called once per frame (whenever the
        # frame happens to be) it could be as simple as:
        return self.stim.page + 1
        # ...which is indefinitely sustainable since page lookup
        # will wrap around to the number of available pages.

# Let's demo this idea:
foo = Foo(Shady.PackagePath('examples/media/alien1/*.png'))
Shady.AutoFinish(foo.wind)

Equivalent to that simple example, you could have the statement self.stim.page += 1 (and whatever other logic) inside a more-general animation callback.

Another useful tool for frame-by-frame animation is support for python's generator functions, i.e. functions that include a yield statement. Worked examples are included in python -m Shady demo precision and python -m Shady demo dithering.

It can also be done in a StateMachine which is always my preferred answer to such things:

import Shady

class Foo(object):
    def __init__(self, stimSources):
        self.wind = Shady.World()
        self.stim = self.wind.Stimulus(stimSources, multipage=True)

foo = Foo(Shady.PackagePath('examples/media/alien1/*.png'))

sm = Shady.StateMachine()
@sm.AddState
class PresentTenFrames(sm.State):
    def ongoing(self): # called on every frame while the state is active
        foo.stim.page += 1
        if foo.stim.page > 9:
            self.ChangeState()

@sm.AddState
class SelfDestruct(sm.State):
    onset = foo.wind.Close

foo.wind.SetAnimationCallback(sm)

Shady.AutoFinish(foo.wind)


问:
How to use session variables in different pages, when the "session_start()" function is already being used?
I have a problem trying to display some session variables in a different page in php. Most of the threads I've seen here are related to the lack of "session_start()". But I already have it at the top of my files.

I'm trying to create a "recover your password module".
I have a form element which has an action set to another page.
I have a database with two tables. The form just allows the user to input his e-mail. When I click the submit button, a mysqli connection is supposed to look in both tables for the user with the e-mail stored in the form and then store the rest of the elements (name, password, recovery question and its answer) of the table in some php variables.

In an if conditional statement I check which table the e-mail is stored in and then create some session variables that store the whole information of said user.

In the other page I'm just trying to echo some text along with the session variable of the name of the user if that variable session is set. If not it will echo a "failed session" text.

Here is the form (the file where this thing is has the session_start() already in top):

```<code><form action="cambio.php" method="post">
     <h1>RECUPERACIÓN DE CONTRASEÑA</h1><br>
     <p>Escriba su dirección de correo para modificar su contraseña:</p><br>
     <div class="form group">
        <label for="email">Correo electrónico:</label>
        <input type="email" class="form-control ancho" id="email" name="email" class="ancho"><br>
      </div>
      <button type="submit" class="btn btn-primary" name="recuperar">Recuperar contraseña</button>
</form>
</code>```

After connecting to the database, this is where I'm setting the session variables (in the same .php as the previous form code):

```<code> if(isset($_POST['recuperar'])) {
                    $c = $_POST["email"];
                    $buscarAlumno="select nombre, correo, password, num_pregunta, respuesta from alumno where correo='$c';"; //first table
                    $buscarProfesor="select nombre, correo, password num_pregunta, respuesta from profesor where correo='$c';"; //second table
                    $resA = $conn->query($buscarAlumno);
                    $resP = $conn->query($buscarProfesor);
                    $rowA = $resA->fetch_array();
                    $rowP = $resP->fetch_array();

                    //Save the e-mail-matching fields (first table)
                    $rnA = $rowA["nombre"];
                    $rcA = $rowA["correo"];
                    $rpA = $rowA["password"];
                    $rnpA = $rowA["pregunta"];
                    $rrA = $rowA["respuesta"];
                    //Save the e-mail-matching fields (second table)
                    $rnP = $rowP["nombre"];
                    $rcP = $rowP["correo"];
                    $rpP = $rowP["password"];
                    $rnpP = $rowP["num_pregunta"];
                    $rrP = $rowP["respuesta"];

                    //In this statement, some of the variables above are going
                    //to be stored in session variables depending on the
                    //table in which the e-mail was found
                    if (isset($c)) {
                        if ($c == $rcP) {
                            $_SESSION['nomCorrecto'] = $rnP;
                            $_SESSION['corCorrecto'] = $rcP;
                            $_SESSION['pasCorrecto'] = $rpP;
                            $_SESSION['preCorrecto'] = $rnpP;
                            $_SESSION['resCorrecto'] = $rrP;
                        }
                        elseif ($c == $rcA) {
                            $_SESSION['nomCorrecto'] = $rnA;
                            $_SESSION['corCorrecto'] = $rcA;
                            $_SESSION['pasCorrecto'] = $rpA;
                            $_SESSION['preCorrecto'] = $rnpA;
                            $_SESSION['resCorrecto'] = $rrA;
                        }
                        else {
                            echo "Usuario no registrado.";
                        }
                    }
                }
</code>```

This code is in another page, where I want the results to be show (again, it already has the session_start() on top of the file).

```<code>        <?php
            //This part should show the name of the user, but is not working
            if(isset($_SESSION['nomCorrecto'])) {
                echo "Hola " .$_SESSION['nomCorrecto']. ".";
            }
            else {
                echo "Sesión fallida.";
            }
        ?>
</code>```

I don't know what I'm doing wrong, I don't know if the error is about the form statement or how I'm saving and echoing the session variables.
I just get the "Sesión fallida" error text.

Any help is welcome.

Thanks in advance.

答:
Finally figured it out. I need to declare the session variables that I'm going to use right after the session_star() function.

Thanks for the help.

Body:
I have a problem trying to display some session variables in a different page in php. Most of the threads I've seen here are related to the lack of "session_start()". But I already have it at the top of my files.

I'm trying to create a "recover your password module".
I have a form element which has an action set to another page.
I have a database with two tables. The form just allows the user to input his e-mail. When I click the submit button, a mysqli connection is supposed to look in both tables for the user with the e-mail stored in the form and then store the rest of the elements (name, password, recovery question and its answer) of the table in some php variables.

In an if conditional statement I check which table the e-mail is stored in and then create some session variables that store the whole information of said user.

In the other page I'm just trying to echo some text along with the session variable of the name of the user if that variable session is set. If not it will echo a "failed session" text.

Here is the form (the file where this thing is has the session_start() already in top):

<form action="cambio.php" method="post">

RECUPERACIÓN DE CONTRASEÑA

Escriba su dirección de correo para modificar su contraseña:

        Correo electrónico:
        <input type="email" class="form-control ancho" id="email" name="email" class="ancho">

      <button type="submit" class="btn btn-primary" name="recuperar">Recuperar contraseña</button>
</form>

After connecting to the database, this is where I'm setting the session variables (in the same .php as the previous form code):

 if(isset($_POST['recuperar'])) {
                    $c = $_POST["email"];
                    $buscarAlumno="select nombre, correo, password, num_pregunta, respuesta from alumno where correo='$c';"; //first table
                    $buscarProfesor="select nombre, correo, password num_pregunta, respuesta from profesor where correo='$c';"; //second table
                    $resA = $conn->query($buscarAlumno);
                    $resP = $conn->query($buscarProfesor);
                    $rowA = $resA->fetch_array();
                    $rowP = $resP->fetch_array();

                    //Save the e-mail-matching fields (first table)
                    $rnA = $rowA["nombre"];
                    $rcA = $rowA["correo"];
                    $rpA = $rowA["password"];
                    $rnpA = $rowA["pregunta"];
                    $rrA = $rowA["respuesta"];
                    //Save the e-mail-matching fields (second table)
                    $rnP = $rowP["nombre"];
                    $rcP = $rowP["correo"];
                    $rpP = $rowP["password"];
                    $rnpP = $rowP["num_pregunta"];
                    $rrP = $rowP["respuesta"];

                    //In this statement, some of the variables above are going
                    //to be stored in session variables depending on the
                    //table in which the e-mail was found
                    if (isset($c)) {
                        if ($c == $rcP) {
                            $_SESSION['nomCorrecto'] = $rnP;
                            $_SESSION['corCorrecto'] = $rcP;
                            $_SESSION['pasCorrecto'] = $rpP;
                            $_SESSION['preCorrecto'] = $rnpP;
                            $_SESSION['resCorrecto'] = $rrP;
                        }
                        elseif ($c == $rcA) {
                            $_SESSION['nomCorrecto'] = $rnA;
                            $_SESSION['corCorrecto'] = $rcA;
                            $_SESSION['pasCorrecto'] = $rpA;
                            $_SESSION['preCorrecto'] = $rnpA;
                            $_SESSION['resCorrecto'] = $rrA;
                        }
                        else {
                            echo "Usuario no registrado.";
                        }
                    }
                }

This code is in another page, where I want the results to be show (again, it already has the session_start() on top of the file).

        <?php
            //This part should show the name of the user, but is not working
            if(isset($_SESSION['nomCorrecto'])) {
                echo "Hola " .$_SESSION['nomCorrecto']. ".";
            }
            else {
                echo "Sesión fallida.";
            }
        ?>

I don't know what I'm doing wrong, I don't know if the error is about the form statement or how I'm saving and echoing the session variables.
I just get the "Sesión fallida" error text.

Any help is welcome.

Thanks in advance.


问:
Secure, portable encrypted config values -- possible?
I'm just curious if anyone has any great ideas on this.

We have a lot of C# windows services.  Each app is installed on multiple machines (anywhere from 2-80, depending on the app.)

Due to the security setup of the network, we cannot (consistently) use Windows authentication to the SQL servers, so our connection strings and credentials have actual usernames and passwords.

Our infrastructure folks want to be able to do the following when deploying the software:
1) Edit the configuration once -- set the appropriate server, user, and passwords for various database connections.
2) Have the connection strings (at least) encrypted or otherwise unreadable to the naked eye
3) Copy that configuration file to all installations of a particular piece of software.  This means that the encryption cannot be tied to a specific machine.

Can DPAPI do this?  Can one set of keys be installed on all targets to allow the decryption of a common config file?  How is the configuration edited in this case?  How do you keep other users from viewing the encrypted configuration in the same manner?

答:
The DPAPI encryption uses the <machineKey> as the private key.

Option 1) You can update this in the machine.config of each server and set machineKey to be identical.  This has wide impact to the server, such as with unrelated apps that depend on machineKey.

Option 2) You can override the <machineKey> in the web.config for narrower scope.

Session and encrypted viewstate validation also depend on the <machineKey>, so by having identical keys across servers, the sessions and viewstate will be mutually readable.  This could be desired for a web farm of identical servers and a centralized session store, but that's out of scope of the original question.

How To: Configure MachineKey in ASP.NET 2.0

OwnerDisplayName: Joe

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: spoulson


问:
how can i track which page i am on in asp.net-mvc
i have a link in a master page that says "Send feedback" which brings up a new web page:

When i go to that new page, i have a form and i want to populate a textbox with the URL that the person was on when they clicked the "Send Feedback" button.

How can i grab the current URL to pass that over?  should i do this on teh client side (jquery) or on the asp.net-mvc server side??

答:
You can do it Server Side(preferred) using

Request.UrlReferrer

For implementing it client side, use a hidden variable and then use a form post.

something like:

```<code><input type="hidden" id="referredPage" name="referredPage"/>

<script type="text/javascript">
    $(function(){
        $("form").submit(function(){
            $("#referredPage").val(window.location.href);
        });
    })
<script>
</code>```

Body:
You can do it Server Side(preferred) using

Request.UrlReferrer

For implementing it client side, use a hidden variable and then use a form post.

something like:

<input type="hidden" id="referredPage" name="referredPage"/>

<script type="text/javascript">
    $(function(){
        $("form").submit(function(){
            $("#referredPage").val(window.location.href);
        });
    })
<script>


问:
Google Sheets Sumifs with date condition
I'm getting an error when trying to grab the money I have spent for a month on another Google Sheet using SUMIFS formula. I'm new to writing formulas and this is the first bottleneck I haven't been able to find.

I'm trying to write a formula in my google sheet but getting an error. I'm new at this so forgive me.

In the Google Sheet, I have three Sheets (Summary, which is main), Leads and Spend.

I'm trying to write a formula to grab how much I spent for a particular month. In the Spend sheet, I have column for the date, name and dollar amount.

Here is the formula I have tried without luck.

```<code>Spend!G:G = Column with text for type of spend (Google PPC)
Spend!E:E = Column with cost of each spend
Spend!A:A = Column with the date
</code>```

```<code>=SUMIFS(Spend!G:G,"Google PPC",Spend!E:E,Spend!A:A,">=1/1/2019", Spend!A:A,"<=1/31/2019")
</code>```

It should just give me a total amount spent on the dates given. But I get an error that says "array arguments to SUMIFS are of different size"

答:
The first argument should be the range of cells to sum. Then follow a series of ranges and criteria.

```<code>=SUMIFS(Spend!E:E,
        Spend!G:G,"Google PPC",
        Spend!A:A,">=1/1/2019",
        Spend!A:A,"<=1/31/2019")
</code>```

see: SUMIFS documentation

Body:
I'm getting an error when trying to grab the money I have spent for a month on another Google Sheet using SUMIFS formula. I'm new to writing formulas and this is the first bottleneck I haven't been able to find.

I'm trying to write a formula in my google sheet but getting an error. I'm new at this so forgive me.

In the Google Sheet, I have three Sheets (Summary, which is main), Leads and Spend.

I'm trying to write a formula to grab how much I spent for a particular month. In the Spend sheet, I have column for the date, name and dollar amount.

Here is the formula I have tried without luck.

Spend!G:G = Column with text for type of spend (Google PPC)
Spend!E:E = Column with cost of each spend
Spend!A:A = Column with the date

=SUMIFS(Spend!G:G,"Google PPC",Spend!E:E,Spend!A:A,">=1/1/2019", Spend!A:A,"<=1/31/2019")

It should just give me a total amount spent on the dates given. But I get an error that says "array arguments to SUMIFS are of different size"

Body:
The first argument should be the range of cells to sum. Then follow a series of ranges and criteria.

=SUMIFS(Spend!E:E,
        Spend!G:G,"Google PPC",
        Spend!A:A,">=1/1/2019",
        Spend!A:A,"<=1/31/2019")

see: SUMIFS documentation


问:
Automapper - Get all entries in resolver
I'm working on a project heavily relying on Automapper, and most of the times we are mapping complete sets of data into a set view models, for example

```<code>IEnumerable<ObjectA> ListOfObjectA = MockupOfObjectA;
IEnumerable<ViewModelA> = Mapper.Map<IEnumerable<ObjectA>>(ListOfOjectA)
</code>```

In the mapping setup we are using Custom resolvers thanks to IMemberValueResolver. The parameters and accessible data in a Resolve and ResolveStatic-method, is only the current entity being mapped. Is it possible to access the complete source (ListOfOjectA) in this case, inside the resolver?

So far I am adding the ListOfOjectA into MappingOperationsOptions.Items and use them from context.Items, but this is a work around that is not easy to work with and does not scale well.

I hope I made my question relatively clear.

答:
You can map a collection of items from a dto collection or other class in a way under.

```<code>public Order Convert(OrderDto orderDto)
{
    var order = new Order { OrderLines = new OrderLines() };
    order.OrderLines = Mapper.Map<List<OrderLine>>(orderDto.Positions);
    return order;
}
</code>```

And your profile class constructor can be written in a way. This is a only a example. You do not need to accept a list in your resolver, you can do it for one object and map to list from outside.

```<code>    public Profile()
    {
      CreateMap<PositionDto, OrderLine>()
        .ForMember(dest => dest, opt => opt.ResolveUsing<OrderResolver>());
    }
  }
}
</code>```

Body:
I'm working on a project heavily relying on Automapper, and most of the times we are mapping complete sets of data into a set view models, for example

IEnumerable<ObjectA> ListOfObjectA = MockupOfObjectA;
IEnumerable<ViewModelA> = Mapper.Map<IEnumerable<ObjectA>>(ListOfOjectA)

In the mapping setup we are using Custom resolvers thanks to IMemberValueResolver. The parameters and accessible data in a Resolve and ResolveStatic-method, is only the current entity being mapped. Is it possible to access the complete source (ListOfOjectA) in this case, inside the resolver?

So far I am adding the ListOfOjectA into MappingOperationsOptions.Items and use them from context.Items, but this is a work around that is not easy to work with and does not scale well.

I hope I made my question relatively clear.

Body:
You can map a collection of items from a dto collection or other class in a way under.

public Order Convert(OrderDto orderDto)
{
    var order = new Order { OrderLines = new OrderLines() };
    order.OrderLines = Mapper.Map<List<OrderLine>>(orderDto.Positions);
    return order;
}

And your profile class constructor can be written in a way. This is a only a example. You do not need to accept a list in your resolver, you can do it for one object and map to list from outside.

    public Profile()
    {
      CreateMap<PositionDto, OrderLine>()
        .ForMember(dest => dest, opt => opt.ResolveUsing<OrderResolver>());
    }
  }
}


问:
ansible task with condition
I am using the below task in my play book and trying to set condition using "when" to trigger the task.

the blow one is working

```<code>ansible-playbook vdomqury.yml -e adom=In-Adom-01  -e FGT=FGVM04TM19001830  -e vdom= -vvv
</code>```

if i remove var vdom playbook stopped

ansible-playbook vdomqury.yml -e adom=In-Adom-01  -e FGT=FGVM04TM19001830  -vvv

```<code> tasks:
  - name: USE CUSTOM TYPE TO QUERY AVAILABLE SCRIPTS
    f_query:
      adom: "{{ adom }}"
      object: "custom"
      custom_endpoint: "/pm/config/adom/{{ adom }}/_package/status/{{ FGT }}/{{ vdom }}"
    register: results
    tags: ADDLAG
    when: vdom != ""

  - name: USE CUSTOM TYPE TO QUERY AVAILABLE SCRIPTS
    f_query:
      adom: "{{ adom }}"
      object: "custom"
      custom_endpoint: "/pm/config/adom/{{ adom }}/_package/status/{{ FGT }}"
    register: results
    tags: ADDLAG
    when: vdom == "" or vdom is not defined
</code>```

答: You should check if vdom is defined before making a comparison on it, otherwise the interpreter will unsuccessfully try to fetch its value. This should work (can't check right now): when: vdom is defined and vdom != "".

Title: ansible task with condition

Body:
I am using the below task in my play book and trying to set condition using "when" to trigger the task.

the blow one is working

ansible-playbook vdomqury.yml -e adom=In-Adom-01  -e FGT=FGVM04TM19001830  -e vdom= -vvv

if i remove var vdom playbook stopped

ansible-playbook vdomqury.yml -e adom=In-Adom-01  -e FGT=FGVM04TM19001830  -vvv

 tasks:
  - name: USE CUSTOM TYPE TO QUERY AVAILABLE SCRIPTS
    f_query:
      adom: "{{ adom }}"
      object: "custom"
      custom_endpoint: "/pm/config/adom/{{ adom }}/_package/status/{{ FGT }}/{{ vdom }}"
    register: results
    tags: ADDLAG
    when: vdom != ""

  - name: USE CUSTOM TYPE TO QUERY AVAILABLE SCRIPTS
    f_query:
      adom: "{{ adom }}"
      object: "custom"
      custom_endpoint: "/pm/config/adom/{{ adom }}/_package/status/{{ FGT }}"
    register: results
    tags: ADDLAG
    when: vdom == "" or vdom is not defined


问:
Linear models in R with different combinations of data frame variables
I have a data frame (myvar) with colnames from act1_1 to act1_144(dependent variable) filled in with numeric values and 7 columns with socio-demographics, DVAge, DVHsize, dhhtype, deconact, Income, NumChild and Rooms (independent variables).

```<code>independents<-DVType[, 1:144]
dependents<-DVType[, 145:151]

myvar<-cbind(dependents,independents)
</code>```

I am trying to generate a linear regression model using the socio-demographic columns variables and trying all the possible combination like Income, Income+Numchild, Income+Rooms,..., dhhtype+deconact .... I am having trouble generating combinations with data frame.

What I managed to do is to regress the dependent variables on the independent variable.

```<code> fit<-lm(as.matrix(dependents) ~ -1 + model.matrix(~ ., data = independents  ))
    require(broom)
    summary(fit)

Output:

    Response DVHsize :

    Call:
    lm(formula = DVHsize ~ -1 + model.matrix(~., data = independents))

    Residuals:
        Min      1Q  Median      3Q     Max
    -3.1356 -1.0056 -0.2886  0.9597  7.2341

    Coefficients:
                                                       Estimate Std. Error t value Pr(>|t|)
    model.matrix(~., data = independents)(Intercept)  3.616e+00  4.300e-02  84.096  < 2e-16 ***
    model.matrix(~., data = independents)act1_1      -2.788e-05  2.911e-05  -0.958  0.33822
    model.matrix(~., data = independents)act1_2       3.703e-05  2.898e-05   1.278  0.20138
    model.matrix(~., data = independents)act1_3      -4.458e-06  2.177e-05  -0.205  0.83773
    model.matrix(~., data = independents)act1_4       2.120e-05  2.557e-05   0.829  0.40705
    model.matrix(~., data = independents)act1_5       2.327e-05  2.724e-05   0.854  0.39296
    model.matrix(~., data = independents)act1_6      -4.578e-05  2.299e-05  -1.991  0.04644 *
    model.matrix(~., data = independents)act1_7       2.087e-05  1.971e-05   1.058  0.28985
    model.matrix(~., data = independents)act1_8      -4.694e-06  2.019e-05  -0.233  0.81612
    model.matrix(~., data = independents)act1_9       3.604e-06  1.756e-05   0.205  0.83738
    model.matrix(~., data = independents)act1_10     -2.924e-06  1.685e-05  -0.174  0.86225
    model.matrix(~., data = independents)act1_11      4.934e-06  1.671e-05   0.295  0.76782

....
</code>```

How can extend this to identify all combinations?

答:
If I understand correctly, your formula is wrong,
your predictors (independents) should be the 7 columns you mention.
I'm not sure if "all possible combinations" is exactly what you want,
maybe you only want second-order interactions (and no intercept due to the -1)?
In that case, you can probably do the following
(see also this question):

```<code>fit <- lm(sprintf("cbind(%s) ~ . ^ 2 - 1",
                  toString(paste("act1", 1:144, sep = "_"))),
          data = DVType)
</code>```

Body:
I have a data frame (myvar) with colnames from act1_1 to act1_144(dependent variable) filled in with numeric values and 7 columns with socio-demographics, DVAge, DVHsize, dhhtype, deconact, Income, NumChild and Rooms (independent variables).

independents<-DVType[, 1:144]
dependents<-DVType[, 145:151]

myvar<-cbind(dependents,independents)

I am trying to generate a linear regression model using the socio-demographic columns variables and trying all the possible combination like Income, Income+Numchild, Income+Rooms,..., dhhtype+deconact .... I am having trouble generating combinations with data frame.

What I managed to do is to regress the dependent variables on the independent variable.

 fit<-lm(as.matrix(dependents) ~ -1 + model.matrix(~ ., data = independents  ))
    require(broom)
    summary(fit)

Output:

    Response DVHsize :

    Call:
    lm(formula = DVHsize ~ -1 + model.matrix(~., data = independents))

    Residuals:
        Min      1Q  Median      3Q     Max
    -3.1356 -1.0056 -0.2886  0.9597  7.2341

    Coefficients:
                                                       Estimate Std. Error t value Pr(>|t|)
    model.matrix(~., data = independents)(Intercept)  3.616e+00  4.300e-02  84.096  < 2e-16 ***
    model.matrix(~., data = independents)act1_1      -2.788e-05  2.911e-05  -0.958  0.33822
    model.matrix(~., data = independents)act1_2       3.703e-05  2.898e-05   1.278  0.20138
    model.matrix(~., data = independents)act1_3      -4.458e-06  2.177e-05  -0.205  0.83773
    model.matrix(~., data = independents)act1_4       2.120e-05  2.557e-05   0.829  0.40705
    model.matrix(~., data = independents)act1_5       2.327e-05  2.724e-05   0.854  0.39296
    model.matrix(~., data = independents)act1_6      -4.578e-05  2.299e-05  -1.991  0.04644 *
    model.matrix(~., data = independents)act1_7       2.087e-05  1.971e-05   1.058  0.28985
    model.matrix(~., data = independents)act1_8      -4.694e-06  2.019e-05  -0.233  0.81612
    model.matrix(~., data = independents)act1_9       3.604e-06  1.756e-05   0.205  0.83738
    model.matrix(~., data = independents)act1_10     -2.924e-06  1.685e-05  -0.174  0.86225
    model.matrix(~., data = independents)act1_11      4.934e-06  1.671e-05   0.295  0.76782

....

How can extend this to identify all combinations?

Body:
If I understand correctly, your formula is wrong,
your predictors (independents) should be the 7 columns you mention.
I'm not sure if "all possible combinations" is exactly what you want,
maybe you only want second-order interactions (and no intercept due to the -1)?
In that case, you can probably do the following
(see also this question):

fit <- lm(sprintf("cbind(%s) ~ . ^ 2 - 1",
                  toString(paste("act1", 1:144, sep = "_"))),
          data = DVType)


问:
Flutter: Widget State: Is this code safe?
The code below is an example to illustrate this question. The code below works, however the following line:

```<code>class WidgetCustom extends StatefulWidget {
</code>```

has "WidgetCustom" underlined in green in vsCode, and when the cursor is positioned over it, it shows the message:
"This class (or a class this class inherits from) is marked as @immutable, but one or more of its instance fields are not final".

The code works fine.

Is it safe to use this code?

Is there a way to achieve this without the warning?

```<code>import 'package:flutter/material.dart';

class WidgetCustom extends StatefulWidget {

  _WidgetCustomState _state;

  WidgetCustom({@required int iCount}) {
    _state = _WidgetCustomState(iCount);
  }

  @override
  State<StatefulWidget> createState() {
    return _state;
  }

  int get getIcount => _state.iCount;
}

class _WidgetCustomState extends State<WidgetCustom> {
  int iCount;

  _WidgetCustomState(this.iCount);

  @override
  Widget build(BuildContext context) {
    return Container(
        child: Row(children: <Widget>[
      Column(
        children: <Widget>[
          RaisedButton(
              child: const Text("Please tap me"),
              onPressed: () {
                setState(() => iCount = iCount + 1);
              }),
          SizedBox(height: 40),
          Text("Tapped $iCount Times")
        ],
      ),
    ]));
  }
}
</code>```

Edited to add main.dart

```<code>import 'package:flutter/material.dart';
import 'widgetCustom.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Custom Widget Demo'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  WidgetCustom _widgetCustom;
  String _sMessage = "Fab has not been pressed";
  @override
  void initState() {
    super.initState();
    _widgetCustom = WidgetCustom(iCount: 99);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Column(children: [
        _widgetCustom,
        SizedBox(height: 40),
        Text(_sMessage),
      ]),
      floatingActionButton: FloatingActionButton(
        onPressed: _fabPressed,
        tooltip: 'Get Value',
        child: Icon(Icons.add),
      ),
    );
  }

  _fabPressed() {
    setState(() => _sMessage =
        "Value from last button click = ${_widgetCustom.getIcount}");
  }
}

</code>```

答:
Updated code:</p>

```<code>void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData.dark(),
      home: MyHomePage(title: 'Custom Widget Demo'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  WidgetCustom _widgetCustom;
  String _sMessage = "Fab has not been pressed";
  int _value = 99;

  @override
  void initState() {
    super.initState();
    _widgetCustom = WidgetCustom(iCount: _value, function: _update);
  }

  void _update(int value) {
    setState(() {
      _value = value;
      _widgetCustom = WidgetCustom(iCount: _value, function: _update);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(widget.title)),
      body: Column(
        children: [
          _widgetCustom,
          SizedBox(height: 40),
          Text(_sMessage),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _fabPressed,
        tooltip: 'Get Value',
        child: Icon(Icons.add),
      ),
    );
  }

  _fabPressed() {
    setState(() => _sMessage = "Value from last button click = ${_value}");
  }
}

class WidgetCustom extends StatefulWidget {
  final int iCount;
  final Function function;

  WidgetCustom({@required this.iCount, this.function});

  @override
  State<StatefulWidget> createState() {
    return _WidgetCustomState();
  }
}

class _WidgetCustomState extends State<WidgetCustom> {
  int _iCount;

  @override
  void initState() {
    super.initState();
    _iCount = widget.iCount;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Row(
        children: <Widget>[
          Column(
            children: <Widget>[
              RaisedButton(child: const Text("Please tap me"), onPressed: (){
                _iCount = _iCount + 1;
                widget.function(_iCount);
              }),
              SizedBox(height: 40),
              Text("Tapped $_iCount Times")
            ],
          ),
        ],
      ),
    );
  }
}
</code>```

Body:
The code below is an example to illustrate this question. The code below works, however the following line:

class WidgetCustom extends StatefulWidget {

has "WidgetCustom" underlined in green in vsCode, and when the cursor is positioned over it, it shows the message:
"This class (or a class this class inherits from) is marked as @immutable, but one or more of its instance fields are not final".

The code works fine.

Is it safe to use this code?

Is there a way to achieve this without the warning?

import 'package:flutter/material.dart';

class WidgetCustom extends StatefulWidget {

  _WidgetCustomState _state;

  WidgetCustom({@required int iCount}) {
    _state = _WidgetCustomState(iCount);
  }

  @override
  State<StatefulWidget> createState() {
    return _state;
  }

  int get getIcount => _state.iCount;
}

class _WidgetCustomState extends State<WidgetCustom> {
  int iCount;

  _WidgetCustomState(this.iCount);

  @override
  Widget build(BuildContext context) {
    return Container(
        child: Row(children: <Widget>[
      Column(
        children: <Widget>[
          RaisedButton(
              child: const Text("Please tap me"),
              onPressed: () {
                setState(() => iCount = iCount + 1);
              }),
          SizedBox(height: 40),
          Text("Tapped $iCount Times")
        ],
      ),
    ]));
  }
}

Edited to add main.dart

import 'package:flutter/material.dart';
import 'widgetCustom.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Custom Widget Demo'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  WidgetCustom _widgetCustom;
  String _sMessage = "Fab has not been pressed";
  @override
  void initState() {
    super.initState();
    _widgetCustom = WidgetCustom(iCount: 99);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Column(children: [
        _widgetCustom,
        SizedBox(height: 40),
        Text(_sMessage),
      ]),
      floatingActionButton: FloatingActionButton(
        onPressed: _fabPressed,
        tooltip: 'Get Value',
        child: Icon(Icons.add),
      ),
    );
  }

  _fabPressed() {
    setState(() => _sMessage =
        "Value from last button click = ${_widgetCustom.getIcount}");
  }
}

Body:
Updated code:

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData.dark(),
      home: MyHomePage(title: 'Custom Widget Demo'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  WidgetCustom _widgetCustom;
  String _sMessage = "Fab has not been pressed";
  int _value = 99;

  @override
  void initState() {
    super.initState();
    _widgetCustom = WidgetCustom(iCount: _value, function: _update);
  }

  void _update(int value) {
    setState(() {
      _value = value;
      _widgetCustom = WidgetCustom(iCount: _value, function: _update);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(widget.title)),
      body: Column(
        children: [
          _widgetCustom,
          SizedBox(height: 40),
          Text(_sMessage),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _fabPressed,
        tooltip: 'Get Value',
        child: Icon(Icons.add),
      ),
    );
  }

  _fabPressed() {
    setState(() => _sMessage = "Value from last button click = ${_value}");
  }
}

class WidgetCustom extends StatefulWidget {
  final int iCount;
  final Function function;

  WidgetCustom({@required this.iCount, this.function});

  @override
  State<StatefulWidget> createState() {
    return _WidgetCustomState();
  }
}

class _WidgetCustomState extends State<WidgetCustom> {
  int _iCount;

  @override
  void initState() {
    super.initState();
    _iCount = widget.iCount;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Row(
        children: <Widget>[
          Column(
            children: <Widget>[
              RaisedButton(child: const Text("Please tap me"), onPressed: (){
                _iCount = _iCount + 1;
                widget.function(_iCount);
              }),
              SizedBox(height: 40),
              Text("Tapped $_iCount Times")
            ],
          ),
        ],
      ),
    );
  }
}


问:
can't open /dev/tty(2,3,4). No such file or directory
When starting QEMU with Busybox (1.30.1) (lkeep getting error
can't open /dev/tty2: No such file or directory
can't open /dev/tty2: No such file or directory
can't open /dev/tty3: No such file or directory
Busybox is running because when I run ls, I see the directories.
Found suggestions online to edit inittab but don't have one in /etc. So I put one there but didn't fix the issue. INITTAB is is enabled in the Busybox .config

thanks

答:
from target root console:</p>

```<code> ln -sf /dev/null /dev/tty2
 ln -sf /dev/null /dev/tty3
</code>```

Body:
from target root console:

 ln -sf /dev/null /dev/tty2
 ln -sf /dev/null /dev/tty3


问:
A few questions about ProgressDialog in Android

1) FOA PD (ProgressDialog) can be created only from Activity, doesn't it? Please provide an useful example if it is really not.

2) If a PD should be created in separate thread could it be created and showed if it's thread doesn't do anything at all? I mean something like this (assuming mProgressDialog is a property of the class):

```<code>new Thread(){
      public void run(){
          mProgressDialog = ProgressDialog.show(appContext,
                  appContext.getResources().getString(R.string.progress_wait),
                  appContext.getResources().getString(R.string.progress_db_installing),
                  true);

  }.start();
</code>```

As I understand the thread dies immediately after executing run() cause there is nothing to do and so PD doesn't show. It should have some processing code or at least an empty cycle with some manageable condition

3) if PD should be created in the main thread should it be created only at the end of OnCreate() method or in the body of some method called/caught(by some Listener) started  in OnCreate() method?

4) PD by itself doesn't suspend any thread while displaying, does it? So the code continues executing after the show() method . I mean the show() by itself doesn't suspend/pause the thread cause I guessed it does.

答:
1) Not sure how it's relevant unless you can come up with a reason to create a ProgressDialog outside of an Activity context; I think the answer is "no," though.

2) No, you can't create a dialog from a background thread directly. Have you tried your code? It'll die with an exception with a helpful traceback. See any one of a number of SO questions about how to call back to the UI thread to do things like show dialogs.

3) You can create it anywhere in your activity; for example, it's common to do this in onPreExecute() in an AsyncTask, which may be triggered from an onClick callback.

4) No.

Body:
1) FOA PD (ProgressDialog) can be created only from Activity, doesn't it? Please provide an useful example if it is really not.

2) If a PD should be created in separate thread could it be created and showed if it's thread doesn't do anything at all? I mean something like this (assuming mProgressDialog is a property of the class):

new Thread(){
      public void run(){
          mProgressDialog = ProgressDialog.show(appContext,
                  appContext.getResources().getString(R.string.progress_wait),
                  appContext.getResources().getString(R.string.progress_db_installing),
                  true);

  }.start();

As I understand the thread dies immediately after executing run() cause there is nothing to do and so PD doesn't show. It should have some processing code or at least an empty cycle with some manageable condition

3) if PD should be created in the main thread should it be created only at the end of OnCreate() method or in the body of some method called/caught(by some Listener) started  in OnCreate() method?

4) PD by itself doesn't suspend any thread while displaying, does it? So the code continues executing after the show() method . I mean the show() by itself doesn't suspend/pause the thread cause I guessed it does.


问:
How to add two time values together in SQL
I have a table with 'accumulate_low_risk' and 'accumulate_high_risk'. Both are timedata (time(7)) in the format 00:00:00.0000000.

I want to add them together and place them into another timedata called 'combined_shift_total'

I have tried to convert them to seconds, add the results together and convert them back to timedata but i'm getting lost.

The table is as follows:

```<code>CREATE TABLE accumulate_time ('id INT IDENTITY(1,1) PRIMARY KEY,time DATETIME NOT NULL,worker_id INTEGER NOT NULL REFERENCES worker_table(worker_id),shift_start DATETIME NOT NULL,accumulate_low_risk TIME NOT NULL,accumulate_high_risk TIME NOT NULL,combined_shift_total TIME NOT NULL)
</code>```

I was trying something along the lines of....

```<code>select Sum(Left (CONVERT(nvarchar(30),accumulate_low_risk, 126),2) * 3600 + substring(accumulate_low_risk, 4,2) * 60 + substring(accumulate_low_risk, 7,2))
from accumulate_time WHERE id IN (SELECT max(id) FROM accumulate_time WHERE worker_id = 6)
</code>```

But this is way too messy.

My knowledge of SQL is limited so I'm sure there's a simple way to achieve this.

I would be very grateful for any and all help.

Thanks!

答:
To me it looks like SQL Server. You can achieve it by counting how many seconds you have in your columns using datediff() and then add it to 00:00:00.0000000 using dateadd(). Please note that I don't know how precise is your data, so if you want it to me more precise you need to i.e. change second to milisecond. It's shift data so it shouldn't excess 24 hours, but please note what in this case it wouldn't work.

```<code>select cast(dateadd(second, datediff(second, '00:00:00.0000000', accumulate_low_risk) + datediff(second, '00:00:00.0000000', accumulate_high_risk), '2019-01-01') as time(7))
from accumulate_time
</code>```

An examply how it works on a temp table:

```<code>create table #time (t1 time(7), t2 time(7))
insert into #time values ('01:12:04.0000000','00:12:04.0000000')

select cast(dateadd(second, datediff(second, '00:00:00.0000000', t1) + datediff(second, '00:00:00.0000000', t2), '2019-01-01') as time(7))
from #time
</code>```

Body:
I have a table with 'accumulate_low_risk' and 'accumulate_high_risk'. Both are timedata (time(7)) in the format 00:00:00.0000000.

I want to add them together and place them into another timedata called 'combined_shift_total'

I have tried to convert them to seconds, add the results together and convert them back to timedata but i'm getting lost.

The table is as follows:

CREATE TABLE accumulate_time ('id INT IDENTITY(1,1) PRIMARY KEY,time DATETIME NOT NULL,worker_id INTEGER NOT NULL REFERENCES worker_table(worker_id),shift_start DATETIME NOT NULL,accumulate_low_risk TIME NOT NULL,accumulate_high_risk TIME NOT NULL,combined_shift_total TIME NOT NULL)

I was trying something along the lines of....

select Sum(Left (CONVERT(nvarchar(30),accumulate_low_risk, 126),2) * 3600 + substring(accumulate_low_risk, 4,2) * 60 + substring(accumulate_low_risk, 7,2))
from accumulate_time WHERE id IN (SELECT max(id) FROM accumulate_time WHERE worker_id = 6)

But this is way too messy.

My knowledge of SQL is limited so I'm sure there's a simple way to achieve this.

I would be very grateful for any and all help.

Thanks!

Body:
To me it looks like SQL Server. You can achieve it by counting how many seconds you have in your columns using datediff() and then add it to 00:00:00.0000000 using dateadd(). Please note that I don't know how precise is your data, so if you want it to me more precise you need to i.e. change second to milisecond. It's shift data so it shouldn't excess 24 hours, but please note what in this case it wouldn't work.

select cast(dateadd(second, datediff(second, '00:00:00.0000000', accumulate_low_risk) + datediff(second, '00:00:00.0000000', accumulate_high_risk), '2019-01-01') as time(7))
from accumulate_time

An examply how it works on a temp table:

create table #time (t1 time(7), t2 time(7))
insert into #time values ('01:12:04.0000000','00:12:04.0000000')

select cast(dateadd(second, datediff(second, '00:00:00.0000000', t1) + datediff(second, '00:00:00.0000000', t2), '2019-01-01') as time(7))
from #time


问:
Save JPA entity model with XML column in Postgres
Postgres supports xml as is datatype for a column.
Hence I have a model that goes like this

```<code>@Entity
class StorageOfXml {
    @Id
    String id;

    @Lob
    @Column(columnDefinition="xml")
    String myXml;
}
</code>```

When I try to persist the model using entity manager, it gives me an error

```<code>StorageOfXml s = new StorageOfXml()
s.setId("sample");
s.setMyXml("<foo><bar></bar></foo>");

entityManager.persist(s)
</code>```

Error is

```<code>Internal Exception: org.postgresql.util.PSQLException: ERROR: column "myXml" is of type xml but expression is of type character varying
  Hint: You will need to rewrite or cast the expression.
</code>```

I notice that I need to cast the string to an xml format. However, I don't know where and how to cast it. How should I be able to persist and fetch this?

答: Without using hibernate or jaxb and if you really really want to save "myXml" as pg xml type, one solution would be to use XMLPARSE on a statement as the accepted answer in this post suggests: How can I insert an XML document in PostgreSQL in Java?</p>

Body:
Postgres supports xml as is datatype for a column.
Hence I have a model that goes like this

@Entity
class StorageOfXml {
    @Id
    String id;

    @Lob
    @Column(columnDefinition="xml")
    String myXml;
}

When I try to persist the model using entity manager, it gives me an error

StorageOfXml s = new StorageOfXml()
s.setId("sample");
s.setMyXml("<foo><bar></bar></foo>");

entityManager.persist(s)

Error is

Internal Exception: org.postgresql.util.PSQLException: ERROR: column "myXml" is of type xml but expression is of type character varying
  Hint: You will need to rewrite or cast the expression.

I notice that I need to cast the string to an xml format. However, I don't know where and how to cast it. How should I be able to persist and fetch this?