问:
InvalidClientTokenID error when running Terraform Plan/Apply
I'm setting up a HA cluster in AWS using Terraform and user data. My main.tf looks like this:

```<code>provider "aws" {
access_key = "access_key"
secret_key = "secret_key"
}

resource "aws_instance" "etcd" {
ami = "${var.ami}" // coreOS 17508
instance_type = "${var.instance_type}"
key_name = "${var.key_name}"
key_path = "${var.key_path}"
count = "${var.count}"
region = "${var.aws_region}"
user_data = "${file("cloud-config.yml")}"

subnet_id = "${aws_subnet.k8s.id}"
private_ip = "${cidrhost("10.43.0.0/16", 10 + count.index)}"
associate_public_ip_address = true

vpc_security_group_ids = ["${aws_security_group.terraform_swarm.id}"]

tags {
name = "coreOS-master"
}
}
</code>```

However, when I run terraform plan I get the following error provider.aws: InvalidClientTokenId: The security token included in the request is invalid.
    status code: 403, request id: 45099d1a-4d6a-11e8-891c-df22e6789996

I've looked around some suggestions were to clear out my ~/.aws/credentials file or update it with the new aws IAM credentials. I'm pretty lost on how to fix this error.

答: Make sure that your access key and secret are correct. I have used Static credentials and substituting variables using variables.tf. The latest error also points to the documentation. Start with making Static Credentials work.</p>

Body:
I'm setting up a HA cluster in AWS using Terraform and user data. My main.tf looks like this:

provider "aws" {
access_key = "access_key"
secret_key = "secret_key"
}

resource "aws_instance" "etcd" {
ami = "${var.ami}" // coreOS 17508
instance_type = "${var.instance_type}"
key_name = "${var.key_name}"
key_path = "${var.key_path}"
count = "${var.count}"
region = "${var.aws_region}"
user_data = "${file("cloud-config.yml")}"

subnet_id = "${aws_subnet.k8s.id}"
private_ip = "${cidrhost("10.43.0.0/16", 10 + count.index)}"
associate_public_ip_address = true

vpc_security_group_ids = ["${aws_security_group.terraform_swarm.id}"]

tags {
name = "coreOS-master"
}
}

However, when I run terraform plan I get the following error provider.aws: InvalidClientTokenId: The security token included in the request is invalid.
    status code: 403, request id: 45099d1a-4d6a-11e8-891c-df22e6789996

I've looked around some suggestions were to clear out my ~/.aws/credentials file or update it with the new aws IAM credentials. I'm pretty lost on how to fix this error.


来源: stackexchange

问:
How To Replace < with < and > with > using jquery
I have a page that is part of a backend CRM admin panel. On that page the HTML output comes from some PHP functions that I can't access. And that HTML automatically changes < and > into HTML encoded characters.

So there is a div that contains html tags like
 that is converted into

So I need to change it back to the HTML characters using only jQuery:

< to <

> to >

Is there a jQuery script I can use to replace those special characters with the corresponding symbols? This will mean my HTML tags will actually work and the HTML will being displayed properly on the screen?

I've tried removewith() but i can't make it work.

ADDED:
The div that im trying to modify is this

```<code><div style="font-size: 11px; width: 90%; font-family: Tahoma;" id="cotiz"><strong>Valuación</strong> de InfoAuto: 35.500,00<br />
Cotización Seleccionada: Ninguna<br />
Allianz, Responsabilidad Civil: $205,25<br />
Allianz, Terceros Completos: $278,85 </div>
</code>```

答:
I needed to step to find an H1 then parse the next element, because I wasn't able to use a specific ID like you did. Good tip!</p>

