问:
Android Studio turning black colors to white when switched to dark mode
I am new to android studio and I am designing an app which must open a pdf file from the android storage device. I set the background color to black in the activity view and it works fine as long as I am not using my android in Dark mode. Once I turn on dark mode, the background color switches from black to white.

The activity view code:

```<code><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ViewPdfActivity"
android:background="@color/black"
android:orientation="vertical"
>

<com.github.barteksc.pdfviewer.PDFView
    android:id="@+id/pdfView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="10dp"
    android:background="@color/black"
    />
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Themes.xml

```<code><resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Theme.PDFwordmeaning" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Primary brand color. -->
    <item name="colorPrimary">@color/black</item>
    <item name="colorPrimaryDark">@color/black</item>
    <item name="colorAccent">@color/black</item>
    <!-- Secondary brand color. -->
    <item name="colorSecondary">@color/black</item>
    <item name="colorSecondaryVariant">@color/black</item>
    <item name="colorOnSecondary">@color/black</item>
    <!-- Status bar color. -->
    <item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
    <!-- Customize your theme here. -->
</style>
<style name="AppTheme" parent="@style/Theme.AppCompat.Light.NoActionBar">
    <item name="windowNoTitle">true</item>
    <item name="android:windowNoTitle">true</item>
</style>
</code>```

night\themes.xml

```<code><resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Theme.PDFwordmeaning" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
    <!-- Primary brand color. -->
    <item name="colorPrimary">@color/black</item>
    <item name="colorPrimaryDark">@color/black</item>
    <item name="colorAccent">@color/black</item>
    <!-- Secondary brand color. -->
    <item name="colorSecondary">@color/black</item>
    <item name="colorSecondaryVariant">@color/black</item>
    <item name="colorOnSecondary">@color/black</item>
    <!-- Status bar color. -->
    <item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
    <!-- Customize your theme here. -->
</style>
</code>```

colors.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="purple_200">#FFBB86FC</color>
    <color name="purple_500">#FF6200EE</color>
    <color name="purple_700">#FF3700B3</color>
    <color name="teal_200">#FF03DAC5</color>
    <color name="teal_700">#FF018786</color>
    <color name="black">#FF000000</color>
    <color name="white">#FFFFFFFF</color>
</resources>
</code>```

答:
I encountered a similar problem.

https://support.google.com/accessibility/android/answer/6151800?hl=en

As stated above, Try using dark theme on your phone and Turn on color inversion on your phone, if it fixes the issue. Then your app doesn't support dark theme. So some devices force it which leads to this behavior.

You can fix this by simply adding the following to your style in themes.xml

```<code> <item name="android:forceDarkAllowed">false</item>
</code>```

Body:
I am new to android studio and I am designing an app which must open a pdf file from the android storage device. I set the background color to black in the activity view and it works fine as long as I am not using my android in Dark mode. Once I turn on dark mode, the background color switches from black to white.

The activity view code:

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ViewPdfActivity"
android:background="@color/black"
android:orientation="vertical"
>

<com.github.barteksc.pdfviewer.PDFView
    android:id="@+id/pdfView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="10dp"
    android:background="@color/black"
    />
</androidx.constraintlayout.widget.ConstraintLayout>

Themes.xml

<resources xmlns:tools="http://schemas.android.com/tools">

night\themes.xml

<resources xmlns:tools="http://schemas.android.com/tools">

colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="purple_200">#FFBB86FC</color>
    <color name="purple_500">#FF6200EE</color>
    <color name="purple_700">#FF3700B3</color>
    <color name="teal_200">#FF03DAC5</color>
    <color name="teal_700">#FF018786</color>
    <color name="black">#FF000000</color>
    <color name="white">#FFFFFFFF</color>
</resources>

Body:
I encountered a similar problem.

https://support.google.com/accessibility/android/answer/6151800?hl=en

As stated above, Try using dark theme on your phone and Turn on color inversion on your phone, if it fixes the issue. Then your app doesn't support dark theme. So some devices force it which leads to this behavior.

You can fix this by simply adding the following to your style in themes.xml

 <item name="android:forceDarkAllowed">false</item>


来源: stackexchange

问:
How can I call a function from the parent component with an event in the child?
I'm busy learning React and one of the tasks is building a game where the cards shuffle on each try. The card array and the shuffle method are in a parent component (I use map to render the cards), but the retry button is in the child component.

I've read almost 20 StackOverflow questions and many docs, but somehow my logic is simply not working.

Can someone please help me to get this to work.

Parent:

```<code>import React from 'react'
import FlipCard from './FlipCard'

const cards = [
    {
        id: 1,
        text: 'NOPE',
    },
    {
        id: 2,
        text: `!!WIN-
        NER!!`,
    },
    {
        id: 3,
        text: 'NOPE',
    },
]

const shuffle = array => {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1))
        const temp = array[i]
        array[i] = array[j]
        array[j] = temp
    }
    return array
}

const shuffleCards = shuffle(cards)

const CardGameUI = () => {
    return (
        <div className="cards-ui">
            {cards.map(card => (
                <FlipCard
                    key={card.id}
                    text={card.text}
                    value={card.id}
                    shuffleCards={shuffleCards}
                />
            ))}
        </div>
    )
}

export default CardGameUI
</code>```

Child:

```<code>import React from 'react'
import ReactCardFlip from 'react-card-flip'
import FrontComponent from './FrontComponent'
import BackComponent from './BackComponent'
import RetryModal from './RetryModal'

class FlipCard extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            isFlipped: false,
            gamesPlayed: 0,
            gamesWon: 0,
            gamesLost: 0,
            show: false,
            gameMsg: '',
        }

        this.handleFlip = this.handleFlip.bind(this)
        this.handleShow = this.handleShow.bind(this)
        this.handleClose = this.handleClose.bind(this)
        this.handleReset = this.handleReset.bind(this)
        this.handleRetry = this.handleRetry.bind(this)
    }

    handleReset() {
        this.setState({
            isFlipped: false,
            gamesPlayed: 0,
            gamesWon: 0,
            gamesLost: 0,
            show: false,
            gameMsg: '',
        })
        this.props.shuffleCards
    }

    handleRetry() {
        this.setState({
            isFlipped: false,
            show: false,
            gameMsg: '',
        })
        this.props.shuffleCards
    }

    handleClose() {
        this.setState({
            show: false,
        })
    }
    handleShow() {
        this.setState({
            show: true,
        })
    }

    handleFlip() {
        this.setState({
            isFlipped: true,
            gamesPlayed: +1,
            show: false,
        })

        if (this.props.value !== 2) {
            this.setState({
                gamesLost: 0,
                gameMsg:
                    'It looks like you lost this round. Want to play another?',
            })
        } else if (this.props.value === 2) {
            this.setState({
                gamesWon: 0,
                gameMsg: 'CONGRATULATIONS!!!. Want to win again?',
            })
        }

        setTimeout(() => {
            this.handleShow()
        }, 1000)
    }

    render() {
        const text = this.props.text
        const value = this.props.value
        const isFlipped = this.state.isFlipped

        return (
            <>
                <ReactCardFlip isFlipped={isFlipped} flipDirection="horizontal">
                    <FrontComponent onClick={this.handleFlip} />

                    <BackComponent text={text} value={value} />
                </ReactCardFlip>

                <RetryModal
                    handleShow={this.handleShow}
                    handleClose={this.handleClose}
                    handleReset={this.handleReset}
                    handleRetry={this.handleRetry}
                    show={this.state.show}
                    text={this.state.gameMsg}
                />
            </>
        )
    }
}

export default FlipCard
</code>```

I included all the code from these two components as I wasn't sure what will help clarify.

Essentially the shuffleCards method needs to run when handleReset and handleRetry are triggered.

答:
```<code>let array = [...cards];
const shuffle = () => {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1))
        const temp = array[i]
        array[i] = array[j]
        array[j] = temp
    }
    return array
}
</code>```

Just replace shuffle function by this code !
I hope it works !

ContentLicense: CC BY-SA 4.0

Body:
I'm busy learning React and one of the tasks is building a game where the cards shuffle on each try. The card array and the shuffle method are in a parent component (I use map to render the cards), but the retry button is in the child component.

I've read almost 20 StackOverflow questions and many docs, but somehow my logic is simply not working.

Can someone please help me to get this to work.

Parent:

import React from 'react'
import FlipCard from './FlipCard'

const cards = [
    {
        id: 1,
        text: 'NOPE',
    },
    {
        id: 2,
        text: `!!WIN-
        NER!!`,
    },
    {
        id: 3,
        text: 'NOPE',
    },
]

const shuffle = array => {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1))
        const temp = array[i]
        array[i] = array[j]
        array[j] = temp
    }
    return array
}

const shuffleCards = shuffle(cards)

const CardGameUI = () => {
    return (

            {cards.map(card => (
                <FlipCard
                    key={card.id}
                    text={card.text}
                    value={card.id}
                    shuffleCards={shuffleCards}
                />
            ))}

    )
}

export default CardGameUI

Child:

import React from 'react'
import ReactCardFlip from 'react-card-flip'
import FrontComponent from './FrontComponent'
import BackComponent from './BackComponent'
import RetryModal from './RetryModal'

class FlipCard extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            isFlipped: false,
            gamesPlayed: 0,
            gamesWon: 0,
            gamesLost: 0,
            show: false,
            gameMsg: '',
        }

        this.handleFlip = this.handleFlip.bind(this)
        this.handleShow = this.handleShow.bind(this)
        this.handleClose = this.handleClose.bind(this)
        this.handleReset = this.handleReset.bind(this)
        this.handleRetry = this.handleRetry.bind(this)
    }

    handleReset() {
        this.setState({
            isFlipped: false,
            gamesPlayed: 0,
            gamesWon: 0,
            gamesLost: 0,
            show: false,
            gameMsg: '',
        })
        this.props.shuffleCards
    }

    handleRetry() {
        this.setState({
            isFlipped: false,
            show: false,
            gameMsg: '',
        })
        this.props.shuffleCards
    }

    handleClose() {
        this.setState({
            show: false,
        })
    }
    handleShow() {
        this.setState({
            show: true,
        })
    }

    handleFlip() {
        this.setState({
            isFlipped: true,
            gamesPlayed: +1,
            show: false,
        })

        if (this.props.value !== 2) {
            this.setState({
                gamesLost: 0,
                gameMsg:
                    'It looks like you lost this round. Want to play another?',
            })
        } else if (this.props.value === 2) {
            this.setState({
                gamesWon: 0,
                gameMsg: 'CONGRATULATIONS!!!. Want to win again?',
            })
        }

        setTimeout(() => {
            this.handleShow()
        }, 1000)
    }

    render() {
        const text = this.props.text
        const value = this.props.value
        const isFlipped = this.state.isFlipped

        return (
            <>
                <ReactCardFlip isFlipped={isFlipped} flipDirection="horizontal">
                    <FrontComponent onClick={this.handleFlip} />

                    <BackComponent text={text} value={value} />
                </ReactCardFlip>

                <RetryModal
                    handleShow={this.handleShow}
                    handleClose={this.handleClose}
                    handleReset={this.handleReset}
                    handleRetry={this.handleRetry}
                    show={this.state.show}
                    text={this.state.gameMsg}
                />
            </>
        )
    }
}

