问:
Closing a bot in AIML
I've been programming a bot that can make an appointment for a dental clinic as an example. If the human tries to make an appointment in a day when there is no hours left, the robot asks if he/she would like another day. If the human says something like 'No', I would like to close the bot so it seems like the human or the robot have hanged up.
Thank you in advance and if I haven't had explained me correctly ask anything you need.</p>

答:
```<code>//textLine is the human answer
    if ((textLine == null) || (textLine.length() < 1))
        textLine = MagicStrings.null_input;
    if (textLine.equals("no")) {
        System.exit(0);
    } else {
        String request = textLine;
        if (MagicBooleans.trace_mode)
            System.out.println("STATE=" + request + ":THAT=" + ((History) chatSession.thatHistory.get(0)).get(0) + ":TOPIC=" + chatSession.predicates.get("topic"));
        String response = chatSession.multisentenceRespond(request);
        while (response.contains("<"))
            response = response.replace("<", "<");
        while (response.contains(">"))
            response = response.replace(">", ">");
    }
</code>```

System.out.println(response);
//response is the bot response

this is my code in java
if i send "no" the bot quit

Title: Closing a bot in AIML

Body:
//textLine is the human answer
    if ((textLine == null) || (textLine.length() < 1))
        textLine = MagicStrings.null_input;
    if (textLine.equals("no")) {
        System.exit(0);
    } else {
        String request = textLine;
        if (MagicBooleans.trace_mode)
            System.out.println("STATE=" + request + ":THAT=" + ((History) chatSession.thatHistory.get(0)).get(0) + ":TOPIC=" + chatSession.predicates.get("topic"));
        String response = chatSession.multisentenceRespond(request);
        while (response.contains("&lt;"))
            response = response.replace("&lt;", "<");
        while (response.contains("&gt;"))
            response = response.replace("&gt;", ">");
    }

System.out.println(response);
//response is the bot response

this is my code in java
if i send "no" the bot quit


来源: stackexchange

问:
Local Dynamodb Console
As the title speaks, is there a way to visualize data in local dynamodb like how it is on AWS Console? This seems to be one of the drawback to me because using localhost:8000/shell (default endpoint) and doing scans requiring the setup of the attributes and etc.</p>

答: Try the NoSQL Workbench for DynamoDB. It can connect to DynamoDB Local.

ContentLicense: CC BY-SA 4.0

Title: Local Dynamodb Console


问:
How to unit test a component that has a ref prop
How do you unit test a component that has a ref prop ? i'm getting this error

● Should render  › should render

```<code>TypeError: Cannot add property current, object is not extensible
</code>```

I looked at another question Unit testing React component ref, but there is no solution for that question.

this is the test

CommentList.test.tsx

```<code>import "@testing-library/jest-dom";
import React from "react";
import { CommentListComponent as CommentList } from "./CommentList";
import { render, getByText, queryByText, getAllByTestId } from "@testing-library/react";

const props = {
    user: {},
    postId: null,
    userId: null,
    currentUser: {},
    ref: {},
    comments: [
        {
            author: { username: "barnowl", gravatar: "https://api.adorable.io/avatars/400/bf1eed82fbe37add91cb4192e4d14de6.png", bio: null },
            comment_body: "fsfsfsfsfs",
            createdAt: "2020-05-27T14:32:01.682Z",
            gifUrl: "",
            id: 520,
            postId: 28,
            updatedAt: "2020-05-27T14:32:01.682Z",
            userId: 9,
        },
        {
            author: { username: "barnowl", gravatar: "https://api.adorable.io/avatars/400/bf1eed82fbe37add91cb4192e4d14de6.png", bio: null },
            comment_body: "fsfsfsfsfs",
            createdAt: "2020-05-27T14:32:01.682Z",
            gifUrl: "",
            id: 519,
            postId: 27,
            updatedAt: "2020-05-27T14:32:01.682Z",
            userId: 10,
        },
    ],
    deleteComment: jest.fn(),
};
describe("Should render <CommentList/>", () => {
    it("should render <CommentList/>", () => {
        const commentList = render(<CommentList {...props} />);
        expect(commentList).toBeTruthy();
    });
});
</code>```

This is the component.

CommentList.tsx

```<code>import React, { Fragment, useState, Ref } from "react";
import Grid from "@material-ui/core/Grid";
import OurSecondaryButton from "../../../common/OurSecondaryButton";
import CommentListContainer from "../commentListContainer/commentListContainer";

function CommentList(props: any, ref: Ref<HTMLDivElement>) {
    const [showMore, setShowMore] = useState<Number>(2);
    const [openModal, setOpenModal] = useState(false);
    const [showLessFlag, setShowLessFlag] = useState<Boolean>(false);
    const the_comments = props.comments.length;
    const inc = showMore as any;
    const min = Math.min(2, the_comments - inc);
    const showComments = (e) => {
        e.preventDefault();
        if (inc + 2 && inc <= the_comments) {
            setShowMore(inc + 2);
            setShowLessFlag(true);
        } else {
            setShowMore(the_comments);
        }
    };
    const handleClickOpen = () => {
        setOpenModal(true);
    };
    const handleCloseModal = () => {
        setOpenModal(false);
    };

    const showLessComments = (e) => {
        e.preventDefault();
        setShowMore(2);
        setShowLessFlag(false);
    };
    const isBold = (comment) => {
        return comment.userId === props.userId ? 800 : 400;
    };
    // show comments by recent, and have the latest comment at the bottom, with the previous one just before it.
    const filterComments = props.comments
        .slice(0)
        .sort((a, b) => {
            const date1 = new Date(a.createdAt) as any;
            const date2 = new Date(b.createdAt) as any;
            return date2 - date1;
        })
        .slice(0, inc)
        .reverse();

    const showMoreComments = () => {
        return filterComments.map((comment, i) => (
            <div key={i}>
                <CommentListContainer ref={ref} comment={comment} openModal={openModal} handleCloseModal={handleCloseModal} isBold={isBold} handleClickOpen={handleClickOpen} {...props} />
            </div>
        ));
    };
    console.log(ref);
    return (
        <Grid>
            <Fragment>
                <div data-testid="comment-list-div" style={{ margin: "30px 0px" }}>
                    {props.comments.length > 2 ? (
                        <Fragment>
                            {min !== -1 && min !== -2 ? (
                                <Fragment>
                                    {min !== 0 ? (
                                        <OurSecondaryButton onClick={(e) => showComments(e)} component="span" color="secondary">
                                            View {min !== -1 && min !== -2 ? min : 0} More Comments
                                        </OurSecondaryButton>
                                    ) : (
                                        <OurSecondaryButton onClick={(e) => showLessComments(e)} component="span" color="secondary">
                                            Show Less Comments
                                        </OurSecondaryButton>
                                    )}
                                </Fragment>
                            ) : (
                                <OurSecondaryButton onClick={(e) => showLessComments(e)} component="span" color="secondary">
                                    Show Less Comments
                                </OurSecondaryButton>
                            )}
                        </Fragment>
                    ) : null}
                </div>
            </Fragment>
            {showLessFlag === true ? (
                // will show most recent comments below
                showMoreComments()
            ) : (
                <Fragment>
                    {/* filter based on first comment  */}
                    {filterComments.map((comment, i) => (
                        <div key={i}>
                            <CommentListContainer ref={ref} comment={comment} openModal={openModal} handleCloseModal={handleCloseModal} isBold={isBold} handleClickOpen={handleClickOpen} {...props} />
                        </div>
                    ))}
                </Fragment>
            )}
        </Grid>
    );
}

export default React.forwardRef(CommentList) as React.RefForwardingComponent<HTMLDivElement, any>;
</code>```

答:
I fixed it, i had to import

```<code>import CommentList from "./CommentList";
</code>```

instead of

```<code>import { CommentListComponent as CommentList } from "./CommentList";
</code>```

and do this to the props

```<code> ref: {
     current: undefined,
 },
</code>```

and comment/remove this line of code from commentList

```<code>// // prevents un-necesary re renders
// // export default React.memo(CommentList);
// // will be useful for unit testing.
// export { CommentList as CommentListComponent };
</code>```

Body:
How do you unit test a component that has a ref prop ? i'm getting this error

● Should render  › should render

TypeError: Cannot add property current, object is not extensible

I looked at another question Unit testing React component ref, but there is no solution for that question.

this is the test

CommentList.test.tsx

import "@testing-library/jest-dom";
import React from "react";
import { CommentListComponent as CommentList } from "./CommentList";
import { render, getByText, queryByText, getAllByTestId } from "@testing-library/react";