```<code>$('#sscContent').find("h1").next().each(function(){
    var $this = $(this);
    var t = $this.text();
    $this.html(t.replace('<','<').replace('>', '>'));
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a page that is part of a backend CRM admin panel. On that page the HTML output comes from some PHP functions that I can't access. And that HTML automatically changes < and > into HTML encoded characters.

So there is a div that contains html tags like
 that is converted into

So I need to change it back to the HTML characters using only jQuery:

< to <

> to >

Is there a jQuery script I can use to replace those special characters with the corresponding symbols? This will mean my HTML tags will actually work and the HTML will being displayed properly on the screen?

I've tried removewith() but i can't make it work.

ADDED:
The div that im trying to modify is this

Valuación de InfoAuto: 35.500,00

Cotización Seleccionada: Ninguna

Allianz, Responsabilidad Civil: $205,25

Allianz, Terceros Completos: $278,85

Body:
I needed to step to find an H1 then parse the next element, because I wasn't able to use a specific ID like you did. Good tip!

$('#sscContent').find("h1").next().each(function(){
    var $this = $(this);
    var t = $this.text();
    $this.html(t.replace('&lt;','<').replace('&gt;', '>'));
});

ContentLicense: CC BY-SA 4.0


问:
How to access collection and documents within it in React.js?
So, basically I have started bulding new app with React, Redux and Firebase.
I am still learning and am not able to solve some things but this is the first moment, when I am really stuck.

I have created a collection in the Firestore called 'posts' and created one post manually just to see if it is working.

Unfortunately, after implementing my code I keep receiving an error:

```<code>TypeError: Cannot read property 'posts' of undefined
AdminpanelAuth.componentDidMount
/src/components/Admin/Adminpanel.js:23
  20 |    componentDidMount() {
  21 |        this.setState({ loading: true });
  22 |
> 23 |        this.props.firebase.posts().on('value', snapshot => { <- HERE IS THE PROBLEM
</code>```

I have tried different variations and different approaches but none of them seemed to be working. Could anyone advise? Below I am attaching a part of my code of Adminpanel.js and Firebase.js

Firebase.js

```<code>import app from 'firebase/app';
import 'firebase/auth';
import 'firebase/firestore';

const firebaseConfig = {
    my config here
  };

  class Firebase {
    constructor() {
      app.initializeApp(firebaseConfig);
      // initialize Firebase Authenticator
      this.auth = app.auth();
      // initialize Firebase Realtime Database
      this.db = app.firestore();

    }

    // Initialize two functions that connect to Firebase : Log In and Log Out

    doSignInWithEmailAndPassword = (email, password) =>
    this.auth.signInWithEmailAndPassword(email, password);

    doSignOut = () => this.auth.signOut();

    // Initialize functions for posts

    post = pid => this.db.doc('posts'+pid);
    posts = () => this.db.collection('posts');
  }

export default Firebase;
</code>```

Adminpanel.js

```<code>import React, { Component } from 'react'
import { connect } from 'react-redux'
import { compose } from 'recompose'
import { withFirebase } from '../Firebase'
import { withAuthorisation } from '../Session'
import SignOutBtn from '../SignOutBtn'

const Adminpanel = ({authUser}) => (
<div>{authUser ? <AdminpanelAuth /> : <AdminpanelNonAuth />}</div>
)

class AdminpanelAuth extends Component {
    constructor(props) {
        super(props);
        this.state = {
            loading:false,
            posts:[]
        }
    }
    componentDidMount() {
        this.setState({ loading: true });

        this.props.firebase.posts().on('value', snapshot => {
      const postsObject = snapshot.val();

      const postsList = Object.keys(postsObject).map(key => ({
        ...postsObject[key],
        pid: key,
      }));

      this.setState({
        posts: postsList,
        loading: false,
      });
        });
    }
</code>```

./Firebase/index.js

```<code>import FirebaseContext, { withFirebase } from './context';
import Firebase from './Firebase';

export default Firebase;

export { FirebaseContext, withFirebase };
</code>```

答:
It looks as though your problem might be that you are trying to access your Firebase class through props when it needs to be instantiated in your Adminpanel component.

In your imports you have:

```<code>import { withFirebase } from '../Firebase'
</code>```

Which looks as though you are trying to use an HOC but looking at Firebase.js, there is no indication of you passing a component in, to then pass props to.

Instead, in your Adminpanel component, try changing your import to:

```<code>import Firebase from '../Firebase'
</code>```

Then, in the constructor of Adminpanel:

```<code>constructor(props) {
    super(props);
    this.state = {
        loading:false,
        posts:[]
    }
  this.firebase = new Firebase()
}
</code>```

Then, try to call the class method by doing:

```<code>this.firebase.posts().on('value', snapshot => {
</code>```

Body:
So, basically I have started bulding new app with React, Redux and Firebase.
I am still learning and am not able to solve some things but this is the first moment, when I am really stuck.

I have created a collection in the Firestore called 'posts' and created one post manually just to see if it is working.

Unfortunately, after implementing my code I keep receiving an error:

TypeError: Cannot read property 'posts' of undefined
AdminpanelAuth.componentDidMount
/src/components/Admin/Adminpanel.js:23
  20 |    componentDidMount() {
  21 |        this.setState({ loading: true });
  22 |
> 23 |        this.props.firebase.posts().on('value', snapshot => { <- HERE IS THE PROBLEM

I have tried different variations and different approaches but none of them seemed to be working. Could anyone advise? Below I am attaching a part of my code of Adminpanel.js and Firebase.js

Firebase.js

import app from 'firebase/app';
import 'firebase/auth';
import 'firebase/firestore';

const firebaseConfig = {
    my config here
  };

  class Firebase {
    constructor() {
      app.initializeApp(firebaseConfig);
      // initialize Firebase Authenticator
      this.auth = app.auth();
      // initialize Firebase Realtime Database
      this.db = app.firestore();

    }

    // Initialize two functions that connect to Firebase : Log In and Log Out

    doSignInWithEmailAndPassword = (email, password) =>
    this.auth.signInWithEmailAndPassword(email, password);

    doSignOut = () => this.auth.signOut();

    // Initialize functions for posts

    post = pid => this.db.doc('posts'+pid);
    posts = () => this.db.collection('posts');
  }

export default Firebase;

Adminpanel.js

import React, { Component } from 'react'
import { connect } from 'react-redux'
import { compose } from 'recompose'
import { withFirebase } from '../Firebase'
import { withAuthorisation } from '../Session'
import SignOutBtn from '../SignOutBtn'

const Adminpanel = ({authUser}) => (

{authUser ? <AdminpanelAuth /> : <AdminpanelNonAuth />}

)

class AdminpanelAuth extends Component {
    constructor(props) {
        super(props);
        this.state = {
            loading:false,
            posts:[]
        }
    }
    componentDidMount() {
        this.setState({ loading: true });

        this.props.firebase.posts().on('value', snapshot => {
      const postsObject = snapshot.val();

      const postsList = Object.keys(postsObject).map(key => ({
        ...postsObject[key],
        pid: key,
      }));

      this.setState({
        posts: postsList,
        loading: false,
      });
        });
    }

./Firebase/index.js

import FirebaseContext, { withFirebase } from './context';
import Firebase from './Firebase';

export default Firebase;

export { FirebaseContext, withFirebase };

Body:
It looks as though your problem might be that you are trying to access your Firebase class through props when it needs to be instantiated in your Adminpanel component.

In your imports you have:

import { withFirebase } from '../Firebase'

Which looks as though you are trying to use an HOC but looking at Firebase.js, there is no indication of you passing a component in, to then pass props to.

Instead, in your Adminpanel component, try changing your import to:

import Firebase from '../Firebase'

Then, in the constructor of Adminpanel:

constructor(props) {
    super(props);
    this.state = {
        loading:false,
        posts:[]
    }
  this.firebase = new Firebase()
}

Then, try to call the class method by doing:

this.firebase.posts().on('value', snapshot => {


问:
Proper way to set ServicePointManager.SecurityProcol when using an unmanaged executable
I have an unmanaged (C++) program that uses multiple managed (C#) DLLs via COM and I need those DLLs to use TLS1.2. All the DLLs target .NET 4.6 or higher,  but that doesn't seem to matter.

When I run managed programs that target .NET 4.6 and 4.7 and call a managed DLL, the SecurityProtocol is set to Tls, Tls11, Tls12 andSystemDefault, respectively, and TLS1.2 is used. When I run my unmanaged program and call the same managed DLL, the SecurityProtocol is set to Ssl3, Tls and it does not use TLS1.2.

What doesn't work:

Setting the supportedRuntime in MyProgram.exe.config. Adding <startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7" /></startup> to the config file had no effect on the SecurityProtocol.

What works, but is not optimal:

Creating a new DLL that explicitly sets the SecurityProtocol and calling it in the unmanaged program before anything else; the SecurityProtocol will then be correctly set for calls to all other DLLs. This works well but I don't want to add another dependency to my project just for this.

Setting AppContextSwitchOverrides in the config file by adding the line <AppContextSwitchOverrides value="Switch.System.Net.DontEnableSchUseStrongCrypto=false" /> will cause the SecurityProtocol to be Tls, Tls11, Tls12. This works well, but seems like a hack that exploits undocumented (and possibly unintended) behavior.

Is there any better way to get the managed DLLs' SecurityProtocol to use either Tls12 or SystemDefault when running my unmanaged program? Thanks.

答: Simon Mourier was correct, setting <AppContextSwitchOverrides value="Switch.System.Net.DontEnableSchUseStrongCrypto=false" /> in the config file is the official way to add Tls12 as a default protocol.


问:
With higher-order functions in Kotlin, why are lambdas shown outside of other function parameters?
In some training I'm reviewing, I don't understand exactly how an example higher-order function and lambda are connected through syntax

This higher-order Kotlin function

```<code>fun myWith(name: String, block: String.() -> Unit) {
  name.block()
}
</code>```

Is invoked like this

```<code>myWith(fish.name) {
  capitalize()
}

</code>```

I understand the second part is a lambda but I don't understand why it's not included as a second parameter to the function and just hung outside of the parameters. Like why is it not invoked as:

```<code>myWith(fish.name, { capitalize() } )
</code>```

Later a more verbose description of the example is shown as

```<code>myWith(fish.name, object : Function1<String, Unit> {
  override fun invoke(name: String) {
    name.capitalize()
  }
})
</code>```

Which IS including the lambda inside the normal list of parameters to myWith

答:
In Kotlin, there is a convention that if the last parameter of a function accepts a function, a lambda expression that is passed as the corresponding argument can be placed outside the parentheses.

Source: https://kotlinlang.org/docs/reference/lambdas.html#passing-a-lambda-to-the-last-parameter

Body:
In some training I'm reviewing, I don't understand exactly how an example higher-order function and lambda are connected through syntax

This higher-order Kotlin function

fun myWith(name: String, block: String.() -> Unit) {
  name.block()
}

Is invoked like this

myWith(fish.name) {
  capitalize()
}

I understand the second part is a lambda but I don't understand why it's not included as a second parameter to the function and just hung outside of the parameters. Like why is it not invoked as:

myWith(fish.name, { capitalize() } )

Later a more verbose description of the example is shown as

myWith(fish.name, object : Function1<String, Unit> {
  override fun invoke(name: String) {
    name.capitalize()
  }
})

Which IS including the lambda inside the normal list of parameters to myWith


问:
How do I select the parent form based on which submit button is clicked?
I have a web page with 3 forms on it.  Not nested, just one after the other (they are almost identical, just one hidden variable that's different).  A user will only fill in one form, and I'd like to validate/etc all the forms with only one JS script.

So how, when a user clicks the submit button of form#1, do I make my js script only deal with the fields in form1?  I gather it has something to do with $(this).parents , but I am not sure what to do with it.

My validation script (which I used elsewhere, with only a single form) looks something like so:

```
<code>
$(document).ready(function(){
    $("#submit").click(function(){
        $(".error").hide();
        var hasError = false;

        var nameVal = $("#name").val();
        if(nameVal == '') {
            $("#name").after('Please enter your name.');
            hasError = true;
        }

        if(hasError == false) {blah blah do all the processing stuff}
</code>
```

So do I need to replace things like $("#name").val() with $(this).parents('form').name.val() ?  Or is there a better way to go about this?

Thanks!

答:
I found this answer when searching for how to find the form of an input element. I wanted to add a note because there is now a better way than using:

```<code>var form = $(this).parents('form:first');
</code>```

I'm not sure when it was added to jQuery but the closest() method does exactly what's needed more cleanly than using parents(). With closest the code can be changed to this:

```<code>var form = $(this).closest('form');
</code>```

It traverses up and finds the first element which matches what you are looking for and stops there, so there's no need to specify :first.

OwnerDisplayName: Eileen

Body:
I have a web page with 3 forms on it.  Not nested, just one after the other (they are almost identical, just one hidden variable that's different).  A user will only fill in one form, and I'd like to validate/etc all the forms with only one JS script.

So how, when a user clicks the submit button of form#1, do I make my js script only deal with the fields in form1?  I gather it has something to do with $(this).parents , but I am not sure what to do with it.

My validation script (which I used elsewhere, with only a single form) looks something like so:

$(document).ready(function(){
    $("#submit").click(function(){
        $(".error").hide();
        var hasError = false;

        var nameVal = $("#name").val();
        if(nameVal == '') {
            $("#name").after('Please enter your name.');
            hasError = true;
        }

        if(hasError == false) {blah blah do all the processing stuff}

So do I need to replace things like $("#name").val() with $(this).parents('form').name.val() ?  Or is there a better way to go about this?

Thanks!

Body:
I found this answer when searching for how to find the form of an input element. I wanted to add a note because there is now a better way than using:

var form = $(this).parents('form:first');

I'm not sure when it was added to jQuery but the closest() method does exactly what's needed more cleanly than using parents(). With closest the code can be changed to this:

var form = $(this).closest('form');

It traverses up and finds the first element which matches what you are looking for and stops there, so there's no need to specify :first.


问:
Select everything before a colon en put it between quotes
I have a big array and I need to get everything before the colon between quotes

I've tried this regex but it didn't work for me.

```<code>^([/.+?(?=:)]+)$
</code>```

this is my array now:

```<code>A0 05 15 : "rgb(60, 50, 51)",
A0 05 25 : "rgb(82, 69, 71)",
S 2030-B : "rgb(120, 172, 191)",
S 2030-B10 : "rgb(119, 175, 187)"
</code>```

What I want it do be:

```<code>"A0 05 15" : "rgb(60, 50, 51)",
"A0 05 25" : "rgb(82, 69, 71)",
"S 2030-B" : "rgb(120, 172, 191)",
"S 2030-B10" : "rgb(119, 175, 187)"
</code>```

答:
Here, we might want to have two capturing groups, one for keys and one for values, similar to:

```<code>(.+)(?:\s+):(?:\s+)(".+",?)
</code>```

then make a replacement with:

```<code>"$1":$2
</code>```

DEMO

RegEx Circuit

jex.im visualizes regular expressions:

Body:
I have a big array and I need to get everything before the colon between quotes

I've tried this regex but it didn't work for me.

^([/.+?(?=:)]+)$

this is my array now:

A0 05 15 : "rgb(60, 50, 51)",
A0 05 25 : "rgb(82, 69, 71)",
S 2030-B : "rgb(120, 172, 191)",
S 2030-B10 : "rgb(119, 175, 187)"

What I want it do be:

"A0 05 15" : "rgb(60, 50, 51)",
"A0 05 25" : "rgb(82, 69, 71)",
"S 2030-B" : "rgb(120, 172, 191)",
"S 2030-B10" : "rgb(119, 175, 187)"

Body:
Here, we might want to have two capturing groups, one for keys and one for values, similar to:

(.+)(?:\s+):(?:\s+)(".+",?)

then make a replacement with:

"$1":$2

DEMO

RegEx Circuit

jex.im visualizes regular expressions:


问:
A safe max() function for empty lists
Evaluating,

```<code>max_val = max(a)
</code>```

will cause the error,

```<code>ValueError: max() arg is an empty sequence
</code>```

Is there a better way of safeguarding against this error other than a try, except catch?

```<code>a = []
try:
    max_val = max(a)
except ValueError:
    max_val = default
</code>```

答:
Another solution could be by using ternary operators:

```<code>nums = []
max_val = max(nums) if nums else 0
</code>```

or

```<code>max val = max(iter(nums) if nums else [0])
</code>```

Title: A safe max() function for empty lists

Body:
Evaluating,

max_val = max(a)

will cause the error,

ValueError: max() arg is an empty sequence

Is there a better way of safeguarding against this error other than a try, except catch?

a = []
try:
    max_val = max(a)
except ValueError:
    max_val = default

Body:
Another solution could be by using ternary operators:

nums = []
max_val = max(nums) if nums else 0

or

max val = max(iter(nums) if nums else [0])


问:
Converting NSData to NSString in Swift 3?
I have a function that returns certain system values. It worked fine in Swift 2.2, and I just upgraded to Xcode 8 and Swift 3, and now it's failing.

```<code>func ioPlatExpertDevString(_ property: String) -> String {
    // Start tapping in to the IO Service
    let ioPlatformExpertDevice:io_service_t? = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("IOPlatformExpertDevice"))

    var sAnswer = "Not Found"
    let cfAnswer:AnyObject! = IORegistryEntryCreateCFProperty(ioPlatformExpertDevice!, "\(property)" as CFString!, kCFAllocatorDefault, 0).takeRetainedValue()
    if (cfAnswer != nil) {
        let nsAnswer = (cfAnswer as! NSString)
        sAnswer = nsAnswer.uppercased
    }

    // Close the IO Service
    IOObjectRelease(ioPlatformExpertDevice!)

    return sAnswer
}
</code>```

Prior, I was using "CFData" instead of "AnyObject". It builds fine, but at runtime, I get the following error:

Could not cast value of type '__NSCFData' (0x7fff7b833ec0) to 'NSString' (0x7fff7ac32038).

答:
For more recent versions of Swift:</p>

```<code>String(decoding: data, as: UTF8.self)
</code>```

Body:
I have a function that returns certain system values. It worked fine in Swift 2.2, and I just upgraded to Xcode 8 and Swift 3, and now it's failing.

func ioPlatExpertDevString(_ property: String) -> String {
    // Start tapping in to the IO Service
    let ioPlatformExpertDevice:io_service_t? = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("IOPlatformExpertDevice"))

    var sAnswer = "Not Found"
    let cfAnswer:AnyObject! = IORegistryEntryCreateCFProperty(ioPlatformExpertDevice!, "\(property)" as CFString!, kCFAllocatorDefault, 0).takeRetainedValue()
    if (cfAnswer != nil) {
        let nsAnswer = (cfAnswer as! NSString)
        sAnswer = nsAnswer.uppercased
    }

    // Close the IO Service
    IOObjectRelease(ioPlatformExpertDevice!)

    return sAnswer
}

Prior, I was using "CFData" instead of "AnyObject". It builds fine, but at runtime, I get the following error:

Could not cast value of type '__NSCFData' (0x7fff7b833ec0) to 'NSString' (0x7fff7ac32038).

Body:
For more recent versions of Swift:

String(decoding: data, as: UTF8.self)


问:
How to load Material UI Theme based on Redux Store entry
I have the below file as the first file that loads when my application loads. I want to pull the palette type from my Redux store like this.props.pageTheme so when I trigger a change to the theme, it takes place in the whole app. though when I enter type: this.props.pageTheme I get an error saying TypeError: Cannot read property 'props' of undefined.. Which would make sense because store is not generated by the time const kicks in. But .. Then, how can I read what's in the store and change on the page? I've seen solutions like creating multiple theme const and applying that based on this.props.getTheme within return of the app but that's so ugly way of doing it. Is there any smart way to handle theme value injection into the createMuiTheme?

```<code>import React, { Component } from "react";
import { MuiThemeProvider, createMuiTheme } from "@material-ui/core/styles";

const theme = createMuiTheme({
  palette: {
    type: "light",
  }
});

class App extends Component {
  render() {
      return (
        <MuiThemeProvider theme={theme}>
          <>page content</>
        </MuiThemeProvider>
      );
    }
  }
}

function mapStateToProps(state) {
  return {
    pageTheme: state.Page.Theme
  };
}

export default connect(
  mapStateToProps
)(App);
</code>```

答:
So I am sure there will be people looking for an answer for this issue since it's sleek to offer users an ability to change the color mode of your app. My solution is below, if I come across any, I will update it.

In Redux Store I have:

```<code>const initialState = {
  Page: {
    Theme: "light"
  },
};
</code>```

In main App.js file I have

```<code><MuiThemeProvider theme={theme(this.props.pageTheme)}>
</code>```

as a wrapper around the content that I have on the page.

and I have the below function for theme

```<code>function theme(mode) {
  return createMuiTheme({
    palette: {
      type: mode,
      primary: {
        light: "#757ce8",
        main: "#3f50b5",
        dark: "#002884",
        contrastText: "#fff"
      },
      secondary: {
        light: "#ff7961",
        main: "#f44336",
        dark: "#ba000d",
        contrastText: "#000"
      }
    }
  });
}
</code>```

If you have any suggestions over this to get it better, still highly appreciated.

Body:
I have the below file as the first file that loads when my application loads. I want to pull the palette type from my Redux store like this.props.pageTheme so when I trigger a change to the theme, it takes place in the whole app. though when I enter type: this.props.pageTheme I get an error saying TypeError: Cannot read property 'props' of undefined.. Which would make sense because store is not generated by the time const kicks in. But .. Then, how can I read what's in the store and change on the page? I've seen solutions like creating multiple theme const and applying that based on this.props.getTheme within return of the app but that's so ugly way of doing it. Is there any smart way to handle theme value injection into the createMuiTheme?

import React, { Component } from "react";
import { MuiThemeProvider, createMuiTheme } from "@material-ui/core/styles";

const theme = createMuiTheme({
  palette: {
    type: "light",
  }
});

class App extends Component {
  render() {
      return (
        <MuiThemeProvider theme={theme}>
          <>page content</>
        </MuiThemeProvider>
      );
    }
  }
}

function mapStateToProps(state) {
  return {
    pageTheme: state.Page.Theme
  };
}

export default connect(
  mapStateToProps
)(App);

Body:
So I am sure there will be people looking for an answer for this issue since it's sleek to offer users an ability to change the color mode of your app. My solution is below, if I come across any, I will update it.

In Redux Store I have:

const initialState = {
  Page: {
    Theme: "light"
  },
};

In main App.js file I have

<MuiThemeProvider theme={theme(this.props.pageTheme)}>

as a wrapper around the content that I have on the page.

and I have the below function for theme

function theme(mode) {
  return createMuiTheme({
    palette: {
      type: mode,
      primary: {
        light: "#757ce8",
        main: "#3f50b5",
        dark: "#002884",
        contrastText: "#fff"
      },
      secondary: {
        light: "#ff7961",
        main: "#f44336",
        dark: "#ba000d",
        contrastText: "#000"
      }
    }
  });
}

If you have any suggestions over this to get it better, still highly appreciated.


问:
Grep for value in string over x milliseconds
I know how to grep and find all the lines in a file that contain a simple string:

```<code>cat my_log.log | grep 'Completed 200 OK in'
</code>```

That returns results similar to the following:

```<code>various info... Completed 200 OK in 250ms various info...
various info... Completed 200 OK in 112ms various info...
various info... Completed 200 OK in 1000ms various info...
various info... Completed 200 OK in 6000ms various info...
various info... Completed 200 OK in 33ms various info...
various info... Completed 200 OK in 100ms various info...
</code>```

I'd like to take it a step further and only return the lines where the milliseconds (ms) is over 1000.

Is this possible with grep?  Other posts suggest using sed but I'm curious if it is possible to do this with grep.

答:
Sure

The grep  command comes with an option -E which enables extended regular expressions in your pattern.

Then you just have to look for a 4 digit value with the regex [0-9]{4}

```<code>cat my_log.log | grep -E "Completed 200 OK in [0-9]{4}ms"
</code>```

If you need 4 or more digits just use the range {4,} instead of {4}

```<code>cat my_log.log | grep -E "Completed 200 OK in [0-9]{4,}ms"
</code>```

Body:
I know how to grep and find all the lines in a file that contain a simple string:

cat my_log.log | grep 'Completed 200 OK in'

That returns results similar to the following:

various info... Completed 200 OK in 250ms various info...
various info... Completed 200 OK in 112ms various info...
various info... Completed 200 OK in 1000ms various info...
various info... Completed 200 OK in 6000ms various info...
various info... Completed 200 OK in 33ms various info...
various info... Completed 200 OK in 100ms various info...

I'd like to take it a step further and only return the lines where the milliseconds (ms) is over 1000.

Is this possible with grep?  Other posts suggest using sed but I'm curious if it is possible to do this with grep.

Body:
Sure

The grep  command comes with an option -E which enables extended regular expressions in your pattern.

Then you just have to look for a 4 digit value with the regex [0-9]{4}

cat my_log.log | grep -E "Completed 200 OK in [0-9]{4}ms"

If you need 4 or more digits just use the range {4,} instead of {4}

cat my_log.log | grep -E "Completed 200 OK in [0-9]{4,}ms"


问:
When using HList with GADTs I am having to cast using asInstanceOf[H]. Is there a way to avoid the cast?
Given 2 GADT Algebras which know about each other and 2 interpreters that are mutually recursive, I am having issues having to cast from type A to type h <: HList even though in the context of the pattern match, it should be implied that type A is type h.

Is there a way to avoid the asInstanceOf[h] call in the interpreter?

```<code>  abstract class KvpHList[H<:HList]
  object KvpNil extends KvpHList[HNil]
  case class KvpCons[H <: A :: T,A, T<:HList](head: KvpValue[A], tail: KvpHList[T])(implicit isHCons: IsHCons.Aux[H,A,T]) extends KvpHList[H] {
    val hCons: IsHCons.Aux[H,A,T] = isHCons
  }

  abstract class KvpValue[A]
  case object StringData extends KvpValue[String]
  case class HListData[H <:HList](member: KvpHList[H]) extends KvpValue[H]

  def hListInterpreter[H<:HList](hList: KvpHList[H]): H => String = {
      hList match {
        case KvpNil => (hNil: H) => "Nil"
        case cons: KvpCons[H,a,t]=> {
          implicit val hCons = cons.hCons
          (input: H) => {
            s"${kvpInterpreter(cons.head)(input.head)} :: ${hListInterpreter(cons.tail)(input.tail)}"
          }
        }
      }
  }

  def kvpInterpreter[A](kvpValue: KvpValue[A]): A => String = {
    kvpValue match {
      case StringData => (str: String) => str
      case h: HListData[h] => {
        (input: A) => {                               // tried (input: h) as well
          val toString: h => String = hListInterpreter(h.member)
          toString(input.asInstanceOf[h])             // <--- CASTING :(
        }
      }
    }
  }

  kvpInterpreter(HListData(KvpCons(StringData, KvpNil))).apply("Hello" :: HNil)
</code>```

答:
Since H in KvpCons is uniquely determined by A and T, KvpCons can be parametrized with two type parameters rather than three.

Type-level pattern matching is type classes

```<code>  abstract class KvpHList[H <: HList]
  object KvpNil extends KvpHList[HNil]
  case class KvpCons[A, T <: HList](head: KvpValue[A], tail: KvpHList[T]) extends KvpHList[A :: T]

  abstract class KvpValue[A]
  case object StringData extends KvpValue[String]
  case class HListData[H <: HList](member: KvpHList[H]) extends KvpValue[H]

  trait HListInterpreter[H <: HList] {
    def apply(hList: KvpHList[H]): H => String
  }

  object HListInterpreter {
    implicit val nil: HListInterpreter[HNil] = new HListInterpreter[HNil] {
      override def apply(hList: KvpHList[HNil]): HNil => String = _ => "Nil"
    }

    implicit def cons[A, T <: HList](implicit
                                     headKvpInterpreter: KvpInterpreter[A],
                                     tailHListInterpreter: HListInterpreter[T]
                                    ): HListInterpreter[A :: T] = new HListInterpreter[A :: T] {
      override def apply(hList: KvpHList[A :: T]): A :: T => String = hList match {
        case cons: KvpCons[_, _] => input => s"${headKvpInterpreter(cons.head)(input.head)} :: ${tailHListInterpreter(cons.tail)(input.tail)}"
      }
    }
  }

  def hListInterpreter[H <: HList](hList: KvpHList[H])(implicit hListInterp: HListInterpreter[H]): H => String = hListInterp(hList)

  trait KvpInterpreter[A] {
    def apply(kvpValue: KvpValue[A]): A => String
  }

  object KvpInterpreter {
    implicit val string: KvpInterpreter[String] = new KvpInterpreter[String] {
      override def apply(kvpValue: KvpValue[String]): String => String = str => str
    }

    implicit def hList[H <: HList : HListInterpreter]: KvpInterpreter[H] = new KvpInterpreter[H] {
      override def apply(kvpValue: KvpValue[H]): H => String = kvpValue match {
        case h: HListData[H] => input => {
          val toString: H => String = hListInterpreter(h.member)
          toString(input)
        }
      }
    }
  }

  def kvpInterpreter[A](kvpValue: KvpValue[A])(a: A)(implicit kvpInterp: KvpInterpreter[A]): String = kvpInterp(kvpValue)(a)
</code>```

Body:
Given 2 GADT Algebras which know about each other and 2 interpreters that are mutually recursive, I am having issues having to cast from type A to type h <: HList even though in the context of the pattern match, it should be implied that type A is type h.

Is there a way to avoid the asInstanceOf[h] call in the interpreter?

  abstract class KvpHList[H<:HList]
  object KvpNil extends KvpHList[HNil]
  case class KvpCons[H <: A :: T,A, T<:HList](head: KvpValue[A], tail: KvpHList[T])(implicit isHCons: IsHCons.Aux[H,A,T]) extends KvpHList[H] {
    val hCons: IsHCons.Aux[H,A,T] = isHCons
  }

  abstract class KvpValue[A]
  case object StringData extends KvpValue[String]
  case class HListData[H <:HList](member: KvpHList[H]) extends KvpValue[H]

  def hListInterpreter[H<:HList](hList: KvpHList[H]): H => String = {
      hList match {
        case KvpNil => (hNil: H) => "Nil"
        case cons: KvpCons[H,a,t]=> {
          implicit val hCons = cons.hCons
          (input: H) => {
            s"${kvpInterpreter(cons.head)(input.head)} :: ${hListInterpreter(cons.tail)(input.tail)}"
          }
        }
      }
  }

  def kvpInterpreter[A](kvpValue: KvpValue[A]): A => String = {
    kvpValue match {
      case StringData => (str: String) => str
      case h: HListData[h] => {
        (input: A) => {                               // tried (input: h) as well
          val toString: h => String = hListInterpreter(h.member)
          toString(input.asInstanceOf[h])             // <--- CASTING :(
        }
      }
    }
  }

  kvpInterpreter(HListData(KvpCons(StringData, KvpNil))).apply("Hello" :: HNil)

Body:
Since H in KvpCons is uniquely determined by A and T, KvpCons can be parametrized with two type parameters rather than three.

Type-level pattern matching is type classes

  abstract class KvpHList[H <: HList]
  object KvpNil extends KvpHList[HNil]
  case class KvpCons[A, T <: HList](head: KvpValue[A], tail: KvpHList[T]) extends KvpHList[A :: T]

  abstract class KvpValue[A]
  case object StringData extends KvpValue[String]
  case class HListData[H <: HList](member: KvpHList[H]) extends KvpValue[H]

  trait HListInterpreter[H <: HList] {
    def apply(hList: KvpHList[H]): H => String
  }

  object HListInterpreter {
    implicit val nil: HListInterpreter[HNil] = new HListInterpreter[HNil] {
      override def apply(hList: KvpHList[HNil]): HNil => String = _ => "Nil"
    }

    implicit def cons[A, T <: HList](implicit
                                     headKvpInterpreter: KvpInterpreter[A],
                                     tailHListInterpreter: HListInterpreter[T]
                                    ): HListInterpreter[A :: T] = new HListInterpreter[A :: T] {
      override def apply(hList: KvpHList[A :: T]): A :: T => String = hList match {
        case cons: KvpCons[_, _] => input => s"${headKvpInterpreter(cons.head)(input.head)} :: ${tailHListInterpreter(cons.tail)(input.tail)}"
      }
    }
  }

  def hListInterpreter[H <: HList](hList: KvpHList[H])(implicit hListInterp: HListInterpreter[H]): H => String = hListInterp(hList)

  trait KvpInterpreter[A] {
    def apply(kvpValue: KvpValue[A]): A => String
  }

  object KvpInterpreter {
    implicit val string: KvpInterpreter[String] = new KvpInterpreter[String] {
      override def apply(kvpValue: KvpValue[String]): String => String = str => str
    }

    implicit def hList[H <: HList : HListInterpreter]: KvpInterpreter[H] = new KvpInterpreter[H] {
      override def apply(kvpValue: KvpValue[H]): H => String = kvpValue match {
        case h: HListData[H] => input => {
          val toString: H => String = hListInterpreter(h.member)
          toString(input)
        }
      }
    }
  }

  def kvpInterpreter[A](kvpValue: KvpValue[A])(a: A)(implicit kvpInterp: KvpInterpreter[A]): String = kvpInterp(kvpValue)(a)


问:
JS: delete first element from array by value
I have an array:

```<code>arr = [50, 40, 50, 50];
</code>```

I need to delete first element, that equal 50 and dont touch another.
This code return only [40].

```<code>arr = arr.filter(function(e) {return e !== 50}) // [40]
</code>```

But I need

```<code>arr = arr.somefunction(function(e) {return e !== 50}) // [40, 50, 50]
</code>```

I would be grateful for any help.

答:
You can use a variable to keep track whether you deleted any value or not

let deleteFirst = (value) => {
  let arr = [50, 40, 50, 50];
  let del = false
  return arr.filter(val=> {
    if(val === value && !del){
      del = true
      return false
    }
    return true
  })
}

console.log(deleteFirst(50))
console.log(deleteFirst(40))```

Body:
I have an array:

arr = [50, 40, 50, 50];

I need to delete first element, that equal 50 and dont touch another.
This code return only [40].

arr = arr.filter(function(e) {return e !== 50}) // [40]

But I need

arr = arr.somefunction(function(e) {return e !== 50}) // [40, 50, 50]

I would be grateful for any help.


问:
Changing class state from an imported function in ReactJS
I am trying to change the state of a class from an imported named component so I only need to write the code once. Is this even possible?

I have 3 files ( Login, ForgotPassword, Register ). On ALL of these files I am listening for an "onChange" event on the input fields that all do the same thing as show below:

onChange method:

```<code>onChange = (e) => {
    this.setState(() => ({ errors: {} }));

    let fields = this.state.fields;
    fields[e.target.name] = e.target.value;
    this.setState(() => {
        return {
            fields
        }
    });
};
</code>```

I'd really like to import this as a named method along with some others that are working already:

```<code>import { onFocus, onBlur, onChange } from './Utils/Input';
</code>```

The issue is (as seen above in the onChange code), that I need to update the class state from this method.

Is this at all possible? I am very new to React, so I might be going about this in the completely wrong way.

Thank you in advance!

答:
When trying to update the state of a component you are always updating the state regarding to a particular this.

You are trying to write on* functions which are independent of the instances you are working with. So it makes no sense to use "this" inside those.

You could pass the instance of the Class to the on-function like this:

https://codesandbox.io/s/focused-cache-zzfvp

Body:
I am trying to change the state of a class from an imported named component so I only need to write the code once. Is this even possible?

I have 3 files ( Login, ForgotPassword, Register ). On ALL of these files I am listening for an "onChange" event on the input fields that all do the same thing as show below:

onChange method:

onChange = (e) => {
    this.setState(() => ({ errors: {} }));

    let fields = this.state.fields;
    fields[e.target.name] = e.target.value;
    this.setState(() => {
        return {
            fields
        }
    });
};

I'd really like to import this as a named method along with some others that are working already:

import { onFocus, onBlur, onChange } from './Utils/Input';

The issue is (as seen above in the onChange code), that I need to update the class state from this method.

Is this at all possible? I am very new to React, so I might be going about this in the completely wrong way.

Thank you in advance!


问:
How can I import several Excel sheets in a multi-index dataframe in Python?
I am trying to import an Excel file with several sheets containing the same structure of bidimensional arrays in a multi-indexed Dataframe in Python.

Assume each sheet contains an array (A,B)x(a,b). Basically I would like to have something like this

```<code>  Sheet1  |   Sheet2   |  Sheet3
   a | b  |   a | b    |  a | b
A
B
</code>```

I have tried to use a for loop.

df={}
for i in Sheets:
    df[i] = pd.read_excel (r'file.xlsx', sheet_name = [i], header=0, index_col=0)
```

<p>I would expect df to be such that, if I recall </p>

<pre class="lang-py prettyprint-override"><code>df['Sheet1']
</code>```

I can retrieve one of the arrays, and this actually works fine. The problem comes up if I try to recall

df['Sheet1']['a']
```

<p>to retrieve the first column of the first sheet. However, I get the following error message </p>

<pre class="lang-py prettyprint-override"><code>KeyError: a
</code>```

and I am stuck here.

答:
sheet_name=None in pd.read_excel

Will produce a dicitonary of all sheets.  Pass that to pd.concat with axis=1

```<code>pd.concat(pd.read_excel('Book1.xlsx', None, index_col=0), axis=1)

  Sheet1    Sheet2    Sheet3
       a  b      a  b      a  b
A      1  2      1  2      1  2
B      3  4      3  4      3  4
</code>```

You can also limit the sheets by passing a list of names

```<code>pd.concat(pd.read_excel('Book1.xlsx', ['Sheet1', 'Sheet2', 'Sheet3'], index_col=0), axis=1)
</code>```

Body:
I am trying to import an Excel file with several sheets containing the same structure of bidimensional arrays in a multi-indexed Dataframe in Python.

Assume each sheet contains an array (A,B)x(a,b). Basically I would like to have something like this

  Sheet1  |   Sheet2   |  Sheet3
   a | b  |   a | b    |  a | b
A
B

I have tried to use a for loop.

df={}
for i in Sheets:
    df[i] = pd.read_excel (r'file.xlsx', sheet_name = [i], header=0, index_col=0)

I would expect df to be such that, if I recall

df['Sheet1']

I can retrieve one of the arrays, and this actually works fine. The problem comes up if I try to recall

df['Sheet1']['a']

to retrieve the first column of the first sheet. However, I get the following error message

KeyError: a

and I am stuck here.

Body:
sheet_name=None in pd.read_excel

Will produce a dicitonary of all sheets.  Pass that to pd.concat with axis=1

pd.concat(pd.read_excel('Book1.xlsx', None, index_col=0), axis=1)

  Sheet1    Sheet2    Sheet3
       a  b      a  b      a  b
A      1  2      1  2      1  2
B      3  4      3  4      3  4

You can also limit the sheets by passing a list of names

pd.concat(pd.read_excel('Book1.xlsx', ['Sheet1', 'Sheet2', 'Sheet3'], index_col=0), axis=1)


问:
Unable to trigger specific collapse with radio button using jquery
Good day, I am using laravel blade to dynamically generate some radio buttons and forms depending on user selections. So the user will select a certain amount of jobs and then forms will be generated for the number of jobs. These forms will be hidden and only revealed(via bootstrap collapse) only if a certain radio button is checked. However, what happens is when I check a radio button from one group of radio buttons, all forms are shown. Can anyone assist me?

I am using jquery to show/hide the collapse depending on what radio button is checked. I have tried assigning individual IDs to the buttons dynamically using loop properties. Still having the error.

Blade file (RADIO BUTTON SECTION)

```<code>    @foreach($interest as $job)
     @if($job != 0)
     <!-- EXPERIENCE RADIO BUTTON-->
      <label></label>
      <label>Experience for {{$jobs[$loop->index]}} </label>
      <div class="custom-control custom-radio">

          <input type="radio" class="custom-control-input" id="noxp{{$loop->iteration}}" name="jbxp{{$loop->iteration}}"  value="0">
          <label class="custom-control-label" for="noxp{{$loop->iteration}}">No Experience</label>
      </div>

      <div class="custom-control custom-radio">

          <input type="radio" class="custom-control-input" id="xp1{{$loop->iteration}}" name="jbxp{{$loop->iteration}}" value="1">
          <label class="custom-control-label" for="xp1{{$loop->iteration}}">1-11 Months</label>
      </div>

      <div class="custom-control custom-radio">

          <input type="radio" class="custom-control-input" id="xp2{{$loop->iteration}}" name="jbxp{{$loop->iteration}}" value="2">
          <label class="custom-control-label" for="xp2{{$loop->iteration}}">1-5 Years</label>
      </div>

      <div class="custom-control custom-radio">

          <input type="radio" class="custom-control-input" id="xp3{{$loop->iteration}}" name="jbxp{{$loop->iteration}}" value="3">
          <label class="custom-control-label" for="xp3{{$loop->iteration}}">5+ Years</label>
      </div>
</code>```

Blade file (FORM SECTION)

```<code>     <form id="ref-form-{{$loop->iteration}}" class="form-horizontal" action="{{url('/send-refs')}}" method="POST">
        @csrf
              <div class="row">
                <div class="collapse panel-collapse collapse" id="panel-{{$loop->iteration}}">
                  <div class="panel-body">
                    <!--REF-1-DETAILS-->
                    <div class="row">
                        <div class="col-md-6 mb-2">
                          <label>Last Place Work As {{$jobs[$loop->index]}}</label>
                          <input type="text" name="PlaceWorked" class="form-control" placeholder="Enter last place worked" value=" " required>

                        </div>
                      </div>
     </form>
</code>```

JQuery being used to show/hide collapse:

```<code>       <script>
      $(".custom-control-input").click(function() {

      $("#ref-form-1 :input").attr("disabled", false);
      $("#ref-form-2 :input").attr("disabled", false);
      $("#ref-form-3 :input").attr("disabled", false);

      if ($("input[name=jbxp1]:checked").val() == "0") {
          $("#ref-form-1 :input").attr("disabled", true);
          $('#panel-1').collapse('hide');

      }

      if($("input[name=jbxp1]:checked").val() != "0") {
        $(' #panel-1').collapse('show');
      }

      if ($("input[name=jbxp2]:checked").val() == "0") {
          $("#ref-form-2 :input").attr("disabled", true);
          $('#panel-2').collapse('hide');
      }
      if($("input[name=jbxp2]:checked").val() != "0") {
        $('#panel-2').collapse('show');
      }

      if ($("input[name=jbxp3]:checked").val() == "0") {
          $("#ref-form-3 :input").attr("disabled", true);
          $(' #panel-3').collapse('hide');
      }
      if($("input[name=jbxp3]:checked").val() != "0") {
        $('#panel-3').collapse('show');
      }
  });
    </script>
</code>```

So, I'm expecting that if a radio button is clicked from the first group, the corresponding action will reflect only on the first form.

答:
You can use the hide function with a duration if you want to. See the jQuery documentation for all the possible options.

```<code>$('#panel-3').hide();
</code>```

Body:
Good day, I am using laravel blade to dynamically generate some radio buttons and forms depending on user selections. So the user will select a certain amount of jobs and then forms will be generated for the number of jobs. These forms will be hidden and only revealed(via bootstrap collapse) only if a certain radio button is checked. However, what happens is when I check a radio button from one group of radio buttons, all forms are shown. Can anyone assist me?

I am using jquery to show/hide the collapse depending on what radio button is checked. I have tried assigning individual IDs to the buttons dynamically using loop properties. Still having the error.

Blade file (RADIO BUTTON SECTION)

    @foreach($interest as $job)
     @if($job != 0)

      Experience for {{$jobs[$loop->index]}}

          <input type="radio" class="custom-control-input" id="noxp{{$loop->iteration}}" name="jbxp{{$loop->iteration}}"  value="0">
          iteration}}">No Experience

          <input type="radio" class="custom-control-input" id="xp1{{$loop->iteration}}" name="jbxp{{$loop->iteration}}" value="1">
          iteration}}">1-11 Months

          <input type="radio" class="custom-control-input" id="xp2{{$loop->iteration}}" name="jbxp{{$loop->iteration}}" value="2">
          iteration}}">1-5 Years

          <input type="radio" class="custom-control-input" id="xp3{{$loop->iteration}}" name="jbxp{{$loop->iteration}}" value="3">
          iteration}}">5+ Years