export default FlipCard

I included all the code from these two components as I wasn't sure what will help clarify.

Essentially the shuffleCards method needs to run when handleReset and handleRetry are triggered.

Body:
let array = [...cards];
const shuffle = () => {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1))
        const temp = array[i]
        array[i] = array[j]
        array[j] = temp
    }
    return array
}

Just replace shuffle function by this code !
I hope it works !


问:
C++ : include string before the vowels in a sentence
I'm a beginner in c++ and I'm training on exercises.

I'm stuck on one part. I would like to insert the string "CH" in front of each vowel in a sentence.

I first tried using string::replace, but it was not the best idea.
I would like to use string::insert to do this.

However, I can't seem to use it properly in a loop to tell it that the [i] is the desired position

Do you have any advice for me?

```<code>    string message = "you have a secret message to decrypt";
    string newMessage = "";
    string InsertMessage = "CH";

    for (int i = 0; i < message.length(); i++) {
        if (
            message[i] == 'a' ||
            message[i] == 'e' ||
            message[i] == 'i' ||
            message[i] == 'o' ||
            message[i] == 'u' ||
            message[i] == 'y')
        {
            //newMessage = message.replace(i, 1, InsertMessage);
            newMessage = message.insert(i, InsertMessage);
        }
    }

    cout << newMessage << endl;

    return 0;
</code>```

答:
This statement

```<code>newMessage = message.insert(i, InsertMessage);
</code>```

does not make a sense at least because it changes the original string message.

I can suggest the following approach shown in the demonstration program below.

```<code>#include <iostream>
#include <string>
#include <iterator>
#include <algorithm>

int main()
{
    std::string message = "you have a secret message to decrypt";
    std::string newMessage;
    std::string InsertMessage = "CH";
    const char *vowels = "aeiouy";

    auto n = std::count_if( std::begin( message ), std::end( message ),
        [vowels]( const auto &c ) { return std::strchr( vowels, c ); } );

    newMessage.resize( message.size() + n * InsertMessage.size() );

    std::string::size_type pos = 0;
    do
    {
        auto i = message.find_first_of( vowels, pos );

        if (i == std::string::npos)
        {
            newMessage += message.substr( pos );
            pos = i;
        }
        else
        {
            newMessage += message.substr( pos, i - pos );
            newMessage += InsertMessage;
            pos = i;
            newMessage += message[pos++];
        }
    } while( pos != std::string::npos );

    std::cout << newMessage << '\n';
}
</code>```

The program output is

```<code>CHyCHoCHu hCHavCHe CHa sCHecrCHet mCHessCHagCHe tCHo dCHecrCHypt
</code>```

Body:
I'm a beginner in c++ and I'm training on exercises.

I'm stuck on one part. I would like to insert the string "CH" in front of each vowel in a sentence.

I first tried using string::replace, but it was not the best idea.
I would like to use string::insert to do this.

However, I can't seem to use it properly in a loop to tell it that the [i] is the desired position

Do you have any advice for me?

    string message = "you have a secret message to decrypt";
    string newMessage = "";
    string InsertMessage = "CH";

    for (int i = 0; i < message.length(); i++) {
        if (
            message[i] == 'a' ||
            message[i] == 'e' ||
            message[i] == 'i' ||
            message[i] == 'o' ||
            message[i] == 'u' ||
            message[i] == 'y')
        {
            //newMessage = message.replace(i, 1, InsertMessage);
            newMessage = message.insert(i, InsertMessage);
        }
    }

    cout << newMessage << endl;

    return 0;

Body:
This statement

newMessage = message.insert(i, InsertMessage);

does not make a sense at least because it changes the original string message.

I can suggest the following approach shown in the demonstration program below.

#include <iostream>
#include <string>
#include <iterator>
#include <algorithm>

int main()
{
    std::string message = "you have a secret message to decrypt";
    std::string newMessage;
    std::string InsertMessage = "CH";
    const char *vowels = "aeiouy";

    auto n = std::count_if( std::begin( message ), std::end( message ),
        [vowels]( const auto &c ) { return std::strchr( vowels, c ); } );

    newMessage.resize( message.size() + n * InsertMessage.size() );

    std::string::size_type pos = 0;
    do
    {
        auto i = message.find_first_of( vowels, pos );

        if (i == std::string::npos)
        {
            newMessage += message.substr( pos );
            pos = i;
        }
        else
        {
            newMessage += message.substr( pos, i - pos );
            newMessage += InsertMessage;
            pos = i;
            newMessage += message[pos++];
        }
    } while( pos != std::string::npos );

    std::cout << newMessage << '\n';
}

The program output is

CHyCHoCHu hCHavCHe CHa sCHecrCHet mCHessCHagCHe tCHo dCHecrCHypt


问:
How to write my_strchr() in C
Right now I hope to write my own my_strchr() in the C language.

I checked that the answer should be like this:

```<code>char *my_strchr(const char *src1, int c) {

    while (*src1 != '\0') { //when the string goes to the last, jump out
        if (c == *src1) {
            return src1;
        }
        src1++;
    }
    return NULL;
}
</code>```

I'm quite confused by:

why we use *src1  in the while loop condition (*src1 != '\0'), is *src1 a pointer to the const char*? Can we just use src1 instead?

When we return value and src1++, we do not have that *src1, why?

For this function, it in fact prints the whole string after the required characters, but why is that? Why does it not print only the character that we need to find?

答:
In addition to Jabberwocky's answer, please note that the code in the question has 2 bugs:

c must be converted to char for the comparison with *src1: strchr("ABC", 'A' + 256) returns a pointer to the string literal unless char has more than 8 bits.

Furthermore, if c converted to a char has the value 0, a pointer to the null terminator should be returned, not NULL as in the posted code.

Here is a modified version:

```<code>char *my_strchr(const char *s, int c) {
    for (;;) {
        if ((char)c == *s) {
            return src1;
        }
        if (*s++ == '\0') {
            return NULL;
        }
    }
}
</code>```

Title: How to write my_strchr() in C

Body:
Right now I hope to write my own my_strchr() in the C language.

I checked that the answer should be like this:

char *my_strchr(const char *src1, int c) {

    while (*src1 != '\0') { //when the string goes to the last, jump out
        if (c == *src1) {
            return src1;
        }
        src1++;
    }
    return NULL;
}

I'm quite confused by:

why we use *src1  in the while loop condition (*src1 != '\0'), is *src1 a pointer to the const char*? Can we just use src1 instead?

When we return value and src1++, we do not have that *src1, why?

For this function, it in fact prints the whole string after the required characters, but why is that? Why does it not print only the character that we need to find?

Body:
In addition to Jabberwocky's answer, please note that the code in the question has 2 bugs:

c must be converted to char for the comparison with *src1: strchr("ABC", 'A' + 256) returns a pointer to the string literal unless char has more than 8 bits.

Furthermore, if c converted to a char has the value 0, a pointer to the null terminator should be returned, not NULL as in the posted code.

Here is a modified version:

char *my_strchr(const char *s, int c) {
    for (;;) {
        if ((char)c == *s) {
            return src1;
        }
        if (*s++ == '\0') {
            return NULL;
        }
    }
}


问:
How to find Records between startDate and endDate - Nodejs, mongodb
There are 4 records in my database.

```<code>{"_id":{"$oid":"6200b15e91f762376cd43ac3"},"startDate":{"$date":"2021-01-01T00:00:00.000Z"},"endDate":{"$date":"2021-01-28T18:29:59.059Z"},"__v":0}
{"_id":{"$oid":"6200b15e91f762376cd43ac4"},"startDate":{"$date":"2021-01-01T00:00:00.000Z"},"endDate":{"$date":"2021-01-23T18:29:59.059Z"},"__v":0}
{"_id":{"$oid":"6200b15e91f762376cd43ac5"},"startDate":{"$date":"2021-01-05T00:00:00.000Z"},"endDate":{"$date":"2021-01-28T18:29:59.059Z"},"__v":0}
{"_id":{"$oid":"6200b15e91f762376cd43ac6"},"startDate":{"$date":"2021-01-05T00:00:00.000Z"},"endDate":{"$date":"2021-01-25T18:29:59.059Z"},"__v":0}
</code>```

My UI looks like this:

My mongodb query is as follows: (what I have tried)

```<code>data.find({
                    "$or": [
                      {"startDate": {"$gte": startDate}},
                      {"endDate": {"$lte": endDate}}
                    ]
                  });
</code>```

When is search using the query above, I get only 1 record, That is: {"_id":{"$oid":"6200b15e91f762376cd43ac3"},"startDate":{"$date":"2021-01-01T00:00:00.000Z"},"endDate":{"$date":"2021-01-28T18:29:59.059Z"},"__v":0} instead of all 4.

While sending from UI, I convert it is:
req.query:

```<code>dateStart: '2021-01-01',
dateEnd: '2021-01-28',
</code>```

And then convert it to new Date() format:

```<code>let startDate = new Date(req.query.dateStart);
let endDate = new Date(req.query.dateEnd);
</code>```

I don't know what wrong I am going in the query. Need Help! Thank you!

答:
With $and seems to work as expected :

```<code> db.collection.aggregate([
  {
    $match: {
      startDate: {
        $gte: {
       "$date": "2021-01-01T00:00:00.000Z"
       }
       },
      endDate: {
        $lte: {
       "$date": "2021-01-28T00:00:00.000Z"
       }
      }
     }
  }
])
</code>```

playground

Body:
There are 4 records in my database.

{"_id":{"$oid":"6200b15e91f762376cd43ac3"},"startDate":{"$date":"2021-01-01T00:00:00.000Z"},"endDate":{"$date":"2021-01-28T18:29:59.059Z"},"__v":0}
{"_id":{"$oid":"6200b15e91f762376cd43ac4"},"startDate":{"$date":"2021-01-01T00:00:00.000Z"},"endDate":{"$date":"2021-01-23T18:29:59.059Z"},"__v":0}
{"_id":{"$oid":"6200b15e91f762376cd43ac5"},"startDate":{"$date":"2021-01-05T00:00:00.000Z"},"endDate":{"$date":"2021-01-28T18:29:59.059Z"},"__v":0}
{"_id":{"$oid":"6200b15e91f762376cd43ac6"},"startDate":{"$date":"2021-01-05T00:00:00.000Z"},"endDate":{"$date":"2021-01-25T18:29:59.059Z"},"__v":0}