const props = {
    user: {},
    postId: null,
    userId: null,
    currentUser: {},
    ref: {},
    comments: [
        {
            author: { username: "barnowl", gravatar: "https://api.adorable.io/avatars/400/bf1eed82fbe37add91cb4192e4d14de6.png", bio: null },
            comment_body: "fsfsfsfsfs",
            createdAt: "2020-05-27T14:32:01.682Z",
            gifUrl: "",
            id: 520,
            postId: 28,
            updatedAt: "2020-05-27T14:32:01.682Z",
            userId: 9,
        },
        {
            author: { username: "barnowl", gravatar: "https://api.adorable.io/avatars/400/bf1eed82fbe37add91cb4192e4d14de6.png", bio: null },
            comment_body: "fsfsfsfsfs",
            createdAt: "2020-05-27T14:32:01.682Z",
            gifUrl: "",
            id: 519,
            postId: 27,
            updatedAt: "2020-05-27T14:32:01.682Z",
            userId: 10,
        },
    ],
    deleteComment: jest.fn(),
};
describe("Should render <CommentList/>", () => {
    it("should render <CommentList/>", () => {
        const commentList = render(<CommentList {...props} />);
        expect(commentList).toBeTruthy();
    });
});

This is the component.

CommentList.tsx

import React, { Fragment, useState, Ref } from "react";
import Grid from "@material-ui/core/Grid";
import OurSecondaryButton from "../../../common/OurSecondaryButton";
import CommentListContainer from "../commentListContainer/commentListContainer";

function CommentList(props: any, ref: Ref<HTMLDivElement>) {
    const [showMore, setShowMore] = useState<Number>(2);
    const [openModal, setOpenModal] = useState(false);
    const [showLessFlag, setShowLessFlag] = useState<Boolean>(false);
    const the_comments = props.comments.length;
    const inc = showMore as any;
    const min = Math.min(2, the_comments - inc);
    const showComments = (e) => {
        e.preventDefault();
        if (inc + 2 && inc <= the_comments) {
            setShowMore(inc + 2);
            setShowLessFlag(true);
        } else {
            setShowMore(the_comments);
        }
    };
    const handleClickOpen = () => {
        setOpenModal(true);
    };
    const handleCloseModal = () => {
        setOpenModal(false);
    };

    const showLessComments = (e) => {
        e.preventDefault();
        setShowMore(2);
        setShowLessFlag(false);
    };
    const isBold = (comment) => {
        return comment.userId === props.userId ? 800 : 400;
    };
    // show comments by recent, and have the latest comment at the bottom, with the previous one just before it.
    const filterComments = props.comments
        .slice(0)
        .sort((a, b) => {
            const date1 = new Date(a.createdAt) as any;
            const date2 = new Date(b.createdAt) as any;
            return date2 - date1;
        })
        .slice(0, inc)
        .reverse();

    const showMoreComments = () => {
        return filterComments.map((comment, i) => (

                <CommentListContainer ref={ref} comment={comment} openModal={openModal} handleCloseModal={handleCloseModal} isBold={isBold} handleClickOpen={handleClickOpen} {...props} />

        ));
    };
    console.log(ref);
    return (
        <Grid>
            <Fragment>

                    {props.comments.length > 2 ? (
                        <Fragment>
                            {min !== -1 && min !== -2 ? (
                                <Fragment>
                                    {min !== 0 ? (
                                        <OurSecondaryButton onClick={(e) => showComments(e)} component="span" color="secondary">
                                            View {min !== -1 && min !== -2 ? min : 0} More Comments
                                        </OurSecondaryButton>
                                    ) : (
                                        <OurSecondaryButton onClick={(e) => showLessComments(e)} component="span" color="secondary">
                                            Show Less Comments
                                        </OurSecondaryButton>
                                    )}
                                </Fragment>
                            ) : (
                                <OurSecondaryButton onClick={(e) => showLessComments(e)} component="span" color="secondary">
                                    Show Less Comments
                                </OurSecondaryButton>
                            )}
                        </Fragment>
                    ) : null}

            </Fragment>
            {showLessFlag === true ? (
                // will show most recent comments below
                showMoreComments()
            ) : (
                <Fragment>
                    {/* filter based on first comment  */}
                    {filterComments.map((comment, i) => (

                            <CommentListContainer ref={ref} comment={comment} openModal={openModal} handleCloseModal={handleCloseModal} isBold={isBold} handleClickOpen={handleClickOpen} {...props} />

                    ))}
                </Fragment>
            )}
        </Grid>
    );
}

export default React.forwardRef(CommentList) as React.RefForwardingComponent<HTMLDivElement, any>;

Body:
I fixed it, i had to import

import CommentList from "./CommentList";

instead of

import { CommentListComponent as CommentList } from "./CommentList";

and do this to the props

 ref: {
     current: undefined,
 },

and comment/remove this line of code from commentList

// // prevents un-necesary re renders
// // export default React.memo(CommentList);
// // will be useful for unit testing.
// export { CommentList as CommentListComponent };


问:
Dependency Injection in every aspect of a spring app?
I am taking a look into Spring as a web framework, however I am needing a bit of help getting my head around DI.

The concept of objects getting constructed in the container on run time is such a new concept.

I am just wondering how this will reflect in a big application, would I have some modules doing work that are more highly coupled or should every object be initialised at runtime?

It all seems a little intensive to me, I mean say for example I have a CSV file data mining application that removes the data per row - each rows data is encapsulated in one of my own CSVRow objects for processing or whatever. These objects are instantiated whenever an Excel file maybe uploaded to the server. I don't know how many I will need to create?

I seem to be getting a bit lost, any clarity, an overview or some guidance would be much appreciated.

Thanks in advance!

答:
You don't need to use DI for your CSV row abstraction.  Once you get the file, when you start parsing it, your code can create the CSVRow things as it goes.  You don't need to wire them up.

You certainly could if you wanted to.  You would grab your applicationContext and just get the beans by name.  You would want to do this if the CsvRow had dependencies that you wanted Spring to manage for you.

ContentLicense: CC BY-SA 3.0


问:
WTD,MTD,YTD query in q/kdb+ with by clause
```<code>q)res:([]date:2020.01.01 2020.05.01 2020.05.03 2020.05.26 2020.05.28;pnl:10 10 10 10 10;name:`john`mary`john`john`mary)
</code>```

Looking to get the WTD,MTD,YTD summed PnL by name to produce the below result

```<code>q)result:([`john`mary]WTD:10 10;MTD:20 20;YTD:30 20)
</code>```

So below for example gives you the time date intervals, I just can't get the query to work (messing around with bin and xbar) to produce end result

```<code>q)mtd:(`date$0 + `month$.z.d;.z.d)

q)ytd:("d"$12 xbar "m"$.z.d;.z.d)
</code>```

答:
One concise way to do it might be:

```<code>d:`WTD`MTD`YTD!({sum y where x>=m-(m:max x)mod 7};{sum y where x>=`date$`month$max x};{sum y where x>="d"$12 xbar "m"$max x});

q)exec d .\:(date;pnl) by name:name from res
name| WTD MTD YTD
----| -----------
john| 10  20  30
mary| 10  20  20
</code>```

The use of max date here is based on the assumption that if one person has a record on a date then they all will. It would also allow it to work on any historical date for a point-in-time view.

If this is not the case then for the current-day view it might be better to use todays date .z.D as the point in time, e.g.

```<code>d:`WTD`MTD`YTD!({sum y where x>=.z.D-.z.D mod 7};{sum y where x>=`date$`month$.z.D};{sum y where x>="d"$12 xbar "m"$.z.D});
</code>```

If your data is sparse and not everyone has a record on every date, and yet you still want a historical week-to-date, month-to-date, year-to-date then I think the best bet would be to "unsparse" the table such that every name has a record on every date, filled with zero pnl if necessary. Then the max approach should work along with a filter on the dates in the table

Body:
q)res:([]date:2020.01.01 2020.05.01 2020.05.03 2020.05.26 2020.05.28;pnl:10 10 10 10 10;name:`john`mary`john`john`mary)

Looking to get the WTD,MTD,YTD summed PnL by name to produce the below result

q)result:([`john`mary]WTD:10 10;MTD:20 20;YTD:30 20)

So below for example gives you the time date intervals, I just can't get the query to work (messing around with bin and xbar) to produce end result

q)mtd:(`date$0 + `month$.z.d;.z.d)

q)ytd:("d"$12 xbar "m"$.z.d;.z.d)

Body:
One concise way to do it might be:

d:`WTD`MTD`YTD!({sum y where x>=m-(m:max x)mod 7};{sum y where x>=`date$`month$max x};{sum y where x>="d"$12 xbar "m"$max x});

q)exec d .\:(date;pnl) by name:name from res
name| WTD MTD YTD
----| -----------
john| 10  20  30
mary| 10  20  20

The use of max date here is based on the assumption that if one person has a record on a date then they all will. It would also allow it to work on any historical date for a point-in-time view.

If this is not the case then for the current-day view it might be better to use todays date .z.D as the point in time, e.g.

d:`WTD`MTD`YTD!({sum y where x>=.z.D-.z.D mod 7};{sum y where x>=`date$`month$.z.D};{sum y where x>="d"$12 xbar "m"$.z.D});