Blade file (FORM SECTION)

     <form id="ref-form-{{$loop->iteration}}" class="form-horizontal" action="{{url('/send-refs')}}" method="POST">
        @csrf

iteration}}">

                          Last Place Work As {{$jobs[$loop->index]}}
                          <input type="text" name="PlaceWorked" class="form-control" placeholder="Enter last place worked" value=" " required>

     </form>

JQuery being used to show/hide collapse:

So, I'm expecting that if a radio button is clicked from the first group, the corresponding action will reflect only on the first form.

Body:
You can use the hide function with a duration if you want to. See the jQuery documentation for all the possible options.

$('#panel-3').hide();


问:
Reportviewer - Prompt for parameters in local mode?
Is it possible for the Microsoft ReportViewer control to prompt for parameters in local mode?

I have added a parameter to filter the report by, which can be mulitple values for the one parameter.

I have set the available Values property of the paramter to read a list of Values from a query.

I was hoping if I did not set parameter values in code the report would prompt for them like crystal reports does ( Im setting the datasource for the parameter available values )

I have done some research on this and as far as I can tell the only time the report would prompt for parameters is if the report is running in server processing mode.

Is this the case? I'm trying to avoid having to add controls to the page to select parameters to pass to the report.

Are available parameter properties relevent to the Local report or are they just there for both?