My UI looks like this:

My mongodb query is as follows: (what I have tried)

data.find({
                    "$or": [
                      {"startDate": {"$gte": startDate}},
                      {"endDate": {"$lte": endDate}}
                    ]
                  });

When is search using the query above, I get only 1 record, That is: {"_id":{"$oid":"6200b15e91f762376cd43ac3"},"startDate":{"$date":"2021-01-01T00:00:00.000Z"},"endDate":{"$date":"2021-01-28T18:29:59.059Z"},"__v":0} instead of all 4.

While sending from UI, I convert it is:
req.query:

dateStart: '2021-01-01',
dateEnd: '2021-01-28',

And then convert it to new Date() format:

let startDate = new Date(req.query.dateStart);
let endDate = new Date(req.query.dateEnd);

I don't know what wrong I am going in the query. Need Help! Thank you!

Body:
With $and seems to work as expected :

 db.collection.aggregate([
  {
    $match: {
      startDate: {
        $gte: {
       "$date": "2021-01-01T00:00:00.000Z"
       }
       },
      endDate: {
        $lte: {
       "$date": "2021-01-28T00:00:00.000Z"
       }
      }
     }
  }
])

playground


问:
Is there a feature extraction method that is scale invariant but not rotation invariant?
Is there a feature extraction method that is scale invariant but not rotation invariant? I would like to match similar images that have been scaled but not rotated...

EDIT: Let me rephrase. How can I check whether an image is a scaled version (or close to) of an original?

答:
Histogram and Gauss Pyramids are used for extract scale invariant features.

How can I check whether an image is a scaled version (or close to) of an original?

It's puzzle for me. Does you mean given two images, one is original and another is scaled? Or is one original and another is a fragment from the original but scaled and you want to locate the fragment in the original one?

[updated]
Given two images, a and b,

Detected their SIFT or SURF feature points and descriptions.

Get the corresponding regions between a and b. If none, return false. Refer to Pattern Matching - Find reference object in second image and Trying to match two images using sift in OpenCv, but too many matches. Name the region in a as Ra, and one in b as Rb.

Using algorithm like template match to determine if Ra is identical enough to Rb. If yes, calculate the scale ratio.

ContentLicense: CC BY-SA 3.0


问:
How to make POSTGRESQL query based on first 2 parameters and latest third parameter
I have DB:

```<code>**client_id  |  Version |  Date(year, month, day)**
</code>```

I need to make query request for last year(or last 12 months) group by Client_id, Version and latest date(!) for them.
For example:

```<code>client_id  |  Version |    **LATEST** Date
   23           v2           2022-1-25
   23           v1           2021-3-23
   25           v0           2021-6-23

</code>```

This is what I have right now:

```<code>SELECT client_id, Version, Date
FROM db_table
WHERE date >= '2022-01-01' AND date < NOW()::DATE
GROUP BY client_id, Version, Date
</code>```

And I'm getting result for EVERY DAY. If I'm removing DATE from group by, its complaining that Date should be in Group by.

I hope I did describe everything properly. I'm new here, so please let me know if I provide not full info.

Thank you for your time.

答:
To get the most recent full year (i.e. not including the partial current day),

```<code>SELECT current_date - interval '1 year'; --this returns 2021-02-07 when run today
</code>```

To consider today as part of the 12 month period, then:

```<code>SELECT current_date - interval '1 year - 1 day'; --this returns 2021-02-08 when run today
</code>```

So, assuming that you want the former option (you can switch it if you like):

```<code>SELECT client_id, "Version", MAX("Date") AS latest_date
FROM db_table
WHERE "Date" BETWEEN current_date - interval '1 year' AND current_date
GROUP BY client_id, "Version";
</code>```

p.s. recommend you don't use "Date" as a column name since it's a reserved word, and avoid using upper case letters in column names :)

Body:
I have DB:

**client_id  |  Version |  Date(year, month, day)**

I need to make query request for last year(or last 12 months) group by Client_id, Version and latest date(!) for them.
For example:

client_id  |  Version |    **LATEST** Date
   23           v2           2022-1-25
   23           v1           2021-3-23
   25           v0           2021-6-23

This is what I have right now:

SELECT client_id, Version, Date
FROM db_table
WHERE date >= '2022-01-01' AND date < NOW()::DATE
GROUP BY client_id, Version, Date

And I'm getting result for EVERY DAY. If I'm removing DATE from group by, its complaining that Date should be in Group by.

I hope I did describe everything properly. I'm new here, so please let me know if I provide not full info.

Thank you for your time.

Body:
To get the most recent full year (i.e. not including the partial current day),

SELECT current_date - interval '1 year'; --this returns 2021-02-07 when run today

To consider today as part of the 12 month period, then:

SELECT current_date - interval '1 year - 1 day'; --this returns 2021-02-08 when run today

So, assuming that you want the former option (you can switch it if you like):

SELECT client_id, "Version", MAX("Date") AS latest_date
FROM db_table
WHERE "Date" BETWEEN current_date - interval '1 year' AND current_date
GROUP BY client_id, "Version";

p.s. recommend you don't use "Date" as a column name since it's a reserved word, and avoid using upper case letters in column names :)


问:
AlarmReceiver is not being called
I've made an android app and I want to get local notifications every day at a specific time. I used AlarmManager and BroadcastReceiver to do this. But the problem is the AlarmReceiver class which extends BroadCastReceiver is not being called. I know this is a repeated question in stackoverflow. I've gone through all the answers and tried everything, but still not able to solve the issue.

Here is my Main Activity

```<code>package com.dileepmanuballa224.alarm_test;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import java.util.Calendar;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
                Calendar calendar=Calendar.getInstance();
                calendar.set(Calendar.HOUR,9);
                AlarmManager alarmManager=(AlarmManager)getSystemService(Context.ALARM_SERVICE);
                Intent intent=new Intent(getApplicationContext(),AlarmReceiver.class);
                PendingIntent pendingIntent=PendingIntent.getActivity(getApplicationContext(),1,intent,0);
                alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pendingIntent);

    }
}
</code>```

My AlarmReceiverClass

```<code>import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

public class AlarmReceiver extends BroadcastReceiver {
    private static final String TAG = "alarm_test_check";

    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context,"AlarmReceiver called",Toast.LENGTH_SHORT).show();
        Log.d(TAG, "onReceive: called ");
    }
}
</code>```

My Manifest file

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.dileepmanuballa224.alarm_test">
<uses-permission android:name="android.permission.SET_ALARM"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver android:name=".AlarmReceiver"/>
        </application>

</manifest>
</code>```

I'm testing this app on Android 'Nougat'.

答:
I was having problem to work with that to. For me it works like this

AlarmReceiver.kt

```<code>import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log

class AlarmReceiver : BroadcastReceiver() {
    private var logTag = "logTag-AlarmReceiver"
    override fun onReceive(context: Context?, intent: Intent?) {
        if (intent?.action == "restart_app") {
            val restartApp = context?.packageManager?.getLaunchIntentForPackage(context.packageName)
            restartApp?.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
            restartApp?.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            context?.startActivity(restartApp)
            Log.d(logTag, "${intent.action}")
        }
    }
}
</code>```

AndroidManifest.xml

```<code><uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<receiver android:name=".AlarmReceiver"
    android:enabled="true"
    android:exported="true">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED"/>
        <action android:name="restart_app"/>
    </intent-filter>
</receiver>
</code>```

Set var

```<code>import android.app.AlarmManager
import android.app.PendingIntent
import android.os.SystemClock
import android.content.Context

private var alarmMgr: AlarmManager? = null
private lateinit var alarmPendingIntent: PendingIntent
</code>```

onCreate()

```<code>alarmMgr = getSystemService(Context.ALARM_SERVICE) as AlarmManager
</code>```

set alarm

```<code>alarmPendingIntent = Intent(this, AlarmReceiver::class.java).let { intent ->
    intent.action = "restart_app"
    PendingIntent.getBroadcast(this, 0, intent, 0)
}
alarmMgr?.set(
    AlarmManager.ELAPSED_REALTIME_WAKEUP,
    SystemClock.elapsedRealtime() + 10 * 1000,
    alarmPendingIntent
)
</code>```

in 10 seconds, our BroadcastReceiver will be fired

Title: AlarmReceiver is not being called

Body:
I've made an android app and I want to get local notifications every day at a specific time. I used AlarmManager and BroadcastReceiver to do this. But the problem is the AlarmReceiver class which extends BroadCastReceiver is not being called. I know this is a repeated question in stackoverflow. I've gone through all the answers and tried everything, but still not able to solve the issue.

Here is my Main Activity

package com.dileepmanuballa224.alarm_test;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import java.util.Calendar;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
                Calendar calendar=Calendar.getInstance();
                calendar.set(Calendar.HOUR,9);
                AlarmManager alarmManager=(AlarmManager)getSystemService(Context.ALARM_SERVICE);
                Intent intent=new Intent(getApplicationContext(),AlarmReceiver.class);
                PendingIntent pendingIntent=PendingIntent.getActivity(getApplicationContext(),1,intent,0);
                alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pendingIntent);

    }
}

My AlarmReceiverClass

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

public class AlarmReceiver extends BroadcastReceiver {
    private static final String TAG = "alarm_test_check";

    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context,"AlarmReceiver called",Toast.LENGTH_SHORT).show();
        Log.d(TAG, "onReceive: called ");
    }
}

My Manifest file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.dileepmanuballa224.alarm_test">
<uses-permission android:name="android.permission.SET_ALARM"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver android:name=".AlarmReceiver"/>
        </application>

</manifest>

I'm testing this app on Android 'Nougat'.

Body:
I was having problem to work with that to. For me it works like this

AlarmReceiver.kt

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log

class AlarmReceiver : BroadcastReceiver() {
    private var logTag = "logTag-AlarmReceiver"
    override fun onReceive(context: Context?, intent: Intent?) {
        if (intent?.action == "restart_app") {
            val restartApp = context?.packageManager?.getLaunchIntentForPackage(context.packageName)
            restartApp?.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
            restartApp?.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            context?.startActivity(restartApp)
            Log.d(logTag, "${intent.action}")
        }
    }
}

AndroidManifest.xml

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<receiver android:name=".AlarmReceiver"
    android:enabled="true"
    android:exported="true">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED"/>
        <action android:name="restart_app"/>
    </intent-filter>
</receiver>

Set var

import android.app.AlarmManager
import android.app.PendingIntent
import android.os.SystemClock
import android.content.Context

private var alarmMgr: AlarmManager? = null
private lateinit var alarmPendingIntent: PendingIntent

onCreate()

alarmMgr = getSystemService(Context.ALARM_SERVICE) as AlarmManager

set alarm

alarmPendingIntent = Intent(this, AlarmReceiver::class.java).let { intent ->
    intent.action = "restart_app"
    PendingIntent.getBroadcast(this, 0, intent, 0)
}
alarmMgr?.set(
    AlarmManager.ELAPSED_REALTIME_WAKEUP,
    SystemClock.elapsedRealtime() + 10 * 1000,
    alarmPendingIntent
)

in 10 seconds, our BroadcastReceiver will be fired


问:
AWS Lambda publish-layer-version, getting: Unknown options: --compatible-architectures, x86_64
I'm trying to create an AWS Lambda Layer using the AWS CLI on Ubuntu, like this:

```<code>aws lambda publish-layer-version \
  --layer-name numpy --description "numpy Python 3.9"  \
  --zip-file fileb://./lambda/deps/numpy/python.zip \
  --compatible-runtimes python3.9 \
  --compatible-architectures "x86_64" --output text --query "LayerVersionArn"