If your data is sparse and not everyone has a record on every date, and yet you still want a historical week-to-date, month-to-date, year-to-date then I think the best bet would be to "unsparse" the table such that every name has a record on every date, filled with zero pnl if necessary. Then the max approach should work along with a filter on the dates in the table


问:
Modifying of css by document.styleSheets
I try to modify CSS by changing:

```<code>document.styleSheets[0].cssRules[0].style.fontSize = '1rem';
</code>```

It works perfect at PC, but using mobile browsers (at least chrome & mozilla) triggering of this script makes no effect.

What did I do wrong? If such way of modification of CSS is not globaly supported by some reason, how can I modify CSS different way?

EDIT: I want to change style for of all existing and all future dynamically added objects with exact class. So el.style.fontSize is not very good option.

答:
You will have more control using css variables, below you can find a small demo that illustrates my point

let root = document.documentElement;

document
  .querySelector('button')
  .addEventListener('click', () => {
    let currentVal = Number(getComputedStyle(root).getPropertyValue('--defaultFontSize').replace('px', ''));
    root.style.setProperty('--defaultFontSize', `${currentVal + 5}px`);
  });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>:root {
  --defaultFontSize: 20px;
}

.text {
  font-size: var(--defaultFontSize);
}</code>```

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

Some text

  <button>Increse font size</button>

```

Body:
I try to modify CSS by changing:

document.styleSheets[0].cssRules[0].style.fontSize = '1rem';

It works perfect at PC, but using mobile browsers (at least chrome & mozilla) triggering of this script makes no effect.

What did I do wrong? If such way of modification of CSS is not globaly supported by some reason, how can I modify CSS different way?

EDIT: I want to change style for of all existing and all future dynamically added objects with exact class. So el.style.fontSize is not very good option.

Body:
You will have more control using css variables, below you can find a small demo that illustrates my point

let root = document.documentElement;

document
  .querySelector('button')
  .addEventListener('click', () => {
    let currentVal = Number(getComputedStyle(root).getPropertyValue('--defaultFontSize').replace('px', ''));
    root.style.setProperty('--defaultFontSize', `${currentVal + 5}px`);
  });

:root {
  --defaultFontSize: 20px;
}

.text {
  font-size: var(--defaultFontSize);
}

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <p class="text">Some text</p>

  <button>Increse font size</button>
</body>
</html>


问:
hide or show a button for authenticated user in react
i want to show "Become Tutor" button if
1. the user is not logged in.
2. the logged in user is not already tutor.

otherwise i want to show "Tutor DashBoard" button.(for user already tutor)
the code works but it shows "Tutor DashBoard" for all logged in users even if they are not already tutor.i hope you understand.
here is code

```<code> //BecomeTutor to show or hide
        const BecomeTutor=(props)=>{

            const user=localStorage.getItem('user')
            console.log("user:"+user);// this shows right user on console

              if(!user){
                return(
                    <div>
            <a  href="NewTutorForm" onClick={()=>onCreate()}><Button
               variant="contained"
               color="primary" >Become a Tutor </Button></a>

                    </div>
                );}

                else{
            const check= props.tutorList.find(x=>x.UserId==user.id)
            console.log("tutorList:", props.tutorList);
            console.log("check:"+ check); // to show tutor on console

            if ( check ){
                return(
                    <div>
            <a  href="TutorDashBoard" onClick={()=>tutorDashBoard(check.UserId)}><Button
               variant="contained"
               color="primary" >Tutor DashBoard </Button></a>

                    </div>
                );
                }
                else{
                    return(
                        <div>
                <a  href="NewTutorForm" onClick={()=>onCreate()}><Button
                   variant="contained"
                   color="primary" >Become a Tutor </Button></a>

                        </div>
                    );
                }
            }

        }
</code>```

value of user on console:

```<code>user: {"id":6,"username":"fiazranjha","email":"fiazmianwal@gmail.com","role":"user","token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6IjYiLCJuYmYiOjE1OTA1ODM2MTMsImV4cCI6MTU5MTE4ODQxMywiaWF0IjoxNTkwNTgzNjEzfQ.J7JWakYMMAwZN02xwOOGBLsagFs_oGbqUAr1aWsGiIk"}
</code>```

value of tutorList on console:

```<code>tutorList: [{…}]0: address: "1km mianwal road kuthiala sheikhan"category: "OnlineTutor"courses: []experience: "this is test"fullName: "fiaz ahmed"mobile: "03466469074"qualification: "test"tutorId: 2updatedOn: "2020-05-26T04:34:52.5088619"userId: 6username: "fiazranjha"whatsapp: "03466469074"__proto__: Objectlength: 1__proto__: Array(0)]
</code>```

value of check on console

```<code>check: {tutorId: 2, fullName: "fiaz ahmed", username: "fiazranjha", userId: 6, mobile: "03466469074", …}address: "1km mianwal road kuthiala sheikhan"category: "OnlineTutor"courses: []experience: "this is test"fullName: "fiaz ahmed"mobile: "03466469074"qualification: "test"tutorId: 2updatedOn: "2020-05-26T04:34:52.5088619"userId: 6username: "fiazranjha"whatsapp: "03466469074"__proto__: Object}
</code>```

答:
found the error .the type of user was string .type of tutorList was object .console.log("user:",typeof(user)); changed the user to object by JSON.pars(). thankful to all specially @Khabir his indication for lower case userId was also helpful. following changing  worked like a charm.

```<code> //BecomeTutor to show or hide
        const BecomeTutor=(props)=>{

            const user=JSON.parse(localStorage.getItem('user'))
            console.log("user:",user);

              if(!user){
                return(
                    <div>
            <a  href="NewTutorForm" onClick={()=>onCreate()}><Button
               variant="contained"
               color="primary" >Become a Tutor </Button></a>

                    </div>
                );}

                else{
            const check= {...props.tutorList.find(x=>x.userId==user.id)}
            console.log("tutorList:", props.tutorList); // to show
            console.log("check:",check); // to show

            if ( check.userId ){
                return(
                    <div>
            <a  href="TutorDashBoard" onClick={()=>props.tutorDashBoard(check.userId,check)}><Button
               variant="contained"
               color="primary" >Tutor DashBoard </Button></a>

                    </div>
                );
                }
                else{
                    return(
                        <div>
                <a  href="NewTutorForm" onClick={()=>onCreate()}><Button
                   variant="contained"
                   color="primary" >Become a Tutor </Button></a>

                        </div>
                    );
                }
            }

        }
</code>```

Body:
i want to show "Become Tutor" button if
1. the user is not logged in.
2. the logged in user is not already tutor.

otherwise i want to show "Tutor DashBoard" button.(for user already tutor)
the code works but it shows "Tutor DashBoard" for all logged in users even if they are not already tutor.i hope you understand.
here is code

 //BecomeTutor to show or hide
        const BecomeTutor=(props)=>{

            const user=localStorage.getItem('user')
            console.log("user:"+user);// this shows right user on console

              if(!user){
                return(

            onCreate()}><Button
               variant="contained"
               color="primary" >Become a Tutor </Button>

                );}

                else{
            const check= props.tutorList.find(x=>x.UserId==user.id)
            console.log("tutorList:", props.tutorList);
            console.log("check:"+ check); // to show tutor on console

            if ( check ){
                return(

            tutorDashBoard(check.UserId)}><Button
               variant="contained"
               color="primary" >Tutor DashBoard </Button>

                );
                }
                else{
                    return(

                onCreate()}><Button
                   variant="contained"
                   color="primary" >Become a Tutor </Button>

                    );
                }
            }

        }

value of user on console:

user: {"id":6,"username":"fiazranjha","email":"fiazmianwal@gmail.com","role":"user","token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6IjYiLCJuYmYiOjE1OTA1ODM2MTMsImV4cCI6MTU5MTE4ODQxMywiaWF0IjoxNTkwNTgzNjEzfQ.J7JWakYMMAwZN02xwOOGBLsagFs_oGbqUAr1aWsGiIk"}

value of tutorList on console:

tutorList: [{…}]0: address: "1km mianwal road kuthiala sheikhan"category: "OnlineTutor"courses: []experience: "this is test"fullName: "fiaz ahmed"mobile: "03466469074"qualification: "test"tutorId: 2updatedOn: "2020-05-26T04:34:52.5088619"userId: 6username: "fiazranjha"whatsapp: "03466469074"__proto__: Objectlength: 1__proto__: Array(0)]

value of check on console