for completeness, here is the code im using to set the datasource for the report:

```<code>            //Set the report
            Reporting.Common.SetReportEmbeddedResource( this.ReportViewer1, "Reporting.Reports.BudgetEnquiryDrilldown.rdlc" );

            //Set the datasources
            this.ReportViewer1.LocalReport.DataSources.Add(
                new ReportDataSource(
                    "BudgetEnquiry",
                     Reporting.Repositories.BudgetEnquiryDrilldown.GetBudgetEnquiryRecords(
                            base.CurrentSageDatabase,
                            base.CurrentUser.UserID ) ) );

            this.ReportViewer1.LocalReport.DataSources.Add(
                new ReportDataSource(
                    "AccountNumber",
                    Reporting.Repositories.BudgetEnquiryDrilldown.GetAccountNumbers(
                        base.CurrentSageDatabase ) ) );

            this.ReportViewer1.LocalReport.DataSources.Add(
                new ReportDataSource(
                    "CostCentre",
                    Reporting.Repositories.BudgetEnquiryDrilldown.GetCostCentres(
                        base.CurrentSageDatabase ) ) );

            //Refresh the report
            this.ReportViewer1.LocalReport.Refresh();
</code>```

答:
I don't think you can using the ReportViewer per say, but it's easy to create a new form with the parameters needed and pass them to the report.