</code>```

But I'm getting this error:

```<code>Unknown options: --compatible-architectures, x86_64
</code>```

I tried all sorts of combinations to no avail. Any ideas?

答:
The root cause was that I had AWS CLI version "aws-cli/2.2.2" installed on my machine...

As soon as I updated to the latest (version aws-cli/2.4.16), it worked.

I hope this helps someone in the future.

Body:
I'm trying to create an AWS Lambda Layer using the AWS CLI on Ubuntu, like this:

aws lambda publish-layer-version \
  --layer-name numpy --description "numpy Python 3.9"  \
  --zip-file fileb://./lambda/deps/numpy/python.zip \
  --compatible-runtimes python3.9 \
  --compatible-architectures "x86_64" --output text --query "LayerVersionArn"

But I'm getting this error:

Unknown options: --compatible-architectures, x86_64

I tried all sorts of combinations to no avail. Any ideas?


问:
Messages.properties file instead of json files with angular translate static file loader
Can we use Messages.properties files instead of json files with angular translate static file loader? Are there any other file extensions apart from json that can be used ?</p>

答:
If you mean the ngx-translate libryry. I don't think you can use properties with it.

What you can do is to convert dynamically the property-files to a json-format with some JSON library in your backend. And provide them to the frontend via Rest endpint for example.

For example Spring-Java:

```<code>@GetMapping(value = "/i18n/{lang}")
@ResponseBody
public ResponseEntity<String> fetchLangJson(@PathVariable String lang) {
    HashMap<String, String> map = new HashMap<>();
    resourceBundleMessageSource.getBasenameSet().forEach(bn -> {
        map.putAll(fetchPropsAsHashMap(bn + "_" + lang + .properties"));
    });
    JSONObject jsonProps = new JSONObject(map);
    return new ResponseEntity<>(jsonProps.toString(), HttpStatus.OK);
};
</code>```

//fetchPropsAsHashMap - read the properties and converts them to
//HashMap<String, String>

See hier Ionic3 / Ngx-translate - TranslateHttpLoader with external URL

Body:
If you mean the ngx-translate libryry. I don't think you can use properties with it.

What you can do is to convert dynamically the property-files to a json-format with some JSON library in your backend. And provide them to the frontend via Rest endpint for example.

For example Spring-Java:

@GetMapping(value = "/i18n/{lang}")
@ResponseBody
public ResponseEntity<String> fetchLangJson(@PathVariable String lang) {
    HashMap<String, String> map = new HashMap<>();
    resourceBundleMessageSource.getBasenameSet().forEach(bn -> {
        map.putAll(fetchPropsAsHashMap(bn + "_" + lang + .properties"));
    });
    JSONObject jsonProps = new JSONObject(map);
    return new ResponseEntity<>(jsonProps.toString(), HttpStatus.OK);
};

//fetchPropsAsHashMap - read the properties and converts them to
//HashMap<String, String>

See hier Ionic3 / Ngx-translate - TranslateHttpLoader with external URL


问:
UTF-8 no BOM gets strange random characters around site
I'm saving my files with UTF-8 with no BOM to get around "headers already sent" issue. However I get strange characters in the whole site, I don't know why since saving files the same in other sites don't cause the same issue.

I get this: ï»¿ a lot of times in random spots of my site and some special characters are displayed incorrectly.

http://chusmix.com/?ciudad=Pilar

How can I fix this?

答: ï»¿ is the BOM so it probably hasn't been removed properly. To completely remove it, you could batch process all your files - check if the first characters match the BOM and if so, remove it. There are plenty of scripts on the internet to do that. For example: Using awk to remove the Byte-order mark


问:
Collecting input through DMs
I'm wondering if it's even possible to get user's input through DMs after calling a slash command. I've created a little mini-game that would ideally be played in the user's DMs to avoid spamming the channel it was called in. An example of my code structure is as followed:

```<code>module.exports = {
    data: new SlashCommandBuilder()
    .setName('game')
    .setDescription('Play game'),
async execute(interaction) {
    const score = await gameLogic(interaction.user);
    await interaction.reply(score);
    },
};
</code>```

Then I send the user a DM letting them know that the game has started and call a function that will wait for the user input.

```<code>async function gameLogic(user) {
    user.send("Game time");
    let userInput = getUserInput();
    .... game logic ...
}
</code>```

I've tried using message collectors and awaitMessage but can't seem to get it working. Really trying to exhaust all options until moving on to a different solution.

I appreciate any advice!

EDIT Unfortunately I don't remember exactly what I've tried but I can give some examples.

My message collector was something along the lines of this:

```<code>async function getUserInput() {

    console.log("Awaiting user input");

    const filter = message => message.author.id === m_user.id;
    const collector = m_interaction.channel.createMessageCollector({ filter, max: 1, time: 15000, errors: ['time'] })
    collector.on('collect', message => console.log(`You wrote ${message.content}`));
    collector.on('error', collected => console.log("Time out"));
}
</code>```

And my awaitMessage was something like this:

```<code>async function getUserInput() {
    const filter = message => message.author.id === m_user.id;
    const message = await m_interaction.channel.awaitMessages({ filter, max: 1, time: 15000, errors: ['time'] })
        .then(message => m_interaction.channel.send(`You wrote ${message.content}`))
        .catch(collected => m_interaction.channel.send("Time out"));

    console.log(message);
}
</code>```

I'm sure these will work for collecting input from the channel the command was called in, but I'm not sure how I could alter them to collect input through the DMs. I did read a little into dmChannel but couldn't seem to get it working the way I wanted it to.

EDIT 2 + SOLUTION I've managed to store the DMChannel with the user by using.

```<code>const channel = user.createDM();
</code>```

And I can now use the MessageCollector there. Hopefully this helps.

Title: Collecting input through DMs

Body:
I'm wondering if it's even possible to get user's input through DMs after calling a slash command. I've created a little mini-game that would ideally be played in the user's DMs to avoid spamming the channel it was called in. An example of my code structure is as followed:

module.exports = {
    data: new SlashCommandBuilder()
    .setName('game')
    .setDescription('Play game'),
async execute(interaction) {
    const score = await gameLogic(interaction.user);
    await interaction.reply(score);
    },
};

Then I send the user a DM letting them know that the game has started and call a function that will wait for the user input.

async function gameLogic(user) {
    user.send("Game time");
    let userInput = getUserInput();
    .... game logic ...
}

I've tried using message collectors and awaitMessage but can't seem to get it working. Really trying to exhaust all options until moving on to a different solution.

I appreciate any advice!

EDIT Unfortunately I don't remember exactly what I've tried but I can give some examples.

My message collector was something along the lines of this:

async function getUserInput() {

    console.log("Awaiting user input");

    const filter = message => message.author.id === m_user.id;
    const collector = m_interaction.channel.createMessageCollector({ filter, max: 1, time: 15000, errors: ['time'] })
    collector.on('collect', message => console.log(`You wrote ${message.content}`));
    collector.on('error', collected => console.log("Time out"));
}

And my awaitMessage was something like this:

async function getUserInput() {
    const filter = message => message.author.id === m_user.id;
    const message = await m_interaction.channel.awaitMessages({ filter, max: 1, time: 15000, errors: ['time'] })
        .then(message => m_interaction.channel.send(`You wrote ${message.content}`))
        .catch(collected => m_interaction.channel.send("Time out"));

    console.log(message);
}

I'm sure these will work for collecting input from the channel the command was called in, but I'm not sure how I could alter them to collect input through the DMs. I did read a little into dmChannel but couldn't seem to get it working the way I wanted it to.

EDIT 2 + SOLUTION I've managed to store the DMChannel with the user by using.

const channel = user.createDM();

And I can now use the MessageCollector there. Hopefully this helps.


问:
How to fully print outer loop before inner loop (Java)
My goal is to print a chart that displays "enemy" number, x and y coordinates, then their distance in respect to the other "enemies", but with my following nested loop below, the enemy number, and coordinates are reversed with the distance numbers. I've tried adjusting the position of the codes, but they don't seem to fix the issue.</p>
```<code>public static void main(String[] args) {

    // array of enemy coordinates
    int[] xCoords = {1, 4, 5, 5, 7, 10};
    int[] yCoords = {3, 4, 6, 2, 5, 2};

    System.out.println("________Enemy Distance Chart________");
    System.out.println("\t\t\t\t\t\tDistance To (Kilometers)");
    System.out.println("Enemies\t  X Coord  \tY Coord  \tE-0\tE-1\tE-2\tE-3\tE-4\tE-5");

    for (int i = 0; i < 6; i++) {
        for (int j = 0; j < 6; j++) {
            double distance = Math.sqrt((yCoords[j]-yCoords[i])*(yCoords[j]-yCoords[i]) + (xCoords[j]-xCoords[i])*(xCoords[j]-xCoords[i]));
            System.out.printf("%.2f\t", distance);
        }
        // the following code below is somehow printed on the far right
        System.out.println("E- " + i + "\t\t  " + xCoords[i] + "\t      " + yCoords[i]);
    }

</code>```

答:
```<code>    for (int i = 0; i < 6; i++) {
        System.out.printf("E-" + i + "\t\t" + xCoords[i] + "\t\t" + yCoords[i] + "\t\t");
        for (int j = 0; j < 6; j++) {
            double distance = Math.sqrt((yCoords[j] - yCoords[i]) * (yCoords[j] - yCoords[i]) + (xCoords[j] - xCoords[i]) * (xCoords[j] - xCoords[i]));
            System.out.printf("%.2f\t", distance);
        }
        System.out.println();
    }
</code>```

Body:
My goal is to print a chart that displays "enemy" number, x and y coordinates, then their distance in respect to the other "enemies", but with my following nested loop below, the enemy number, and coordinates are reversed with the distance numbers. I've tried adjusting the position of the codes, but they don't seem to fix the issue.

public static void main(String[] args) {

    // array of enemy coordinates
    int[] xCoords = {1, 4, 5, 5, 7, 10};
    int[] yCoords = {3, 4, 6, 2, 5, 2};

    System.out.println("________Enemy Distance Chart________");
    System.out.println("\t\t\t\t\t\tDistance To (Kilometers)");
    System.out.println("Enemies\t  X Coord  \tY Coord  \tE-0\tE-1\tE-2\tE-3\tE-4\tE-5");

    for (int i = 0; i < 6; i++) {
        for (int j = 0; j < 6; j++) {
            double distance = Math.sqrt((yCoords[j]-yCoords[i])*(yCoords[j]-yCoords[i]) + (xCoords[j]-xCoords[i])*(xCoords[j]-xCoords[i]));
            System.out.printf("%.2f\t", distance);
        }
        // the following code below is somehow printed on the far right
        System.out.println("E- " + i + "\t\t  " + xCoords[i] + "\t      " + yCoords[i]);
    }


问:
Reduce time /space complexity of simple loop
So basically if i have an iteration like this in python
Ive editted the question to include my full code

```<code>class Solution:
    def myPow(self, x: float, n: int) -> float:
        temp = [];
        span = range(1,abs(n))
        if n ==0:
            return 1
        if abs(n)==1:
            temp.append(x)
        else:
            for y in span:
                if y == 1:
                    temp = []
                    temp.append(x*x)
                else:
                    temp.append(temp[-1] * x)
        if(n < 0):
            return 1/temp[-1]
        else:
            return temp[-1]
</code>```

The problem link is : Pow(x,n)-leetcode
How can I modify this to conserve memory and time. Is there another data structure i can use. Im just learning python....

------------EDIT------------
ive modified the code to use a variable instead of a list for the temp data

```<code>class Solution:
    def myPow(self, x: float, n: int) -> float:
        span = range(1,abs(n))
        if n ==0:
            return 1
        if abs(n)==1:
            temp = x
        else:
            for y in span:
                if y == 1:
                    temp = x*x
                else:
                    temp = temp * x
        if(n < 0):
            return 1/temp
        else:
            return temp
</code>```

I still have a problem with my time complexity.
Its working for many testcases, however when it trys to run with x = 0.00001 and n = 2147483647. The time limit issue arises

答: If you have to loop, you have to lope and there is nothing that can be done.  Loops in python are slow.   That said you may not have to loop and if you do have to loop, it may be possible to push this loop to a highly optimised internal function.  Tell us what you are trying to do  (not how you think you have to do it, appending elements to a lis may or may not be needed).  Always recall the two rules of program optimisation  General Rule:  Don't do it.  Rule for experts:  Don't do it yet.   Make it work before you make it fast, who knows, it may be fast enough.</p>

Body:
So basically if i have an iteration like this in python
Ive editted the question to include my full code

class Solution:
    def myPow(self, x: float, n: int) -> float:
        temp = [];
        span = range(1,abs(n))
        if n ==0:
            return 1
        if abs(n)==1:
            temp.append(x)
        else:
            for y in span:
                if y == 1:
                    temp = []
                    temp.append(x*x)
                else:
                    temp.append(temp[-1] * x)
        if(n < 0):
            return 1/temp[-1]
        else:
            return temp[-1]

The problem link is : Pow(x,n)-leetcode
How can I modify this to conserve memory and time. Is there another data structure i can use. Im just learning python....

------------EDIT------------
ive modified the code to use a variable instead of a list for the temp data

class Solution:
    def myPow(self, x: float, n: int) -> float:
        span = range(1,abs(n))
        if n ==0:
            return 1
        if abs(n)==1:
            temp = x
        else:
            for y in span:
                if y == 1:
                    temp = x*x
                else:
                    temp = temp * x
        if(n < 0):
            return 1/temp
        else:
            return temp

I still have a problem with my time complexity.
Its working for many testcases, however when it trys to run with x = 0.00001 and n = 2147483647. The time limit issue arises


问:
Controlling the labels on the primary and secondary axis with facet_wrap()
The following code produces a single plot:

```<code>data <- tibble(model = rep(c("model 0", "model I", "model II", "model III", "model IV"),3),
                year = c(rep('2005-2009', 5), rep('2010-2014',5), rep('2015-2017',5)),
                value = c(0.0, 10.4, 30.7, 26.7, 32.2, 0.0, 9.9, 31.0, 26.5, 32.6, 0.0, 19.1, 29.6, 25.6, 25.7),
                unknown = c(rep(30,5), rep(40,5), rep(27,5)),
                region = 'Asia')

# Numeric year
data$year_num <- as.numeric(factor(data$year))
# Labels for primary scale
labels <- levels(factor(data$year))
# Labels for secondary scale
dup_labels <- distinct(data, year, unknown) %>% tibble::deframe()

p1 <- ggplot(data, aes(fill=model, x=value, y = year_num)) +
  geom_bar(stat='identity', position = position_fill(reverse = TRUE), orientation = "y") +
  scale_fill_grey(start=0.8, end=0.2) +
  theme_bw() +
  ggtitle('Model') +
  xlab('') + ylab('') +
  theme(legend.position="bottom",
        plot.title = element_text(hjust = 0.5),
        legend.title=element_blank(),
        text = element_text(family = "serif")
  ) +
  scale_x_continuous(labels = percent_format(scale = 100)) +
  scale_y_continuous(breaks = seq_along(labels), labels = labels, sec.axis = dup_axis(labels = dup_labels))

p1
</code>```

Next, I would like to produce several plots with facet_wrap but I have a challenge controlling the labels. I am not quite sure how to iterate the labels for the corresponding plot.

Eg., if I want to plot the following data with facet_wrap(~region, dir = 'v', nrow = 2):

```<code>data1 <- tibble(model = rep(c("model 0", "model I", "model II", "model III", "model IV"),3),
                year = c(rep('2005-2009', 5), rep('2010-2014',5), rep('2015-2017',5)),
                value = c(0.0, 10.4, 30.7, 26.7, 32.2, 0.0, 9.9, 31.0, 26.5, 32.6, 0.0, 19.1, 29.6, 25.6, 25.7),
                unknown = c(rep(30,5), rep(40,5), rep(27,5)),
                region = 'Asia')

data2 <- tibble(model = rep(c("model 0", "model I", "model II", "model III", "model IV"),3),
                year = c(rep('2005-2009', 5), rep('2010-2014',5), rep('2015-2017',5)),
                value = c(0.4, 15.0, 25.6, 20.6, 38.3, 1.1, 15, 13, 14.6, 56.9, 0.8, 19.8, 22, 18.8,38.1),
                unknown = c(rep(28,5), rep(35,5), rep(17,5)),
                region = 'Europe')

data <- rbind(data1, data2)

</code>```

I reckon that I need to have some sort of iteration but I can't really figure it out for this problem.

答: Facet-wrap will automatically label based on the values for the facet specified. In your case you are wrapping on the facet 'region,' so your plots will be labeled "Asia" and "Europe." If you want another label, this is generally accomplished with labeller as an argument to facet_wrap.</p>

Body:
The following code produces a single plot:

data <- tibble(model = rep(c("model 0", "model I", "model II", "model III", "model IV"),3),
                year = c(rep('2005-2009', 5), rep('2010-2014',5), rep('2015-2017',5)),
                value = c(0.0, 10.4, 30.7, 26.7, 32.2, 0.0, 9.9, 31.0, 26.5, 32.6, 0.0, 19.1, 29.6, 25.6, 25.7),
                unknown = c(rep(30,5), rep(40,5), rep(27,5)),
                region = 'Asia')

# Numeric year
data$year_num <- as.numeric(factor(data$year))
# Labels for primary scale
labels <- levels(factor(data$year))
# Labels for secondary scale
dup_labels <- distinct(data, year, unknown) %>% tibble::deframe()

p1 <- ggplot(data, aes(fill=model, x=value, y = year_num)) +
  geom_bar(stat='identity', position = position_fill(reverse = TRUE), orientation = "y") +
  scale_fill_grey(start=0.8, end=0.2) +
  theme_bw() +
  ggtitle('Model') +
  xlab('') + ylab('') +
  theme(legend.position="bottom",
        plot.title = element_text(hjust = 0.5),
        legend.title=element_blank(),
        text = element_text(family = "serif")
  ) +
  scale_x_continuous(labels = percent_format(scale = 100)) +
  scale_y_continuous(breaks = seq_along(labels), labels = labels, sec.axis = dup_axis(labels = dup_labels))

p1

Next, I would like to produce several plots with facet_wrap but I have a challenge controlling the labels. I am not quite sure how to iterate the labels for the corresponding plot.

Eg., if I want to plot the following data with facet_wrap(~region, dir = 'v', nrow = 2):

data1 <- tibble(model = rep(c("model 0", "model I", "model II", "model III", "model IV"),3),
                year = c(rep('2005-2009', 5), rep('2010-2014',5), rep('2015-2017',5)),
                value = c(0.0, 10.4, 30.7, 26.7, 32.2, 0.0, 9.9, 31.0, 26.5, 32.6, 0.0, 19.1, 29.6, 25.6, 25.7),
                unknown = c(rep(30,5), rep(40,5), rep(27,5)),
                region = 'Asia')

data2 <- tibble(model = rep(c("model 0", "model I", "model II", "model III", "model IV"),3),
                year = c(rep('2005-2009', 5), rep('2010-2014',5), rep('2015-2017',5)),
                value = c(0.4, 15.0, 25.6, 20.6, 38.3, 1.1, 15, 13, 14.6, 56.9, 0.8, 19.8, 22, 18.8,38.1),
                unknown = c(rep(28,5), rep(35,5), rep(17,5)),
                region = 'Europe')

data <- rbind(data1, data2)

I reckon that I need to have some sort of iteration but I can't really figure it out for this problem.


问:
Loader animation in pure CSS
I try to code loader animation inspired by this dribbble: https://dribbble.com/shots/14420202-Processing-Animation
and in comment section I found codepen with similar animation, but it is made all in JS: https://codepen.io/AbubakerSaeed/full/yLaQVdq

```<code>tl2
  .set(".dC-1", { rotate: 0 })
  .set(".dC-2", { rotate: 30 })
  .set(".dC-3", { rotate: 60 })
  .set(".dC-4", { rotate: 90 })
  .set(".dC-5", { rotate: 120 })
  .set(".dC-6", { rotate: 150 })
  .set(".dC-7", { rotate: 180 })
  .set(".dC-8", { rotate: 210 })
  .set(".dC-9", { rotate: 240 })
  .set(".dC-10", { rotate: 270 })
  .set(".dC-11", { rotate: 300 })
  .set(".dC-12", { rotate: 330 })
  .to(".dC-1", {
  delay: s,
  duration: s,
    rotate: 30,
})
</code>```

I try to make pure CSS animation from it but I don't understand how to do it. Can someone explain for me how to make these two timelines in SCSS, how to translate JS code into SCSS?

答:
You can do this by keeping track of 2 animations:

rotating plane with blocks that move in and out

showing/hiding divs on a static plane.

You can sync up the animation and show/hide the blocks on the different plane when they should not be shown.

for example:
if 1 rotation would take 5 seconds,
the total animation would be 10 seconds.
where 5 seconds is spend invisible, and the other 5 seconds visible.

In the snippet bellow, i've made an example with 2 blocks.
You can expand it for as many blocks as you want.
I've made the blocks slightly visible when they should be invisible, just to show what's going on in the animation.

body {
  background-color: #1f2227;
}

.wrapper {
  width: 200px;
  height: 200px;
  position: relative;
  border: 1px solid white;
  padding: 20px;
  transform: rotate(-90deg)
}

.spinner,
.static {
  position: absolute;
  left: 50%;
  top: 50%;
}

.spinner {
  animation: 5s linear infinite spin;
}

.block {
  width: 10px;
  height: 10px;
  background-color: #EEE;
  display: inline-block;
  position: absolute;
  left: calc(50% - 5px);
  top: calc(50% - 5px);
}

.static .b1 {
  transform: translateX(100px);
  animation: 10s ease-in-out infinite hide-1;
}

.static .b2 {
  transform: rotate(30deg) translateX(100px);
  animation: 10s ease-in-out infinite hide-2;
}

.static .b3 {
  transform: rotate(60deg) translateX(100px);
}

.spinner .b1 {
  transform: translateX(100px);
  animation: 10s ease-in-out infinite go-in-out-1;
}

.spinner .b2 {
  transform: rotate(30deg) translateX(100px);
  animation: 10s ease-in-out infinite go-in-out-2;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

@keyframes go-in-out-1 {
  0% {
    transform: translateX(100px);
    opacity: 1;
  }
  4%,
  50% {
    transform: translateX(0px);
    opacity: 1;
  }
  54% {
    transform: translateX(100px);
    opacity: 1;
  }
  54.1%,
  100% {
    transform: translateX(100px);
    opacity: .1;
  }
}

@keyframes go-in-out-2 {
  4% {
    transform: translateX(100px);
    opacity: 1;
  }
  8%,
  46% {
    transform: translateX(10px);
    opacity: 1;
  }
  50% {
    transform: translateX(100px);
    opacity: 1;
  }
  50.1%,
  100% {
    transform: translateX(100px);
    opacity: .1;
  }
}

@keyframes hide-1 {
  0% {
    opacity: .1;
  }
  4%,
  50% {
    opacity: .1;
  }
  50.1%,
  100% {
    opacity: 1;
  }
}

@keyframes hide-2 {
  4% {
    opacity: .1;
  }
  8%,
  54% {
    opacity: .1;
  }
  54.1%,
  100% {
    opacity: 1;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <div class="static">
    <div class="block b1"> </div>
    <div class="block b2"> </div>
    <div class="block b3"> </div>
  </div>
  <div class="spinner">
    <div class="block b1"> </div>
    <div class="block b2"> </div>
  </div>
</div></code>```

Title: Loader animation in pure CSS

Body:
I try to code loader animation inspired by this dribbble: https://dribbble.com/shots/14420202-Processing-Animation
and in comment section I found codepen with similar animation, but it is made all in JS: https://codepen.io/AbubakerSaeed/full/yLaQVdq

tl2
  .set(".dC-1", { rotate: 0 })
  .set(".dC-2", { rotate: 30 })
  .set(".dC-3", { rotate: 60 })
  .set(".dC-4", { rotate: 90 })
  .set(".dC-5", { rotate: 120 })
  .set(".dC-6", { rotate: 150 })
  .set(".dC-7", { rotate: 180 })
  .set(".dC-8", { rotate: 210 })
  .set(".dC-9", { rotate: 240 })
  .set(".dC-10", { rotate: 270 })
  .set(".dC-11", { rotate: 300 })
  .set(".dC-12", { rotate: 330 })
  .to(".dC-1", {
  delay: s,
  duration: s,
    rotate: 30,
})

I try to make pure CSS animation from it but I don't understand how to do it. Can someone explain for me how to make these two timelines in SCSS, how to translate JS code into SCSS?

Body:
You can do this by keeping track of 2 animations:

rotating plane with blocks that move in and out

showing/hiding divs on a static plane.

You can sync up the animation and show/hide the blocks on the different plane when they should not be shown.

for example:
if 1 rotation would take 5 seconds,
the total animation would be 10 seconds.
where 5 seconds is spend invisible, and the other 5 seconds visible.

In the snippet bellow, i've made an example with 2 blocks.
You can expand it for as many blocks as you want.
I've made the blocks slightly visible when they should be invisible, just to show what's going on in the animation.

body {
  background-color: #1f2227;
}

.wrapper {
  width: 200px;
  height: 200px;
  position: relative;
  border: 1px solid white;
  padding: 20px;
  transform: rotate(-90deg)
}

.spinner,
.static {
  position: absolute;
  left: 50%;
  top: 50%;
}

.spinner {
  animation: 5s linear infinite spin;
}

.block {
  width: 10px;
  height: 10px;
  background-color: #EEE;
  display: inline-block;
  position: absolute;
  left: calc(50% - 5px);
  top: calc(50% - 5px);
}

.static .b1 {
  transform: translateX(100px);
  animation: 10s ease-in-out infinite hide-1;
}

.static .b2 {
  transform: rotate(30deg) translateX(100px);
  animation: 10s ease-in-out infinite hide-2;
}

.static .b3 {
  transform: rotate(60deg) translateX(100px);
}

.spinner .b1 {
  transform: translateX(100px);
  animation: 10s ease-in-out infinite go-in-out-1;
}

.spinner .b2 {
  transform: rotate(30deg) translateX(100px);
  animation: 10s ease-in-out infinite go-in-out-2;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

@keyframes go-in-out-1 {
  0% {
    transform: translateX(100px);
    opacity: 1;
  }
  4%,
  50% {
    transform: translateX(0px);
    opacity: 1;
  }
  54% {
    transform: translateX(100px);
    opacity: 1;
  }
  54.1%,
  100% {
    transform: translateX(100px);
    opacity: .1;
  }
}

@keyframes go-in-out-2 {
  4% {
    transform: translateX(100px);
    opacity: 1;
  }
  8%,
  46% {
    transform: translateX(10px);
    opacity: 1;
  }
  50% {
    transform: translateX(100px);
    opacity: 1;
  }
  50.1%,
  100% {
    transform: translateX(100px);
    opacity: .1;
  }
}

@keyframes hide-1 {
  0% {
    opacity: .1;
  }
  4%,
  50% {
    opacity: .1;
  }
  50.1%,
  100% {
    opacity: 1;
  }
}

@keyframes hide-2 {
  4% {
    opacity: .1;
  }
  8%,
  54% {
    opacity: .1;
  }
  54.1%,
  100% {
    opacity: 1;
  }
}

<div class="wrapper">
  <div class="static">
    <div class="block b1"> </div>
    <div class="block b2"> </div>
    <div class="block b3"> </div>
  </div>
  <div class="spinner">
    <div class="block b1"> </div>
    <div class="block b2"> </div>
  </div>
</div>


问:
Split each line at each space to create a list of lists
I have the python zen text and want to split each line at each space to create a list of lists. I have split each line, but how can I create a list of lists? Thanks so much for your help.

```<code>zen = '''
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
'''

zen.split('\n')
</code>```

答:
Since str.split creates a list, you can use str.split again in a list comprehension:

```<code>out = [line.split() for line in zen.split('\n')]
</code>```

Output:

[[], ['Beautiful', 'is', 'better', 'than', 'ugly.'], ['Explicit',
'is', 'better', 'than', 'implicit.'], ['Simple', 'is', 'better',
'than', 'complex.'], ['Complex', 'is', 'better', 'than',
'complicated.'], ['Flat', 'is', 'better', 'than', 'nested.'],
['Sparse', 'is', 'better', 'than', 'dense.'], ['Readability',
'counts.'], ['Special', 'cases', "aren't", 'special', 'enough', 'to',
'break', 'the', 'rules.'], ['Although', 'practicality', 'beats',
'purity.'], ['Errors', 'should', 'never', 'pass', 'silently.'],
['Unless', 'explicitly', 'silenced.'], ['In', 'the', 'face', 'of',
'ambiguity,', 'refuse', 'the', 'temptation', 'to', 'guess.'],
['There', 'should', 'be', 'one--', 'and', 'preferably', 'only', 'one',
'--obvious', 'way', 'to', 'do', 'it.'], ['Although', 'that', 'way',
'may', 'not', 'be', 'obvious', 'at', 'first', 'unless', "you're",
'Dutch.'], ['Now', 'is', 'better', 'than', 'never.'], ['Although',
'never', 'is', 'often', 'better', 'than', 'right', 'now.'], ['If',
'the', 'implementation', 'is', 'hard', 'to', 'explain,', "it's", 'a',
'bad', 'idea.'], ['If', 'the', 'implementation', 'is', 'easy', 'to',
'explain,', 'it', 'may', 'be', 'a', 'good', 'idea.'], ['Namespaces',
'are', 'one', 'honking', 'great', 'idea', '--', "let's", 'do', 'more',
'of', 'those!'], []]

Body:
I have the python zen text and want to split each line at each space to create a list of lists. I have split each line, but how can I create a list of lists? Thanks so much for your help.

zen = '''
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
'''

zen.split('\n')

Body:
Since str.split creates a list, you can use str.split again in a list comprehension:

out = [line.split() for line in zen.split('\n')]

Output:

[[], ['Beautiful', 'is', 'better', 'than', 'ugly.'], ['Explicit',
'is', 'better', 'than', 'implicit.'], ['Simple', 'is', 'better',
'than', 'complex.'], ['Complex', 'is', 'better', 'than',
'complicated.'], ['Flat', 'is', 'better', 'than', 'nested.'],
['Sparse', 'is', 'better', 'than', 'dense.'], ['Readability',
'counts.'], ['Special', 'cases', "aren't", 'special', 'enough', 'to',
'break', 'the', 'rules.'], ['Although', 'practicality', 'beats',
'purity.'], ['Errors', 'should', 'never', 'pass', 'silently.'],
['Unless', 'explicitly', 'silenced.'], ['In', 'the', 'face', 'of',
'ambiguity,', 'refuse', 'the', 'temptation', 'to', 'guess.'],
['There', 'should', 'be', 'one--', 'and', 'preferably', 'only', 'one',
'--obvious', 'way', 'to', 'do', 'it.'], ['Although', 'that', 'way',
'may', 'not', 'be', 'obvious', 'at', 'first', 'unless', "you're",
'Dutch.'], ['Now', 'is', 'better', 'than', 'never.'], ['Although',
'never', 'is', 'often', 'better', 'than', 'right', 'now.'], ['If',
'the', 'implementation', 'is', 'hard', 'to', 'explain,', "it's", 'a',
'bad', 'idea.'], ['If', 'the', 'implementation', 'is', 'easy', 'to',
'explain,', 'it', 'may', 'be', 'a', 'good', 'idea.'], ['Namespaces',
'are', 'one', 'honking', 'great', 'idea', '--', "let's", 'do', 'more',
'of', 'those!'], []]


答:
It's important here to remember that in C a string is a series of characters that ends with a null ('\0') character. We reference the string in our code using a character pointer that points to the beginning of the string. When we pass a string as a parameter to a function what we're really getting is a pointer to the first character in the string.

Because of this fact, we can use pointer math to increment through a string. The pattern:

```<code>while (*src1 != '\0') {
    //do stuff
    src1++;
}
</code>```

is a very common idiom in C. We might phrase it in English as:
While the value of the character in the string we are looking at (dereference src1 with the * operator) is not (inequality operator !=) the end of string indicator (null byte, 0 or '\0'), do some stuff, then move the pointer to point to the next character in the string (increment operator ++).

We often use the same kind of code structure to process other arrays or linked lists of things, comparing pointers to the NULL pointer.

To question #2, we're returning the value of the pointer from this function src1 and not the value of what it points to *scr1 because the question that this function should answer is "Where is the first instance of character c in the string that starts at the location pointed to by src1.

Question #3 implies that the code that calls this function is printing a string that starts from the pointer returned from this function. My guess is that the code looks something like this:

```<code>printf("%s", my_strchr(string, 'a'));
</code>```

printf() and friends will print from the location provided in the argument list that matches up with the %s format specifier and then keep printing until it gets to the end of string character ('\0', the null terminator).

Title: How to write my_strchr() in C

Body:
Right now I hope to write my own my_strchr() in the C language.

I checked that the answer should be like this:

char *my_strchr(const char *src1, int c) {

    while (*src1 != '\0') { //when the string goes to the last, jump out
        if (c == *src1) {
            return src1;
        }
        src1++;
    }
    return NULL;
}

I'm quite confused by:

why we use *src1  in the while loop condition (*src1 != '\0'), is *src1 a pointer to the const char*? Can we just use src1 instead?

When we return value and src1++, we do not have that *src1, why?

For this function, it in fact prints the whole string after the required characters, but why is that? Why does it not print only the character that we need to find?

Body:
It's important here to remember that in C a string is a series of characters that ends with a null ('\0') character. We reference the string in our code using a character pointer that points to the beginning of the string. When we pass a string as a parameter to a function what we're really getting is a pointer to the first character in the string.

Because of this fact, we can use pointer math to increment through a string. The pattern:

while (*src1 != '\0') {
    //do stuff
    src1++;
}

is a very common idiom in C. We might phrase it in English as:
While the value of the character in the string we are looking at (dereference src1 with the * operator) is not (inequality operator !=) the end of string indicator (null byte, 0 or '\0'), do some stuff, then move the pointer to point to the next character in the string (increment operator ++).

We often use the same kind of code structure to process other arrays or linked lists of things, comparing pointers to the NULL pointer.

To question #2, we're returning the value of the pointer from this function src1 and not the value of what it points to *scr1 because the question that this function should answer is "Where is the first instance of character c in the string that starts at the location pointed to by src1.

Question #3 implies that the code that calls this function is printing a string that starts from the pointer returned from this function. My guess is that the code looks something like this:

printf("%s", my_strchr(string, 'a'));

printf() and friends will print from the location provided in the argument list that matches up with the %s format specifier and then keep printing until it gets to the end of string character ('\0', the null terminator).


问:
JWT: Why Access & Refresh Token
I'm making an app in Node.js & Mongoose which needs to have some way of authentication. I first thought of simple session but then came across JWT's. I read through many articles but I'm still unsure if I should use them. My questions are:

Let's say someone steals a short lived access token that expires in 15 minutes, wouldn't the refresh token be useless, as 15 minutes is a lot of time to do something?

Where & How should I store refresh & access tokens? I guess access in client side memory and refresh tokens in database? But what if a attacker hacked the database and got the refresh token? Does he have acccess then?

Are there any other secure and good ways of authenticate with Node.js?

Thanks in advance!

答:
Short lived token is much better than non-expiring or longer life token so absolutely no to longer life. token loss/theft is a problem that needs dual solution to lock the client to server (ip lock is a bad idea given the ip spoofing) the real solution depends on how deep you want to go like going through a third service establishing trust among both. logout is always possible all depends on as soon the server stops recognising its issued token and client app can code the logic and server rejection.

storing token to persistent storage is not hacker proof unless there is a some sort of transformation like decryption or unwrapping in the server side application layer before storage (so that the token is not as is on client side as stored in the db.).

there are quite few answers present in JWT RFC https://datatracker.ietf.org/doc/html/rfc7519  so using it is reasonably secure for majority of applications. Remember security always demands double checking and two factors in each step but there is always a judgment call that applies.

Title: JWT: Why Access & Refresh Token


问:
How do I make 19 Sub Cells and 3 Header Cells Table in Bootstrap 3.3.7?
I need to make 3 cells header and 19 cells sub header Bootstrap 3.3.7 table as I attached.
Example screen shot attached. (Sorry for attaching screen shot I cannot draw here easily)

Thanks for your help.

Table Screenshot

答:
Something like this should get you started, you will need to add additional classes to further customize the look and feel.</p>
```<code><!DOCTYPE html>
<html>

<head>

    <title>Bootstrap 3.3.7 Table</title>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />

    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
        integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <!-- Optional theme -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css"
        integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

    <!-- Latest compiled and minified JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"
        integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
        crossorigin="anonymous"></script>

</head>

<body>

    <div class="container">

        <div class="row">

            <table class="table table-bordered text-center align-middle">
                <thead>
                    <tr>
                        <th scope="col"></th>
                        <th scope="col" colspan="9" class="h3 text-uppercase text-center text-danger">Home</th>
                        <th scope="col" colspan="9" class="h3 text-uppercase text-center text-primary">Away</th>
                    </tr>
                    <tr>
                        <th scope="col">Names</th>
                        <th scope="col" class="text-center text-danger">H1</th>
                        <th scope="col" class="text-center text-danger">H2</th>
                        <th scope="col" class="text-center text-danger">H3</th>
                        <th scope="col" class="text-center text-danger">H4</th>
                        <th scope="col" class="text-center text-danger">H5</th>
                        <th scope="col" class="text-center text-danger">H6</th>
                        <th scope="col" class="text-center text-danger">H7</th>
                        <th scope="col" class="text-center text-danger">H8</th>
                        <th scope="col" class="text-center text-danger">H9</th>
                        <th scope="col" class="text-center text-primary">A2</th>
                        <th scope="col" class="text-center text-primary">A1</th>
                        <th scope="col" class="text-center text-primary">A3</th>
                        <th scope="col" class="text-center text-primary">A4</th>
                        <th scope="col" class="text-center text-primary">A5</th>
                        <th scope="col" class="text-center text-primary">A6</th>
                        <th scope="col" class="text-center text-primary">A7</th>
                        <th scope="col" class="text-center text-primary">A8</th>
                        <th scope="col" class="text-center text-primary">A9</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <th scope="row">Johnny Walker</th>
                        <td>1</td>
                        <td>2</td>
                        <td>3</td>
                        <td>4</td>
                        <td>5</td>
                        <td>6</td>
                        <td>7</td>
                        <td>8</td>
                        <td>9</td>
                        <td>1</td>
                        <td>2</td>
                        <td>3</td>
                        <td>4</td>
                        <td>5</td>
                        <td>6</td>
                        <td>7</td>
                        <td>8</td>
                        <td>9</td>
                    </tr>
                    <tr>
                        <th scope="row">Andy Mcdowell</th>
                        <td>1</td>
                        <td>2</td>
                        <td>3</td>
                        <td>4</td>
                        <td>5</td>
                        <td>6</td>
                        <td>7</td>
                        <td>8</td>
                        <td>9</td>
                        <td>1</td>
                        <td>2</td>
                        <td>3</td>
                        <td>4</td>
                        <td>5</td>
                        <td>6</td>
                        <td>7</td>
                        <td>8</td>
                        <td>9</td>
                    </tr>
                    <tr>
                        <th scope="row">Cristiano Ronaldo</th>
                        <td>1</td>
                        <td>2</td>
                        <td>3</td>
                        <td>4</td>
                        <td>5</td>
                        <td>6</td>
                        <td>7</td>
                        <td>8</td>
                        <td>9</td>
                        <td>1</td>
                        <td>2</td>
                        <td>3</td>
                        <td>4</td>
                        <td>5</td>
                        <td>6</td>
                        <td>7</td>
                        <td>8</td>
                        <td>9</td>
                    </tr>
                </tbody>
            </table>
        </div>

    </div>

</body>

</html>
</code>```

Body:
Something like this should get you started, you will need to add additional classes to further customize the look and feel.

<!DOCTYPE html>
<html>

<head>

    <title>Bootstrap 3.3.7 Table</title>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />

    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
        integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <!-- Optional theme -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css"
        integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

    <!-- Latest compiled and minified JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"
        integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
        crossorigin="anonymous"></script>

</head>

<body>

    <div class="container">

        <div class="row">

            <table class="table table-bordered text-center align-middle">
                <thead>
                    <tr>
                        <th scope="col"></th>
                        <th scope="col" colspan="9" class="h3 text-uppercase text-center text-danger">Home</th>
                        <th scope="col" colspan="9" class="h3 text-uppercase text-center text-primary">Away</th>
                    </tr>
                    <tr>
                        <th scope="col">Names</th>
                        <th scope="col" class="text-center text-danger">H1</th>
                        <th scope="col" class="text-center text-danger">H2</th>
                        <th scope="col" class="text-center text-danger">H3</th>
                        <th scope="col" class="text-center text-danger">H4</th>
                        <th scope="col" class="text-center text-danger">H5</th>
                        <th scope="col" class="text-center text-danger">H6</th>
                        <th scope="col" class="text-center text-danger">H7</th>
                        <th scope="col" class="text-center text-danger">H8</th>
                        <th scope="col" class="text-center text-danger">H9</th>
                        <th scope="col" class="text-center text-primary">A2</th>
                        <th scope="col" class="text-center text-primary">A1</th>
                        <th scope="col" class="text-center text-primary">A3</th>
                        <th scope="col" class="text-center text-primary">A4</th>
                        <th scope="col" class="text-center text-primary">A5</th>
                        <th scope="col" class="text-center text-primary">A6</th>
                        <th scope="col" class="text-center text-primary">A7</th>
                        <th scope="col" class="text-center text-primary">A8</th>
                        <th scope="col" class="text-center text-primary">A9</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <th scope="row">Johnny Walker</th>
                        <td>1</td>
                        <td>2</td>
                        <td>3</td>
                        <td>4</td>
                        <td>5</td>
                        <td>6</td>
                        <td>7</td>
                        <td>8</td>
                        <td>9</td>
                        <td>1</td>
                        <td>2</td>
                        <td>3</td>
                        <td>4</td>
                        <td>5</td>
                        <td>6</td>
                        <td>7</td>
                        <td>8</td>
                        <td>9</td>
                    </tr>
                    <tr>
                        <th scope="row">Andy Mcdowell</th>
                        <td>1</td>
                        <td>2</td>
                        <td>3</td>
                        <td>4</td>
                        <td>5</td>
                        <td>6</td>
                        <td>7</td>
                        <td>8</td>
                        <td>9</td>
                        <td>1</td>
                        <td>2</td>
                        <td>3</td>
                        <td>4</td>
                        <td>5</td>
                        <td>6</td>
                        <td>7</td>
                        <td>8</td>
                        <td>9</td>
                    </tr>
                    <tr>
                        <th scope="row">Cristiano Ronaldo</th>
                        <td>1</td>
                        <td>2</td>
                        <td>3</td>
                        <td>4</td>
                        <td>5</td>
                        <td>6</td>
                        <td>7</td>
                        <td>8</td>
                        <td>9</td>
                        <td>1</td>
                        <td>2</td>
                        <td>3</td>
                        <td>4</td>
                        <td>5</td>
                        <td>6</td>
                        <td>7</td>
                        <td>8</td>
                        <td>9</td>
                    </tr>
                </tbody>
            </table>
        </div>

    </div>

</body>

</html>


问:
to fetch the seq_no of the columns in plsql
How to get

table1

```<code>column1
123 -seq_no
</code>```

table2

```<code>column1  column2
123     1
123     2
123     3
</code>```

how to get the column2 of table2 for column1 seq no of first table.

Please help

答:
Littlefoot,

What you are asking is a very basic question, one that might be expected of someone who has never had any training in PL/SQL. This will get you started, but I strongly suggest you look for some getting started training.

```<code> DECLARE
     l_col_result   table2.column2%TYPE;
 BEGIN
     SELECT column2
       INTO l_col_result
       FROM table1 INNER JOIN table2 ON table1.column1 = table2.column2;

     DBMS_OUTPUT.put_line (a => l_col_result);
 END;
</code>```

Body:
How to get

table1

column1
123 -seq_no

table2

column1  column2
123     1
123     2
123     3

how to get the column2 of table2 for column1 seq no of first table.

Please help

Body:
Littlefoot,

What you are asking is a very basic question, one that might be expected of someone who has never had any training in PL/SQL. This will get you started, but I strongly suggest you look for some getting started training.

 DECLARE
     l_col_result   table2.column2%TYPE;
 BEGIN
     SELECT column2
       INTO l_col_result
       FROM table1 INNER JOIN table2 ON table1.column1 = table2.column2;

     DBMS_OUTPUT.put_line (a => l_col_result);
 END;


问:
Best practice for filling a text range in Google Docs App Script
I use a template in google docs for a letter and I want to fill the letter after the (dynamic) header of the letter automatically via App Scripts. Is there any best practice to set the text always to the same position? I've tried to use a placeholder and replace it. But sometimes I need to replace the text more than one time.</p>

答:
I don't know about best practice but you could use bookmarks.  You can't name them but if you know, lets say, the 5th bookmark is user name then cycle through the bookmarks and when you get to the 5th edit the text.

Before:

```<code>function myFunction() {
  try {
    var doc = DocumentApp.getActiveDocument();
    var bmarks = doc.getBookmarks();
    var position = null;
    var i = 0;
    for( i=0; i<bmarks.length; i++ ) {
      console.log(bmarks[i].getId());
      position = bmarks[i].getPosition();
      position.insertText("i = "+i)
    }
  }
  catch(err) {
    console.log(err);
  }
}
</code>```

After:

Body:
I don't know about best practice but you could use bookmarks.  You can't name them but if you know, lets say, the 5th bookmark is user name then cycle through the bookmarks and when you get to the 5th edit the text.

Before:

function myFunction() {
  try {
    var doc = DocumentApp.getActiveDocument();
    var bmarks = doc.getBookmarks();
    var position = null;
    var i = 0;
    for( i=0; i<bmarks.length; i++ ) {
      console.log(bmarks[i].getId());
      position = bmarks[i].getPosition();
      position.insertText("i = "+i)
    }
  }
  catch(err) {
    console.log(err);
  }
}

After:


问:
Require All Fields in Initializer List
Suppose, I have a structure

```<code>struct A
{
  int a;
  int b;
};
</code>```

I would like to forbid initialization it the following way:

```<code>A a = {1};
</code>```

But the following should be OK:

```<code>A a = {1, 2};
</code>```

I can add an explicit constructor. But such a solution requires adding the constructor to all the structures in the project that is not convenient.

答:
Both GCC and Clang support -Werror=missing-field-initializers, which turns this into an error.

-Wmissing-field-initializers (warning, not error) is a part of the -Wextra.

Title: Require All Fields in Initializer List

Body:
Suppose, I have a structure

struct A
{
  int a;
  int b;
};

I would like to forbid initialization it the following way:

A a = {1};

But the following should be OK:

A a = {1, 2};

I can add an explicit constructor. But such a solution requires adding the constructor to all the structures in the project that is not convenient.


问:
C# Winform PrintDialog Pages popup
in C# Winform, i'm sending an Image to the printer using the PrintDialog... using this code:

```<code>       private void PrintSnippedImage()
    {
        PrintDocument pDoc = new PrintDocument();
        pDoc.PrintPage += PrintPage;

        PrintDialog pDialog = new PrintDialog();
        pDialog.ShowHelp = true;
        pDialog.AllowSelection = false;
        pDialog.AllowSomePages = false;
        pDialog.Document = pDoc;
        if (pDialog.ShowDialog() == DialogResult.OK)
        {
            pDoc.Print();
        };
    }

    private void PrintPage(object o, PrintPageEventArgs e)
    {
        System.Drawing.Image img = Glob.SnippedImage;
        Point loc = new Point(10, 10);
        e.Graphics.DrawImage(img, loc);
    }
</code>```

I get a popup that shows "Printing... Page 1 of document" with a Cancel button.
it appears in seemingly random locations on one of my monitors.

is there a way to inhibit this popup, or at least force it to appear on the monitor in the general location of the application that called it?

it looks like this:

答: It should be a case of swapping the PrintController implementation from PrintControllerWithStatusDialog (the default) to StandardPrintController. See https://learn.microsoft.com/en-us/dotnet/api/system.drawing.printing.printdocument.printcontroller?view=dotnet-plat-ext-6.0#system-drawing-printing-printdocument-printcontroller

Title: C# Winform PrintDialog Pages popup

Body:
in C# Winform, i'm sending an Image to the printer using the PrintDialog... using this code:

       private void PrintSnippedImage()
    {
        PrintDocument pDoc = new PrintDocument();
        pDoc.PrintPage += PrintPage;

        PrintDialog pDialog = new PrintDialog();
        pDialog.ShowHelp = true;
        pDialog.AllowSelection = false;
        pDialog.AllowSomePages = false;
        pDialog.Document = pDoc;
        if (pDialog.ShowDialog() == DialogResult.OK)
        {
            pDoc.Print();
        };
    }

    private void PrintPage(object o, PrintPageEventArgs e)
    {
        System.Drawing.Image img = Glob.SnippedImage;
        Point loc = new Point(10, 10);
        e.Graphics.DrawImage(img, loc);
    }

I get a popup that shows "Printing... Page 1 of document" with a Cancel button.
it appears in seemingly random locations on one of my monitors.

is there a way to inhibit this popup, or at least force it to appear on the monitor in the general location of the application that called it?

it looks like this:


问:
self signed certificate in certificate chain atom
Atom Package install issue.png

Hello,
I am using Atom to develop nodejs code for the very first time, problem with accessing the packages tab of the settings. Whenever I search for something, I get this error come up:
self signed certificate in certificate chain
I have tried uninstalling Atom and reinstalling it, and the same problem comes up.
Is this an Atom problem, or more likely something to do with my machine, and if so, what?
Am using win10 and my atom version is Atom 1.33.0x64
Any help would be most appreciated, since I don't seem to be able to add extensions any more.

Many thanks,
Sathiya

答:
Below instructions useful you are behind corporate proxy and
using Atom zip download.
If you are on windows, Locate you apm.cmd file.
mostly at -> cd 'C:\Atom\atom-x64-windows\Atom x64\resources\app\apm\bin\'
Execute below command at your windows power shell:

```<code>   .\apm.cmd config set strict-ssl false
</code>```

After this in your Atom,

```<code>File -> Settings -> init.coffee

ssl=false
process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0
proxy = "http://your.proxy:8080"
</code>```

Restart your Atom, at try to install

```<code>File -> Settings -> Install -> (for eg. minimap)
</code>```

Restart your Atom.exe

Body:
Below instructions useful you are behind corporate proxy and
using Atom zip download.
If you are on windows, Locate you apm.cmd file.
mostly at -> cd 'C:\Atom\atom-x64-windows\Atom x64\resources\app\apm\bin\'
Execute below command at your windows power shell:

   .\apm.cmd config set strict-ssl false

After this in your Atom,

File -> Settings -> init.coffee

ssl=false
process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0
proxy = "http://your.proxy:8080"

Restart your Atom, at try to install

File -> Settings -> Install -> (for eg. minimap)

Restart your Atom.exe