check: {tutorId: 2, fullName: "fiaz ahmed", username: "fiazranjha", userId: 6, mobile: "03466469074", …}address: "1km mianwal road kuthiala sheikhan"category: "OnlineTutor"courses: []experience: "this is test"fullName: "fiaz ahmed"mobile: "03466469074"qualification: "test"tutorId: 2updatedOn: "2020-05-26T04:34:52.5088619"userId: 6username: "fiazranjha"whatsapp: "03466469074"__proto__: Object}

Body:
found the error .the type of user was string .type of tutorList was object .console.log("user:",typeof(user)); changed the user to object by JSON.pars(). thankful to all specially @Khabir his indication for lower case userId was also helpful. following changing  worked like a charm.

 //BecomeTutor to show or hide
        const BecomeTutor=(props)=>{

            const user=JSON.parse(localStorage.getItem('user'))
            console.log("user:",user);

              if(!user){
                return(
                    <div>
            <a  href="NewTutorForm" onClick={()=>onCreate()}><Button
               variant="contained"
               color="primary" >Become a Tutor </Button></a>

                    </div>
                );}

                else{
            const check= {...props.tutorList.find(x=>x.userId==user.id)}
            console.log("tutorList:", props.tutorList); // to show
            console.log("check:",check); // to show

            if ( check.userId ){
                return(
                    <div>
            <a  href="TutorDashBoard" onClick={()=>props.tutorDashBoard(check.userId,check)}><Button
               variant="contained"
               color="primary" >Tutor DashBoard </Button></a>

                    </div>
                );
                }
                else{
                    return(
                        <div>
                <a  href="NewTutorForm" onClick={()=>onCreate()}><Button
                   variant="contained"
                   color="primary" >Become a Tutor </Button></a>

                        </div>
                    );
                }
            }

        }


问:
State Management with ViewModel on Android when on a flow
Basically I have a state management system using ViewModel that looks like this:

class ViewModelA: ViewModel() {

    private val repository: RepositoryA by inject()

    private val _stateLiveData = MutableLiveData<ViewState>()
    val stateLiveData: LiveData<ViewState> get() = _stateLiveData

    private val _eventLiveData = SingleLiveEvent<ViewEvent>()
    val eventLiveData: LiveData<ViewEvent> get() = _eventLiveData

    private val exceptionHandler = CoroutineExceptionHandler { _, _ ->
        _stateLiveData.postValue(ViewState.Error)
    }

    fun loadList() {
        if (_stateLiveData.value is ViewState.Loading) return
        launch(exceptionHandler) {
            _stateLiveData.run {
                value = ViewState.Loading
                value = repository.getDocumentList().let {
                    if (it.isEmpty()) ViewState.Error
                    else ViewState.Data(it)
                }
            }
        }
    }
}
```

But whenever I am sharing a ViewModel with several Fragments, it becomes bigger and bigger. I am looking for a solution for this, because I don't want to centralize all the logic for an entire application flow inside a ViewModel and I also don't want to pass arguments here and there all the time.

PS: Sorry about my bad english.
Edit: Clarify a bit the question.

答:
I didn't quite understand your question. However, if your question was as follows:

How can I share the same ViewModel Object and use it inside multiple Fragments.

You can check the documentation of ViewModelProvider which is a utility class that provides ViewModels for a specific scope like Activity.

Following is an example code of the usage of ViewModelProvider within two Fragments that will be created and used in the same Activity object:

```<code>// An example ViewModel
class SharedViewModel : ViewModel() {

    val intLiveData = MutableLiveData<Int>() // an example LiveData field

}
</code>```

```<code>// the first fragment
class Fragment1 : Fragment() {

    private lateinit var viewModel: SharedViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        viewModel = requireActivity().let { activity ->
            ViewModelProvider(activity).get(SharedViewModel::class.java)
        }
    }

}
</code>```

```<code>// the other fragment
class Fragment2 : Fragment() {

    private lateinit var viewModel: SharedViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        viewModel = requireActivity().let { activity ->
            ViewModelProvider(activity).get(SharedViewModel::class.java)
        }
    }
}
</code>```

Body:
Basically I have a state management system using ViewModel that looks like this:

class ViewModelA: ViewModel() {

    private val repository: RepositoryA by inject()

    private val _stateLiveData = MutableLiveData<ViewState>()
    val stateLiveData: LiveData<ViewState> get() = _stateLiveData

    private val _eventLiveData = SingleLiveEvent<ViewEvent>()
    val eventLiveData: LiveData<ViewEvent> get() = _eventLiveData

    private val exceptionHandler = CoroutineExceptionHandler { _, _ ->
        _stateLiveData.postValue(ViewState.Error)
    }

    fun loadList() {
        if (_stateLiveData.value is ViewState.Loading) return
        launch(exceptionHandler) {
            _stateLiveData.run {
                value = ViewState.Loading
                value = repository.getDocumentList().let {
                    if (it.isEmpty()) ViewState.Error
                    else ViewState.Data(it)
                }
            }
        }
    }
}

But whenever I am sharing a ViewModel with several Fragments, it becomes bigger and bigger. I am looking for a solution for this, because I don't want to centralize all the logic for an entire application flow inside a ViewModel and I also don't want to pass arguments here and there all the time.

PS: Sorry about my bad english.
Edit: Clarify a bit the question.

Body:
I didn't quite understand your question. However, if your question was as follows:

How can I share the same ViewModel Object and use it inside multiple Fragments.

You can check the documentation of ViewModelProvider which is a utility class that provides ViewModels for a specific scope like Activity.

Following is an example code of the usage of ViewModelProvider within two Fragments that will be created and used in the same Activity object:

// An example ViewModel
class SharedViewModel : ViewModel() {

    val intLiveData = MutableLiveData<Int>() // an example LiveData field

}

// the first fragment
class Fragment1 : Fragment() {

    private lateinit var viewModel: SharedViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        viewModel = requireActivity().let { activity ->
            ViewModelProvider(activity).get(SharedViewModel::class.java)
        }
    }

}

// the other fragment
class Fragment2 : Fragment() {

    private lateinit var viewModel: SharedViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        viewModel = requireActivity().let { activity ->
            ViewModelProvider(activity).get(SharedViewModel::class.java)
        }
    }
}


问:
how to insert a big list into a sqlite table with sqlalchemy
i don't understand very well flask_sqlalchemy but as far as i get, if i have a pandas(130 columns, 1 row) dataframe and i want to insert it into a sqlite db i should first build a class "Mytable"  like

```<code>class Mytable(db.Model):
      __tablename__ = 'mytable'
      id = db.Column(db.Integer, primary_key=True)
      val0 = db.Column(db.String(64), unique=True)
      val1 = db.Column(db.String(64))
      .
      .
      .
      va129 = db.Column(db.String(64))
      def __repr__(self):
             return '<Mytable %r>' % self.name
</code>```

for the table, w/ the columns matching between the pandas and the sqlite db table, then use something like

```<code>mytable = Mytable(col1=pandas[0],col1=pandas[1],......)
db.session.add(mytable)
db.session.commit()
</code>```

in order to insert it on the database, is this true? is there any less painful way to create the 130 columns table class? do you have any advice in order to avoid writing all the 130 lines from Mytable class and the mytable line?

答:
i solved whit this method, if encode_pd is the row to insert on Mytable we can use</p>

```<code>row_to_write = list(encode_pd.loc[0])
row_value_markers = ','.join(['?']*len(row_to_write))
engine.execute("INSERT INTO Encodes VALUES (%s)"%row_value_markers, row_to_write)
</code>```

Body:
i don't understand very well flask_sqlalchemy but as far as i get, if i have a pandas(130 columns, 1 row) dataframe and i want to insert it into a sqlite db i should first build a class "Mytable"  like

class Mytable(db.Model):
      __tablename__ = 'mytable'
      id = db.Column(db.Integer, primary_key=True)
      val0 = db.Column(db.String(64), unique=True)
      val1 = db.Column(db.String(64))
      .
      .
      .
      va129 = db.Column(db.String(64))
      def __repr__(self):
             return '<Mytable %r>' % self.name

for the table, w/ the columns matching between the pandas and the sqlite db table, then use something like

mytable = Mytable(col1=pandas[0],col1=pandas[1],......)
db.session.add(mytable)
db.session.commit()

in order to insert it on the database, is this true? is there any less painful way to create the 130 columns table class? do you have any advice in order to avoid writing all the 130 lines from Mytable class and the mytable line?

Body:
i solved whit this method, if encode_pd is the row to insert on Mytable we can use

row_to_write = list(encode_pd.loc[0])
row_value_markers = ','.join(['?']*len(row_to_write))
engine.execute("INSERT INTO Encodes VALUES (%s)"%row_value_markers, row_to_write)


问:
Strip list items with multiple arguments error
I'm trying to remove a lot of stuff from a text file to rewrite it.
The text file has several hundred items each consisting of 6 lines of.
I got my code working to a point where puts all lines in an array, identifies the only 2 important in every item and deletes the whitespaces, but any further stripping gives me the following error:

'list' object has no attribute 'strip'

Here my code:

```<code>x = 0
y = 0
names = []
colors = []
array = []