Look at this :

```

    Dim params As New List(Of Microsoft.Reporting.WinForms.ReportParameter)
' Add Parameters of type Microsoft.Reporting.Windows.ReportParameter
    params.Add(New Microsoft.Reporting.WinForms.ReportParameter("Test", "Whatever"))

    RptViewer.LocalReport.SetParameters(params)
```

In this case, the param test is given the value "whatever".

Body:
Is it possible for the Microsoft ReportViewer control to prompt for parameters in local mode?

I have added a parameter to filter the report by, which can be mulitple values for the one parameter.

I have set the available Values property of the paramter to read a list of Values from a query.

I was hoping if I did not set parameter values in code the report would prompt for them like crystal reports does ( Im setting the datasource for the parameter available values )

I have done some research on this and as far as I can tell the only time the report would prompt for parameters is if the report is running in server processing mode.

Is this the case? I'm trying to avoid having to add controls to the page to select parameters to pass to the report.

Are available parameter properties relevent to the Local report or are they just there for both?

for completeness, here is the code im using to set the datasource for the report:

            //Set the report
            Reporting.Common.SetReportEmbeddedResource( this.ReportViewer1, "Reporting.Reports.BudgetEnquiryDrilldown.rdlc" );

            //Set the datasources
            this.ReportViewer1.LocalReport.DataSources.Add(
                new ReportDataSource(
                    "BudgetEnquiry",
                     Reporting.Repositories.BudgetEnquiryDrilldown.GetBudgetEnquiryRecords(
                            base.CurrentSageDatabase,
                            base.CurrentUser.UserID ) ) );

            this.ReportViewer1.LocalReport.DataSources.Add(
                new ReportDataSource(
                    "AccountNumber",
                    Reporting.Repositories.BudgetEnquiryDrilldown.GetAccountNumbers(
                        base.CurrentSageDatabase ) ) );

            this.ReportViewer1.LocalReport.DataSources.Add(
                new ReportDataSource(
                    "CostCentre",
                    Reporting.Repositories.BudgetEnquiryDrilldown.GetCostCentres(
                        base.CurrentSageDatabase ) ) );

            //Refresh the report
            this.ReportViewer1.LocalReport.Refresh();

Body:
I don't think you can using the ReportViewer per say, but it's easy to create a new form with the parameters needed and pass them to the report.

Look at this :

    Dim params As New List(Of Microsoft.Reporting.WinForms.ReportParameter)
' Add Parameters of type Microsoft.Reporting.Windows.ReportParameter
    params.Add(New Microsoft.Reporting.WinForms.ReportParameter("Test", "Whatever"))

    RptViewer.LocalReport.SetParameters(params)

In this case, the param test is given the value "whatever".


问:
How do I do the equivalent of Gimp's Colors, Auto, White Balance in Python-Fu?
the only function I can find is : gimp-color-balance, which takes the applicable parameters : preserve-lum(osity), cyan-red, magenta-green, and yellow-blue.

I'm not sure what values to pass for these parameters to duplicate the menu option in the title.

答:
To complete the answer of @banderlog013, I think the Gimp Doc specifies that the end pixels of each channel are first discarded, then the remaining ranges are stretched. I believe the right code is : </p>

```<code>img = cv2.imread('test.jpg')
balanced_img = np.zeros_like(img) #Initialize final image

for i in range(3): #i stands for the channel index
    hist, bins = np.histogram(img[..., i].ravel(), 256, (0, 256))
    bmin = np.min(np.where(hist>(hist.sum()*0.0005)))
    bmax = np.max(np.where(hist>(hist.sum()*0.0005)))
    balanced_img[...,i] = np.clip(img[...,i], bmin, bmax)
    balanced_img[...,i] = (balanced_img[...,i]-bmin) / (bmax - bmin) * 255
</code>```

<p>I obtain good results with it, try it out ! </p>

Body:
To complete the answer of @banderlog013, I think the Gimp Doc specifies that the end pixels of each channel are first discarded, then the remaining ranges are stretched. I believe the right code is :

img = cv2.imread('test.jpg')
balanced_img = np.zeros_like(img) #Initialize final image

for i in range(3): #i stands for the channel index
    hist, bins = np.histogram(img[..., i].ravel(), 256, (0, 256))
    bmin = np.min(np.where(hist>(hist.sum()*0.0005)))
    bmax = np.max(np.where(hist>(hist.sum()*0.0005)))
    balanced_img[...,i] = np.clip(img[...,i], bmin, bmax)
    balanced_img[...,i] = (balanced_img[...,i]-bmin) / (bmax - bmin) * 255

I obtain good results with it, try it out !


问:
Laravel 5.8 Won’t Connect to Non-Local Database
I am having an issue where a new Laravel Project (5.8) will not connect to a non-local database. I continue getting an “Access Denied for User...” error. I know that the configuration is correct because I have another project running in 5.6 connecting to the same database with the same configuration and it works. It appears that once I use a hostname other than “localhost”, it breaks. It was working locally until I attempted to connect to another non-local database.

I believe Laravel is not accepting the hostname correctly. I have recached everything as well, with no luck. The access denied error always shows the same local hostname of the machine the project is on, never the remote hostname in the env, so I assume it is trying to connect to that. Any ideas on how to fix this issue? I am stumped with no idea where to go.

Thanks in advance!

EDIT:
I know for sure there is not a configuration error, IP access error, or caching error as I have already troubleshooted all of these possible issues (it sounds like one of these issues). My env and the error are below (anything starting with "my" is the correct information that I have changed for security):

DB_CONNECTION=mysql
DB_HOST=mysql.myURL.com
DB_PORT=3306
DB_DATABASE=myDbName
DB_USERNAME=myDbUsername
DB_PASSWORD=myDbPassword
```

<pre class="lang-sql prettyprint-override"><code>SQLSTATE[HY000] [1045] Access denied for user 'myDbUsername'@'NOTmysql.myURL.com' (using password: YES) (SQL: select count(*) as aggregate from `myTable`)
</code>```

NOTmysql.myURL.com in the error actually happens to be the local hostname of the server that the website is running on, but myDbUsername is the username I set in the configuration.

答: Embarrassing mistake on my part, but I figured out the answer to my question. I have a # in the password and it was causing the part of the password after the # to be read as a comment so it was only using part of the password. I put the password in quotes and everything is now working.</p>

Body:
I am having an issue where a new Laravel Project (5.8) will not connect to a non-local database. I continue getting an “Access Denied for User...” error. I know that the configuration is correct because I have another project running in 5.6 connecting to the same database with the same configuration and it works. It appears that once I use a hostname other than “localhost”, it breaks. It was working locally until I attempted to connect to another non-local database.

I believe Laravel is not accepting the hostname correctly. I have recached everything as well, with no luck. The access denied error always shows the same local hostname of the machine the project is on, never the remote hostname in the env, so I assume it is trying to connect to that. Any ideas on how to fix this issue? I am stumped with no idea where to go.

Thanks in advance!

EDIT:
I know for sure there is not a configuration error, IP access error, or caching error as I have already troubleshooted all of these possible issues (it sounds like one of these issues). My env and the error are below (anything starting with "my" is the correct information that I have changed for security):

DB_CONNECTION=mysql
DB_HOST=mysql.myURL.com
DB_PORT=3306
DB_DATABASE=myDbName
DB_USERNAME=myDbUsername
DB_PASSWORD=myDbPassword

SQLSTATE[HY000] [1045] Access denied for user 'myDbUsername'@'NOTmysql.myURL.com' (using password: YES) (SQL: select count(*) as aggregate from `myTable`)

NOTmysql.myURL.com in the error actually happens to be the local hostname of the server that the website is running on, but myDbUsername is the username I set in the configuration.


答:
You can use findIndex and splice()

let arr = [50, 40, 50, 50];
arr.splice(arr.findIndex(a => a === 50), 1);
console.log(arr)```
</div>
</div>
</p>

<p>If you need it on the <code>prototype</code> of the Array then you can define your custom method.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function removeFirst(cb){
  for(let i = 0;i<this.length;i++){
    if(cb(this[i],i,this)){
      return this.slice(0,i).concat(this.slice(i+1));
    }
  }
  return this;
}

Object.defineProperty(Array.prototype,'removeFirst',{
  value:removeFirst
})

let arr = [50,40,50,50];
let res = arr.removeFirst(x => x === 50);
console.log(res)</code>```

Title: JS: delete first element from array by value

Body:
You can use findIndex and splice()

let arr = [50, 40, 50, 50];
arr.splice(arr.findIndex(a => a === 50), 1);
console.log(arr)

If you need it on the prototype of the Array then you can define your custom method.

function removeFirst(cb){
  for(let i = 0;i<this.length;i++){
    if(cb(this[i],i,this)){
      return this.slice(0,i).concat(this.slice(i+1));
    }
  }
  return this;
}

Object.defineProperty(Array.prototype,'removeFirst',{
  value:removeFirst
})

let arr = [50,40,50,50];
let res = arr.removeFirst(x => x === 50);
console.log(res)


问:
How to use two instances of a base class from a derived class
I want to use two instances of a base class from one derived class. I am not sure if the following code is technically correct or if there is a better way. Can the two instances mix up in any situation?

The base class A is intended to perform a common task: "changevar" which changes the variable "var" to "dv". The derived class B use this method but with two variables "var1", "var2" to change it to "dv1", and "dv2" respectively. class B then performs an "operation" over the changed variables "var1", and "var2" and return the result (in this case multiply).

```<code>test.py:
class A:
    def __init__(self, var):
        self.var = var

    def changevar(self, dv):
        self.var = self.var + dv

    def getvar(self):
        return self.var

class B(A):
    def __init__(self, var1, var2):
        self.var1 = var1
        self.var2 = var2
        A.__init__(self, var1)
        self.inst1 = A(self.var)
        A.__init__(self, var2)
        self.inst2 = A(self.var)

    def operation(self):
        dv1 = 2
        dv2 = -2
        self.inst1.changevar(dv1)
        self.inst2.changevar(dv2)
        self.var1 = self.inst1.getvar()
        self.var2 = self.inst2.getvar()
        return self.var1, self.var2, self.var1 * self.var2

def main():
    test = B(10, 10)
    v1, v2, v3 = test.operation()
    print (v1, v2, v3)
    return

if __name__ == "__main__":
    main()```

>>>python3 test.py
>>>12 8 96
```

答:
In your code, you're not actually using the inheritance.

When you execute self.inst1 = A(self.var) you are creating a whole new instace of A, which is different from that which is the base for your B, and assigning it to a field.

Good news are: you don't need inheritance in your case. what you need (and de-facto do) is composition - having fields of type A in your type B.

Just remove A as a base from B at all, and use the inner fields of this type, the result will be the same:

class A:
    def __init__(self, var):
        self.var = var

    def changevar(self, dv):
        self.var = self.var + dv

    def getvar(self):
        return self.var

class B:
    def __init__(self, var1, var2):
        self.inst1 = A(var1)
        self.inst2 = A(var2)

    def operation(self):
        dv1 = 2
        dv2 = -2
        self.inst1.changevar(dv1)
        self.inst2.changevar(dv2)

        var1 = self.inst1.getvar()
        var2 = self.inst2.getvar()
        return var1, var2, var1 * var2

def main():
    test = B(10, 10)
    v1, v2, v3 = test.operation()
    print (v1, v2, v3)
    return

if __name__ == "__main__":
    main()

```

Inheritance should be used when you want to use instances of type B as if they were of type A (e.g., call A's methods on instances of type B).
Generally we say that B should inherit from A, ib B "is-a" A - e.g. a Dog is an Animal, a Square is a Shape.
Composition is more of "has-a" relationship, like a Car has a Radio

I hope I made it clear, it's a little hard to grasp that reasoning with meaningless class names like A and B :)

Body:
I want to use two instances of a base class from one derived class. I am not sure if the following code is technically correct or if there is a better way. Can the two instances mix up in any situation?

The base class A is intended to perform a common task: "changevar" which changes the variable "var" to "dv". The derived class B use this method but with two variables "var1", "var2" to change it to "dv1", and "dv2" respectively. class B then performs an "operation" over the changed variables "var1", and "var2" and return the result (in this case multiply).

test.py:
class A:
    def __init__(self, var):
        self.var = var

    def changevar(self, dv):
        self.var = self.var + dv

    def getvar(self):
        return self.var

class B(A):
    def __init__(self, var1, var2):
        self.var1 = var1
        self.var2 = var2
        A.__init__(self, var1)
        self.inst1 = A(self.var)
        A.__init__(self, var2)
        self.inst2 = A(self.var)

    def operation(self):
        dv1 = 2
        dv2 = -2
        self.inst1.changevar(dv1)
        self.inst2.changevar(dv2)
        self.var1 = self.inst1.getvar()
        self.var2 = self.inst2.getvar()
        return self.var1, self.var2, self.var1 * self.var2

def main():
    test = B(10, 10)
    v1, v2, v3 = test.operation()
    print (v1, v2, v3)
    return

if __name__ == "__main__":
    main()```

>>>python3 test.py
>>>12 8 96

Body:
In your code, you're not actually using the inheritance.

When you execute self.inst1 = A(self.var) you are creating a whole new instace of A, which is different from that which is the base for your B, and assigning it to a field.

Good news are: you don't need inheritance in your case. what you need (and de-facto do) is composition - having fields of type A in your type B.

Just remove A as a base from B at all, and use the inner fields of this type, the result will be the same:

class A:
    def __init__(self, var):
        self.var = var

    def changevar(self, dv):
        self.var = self.var + dv

    def getvar(self):
        return self.var

class B:
    def __init__(self, var1, var2):
        self.inst1 = A(var1)
        self.inst2 = A(var2)

    def operation(self):
        dv1 = 2
        dv2 = -2
        self.inst1.changevar(dv1)
        self.inst2.changevar(dv2)

        var1 = self.inst1.getvar()
        var2 = self.inst2.getvar()
        return var1, var2, var1 * var2

def main():
    test = B(10, 10)
    v1, v2, v3 = test.operation()
    print (v1, v2, v3)
    return

if __name__ == "__main__":
    main()

Inheritance should be used when you want to use instances of type B as if they were of type A (e.g., call A's methods on instances of type B).
Generally we say that B should inherit from A, ib B "is-a" A - e.g. a Dog is an Animal, a Square is a Shape.
Composition is more of "has-a" relationship, like a Car has a Radio

I hope I made it clear, it's a little hard to grasp that reasoning with meaningless class names like A and B :)


问:
Datatables multi column dropdown search
I am trying to employ this:
http://www.datatables.net/examples/api/multi_filter_select.html

which allows dropdowns for each column in datatables to search on.

```<code>$(document).ready(function() {
$('#example').DataTable( {
    initComplete: function () {
        this.api().columns().every( function () {
            var column = this;
            var select = $('<select><option value=""></option></select>')
                .appendTo( $(column.footer()).empty() )
                .on( 'change', function () {
                    var val = $.fn.dataTable.util.escapeRegex(
                        $(this).val()
                    );

                    column
                        .search( val ? '^'+val+'$' : '', true, false )
                        .draw();
                } );

            column.data().unique().sort().each( function ( d, j ) {
                select.append( '<option value="'+d+'">'+d+'</option>' )
            } );
        } );
    }
} );
</code>```

} );

however, i get:

```<code>Uncaught TypeError: this.api(...).columns(...).every is not a function
</code>```

and have no idea where to begin to troubleshoot.

答:
make sure to specify your column indexes. Below is an example:</p>

```<code> initComplete: function () { // After DataTable initialized
            this.api().columns([1, 5, 6]).every(function () {
                /* use of [1,2,3] for second, third and fourth column.  Leave blank - columns() - for all.
                Multiples? Use columns[0,1]) for first and second, e.g. */
                var column = this;
                var select = $('<select><option value=""/></select>')
                    .appendTo($(column.footer()).empty())
                    .on('change', function () {
                        var val = $.fn.dataTable.util.escapeRegex(
                            $(this).val()
                        );
                        column
                            .search(val ? '^' + val + '$' : '', true, false)
                            .draw();
                    });
                column.data().unique().sort().each(function (d, j) {
                    select.append('<option value="' + d + '">' + d + '</option>')
                });
            }); // this.api function
        } //initComplete function

    });
});
</code>```

Title: Datatables multi column dropdown search

Body:
I am trying to employ this:
http://www.datatables.net/examples/api/multi_filter_select.html

which allows dropdowns for each column in datatables to search on.

$(document).ready(function() {
$('#example').DataTable( {
    initComplete: function () {
        this.api().columns().every( function () {
            var column = this;
            var select = $('<select><option value=""></option></select>')
                .appendTo( $(column.footer()).empty() )
                .on( 'change', function () {
                    var val = $.fn.dataTable.util.escapeRegex(
                        $(this).val()
                    );

                    column
                        .search( val ? '^'+val+'$' : '', true, false )
                        .draw();
                } );

            column.data().unique().sort().each( function ( d, j ) {
                select.append( '<option value="'+d+'">'+d+'</option>' )
            } );
        } );
    }
} );

} );

however, i get:

Uncaught TypeError: this.api(...).columns(...).every is not a function

and have no idea where to begin to troubleshoot.

Body:
make sure to specify your column indexes. Below is an example:

 initComplete: function () { // After DataTable initialized
            this.api().columns([1, 5, 6]).every(function () {
                /* use of [1,2,3] for second, third and fourth column.  Leave blank - columns() - for all.
                Multiples? Use columns[0,1]) for first and second, e.g. */
                var column = this;
                var select = $('<select><option value=""/></select>')
                    .appendTo($(column.footer()).empty())
                    .on('change', function () {
                        var val = $.fn.dataTable.util.escapeRegex(
                            $(this).val()
                        );
                        column
                            .search(val ? '^' + val + '$' : '', true, false)
                            .draw();
                    });
                column.data().unique().sort().each(function (d, j) {
                    select.append('<option value="' + d + '">' + d + '</option>')
                });
            }); // this.api function
        } //initComplete function

    });
});


问:
Accessing a Rails model name from within a lib file of the same method
This may seem like a silly question but I have a model named Ad and I have a library name auto which contains a class Ad(lib/auto.rb).

```<code>#auto.rb lib file
module auto
 class Ad
   def initialize
    ...
   end

   def convert
    # here I would like to access my model class Ad
    # ::Ad does not work. Requiring it does not work either.
   end

 end