with open("AA_Ivory.txt", "r") as ins:

    for line in ins:
        array.append(line)

def Function (currentElement, lineInSkinElement):
    name = ""
    color = ""
    string = array[currentElement]
    if lineInSkinElement == 1:
        string = [string.strip()]
#       string = [string.strip()]
#       name = [str.strip("\n")]
#       name = [str.strip(";")]
#       name = [str.strip(" ")]
#       name = [str.strip("=")]
        names.append(name)
        return name
#   if lineInSkinElement == 2:
#       color = [str.strip("\t")]
#       color = [str.strip("\n")]
#       color = [str.strip(";")]
#       color = [str.strip(" ")]
#       color = [str.strip("=")]
#       colors.append(color)
#       return color
    print "I got called %s times" % currentElement
    print lineInSkinElement
    print currentElement

for val in array:
    Function(x, y)
    x = x +1
    y = x % 6

#print names
#print colors
</code>```

In the if statement for the names, deleting the first # will give me the error.
I tried converting the list item to string, but then I get extra [] around the string.

The if statement for color can be ignored, I know it's faulty and trying to fix this is what got me to my current issue.

答:
You can also do that in one line using the following code.

```<code>item = item.strip("\n").strip("=").strip(";").strip()
</code>```

The last strip will strip the white spaces.

Body:
I'm trying to remove a lot of stuff from a text file to rewrite it.
The text file has several hundred items each consisting of 6 lines of.
I got my code working to a point where puts all lines in an array, identifies the only 2 important in every item and deletes the whitespaces, but any further stripping gives me the following error:

'list' object has no attribute 'strip'

Here my code:

x = 0
y = 0
names = []
colors = []
array = []

with open("AA_Ivory.txt", "r") as ins:

    for line in ins:
        array.append(line)

def Function (currentElement, lineInSkinElement):
    name = ""
    color = ""
    string = array[currentElement]
    if lineInSkinElement == 1:
        string = [string.strip()]
#       string = [string.strip()]
#       name = [str.strip("\n")]
#       name = [str.strip(";")]
#       name = [str.strip(" ")]
#       name = [str.strip("=")]
        names.append(name)
        return name
#   if lineInSkinElement == 2:
#       color = [str.strip("\t")]
#       color = [str.strip("\n")]
#       color = [str.strip(";")]
#       color = [str.strip(" ")]
#       color = [str.strip("=")]
#       colors.append(color)
#       return color
    print "I got called %s times" % currentElement
    print lineInSkinElement
    print currentElement

for val in array:
    Function(x, y)
    x = x +1
    y = x % 6

#print names
#print colors

In the if statement for the names, deleting the first # will give me the error.
I tried converting the list item to string, but then I get extra [] around the string.

The if statement for color can be ignored, I know it's faulty and trying to fix this is what got me to my current issue.

Body:
You can also do that in one line using the following code.

item = item.strip("\n").strip("=").strip(";").strip()

The last strip will strip the white spaces.


问:
How can I map items together in a json structure with jq?
I have a json structure that looks like this:

```<code>{
        "lorry1": {
                "box1": [
                        {"item": "shoes", "state": "new"},
                        {"item": "snacks", "state": "new"}
                ],
                "box2": [
                        {"item": "beer", "state": "cold"},
                        {"item": "potatoes"}
                ]
        },
        "lorry2": {
                "box1": [
                        {"item": "shoes", "state": "new"},
                        {"item": "snacks", "state": "new"}
                ],
                "box2": [
                        {"item": "beer", "state": "lukewarm"}
                ]
        }
}
</code>```

Now I want to know where I can find shoes:
I could come up with this jq query:

```<code>to_entries | select(.[].value | .[][].item=="shoes") | map({"lorry": "\(.key)"  })
</code>```

But that only gives me the lorries. Useful, but not quite there yet. I'd like to know the box they're in as well.

I came up with this, but it obviously is not correct:

```<code>to_entries | select(.[].value | .[][].item=="shoes") | keys as $box |map({"lorry": "\(.key)", "box": $box })
</code>```

The answer I'd like to get is lorry1, box1 and lorry2, box1.

Even better yet: I'd like to find all items and provide the information, like this:

```<code>"shoes": [ {"lorry1", "box1"}, {"lorry2", "box1" } ],
"snacks": [ {"lorry1", "box1"}, {"lorry2", "box1"} ],
"beer": [ {"lorry1", "box2"}, {"lorry2", "box2"} ],
"potatoes": [ {"lorry1", "box2"} ]
</code>```

but that may be asking a bit too much :)

答:
The answer I'd like to get is lorry1, box1 and lorry2, box1

In this case, you can get it with:

path(.. | select(.item? == "shoes"))
```

<p>Which returns:</p>

```["lorry1","box1",0]
["lorry2","box1",0]
```

These are the paths in your object that will lead to an object which .item property is set to "shoes"

Body:
I have a json structure that looks like this:

{
        "lorry1": {
                "box1": [
                        {"item": "shoes", "state": "new"},
                        {"item": "snacks", "state": "new"}
                ],
                "box2": [
                        {"item": "beer", "state": "cold"},
                        {"item": "potatoes"}
                ]
        },
        "lorry2": {
                "box1": [
                        {"item": "shoes", "state": "new"},
                        {"item": "snacks", "state": "new"}
                ],
                "box2": [
                        {"item": "beer", "state": "lukewarm"}
                ]
        }
}

Now I want to know where I can find shoes:
I could come up with this jq query:

to_entries | select(.[].value | .[][].item=="shoes") | map({"lorry": "\(.key)"  })

But that only gives me the lorries. Useful, but not quite there yet. I'd like to know the box they're in as well.

I came up with this, but it obviously is not correct:

to_entries | select(.[].value | .[][].item=="shoes") | keys as $box |map({"lorry": "\(.key)", "box": $box })

The answer I'd like to get is lorry1, box1 and lorry2, box1.

Even better yet: I'd like to find all items and provide the information, like this:

"shoes": [ {"lorry1", "box1"}, {"lorry2", "box1" } ],
"snacks": [ {"lorry1", "box1"}, {"lorry2", "box1"} ],
"beer": [ {"lorry1", "box2"}, {"lorry2", "box2"} ],
"potatoes": [ {"lorry1", "box2"} ]

but that may be asking a bit too much :)

Body:
The answer I'd like to get is lorry1, box1 and lorry2, box1

In this case, you can get it with:

path(.. | select(.item? == "shoes"))

Which returns:

["lorry1","box1",0]
["lorry2","box1",0]

These are the paths in your object that will lead to an object which .item property is set to "shoes"


问:
history.back() doesn't work in firefox and internet explorer but it work in google chrome
I encountered an anomaly by adding a button back to the previous page on JSP:
indeed when I click on the button the values of the fields that i filled will be lost
this behavior is detected on firefoxe and internet explorer,
on the other hand everything works well on chrome when I click on the button the values that I filled are displayed correctly.
can you help me on this point knowing that i tried the code below:

<button type="button" name="back" onCLick="history.back()">Retour</button>

<button type="button" name="back" onCLick="window.history.go(-1)">Retour</button>

<button type="button" name="back" onClick="goBack()">Retour</button>

function goBack() {
    window.history.back();
}

-below the current code:

```<code><button type="button" name="back" onclick="history.back()">Retour</button>
</code>```

Wainting for your help.

答:
You are trying to set an event handler on your button using onclick attribute.

It's not onClick or onCLick. You were close:

```<code><button type="button" name="back" onclick="window.history.back()">Retour</button>
</code>```

Body:
I encountered an anomaly by adding a button back to the previous page on JSP:
indeed when I click on the button the values of the fields that i filled will be lost
this behavior is detected on firefoxe and internet explorer,
on the other hand everything works well on chrome when I click on the button the values that I filled are displayed correctly.
can you help me on this point knowing that i tried the code below:

<button type="button" name="back" onCLick="history.back()">Retour</button>

<button type="button" name="back" onCLick="window.history.go(-1)">Retour</button>

<button type="button" name="back" onClick="goBack()">Retour</button>

function goBack() {
    window.history.back();
}

-below the current code:

<button type="button" name="back" onclick="history.back()">Retour</button>

Wainting for your help.

Body:
You are trying to set an event handler on your button using onclick attribute.

It's not onClick or onCLick. You were close:

<button type="button" name="back" onclick="window.history.back()">Retour</button>


问:
SDL 2.0 Key repeat and delay
I'm having a problem with SDL 2.0 keyboard input in pong-like game. When I order to move to the left by pressing left arrow, it is processed by SDL_PollEvents() and responds correctly if the key was pressed once. However, if I keep the key pressed, I get a short delay (as long as Windows key repeat delay) before moving continuously.