end
</code>```

Does Rails 3 store models under some global namespace?

答:
Am I missing something or you are defining auto::Ad?
If so, then ::Ad will never work. use auto::Ad or Ad (from within the auto module).
If you really don't want the auto namespace . Remvoe the module auto part in your code.

Body:
This may seem like a silly question but I have a model named Ad and I have a library name auto which contains a class Ad(lib/auto.rb).

#auto.rb lib file
module auto
 class Ad
   def initialize
    ...
   end

   def convert
    # here I would like to access my model class Ad
    # ::Ad does not work. Requiring it does not work either.
   end

 end
end

Does Rails 3 store models under some global namespace?


问:
Modal component renders Twice on open
I'm using react-spring to animate a Modal based on @reach/dialog. The Modal can have any children. In the children I'm fetching some data based on some prop.

The problem is that the fetch call is made two times on opening the modal. I think it has probably to do with how I'm managing the state and that is causing re-renders.

I'v tried memoizing the children inside the modal and it didn't work, so I think that the problem is outside of the Modal component.

Here is something close to my code and how it is working  https://codesandbox.io/s/loving-liskov-1xouh

EDIT: I already know that if I remove the react-spring animation the double rendering doesn't happen, but I want to try keeping the animation intact.

Do you think you can help me to identify where is the bug? (Also some tips on good practice with hooks are highly appreciated).

答:
it renders three times because your return component has transitions.map since you have three item inside the

```<code>    from: { opacity: 0 }
    enter: { opacity: 1 }
    leave: { opacity: 0 }
</code>```

the {children} was called two times when the isOpen is true
you can fix the issue with just removing the from: { opacity: 0 } and leave: { opacity: 0 }

so change your modal.js => transitions

```<code>  const transitions = useTransition(isOpen, null, {
    enter: { opacity: 1 }
  });
</code>```

Title: Modal component renders Twice on open

Body:
it renders three times because your return component has transitions.map since you have three item inside the

    from: { opacity: 0 }
    enter: { opacity: 1 }
    leave: { opacity: 0 }

the {children} was called two times when the isOpen is true
you can fix the issue with just removing the from: { opacity: 0 } and leave: { opacity: 0 }

so change your modal.js => transitions

  const transitions = useTransition(isOpen, null, {
    enter: { opacity: 1 }
  });


问:
Update user password in Mysql 5.7
I wrote an installation script to change the root password with this SQL command:

```<code>UPDATE user SET password='*C563415623144561...' WHERE user='root';
</code>```

This doesn't work on Mysql 5.7:
http://dev.mysql.com/doc/relnotes/mysql/5.7/en/news-5-7-6.html#mysqld-5-7-6-account-management

My question is: how to change this command with another one compatible with 5.6 and 5.7 version of Mysql? I would like to update the password with a hashed string and not with a clear password.

答:
I'm no MySQL authority, but based on MySQL's current 5.7 documentation, the suggestions in the currently accepted and most upvoted answer strike me as inadvisable.  (This is likely due to the passage of time -- the question and @mdamia's answer were both posted in 2015.)

The MySQL 5.7.6 (2015-03-09, Milestone 16) release notes linked by @Tobia's question say "ALTER USER is now the preferred statement for assigning passwords."

The question did ask if a single command could be used for both MySQL 5.6 and 5.7, but given that the ALTER USER syntax implemented by MySQL >= 5.7.6 offers a security enhancement, I would use the newer syntax when it is available.  If I still had to operate a MySQL < 5.7.6 installation, I would limit my use of older and deprecated/discouraged password-updating syntax to those circumstances.

The ALTER USER statements suggested by @Carlos Alberto García Guardia and @Venkat Kotra in their answers thus seem to me like the right syntax to use for MySQL >= 5.7.6.  Two examples (adapted from their answers and the ALTER USER documentation for MySQL 5.7): :

```<code>ALTER USER '<username>'@'localhost'
  IDENTIFIED BY '<new_cleartext_password>';

ALTER USER '<username>'@'localhost'
  IDENTIFIED WITH <auth_plugin>
  BY '<new_cleartext_password>';
</code>```

The second example above contains an optional WITH clause to specify an authentication plugin.  The plugin specified gets written to the "plugin" field of the mysql.user table.  For background on the history and future of MySQL authentication plugins, I found these MySQL Server Team blog posts helpful:

"Protecting MySQL Passwords With the sha256_password Plugin"

"New Default Authentication Plugin: caching_sha2_password"

In answer to @Tobia's question how to pass the new password to MySQL in hashed format rather than cleartext, the MySQL ALTER USER documentation indicates that this is done by using AS in place of BY in the ALTER USER statement:

```<code>ALTER USER '<username>'@'localhost'
  IDENTIFIED WITH <auth_plugin>
  AS '<new_hashed_password_value>';
</code>```

When using AS instead of BY, the ALTER USER documentation says, the password string "is assumed to be already in the format the authentication plugin requires, and is stored as is in the mysql.user table." If a plugin requires a hashed value, "the value must be hashed in a format appropriate for the plugin. Otherwise, the value is not usable by the plugin and correct authentication of client connections will not occur."  Id.

The currently accepted answer suggests using either a SET PASSWORD ... PASSWORD() statement or an UPDATE statement (the former for passing the new password in cleartext and the latter for passing it in hashed format):

```<code>SET PASSWORD
  FOR '<username>'@'localhost' =
  PASSWORD('<mypass_in_cleartext>');
</code>```

or

```<code>UPDATE mysql.user
  SET authentication_string='<mypass_as_hash>'
  WHERE User='<username>';