Here is function processing events:

```<code>void Event::PlayerEvent (Player &player)
{
    while (SDL_PollEvent (&mainEvent))
    {
        switch (mainEvent.type)
        {
            case SDL_KEYDOWN :
                switch (mainEvent.key.keysym.sym)
                {
                    case SDLK_ESCAPE :
                        gameRunning = false;
                        break;
                    case SDLK_LEFT :
                        player.moving = player.left;
                        break;
                    case SDLK_RIGHT :
                        player.moving = player.right;
                }
                break;
            case SDL_QUIT :
                gameRunning = false;
        }
    }
}
</code>```

EDIT: After all, I managed to fix this issue by calling
SystemParametersInfo (SPI_SETKEYBOARDDELAY, 0, 0, 0) at the start of the program and SystemParametersInfo (SPI_SETKEYBOARDDELAY, 1, 0, 0) at the end, to return to standard key repeat delay.

答:
using SPI_SETKEYBOARDDELAY is not a good approach. This way your game will not be protable anymore since its only available on Windows.

Instead you should use like menthiond in an answer before SDL_GetKeyboardState.

Howeve be aware that you still have to collect the SDL_PollEvent. Otherwise SDL_GetKeyboardState will be always empty.

So it should be like this:

```<code>//...
SDL_Event sdlEvent;
while (SDL_PollEvent(&sdlEvent)) {
    if (sdlEvent.type == SDL_QUIT) {
        //..
    }
}

const Uint8* keystates = SDL_GetKeyboardState(NULL);

if(keystates[SDL_SCANCODE_LEFT]) {
    //...
}
if(keystates[SDL_SCANCODE_RIGHT]) {
    /...
}
//...
</code>```

Title: SDL 2.0 Key repeat and delay

Body:
I'm having a problem with SDL 2.0 keyboard input in pong-like game. When I order to move to the left by pressing left arrow, it is processed by SDL_PollEvents() and responds correctly if the key was pressed once. However, if I keep the key pressed, I get a short delay (as long as Windows key repeat delay) before moving continuously.

Here is function processing events:

void Event::PlayerEvent (Player &player)
{
    while (SDL_PollEvent (&mainEvent))
    {
        switch (mainEvent.type)
        {
            case SDL_KEYDOWN :
                switch (mainEvent.key.keysym.sym)
                {
                    case SDLK_ESCAPE :
                        gameRunning = false;
                        break;
                    case SDLK_LEFT :
                        player.moving = player.left;
                        break;
                    case SDLK_RIGHT :
                        player.moving = player.right;
                }
                break;
            case SDL_QUIT :
                gameRunning = false;
        }
    }
}

EDIT: After all, I managed to fix this issue by calling
SystemParametersInfo (SPI_SETKEYBOARDDELAY, 0, 0, 0) at the start of the program and SystemParametersInfo (SPI_SETKEYBOARDDELAY, 1, 0, 0) at the end, to return to standard key repeat delay.

Body:
using SPI_SETKEYBOARDDELAY is not a good approach. This way your game will not be protable anymore since its only available on Windows.

Instead you should use like menthiond in an answer before SDL_GetKeyboardState.

Howeve be aware that you still have to collect the SDL_PollEvent. Otherwise SDL_GetKeyboardState will be always empty.

So it should be like this:

//...
SDL_Event sdlEvent;
while (SDL_PollEvent(&sdlEvent)) {
    if (sdlEvent.type == SDL_QUIT) {
        //..
    }
}

const Uint8* keystates = SDL_GetKeyboardState(NULL);

if(keystates[SDL_SCANCODE_LEFT]) {
    //...
}
if(keystates[SDL_SCANCODE_RIGHT]) {
    /...
}
//...


问:
Does a JavaScript-function can be seen as an execution context respectively as this?
In the lower example, why does the function outer which is assigned as method to the object-property with the identifier meth does not have an execution context which would be the this in the inner-function?

Since the function outer assigned to meth seems to automatically get the this-keyword set to the surrounding object as execution context, you could assume, that the function inner is getting handled the same way, or is it because a surrounding function can not be seen as an execution context, therefore JavaScript does not know for the function inner which execution context it is in, so it assumes the default, which is then window?

```<code>var foo = {
    meth: function outer() {
        console.log(this);
        // let that = this;
        function inner() {
            console.log(this);
        }
        inner();
    }
};
</code>```

```<code>//Output
{meth: ƒ}
Window {parent: Window, opener: null, top: Window, length: 0, frames: Window, …}
</code>```

Thanks in advance for demystifying

答:
When you see this code:

```<code>function inner() {
    console.log(this);
}
inner();
</code>```

It really is irrelevant whether that code occurs in another function body or not, or whether that function body belongs to a method of some object, ...etc. It is irrelevant.

What is relevant is how you call inner. You call it not as someobject.inner(), nor with explicit binding, like inner.call(this), ... so there is no binding of this, hence you get the default binding, which is the window object when running in sloppy mode, or undefined in strict mode.

The function outer assigned to meth seems to automatically get the this-keyword set to the surrounding object as execution context

This is not assured. If you do:

```<code>let outer = meth.outer;
outer();
</code>```

...then you will notice that this is getting the default binding as well. Again, it depends on how you call the function.

If you call it with the dot-notation, then you implicitly bind it with the object:

```<code>meth.outer();
</code>```

So now this will be meth in the execution context of outer.

Body:
In the lower example, why does the function outer which is assigned as method to the object-property with the identifier meth does not have an execution context which would be the this in the inner-function?

Since the function outer assigned to meth seems to automatically get the this-keyword set to the surrounding object as execution context, you could assume, that the function inner is getting handled the same way, or is it because a surrounding function can not be seen as an execution context, therefore JavaScript does not know for the function inner which execution context it is in, so it assumes the default, which is then window?

var foo = {
    meth: function outer() {
        console.log(this);
        // let that = this;
        function inner() {
            console.log(this);
        }
        inner();
    }
};

//Output
{meth: ƒ}
Window {parent: Window, opener: null, top: Window, length: 0, frames: Window, …}

Thanks in advance for demystifying

Body:
When you see this code:

function inner() {
    console.log(this);
}
inner();

It really is irrelevant whether that code occurs in another function body or not, or whether that function body belongs to a method of some object, ...etc. It is irrelevant.

What is relevant is how you call inner. You call it not as someobject.inner(), nor with explicit binding, like inner.call(this), ... so there is no binding of this, hence you get the default binding, which is the window object when running in sloppy mode, or undefined in strict mode.

The function outer assigned to meth seems to automatically get the this-keyword set to the surrounding object as execution context

This is not assured. If you do:

let outer = meth.outer;
outer();

...then you will notice that this is getting the default binding as well. Again, it depends on how you call the function.

If you call it with the dot-notation, then you implicitly bind it with the object:

meth.outer();

So now this will be meth in the execution context of outer.


问:
Complex promql queries
I have prometheus with metrics of many users. I need to apply some promql functions to EACH metric. Can i create one request to prometheus, to get metrics in desired format?
For example, apply avg on CPU metric and irate on IO at the same time</p>

答: That's not possible, each query/query_range API call can only evaluate one PromQL expression.</p>

Title: Complex promql queries


问:
how to draw chart using in python
I have a CSV file customer:

```<code>-------------------------------------------
index | age_group | female | male | total |
-------------------------------------------
  0       16-20       23      5      28   |
  1       20-26       66      12     78   |
  2       26-32       12      3      15   |
 ...       ...        ..     ...     ..   |
-------------------------------------------
</code>```

I want to make a barchart to show the relationship between age group and total and a barchart to show the relationship between different gender and total.

答:
I used pandas to do the plotting.

import pandas as pd

# Barchart to show the relationship between age group and total
df.plot.bar(x='age_group', y='total', rot=0)

# Barchart to show the relationship between different gender and total
df.plot.bar(x='age_group', y=['female', 'male'], rot=0)
```

Title: how to draw chart using in python

Body:
I have a CSV file customer:

-------------------------------------------
index | age_group | female | male | total |
-------------------------------------------
  0       16-20       23      5      28   |
  1       20-26       66      12     78   |
  2       26-32       12      3      15   |
 ...       ...        ..     ...     ..   |
-------------------------------------------

I want to make a barchart to show the relationship between age group and total and a barchart to show the relationship between different gender and total.


问:
How to do background sync instead of fetch requests on UI changes?
For example, let's take a simple web application with comments feature. In my understanding, when a user posts a new comment, the following would occur:

display UI loader;

update the front-end state;

send a fetch request to the API to post a new comment;

Wait for the response;

send another fetch request to the API to request the new list of comments;

waiting;

update the front-end state with new comments;

update UI to reflect the new state with a new comment;

And the user needs to wait while front-end app interacts with back-end on almost every data change. The same way we did it earlier with PHP/Python/Ruby, ajax, server-side rendering and templates.

That makes me think what's the point of adding so much front-end complexity with something like react, when the result is basically the same.

My question is: are there any alternative approaches to this? Is it possible instead to do the above case the following way:

user clicks to post a comment;

update the front-end state;

update UI to reflect the new state with a new comment;

sync front-end state with API DB in the background;

答: Well, as your question is tagged react, you could use the Apollo library (it is intended to work together with graphql on the backend) for data fetching. It offers a feature called Optimistic UI, which will be update the frontend with the respected result, until it receives an answer from the backend. If the expected result differs from the received one, the component will change the UI automatically to the real result. In case of an error, it will show an error message.


问:
CSV File with minus sign after number. "ValueError: could not convert string to float:"
I have several CSV Files, where the a negative number is displayed with the minus sign after the number (30.50- instead of -30.50). If I try to convert the column to an integer, Python returns an ValueError (ValueError: could not convert string to float: '30.50-')

Does anybody have an idea how to handle that?

Thanks in Advance!

Best,
Moritz

答:
As your string is not in valid format to convert into float you first need to make it right by remove - from right using rstrip and add it to front.

For example:

```<code>df = pd.DataFrame({'a':['1.5-','1.7','2.0','4.1-']})
df.a.apply(lambda x: '-'+(x.rstrip('-')) if x[-1] =='-' else x).astype(float)
0   -1.5
1    1.7
2    2.0
3   -4.1
Name: a, dtype: float64
</code>```

Body:
As your string is not in valid format to convert into float you first need to make it right by remove - from right using rstrip and add it to front.

For example:

df = pd.DataFrame({'a':['1.5-','1.7','2.0','4.1-']})
df.a.apply(lambda x: '-'+(x.rstrip('-')) if x[-1] =='-' else x).astype(float)
0   -1.5
1    1.7
2    2.0
3   -4.1
Name: a, dtype: float64


问:
.NET Regex: Get all matched groups
I've stuck with regex problem using .NET. For example, I have next regex pattern: (?'group1'A|C)|(?'group2'B|C)|(?'group3'A|B|C)

When I do match of "AXYZ" I receive match object which contains Value and Groups; if I go to Groups I'll see that only one group has success in true - group1 (group3 is in false). If I do match of "BXYZ" I'll receive only group2 with success in true (group3 is in false).

How could I receive in match not only one group but all groups satisfying the match?

For example above it should be: group1 & group3 in "AXYZ" and group2 & group3 in "BXYZ".

All above is only example in real system there are different patterns (3+ letters each) and more complicated input text (1000+ words).

答:
The regex you have there will only match single characters; as soon as a match has been found on a character, the regex moves onto the next character in the input string. In your example, 'B' will never be matched by 'group2' or 'group3' as it will always be matched by 'group1'. Similarly, 'A' will never be matched by 'group3' for the same reason.

One way of getting the outcome you require using regexes is to treat each group as a separate regex and use Regex.IsMatch() on each one. For counts, the following C# does what I think you're asking for:

```<code>string input = "AXYZ";
int count = 0;

count += Regex.IsMatch(input, "A|B") ? 1 : 0;
count += Regex.IsMatch(input, "B|C") ? 1 : 0;
count += Regex.IsMatch(input, "A|B|D") ? 1 : 0;

Console.WriteLine(count); // returns 2
</code>```

Title: .NET Regex: Get all matched groups

Body:
The regex you have there will only match single characters; as soon as a match has been found on a character, the regex moves onto the next character in the input string. In your example, 'B' will never be matched by 'group2' or 'group3' as it will always be matched by 'group1'. Similarly, 'A' will never be matched by 'group3' for the same reason.

One way of getting the outcome you require using regexes is to treat each group as a separate regex and use Regex.IsMatch() on each one. For counts, the following C# does what I think you're asking for:

string input = "AXYZ";
int count = 0;

count += Regex.IsMatch(input, "A|B") ? 1 : 0;
count += Regex.IsMatch(input, "B|C") ? 1 : 0;
count += Regex.IsMatch(input, "A|B|D") ? 1 : 0;

Console.WriteLine(count); // returns 2


问:
"None of [Float64Index([nan, nan], dtype='float64')] are in the [index]" setting col A value if col B contains string
I have a dataframe (called corpus) with one column (tweet) and 2 rows:

```<code>['check, tihs, out, this, bear, love, jumping, on, this, plant']
['i, can, t, bear, the, noise, from, that, power, plant, it, make, me, jump']
</code>```

I have a list (called vocab) of unique words in the column:

```<code>['check',
 'tihs',
 'out',
 'this',
 'bear',
 'love',
 'jumping',
 'on',
 'plant',
 'i',
 'can',
 't',
 'the',
 'noise',
 'from',
 'that',
 'power',
 'it',
 'make',
 'me',
 'jump']
</code>```

I want to add a new column for each word in vocab. I want all values for the new columns to be zero, except for when the tweet contains the word, in which case I want the value of the word column to be 1.

So I tried running the code below:

```<code>for word in vocab:
    corpus[word] = 0
    corpus.loc[corpus["tweet"].str.contains(word), word] = 1
</code>```

...and the following error was displayed:

```<code>"None of [Float64Index([nan, nan], dtype='float64')] are in the [index]"
</code>```

How can I check to see if the tweet contains the word, and then if so, set the value of the new column for the word to 1?

答:
This will do:

```<code>from sklearn.feature_extraction.text import CountVectorizer

l = ['check, this, out, this, bear, love, jumping, on, this, plant',
'i, can, t, bear, the, noise, from, that, power, plant, it, make, me, jump']
vect = CountVectorizer()
X = pd.DataFrame(vect.fit_transform(l).toarray())
X.columns = vect.get_feature_names()
</code>```

Output:

```<code>bear  can  check  from  it  jump  ...  out  plant  power  that  the  this
0     1    0      1     0   0     0  ...    1      1      0     0    0     3
1     1    1      0     1   1     1  ...    0      1      1     1    1     0
</code>```

Body:
I have a dataframe (called corpus) with one column (tweet) and 2 rows:

['check, tihs, out, this, bear, love, jumping, on, this, plant']
['i, can, t, bear, the, noise, from, that, power, plant, it, make, me, jump']

I have a list (called vocab) of unique words in the column:

['check',
 'tihs',
 'out',
 'this',
 'bear',
 'love',
 'jumping',
 'on',
 'plant',
 'i',
 'can',
 't',
 'the',
 'noise',
 'from',
 'that',
 'power',
 'it',
 'make',
 'me',
 'jump']

I want to add a new column for each word in vocab. I want all values for the new columns to be zero, except for when the tweet contains the word, in which case I want the value of the word column to be 1.

So I tried running the code below:

for word in vocab:
    corpus[word] = 0
    corpus.loc[corpus["tweet"].str.contains(word), word] = 1

...and the following error was displayed:

"None of [Float64Index([nan, nan], dtype='float64')] are in the [index]"

How can I check to see if the tweet contains the word, and then if so, set the value of the new column for the word to 1?

Body:
This will do:

from sklearn.feature_extraction.text import CountVectorizer

l = ['check, this, out, this, bear, love, jumping, on, this, plant',
'i, can, t, bear, the, noise, from, that, power, plant, it, make, me, jump']
vect = CountVectorizer()
X = pd.DataFrame(vect.fit_transform(l).toarray())
X.columns = vect.get_feature_names()

Output:

bear  can  check  from  it  jump  ...  out  plant  power  that  the  this
0     1    0      1     0   0     0  ...    1      1      0     0    0     3
1     1    1      0     1   1     1  ...    0      1      1     1    1     0


问:
setState upon pressing creates new object
Before pressing there are only 3 buttons but after pressing any button as you can see there is 6 buttons

I'm trying to create rating system for my app, but whenever I press a button a new Button is created and I'm not quite sure why that happens.

If i try to run it without setState() and I press button no new object is created and that is what I want in the end.

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

class Rating extends StatefulWidget {
  @override
  _RatingState createState() => _RatingState();
}

class _RatingState extends State<Rating> {
  final List<IconData> iconsImage = [
    Icons.star,
    Icons.star,
    Icons.star,
    Icons.star,
  ];
  List<ButtonTheme> buttonsList = new List<ButtonTheme>();

  List<Widget> _buildButtons() {
    for (int i = 0; i < 3; i++) {
      buttonsList.add(ButtonTheme(
        height: 20,
        minWidth: 40,
        child: FlatButton(
          onPressed: () {
            //When i press button new star is created not sure why
            setState(() {
              print(i);
            });
          },
          child: Icon(Icons.star),
        ),
      ));
    }
    return buttonsList;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[900],
      body: Container(
        child: Column(
          children: <Widget>[
            Container(
              child: Text('Rate the homework',
                  style: TextStyle(
                    color: Colors.white,
                  )),
            ),
            Divider(
              height: 30,
              color: Colors.red,
            ),
            Row(
              children: _buildButtons(),
            )
          ],
        ),
      ),
    );
  }
}
</code>```