</code>```

These statements are deprecated and/or discouraged in relation to the currently preferred ALTER USER statement.

SET PASSWORD ... = PASSWORD(<cleartext>) "is deprecated as of MySQL 5.7.6 and will be removed in a future MySQL release", according to the SET PASSWORD documentation.

The SET PASSWORD ... = 'auth_string' syntax (i.e., leaving out the PASSWORD(str) encryption function) "is not deprecated, but ALTER USER is the preferred statement for account alterations, including assigning passwords."  Id.  See also Removal and Deprecation in MySQL 5.7:

We have deprecated the SET PASSWORD syntax and the PASSWORD() function. The existing ALTER USER statement is modified to cover the deprecated functionality. The PASSWORD() function was originally introduced as a way to manually update the mysql.user table. This is generally a bad idea and we want to leave the task of managing user authentication properties exclusively to using the ALTER USER statement which automatically determines which authentication plugin should be used and then adjusts the password algorithm accordingly.

As described by the manual, it also appears that UPDATE is less secure than ALTER PASSWORD with respect to logging.  The manual indicates that UPDATE statements are written to logs as is, becoming visible to anyone with read access to the logs.[1]  In contrast, the manual indicates, when MySQL writes ALTER USER ... IDENTIFIED BY ... statements (and also SET PASSWORD statements) to logs, it rewrites the contained passwords so they do "not appear literally".[1]

At least in most circumstances.  The documentation for SET PASSWORD and ALTER USER warns that these statements too can be logged with visible passwords "under some circumstances",[2] although presumably not in all circumstances as apparently is the case with UPDATE.

1: See MySQL 5.7 manual on password logging ("In particular, INSERT or UPDATE statements for the mysql.user system table that refer to literal passwords are logged as is, so you should avoid such statements. (Direct modification of grant tables is discouraged, anyway.)")

2: See MySQL 5.7 SET PASSWORD documentation and MySQL 5.7 ALTER USER documentation

Disclaimer:  I'm just sharing my interpretation upon reading the MySQL manual today.  I haven't tested MySQL's behavior with respect to what password-altering statements it logs where in what format.

Title: Update user password in Mysql 5.7

Body:
I wrote an installation script to change the root password with this SQL command:

UPDATE user SET password='*C563415623144561...' WHERE user='root';

This doesn't work on Mysql 5.7:
http://dev.mysql.com/doc/relnotes/mysql/5.7/en/news-5-7-6.html#mysqld-5-7-6-account-management

My question is: how to change this command with another one compatible with 5.6 and 5.7 version of Mysql? I would like to update the password with a hashed string and not with a clear password.

Body:
I'm no MySQL authority, but based on MySQL's current 5.7 documentation, the suggestions in the currently accepted and most upvoted answer strike me as inadvisable.  (This is likely due to the passage of time -- the question and @mdamia's answer were both posted in 2015.)

The MySQL 5.7.6 (2015-03-09, Milestone 16) release notes linked by @Tobia's question say "ALTER USER is now the preferred statement for assigning passwords."

The question did ask if a single command could be used for both MySQL 5.6 and 5.7, but given that the ALTER USER syntax implemented by MySQL >= 5.7.6 offers a security enhancement, I would use the newer syntax when it is available.  If I still had to operate a MySQL < 5.7.6 installation, I would limit my use of older and deprecated/discouraged password-updating syntax to those circumstances.

The ALTER USER statements suggested by @Carlos Alberto García Guardia and @Venkat Kotra in their answers thus seem to me like the right syntax to use for MySQL >= 5.7.6.  Two examples (adapted from their answers and the ALTER USER documentation for MySQL 5.7): :

ALTER USER '<username>'@'localhost'
  IDENTIFIED BY '<new_cleartext_password>';

ALTER USER '<username>'@'localhost'
  IDENTIFIED WITH <auth_plugin>
  BY '<new_cleartext_password>';

The second example above contains an optional WITH clause to specify an authentication plugin.  The plugin specified gets written to the "plugin" field of the mysql.user table.  For background on the history and future of MySQL authentication plugins, I found these MySQL Server Team blog posts helpful:

"Protecting MySQL Passwords With the sha256_password Plugin"

"New Default Authentication Plugin: caching_sha2_password"

In answer to @Tobia's question how to pass the new password to MySQL in hashed format rather than cleartext, the MySQL ALTER USER documentation indicates that this is done by using AS in place of BY in the ALTER USER statement:

ALTER USER '<username>'@'localhost'
  IDENTIFIED WITH <auth_plugin>
  AS '<new_hashed_password_value>';

When using AS instead of BY, the ALTER USER documentation says, the password string "is assumed to be already in the format the authentication plugin requires, and is stored as is in the mysql.user table." If a plugin requires a hashed value, "the value must be hashed in a format appropriate for the plugin. Otherwise, the value is not usable by the plugin and correct authentication of client connections will not occur."  Id.

The currently accepted answer suggests using either a SET PASSWORD ... PASSWORD() statement or an UPDATE statement (the former for passing the new password in cleartext and the latter for passing it in hashed format):

SET PASSWORD
  FOR '<username>'@'localhost' =
  PASSWORD('<mypass_in_cleartext>');

or

UPDATE mysql.user
  SET authentication_string='<mypass_as_hash>'
  WHERE User='<username>';

These statements are deprecated and/or discouraged in relation to the currently preferred ALTER USER statement.

SET PASSWORD ... = PASSWORD(<cleartext>) "is deprecated as of MySQL 5.7.6 and will be removed in a future MySQL release", according to the SET PASSWORD documentation.

The SET PASSWORD ... = 'auth_string' syntax (i.e., leaving out the PASSWORD(str) encryption function) "is not deprecated, but ALTER USER is the preferred statement for account alterations, including assigning passwords."  Id.  See also Removal and Deprecation in MySQL 5.7:

We have deprecated the SET PASSWORD syntax and the PASSWORD() function. The existing ALTER USER statement is modified to cover the deprecated functionality. The PASSWORD() function was originally introduced as a way to manually update the mysql.user table. This is generally a bad idea and we want to leave the task of managing user authentication properties exclusively to using the ALTER USER statement which automatically determines which authentication plugin should be used and then adjusts the password algorithm accordingly.

As described by the manual, it also appears that UPDATE is less secure than ALTER PASSWORD with respect to logging.  The manual indicates that UPDATE statements are written to logs as is, becoming visible to anyone with read access to the logs.[1]  In contrast, the manual indicates, when MySQL writes ALTER USER ... IDENTIFIED BY ... statements (and also SET PASSWORD statements) to logs, it rewrites the contained passwords so they do "not appear literally".[1]

At least in most circumstances.  The documentation for SET PASSWORD and ALTER USER warns that these statements too can be logged with visible passwords "under some circumstances",[2] although presumably not in all circumstances as apparently is the case with UPDATE.

1: See MySQL 5.7 manual on password logging ("In particular, INSERT or UPDATE statements for the mysql.user system table that refer to literal passwords are logged as is, so you should avoid such statements. (Direct modification of grant tables is discouraged, anyway.)")

2: See MySQL 5.7 SET PASSWORD documentation and MySQL 5.7 ALTER USER documentation

Disclaimer:  I'm just sharing my interpretation upon reading the MySQL manual today.  I haven't tested MySQL's behavior with respect to what password-altering statements it logs where in what format.


问:
Question about Netty's Channel.write(Object) signature - Unclear documentation
The Netty library (written in Java) defines the following write method in the channel interface:

```<code>ChannelFuture write(Object message)
</code>```

However, the Javadoc does not explain how this method is going to use the provided message to extract data and send it. It is not like one could pass any object. It does not make sense.

The user guide shows a call example with a ChannelBuffer, but it does not connect the dots between the signature and the usage.

My question what is the proper use of this method? And why hasn't it been defined like this:

```<code>ChannelFuture write(ChannelBuffer message)
</code>```

Is there a special use case for 'object'? Is there any documentation about this?

答:
I think the "Speaking POJO" section of the user guide explains it fairly well: http://docs.jboss.org/netty/3.2/guide/html/start.html#start.pojo.

Simply put, a stream or frame of bytes can be converted to Java objects upstream, and vice versa downstream.

Body:
The Netty library (written in Java) defines the following write method in the channel interface:

ChannelFuture write(Object message)

However, the Javadoc does not explain how this method is going to use the provided message to extract data and send it. It is not like one could pass any object. It does not make sense.

The user guide shows a call example with a ChannelBuffer, but it does not connect the dots between the signature and the usage.

My question what is the proper use of this method? And why hasn't it been defined like this:

ChannelFuture write(ChannelBuffer message)

Is there a special use case for 'object'? Is there any documentation about this?


问:
What is the correct approach to check if array exists in JS?
I'm getting the below error when I check the length of an array. What would be the correct approach?

main.js

```<code>if (drugPrice.mailPrice.rejectMessage.length !== 0 && Array.isArray(drugPrice.mailPrice.rejectMessage)) {
   //code goes here
}
</code>```

Error

```<code>TypeError: Cannot read property 'length' of undefined
</code>```

答:
The problem in your code is that javascript checks array length before checking if the array is the type of the array. You should change the order in the if statement.

You can try with:

```<code>if (myArr && Array.isArray(myArr) && myArr.length !== 0) {
    // your code
}
</code>```

Now the code is executed in the right order.

The first condition checks if myArr is defined,

The second condition checks if myArr is the type of Array, you can also do this way:

if (myArr && myArr.push && myArr.length !== 0) {
     // your code
}

The third condition checks if myArr is not empty.

Body:
I'm getting the below error when I check the length of an array. What would be the correct approach?

main.js

if (drugPrice.mailPrice.rejectMessage.length !== 0 && Array.isArray(drugPrice.mailPrice.rejectMessage)) {
   //code goes here
}

Error

TypeError: Cannot read property 'length' of undefined

Body:
The problem in your code is that javascript checks array length before checking if the array is the type of the array. You should change the order in the if statement.

You can try with:

if (myArr && Array.isArray(myArr) && myArr.length !== 0) {
    // your code
}

Now the code is executed in the right order.

The first condition checks if myArr is defined,

The second condition checks if myArr is the type of Array, you can also do this way:

if (myArr && myArr.push && myArr.length !== 0) {
     // your code
}

The third condition checks if myArr is not empty.


问:
mongoose - array of subdocument are not saved in parent document
I'm trying to push subdocuments into a parent document using push() method.
After that, I want to save the parent document calling save() method on it. But the result is an empty array.

I've also tried to call parent.markModified('children') before saving the parent doc, but it makes no difference.

Below is my Schemas and the code that should save the subdocuments :

Schema :

const profileSessionSchema = mongoose.Schema({
    firstName: { type: String, trim:true},
...
   realisations : [realisationSchema],
 });
ProfileSession = mongoose.model('ProfileSession',profileSessionSchema);

const realisationSchema = mongoose.Schema({
   profileId :{ type: mongoose.Schema.Types.ObjectId, ref: 'ProfileSession'},
   ...
   type : { type: String, enum:conf.wallTypes, required:true, default:'classic'},
});
Realisation = mongoose.model('Realisation', realisationSchema);

```

<pre class="lang-js prettyprint-override"><code>ProfileSession.create(profileData,function(err,profile){
   for(j=0;j<realisations.length;j++){  // realisations array is not empty
     var r = Realisation(realisations[j])
     r.save(function(a,real){
        profile.realisations.push(real)
     })
   }

   profile.markModified('realisations')
   profile.save()
})
</code>```

The profile document is indeed created in DB, but without the realisations subdocuments. I've found plenty of subjects about this, and it appears that the method markModified should solve the issue. But it does not in my case and I can't understand why...

Thank you for you help.
Cheers

答: I think your for loop is iterating too quickly for r.save() to complete and then it's calling profile.save() before it actually saves. Maybe put some console.log inside of your r.save() and then above your profile.save() so you can see the order in which each get called</p>

Body:
I'm trying to push subdocuments into a parent document using push() method.
After that, I want to save the parent document calling save() method on it. But the result is an empty array.

I've also tried to call parent.markModified('children') before saving the parent doc, but it makes no difference.

Below is my Schemas and the code that should save the subdocuments :

Schema :

const profileSessionSchema = mongoose.Schema({
    firstName: { type: String, trim:true},
...
   realisations : [realisationSchema],
 });
ProfileSession = mongoose.model('ProfileSession',profileSessionSchema);

const realisationSchema = mongoose.Schema({
   profileId :{ type: mongoose.Schema.Types.ObjectId, ref: 'ProfileSession'},
   ...
   type : { type: String, enum:conf.wallTypes, required:true, default:'classic'},
});
Realisation = mongoose.model('Realisation', realisationSchema);

ProfileSession.create(profileData,function(err,profile){
   for(j=0;j<realisations.length;j++){  // realisations array is not empty
     var r = Realisation(realisations[j])
     r.save(function(a,real){
        profile.realisations.push(real)
     })
   }

   profile.markModified('realisations')
   profile.save()
})

The profile document is indeed created in DB, but without the realisations subdocuments. I've found plenty of subjects about this, and it appears that the method markModified should solve the issue. But it does not in my case and I can't understand why...

Thank you for you help.
Cheers


问:
Difference between implement pieces of UI in var and final variables
This example from Google shows how you can store pieces of UI in variables.

```<code>var stars = Row(
  mainAxisSize: MainAxisSize.min,
  children: [
    Icon(Icons.star, color: Colors.green[500]),
    Icon(Icons.star, color: Colors.green[500]),
    Icon(Icons.star, color: Colors.green[500]),
    Icon(Icons.star, color: Colors.black),
    Icon(Icons.star, color: Colors.black),
  ],
);

final ratings = Container(
  padding: EdgeInsets.all(20),
  child: Row(
    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
    children: [
      stars,
      Text(
        '170 Reviews',
        style: TextStyle(
          color: Colors.black,
          fontWeight: FontWeight.w800,
          fontFamily: 'Roboto',
          letterSpacing: 0.5,
          fontSize: 20,
        ),
      ),
    ],
  ),
);
</code>```

Note that the stars piece of UI is stored in a var variable while the ratings piece of UI is stored in a final variable.

var stars = Row(...);
  final ratings = Container(...);

My questions are:

What is the motivation behind this difference?

When to store a piece of UI in a var variable and when in a final variable?

答:
As the name suggest, var means something whose value can be changed later on, and final is something whose value once assigned will never be changed. So, you can pretty much use any of them, it all depends on your need.

```<code>var widget = Container(color: Colors.black);
widget = Container(color: Colors.white); // no problem

final widget2 = Container(color: Colors.black);
widget2 = Container(...)// error you can't assign anything to this widget again
</code>```

Body:
This example from Google shows how you can store pieces of UI in variables.

var stars = Row(
  mainAxisSize: MainAxisSize.min,
  children: [
    Icon(Icons.star, color: Colors.green[500]),
    Icon(Icons.star, color: Colors.green[500]),
    Icon(Icons.star, color: Colors.green[500]),
    Icon(Icons.star, color: Colors.black),
    Icon(Icons.star, color: Colors.black),
  ],
);

final ratings = Container(
  padding: EdgeInsets.all(20),
  child: Row(
    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
    children: [
      stars,
      Text(
        '170 Reviews',
        style: TextStyle(
          color: Colors.black,
          fontWeight: FontWeight.w800,
          fontFamily: 'Roboto',
          letterSpacing: 0.5,
          fontSize: 20,
        ),
      ),
    ],
  ),
);

Note that the stars piece of UI is stored in a var variable while the ratings piece of UI is stored in a final variable.

var stars = Row(...);
  final ratings = Container(...);

My questions are:

What is the motivation behind this difference?

When to store a piece of UI in a var variable and when in a final variable?

Body:
As the name suggest, var means something whose value can be changed later on, and final is something whose value once assigned will never be changed. So, you can pretty much use any of them, it all depends on your need.

var widget = Container(color: Colors.black);
widget = Container(color: Colors.white); // no problem

final widget2 = Container(color: Colors.black);
widget2 = Container(...)// error you can't assign anything to this widget again