答:
Place your _buildButtons method inside a build function.

Reason: State Class in Stateful Widget are meant to hold and persist the state even during rebuild so that old state is remembered.

Here buttonsList is your state which will not be overwritten. So
  Clicking button (which will set state) will push new button to an existing button list(not to
  a newly created list).

Solution: If you initialize you buttonsList inside a build function,it will also be reinitialized during re-build. So Clicking button (which will set state) will push new button to an newly created button list(not to a existing created list).

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

class Rating extends StatefulWidget {
  @override
  _RatingState createState() => _RatingState();
}

class _RatingState extends State<Rating> {
  @override
  Widget build(BuildContext context) {
    List<ButtonTheme> buttonsList = new List<ButtonTheme>();

    List<Widget> _buildButtons() {
      for (int i = 0; i < 3; i++) {
        buttonsList.add(ButtonTheme(
          height: 20,
          minWidth: 40,
          child: FlatButton(
            onPressed: () {
              //When i press button new star is created not sure why
              setState(() {
                print(i);
              });
            },
            child: Icon(Icons.star),
          ),
        ));
      }
      return buttonsList;
    }

    return Scaffold(
      backgroundColor: Colors.grey[900],
      body: Container(
        child: Column(
          children: <Widget>[
            Container(
              child: Text('Rate the homework',
                  style: TextStyle(
                    color: Colors.white,
                  )),
            ),
            Divider(
              height: 30,
              color: Colors.red,
            ),
            Row(
              children: _buildButtons(),
            )
          ],
        ),
      ),
    );
  }
}
</code>```

Body:
Before pressing there are only 3 buttons but after pressing any button as you can see there is 6 buttons

I'm trying to create rating system for my app, but whenever I press a button a new Button is created and I'm not quite sure why that happens.

If i try to run it without setState() and I press button no new object is created and that is what I want in the end.

import 'package:flutter/material.dart';

class Rating extends StatefulWidget {
  @override
  _RatingState createState() => _RatingState();
}

class _RatingState extends State<Rating> {
  final List<IconData> iconsImage = [
    Icons.star,
    Icons.star,
    Icons.star,
    Icons.star,
  ];
  List<ButtonTheme> buttonsList = new List<ButtonTheme>();

  List<Widget> _buildButtons() {
    for (int i = 0; i < 3; i++) {
      buttonsList.add(ButtonTheme(
        height: 20,
        minWidth: 40,
        child: FlatButton(
          onPressed: () {
            //When i press button new star is created not sure why
            setState(() {
              print(i);
            });
          },
          child: Icon(Icons.star),
        ),
      ));
    }
    return buttonsList;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[900],
      body: Container(
        child: Column(
          children: <Widget>[
            Container(
              child: Text('Rate the homework',
                  style: TextStyle(
                    color: Colors.white,
                  )),
            ),
            Divider(
              height: 30,
              color: Colors.red,
            ),
            Row(
              children: _buildButtons(),
            )
          ],
        ),
      ),
    );
  }
}

Body:
Place your _buildButtons method inside a build function.

Reason: State Class in Stateful Widget are meant to hold and persist the state even during rebuild so that old state is remembered.

Here buttonsList is your state which will not be overwritten. So
  Clicking button (which will set state) will push new button to an existing button list(not to
  a newly created list).

Solution: If you initialize you buttonsList inside a build function,it will also be reinitialized during re-build. So Clicking button (which will set state) will push new button to an newly created button list(not to a existing created list).

import 'package:flutter/material.dart';

class Rating extends StatefulWidget {
  @override
  _RatingState createState() => _RatingState();
}

class _RatingState extends State<Rating> {
  @override
  Widget build(BuildContext context) {
    List<ButtonTheme> buttonsList = new List<ButtonTheme>();

    List<Widget> _buildButtons() {
      for (int i = 0; i < 3; i++) {
        buttonsList.add(ButtonTheme(
          height: 20,
          minWidth: 40,
          child: FlatButton(
            onPressed: () {
              //When i press button new star is created not sure why
              setState(() {
                print(i);
              });
            },
            child: Icon(Icons.star),
          ),
        ));
      }
      return buttonsList;
    }

    return Scaffold(
      backgroundColor: Colors.grey[900],
      body: Container(
        child: Column(
          children: <Widget>[
            Container(
              child: Text('Rate the homework',
                  style: TextStyle(
                    color: Colors.white,
                  )),
            ),
            Divider(
              height: 30,
              color: Colors.red,
            ),
            Row(
              children: _buildButtons(),
            )
          ],
        ),
      ),
    );
  }
}


问:
Using props in vue components
I'm just learning Vue, and now starting with props. I'm having trouble integrating them into my code below.
I want to make so a prop name can be sent to the greet component. I want name to  be shown in the component<greet name="User"></greet> and it to render:
Welcome, User!

```<code>Vue.component('greet', {
  data() {
    return {

    }
  },
  template: '<div>Welcome !</div>'
})

new Vue({ el: '#app' })
</code>```

答:
There is good documentation about it

Vue.component('greet', {
  props: {
    'player-name': {
      type: String,
      required: true
    }
  },
  data() {
    return {

    }
  },
  template: '
Welcome {{playerName}}!
'
})

new Vue({
  el: '#app'
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <greet player-name="User"></greet>
</div></code>```

Title: Using props in vue components

Body:
I'm just learning Vue, and now starting with props. I'm having trouble integrating them into my code below.
I want to make so a prop name can be sent to the greet component. I want name to  be shown in the component<greet name="User"></greet> and it to render:
Welcome, User!

Vue.component('greet', {
  data() {
    return {

    }
  },
  template: '
Welcome !
'
})

new Vue({ el: '#app' })

Body:
There is good documentation about it

Vue.component('greet', {
  props: {
    'player-name': {
      type: String,
      required: true
    }
  },
  data() {
    return {

    }
  },
  template: '<div>Welcome {{playerName}}!</div>'
})

new Vue({
  el: '#app'
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <greet player-name="User"></greet>
</div>


问:
How do I do an IF in Microsoft SQL SELECT query?
I am an absolute beginner in SQL.
Example:
I want to do a query to select people whose names begin with X if the result is 0, I want to select people whose names begin with Y.

How do I do this? Thanks.

答: There are ways to do perform this in a single SQL statement, but they are extremely expensive (both in time and resources). You would be best served to do this kind of logic in a stored procedure.</p>


问:
How to center (vertically and horizontally) an image inside a div centered (horizontally) in another div
I would like to have an image centered horizontally and vertically in a div which is also centered (horizontally) in another div.

Something like this:

I imagine this being done like this:

```<code><div class="grandad">
  <div class="parent">
    <img src="someUrl"/>
  </div>
</div>
</code>```

https://codepen.io/lucasactimo/pen/qBOzjwb

But I can't manage to find the right CSS rules to achieve this arrangement. Some help would be very much appreciated!

答:
Use flexbox twice, for the inner and outer container, with those settings to center the (only) child:

```<code>  display: flex;
  justify-content: center;
  align-items: center;
</code>```

.grandad {
  height: 300px;
  border: 1px solid #bbb;
  display: flex;
  justify-content: center;
  align-items: center;
}

.parent {
  height: 200px;
  width: 200px;
  border-radius: 50%;
  background-color: red;
  display: flex;
  justify-content: center;
  align-items: center;
}

img {
  height: 64px;
  width: 64px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grandad">
  <div class="parent">
    <img src="https://p0.pikist.com/photos/915/114/flower-macro-nature-flora-wild-flowers-blossomed-summer-flowers-white-flowers-pollen.jpg" />
  </div>
</div></code>```

Body:
I would like to have an image centered horizontally and vertically in a div which is also centered (horizontally) in another div.

Something like this:

I imagine this being done like this:

https://codepen.io/lucasactimo/pen/qBOzjwb

But I can't manage to find the right CSS rules to achieve this arrangement. Some help would be very much appreciated!

Body:
Use flexbox twice, for the inner and outer container, with those settings to center the (only) child:

  display: flex;
  justify-content: center;
  align-items: center;

.grandad {
  height: 300px;
  border: 1px solid #bbb;
  display: flex;
  justify-content: center;
  align-items: center;
}

.parent {
  height: 200px;
  width: 200px;
  border-radius: 50%;
  background-color: red;
  display: flex;
  justify-content: center;
  align-items: center;
}

img {
  height: 64px;
  width: 64px;
}

<div class="grandad">
  <div class="parent">
    <img src="https://p0.pikist.com/photos/915/114/flower-macro-nature-flora-wild-flowers-blossomed-summer-flowers-white-flowers-pollen.jpg" />
  </div>
</div>