问:
too many positional arguments in python
Explanation
I am currently writing a code that simulates a game of hangman, but cheats by attempting to evade the player's guesses by changing the word. The class and methods are defined in hangman.py, while play_hangman.py calls the instance of Hangman and the play method (cannot be changed per the instructions of the assignment).

Problem
In the play method, I received the following error: "
TypeError: askForWordLength() takes 1 positional argument but 2 were given "
I know that this means I am giving too many arguments into the call of the method, but I am unsure of how to change it. I have tried rewriting the 5th line of the following code multiple times to fix this error, but it does not cease:

Specific Section of Code*

```<code>    def play(self):
        MODE = 1
        openSession = 1

        while(openSession == 1):
            word_length = self.askForWordLength(self.words)
            num_guesses = self.askForNumOfGuesses()
            wordStatus = self.wordStatus(word_length)
            letters_already_guessed = []
        print()

        gameOver = 0
        while (gameOver == 0):
            if (MODE == 1):
                self.printCountOfRemainingWords(self.remainingWords)

        self.printGameStats(self.remainingWords. letters_already_guessed,
                            self.num_guesses, self.wordStatus)

        guess = self.askPlayerForGuess(letters_already_guessed)
        letters_already_guessed.append(guess)
        num_guesses -= 1

        remainingWords = self.retrieveRemainingWords(guess, self.remainingWords,
                                                     num_guesses, word_length)

        wordStatus = self.wordStatus(remainingWords[0], letters_already_guessed)
        print()

        if (guess in wordStatus):
            num_guesses += 1

        if ('-' not in wordStatus):
            game_over = 1
            print('Congratulations! You won!')
            print('Your word was: ' + wordStatus)

        if (num_guesses == 0 and game_over == 0):
            game_over = 1
            print('Haha! You Lose')
            print('Your word was: ' + remainingWords[0])

        print('Thanks for playing Hangman!')
</code>```

ENTIRE CODE

hangman.py

```<code>import re
class Hangman:
    # hangman self method
    def hangman(self):
        self.hangman = Hangman()  # object of the Hangman class

    def words(self):
        with open('dictionary.txt') as file:  # opens dictionary text file
            file_lines = file.read().splitlines()  # reads and splits each line

        all_words = []  # empty list to contain all words
        valid_words = []  # empty list to contain all valid words

        for word in file_lines:  # traverses all words in the file lines
            if len(word) >= 3:  # accepts word if it has at least 3 letters
                all_words.append(word)  # appends accepted word to list

        # list of all invalid characters in python
        CHARACTERS = ["~", "`", "!", "@", "#", "$", "%", "^", "&", "*", "(",
                      ")", "-", "_", "=", "+", "[", "]", "{", "}", "|", "\","
                      "", "'", "?", "/", ">", ".", "<", ",", "", ";", ":"]

        for i in CHARACTERS:    # traverse list of invalids
            for word in all_words:
                if i not in word:   # if invalid character is not in word
                    valid_words.append(word)    # accept and append to list

        return valid_words  # return list of valid words

    def askForWordLength(self, valid_words):

        word_lengths = []   # empty list for possible word lengths
        for word in valid_words:    # traverse list of valid words
            length = word.__len__()  # record length of current word
            if (length not in word_lengths):
                word_lengths.append(length)     # accept and append to list
        word_lengths.sort()

        # inform user of possible word lengths
        print('The available word lengths are: ' + str(word_lengths[0]) + '-'
              + str(word_lengths[-1]))
        print()

        # have user choose from possible word lengths
        while(1):
            try:
                length = int(input('Please enter the word length you want: '))
                if (length in word_lengths):
                    return length
            except ValueError:
                print('Your input is invalid!. Please use a valid input!')
                print()

    def askForNumberOfGuesses(self):
        while(1):
            try:
                num_guesses = int(input('Enter number of guesses you want: '))
                if (num_guesses >= 3):
                    return num_guesses
            except ValueError:
                print('Your input is invalid!. Please use a valid input!')
                print()

    def wordStatus(self, length):
        status = '-'
        for i in range(0, length):
            status += '-'
        return

    def remainingWords(self, file_lines, length):
        words = []
        for word in file_lines:
            if (word.__len__() == length):
                words.append(word)
        return words

    def printGameStats(self, letters_guessed, status, num_guesses):
        print('Game Status: ' + str(status))
        print()
        print('Attempted Guesses' + str(letters_guessed))
        print('Remaining Guesses' + str(num_guesses))

    def askPlayerForGuess(self, letters_guessed):
        letter = str(input('Guess a letter: ')).lower()
        pattern = re.compile("^[a-z]{1}$")
        invalid_guess = letter in letters_guessed or re.match(pattern, letter) == None

        if (invalid_guess):
            while (1):
                print()
                if (re.match(pattern, letter) == None):
                    print('Invalid guess. Please enter a correct character!')
                if (letter in letters_guessed):
                    print('\nYou already guessed that letter' + letter)

                letter = str(input('Please guess a letter: '))
                valid_guess = letter not in letters_guessed and re.match(pattern, letter) != None

                if (valid_guess):
                    return letter
        return letter

    def retrieveWordStatus(self, word_family, letters_already_guessed):
        status = ''
        for letter in word_family:
            if (letter in letters_already_guessed):
                status += letter
            else:
                status += '-'
        return status

    def retrieveRemainingWords(self, guess, num_guesses, remaining_words,
                               wordStatus, guesses_num, word_length,
                               createWordFamiliesDict,
                               findHighestCountWordFamily,
                               generateListOfWords):

        word_families = createWordFamiliesDict(remaining_words, guess)
        family_return = wordStatus(word_length)
        avoid_guess = num_guesses == 0 and family_return in word_families

        if (avoid_guess):
            family_return = wordStatus(word_length)
        else:
            family_return = findHighestCountWordFamily(word_families)

        words = generateListOfWords(remaining_words, guess, family_return)
        return words

    def createWordFamiliesDict(self, remainingWords, guess):
        wordFamilies = dict()
        for word in remainingWords:
            status = ''
            for letter in word:
                if (letter == guess):
                    status += guess
                else:
                    status += '-'

            if (status not in wordFamilies):
                wordFamilies[status] = 1
            else:
                wordFamilies[status] = wordFamilies[status] + 1
        return wordFamilies

    def generateListOfWords(self, remainingWords, guess, familyToReturn):
        words = []
        for word in remainingWords:
            word_family = ''
            for letter in word:
                if (letter == guess):
                    word_family += guess
                else:
                    word_family += '-'

            if (word_family == familyToReturn):
                words.append(word)
        return words

    def findHighestCountWordFamily(self, wordFamilies):
        familyToReturn = ''
        maxCount = 0
        for word_family in wordFamilies:
            if wordFamilies[word_family] > maxCount:
                maxCount = wordFamilies[word_family]
                familyToReturn = word_family
        return familyToReturn

    def printCountOfRemainingWords(self, remainingWords):
        show_remain_words = str(input('Want to view the remaining words?: '))
        if (show_remain_words == 'yes'):
            print('Remaining words: ' + str(len(remainingWords)))
        else:
            print()

    def play(self, askForWordLength, askForNumberOfGuesses, remainingWords,
             words, wordStatus, printCountOfRemainingWords, printGameStats,
             askPlayerForGuess, retrieveRemainingWords):
        MODE = 1
        openSession = 1

        while (openSession == 1):
            word_length = askForWordLength(words)
            num_guesses = askForNumberOfGuesses()

            wordStatus = wordStatus(word_length)
            letters_already_guessed = []
            print()

            game_over = 0
            while (game_over == 0):
                if (MODE == 1):
                    printCountOfRemainingWords(remainingWords)

            printGameStats(remainingWords, letters_already_guessed,
                           num_guesses, wordStatus)

            guess = askPlayerForGuess(letters_already_guessed)
            letters_already_guessed.append(guess)
            num_guesses -= 1

            remainingWords = retrieveRemainingWords(guess, remainingWords,
                                                    num_guesses, word_length)

            wordStatus = wordStatus(remainingWords[0], letters_already_guessed)
            print()

            if (guess in wordStatus):
                num_guesses += 1

            if ('-' not in wordStatus):
                game_over = 1
                print('Congratulations! You won!')
                print('Your word was: ' + wordStatus)

            if (num_guesses == 0 and game_over == 0):
                game_over = 1
                print('Haha! You Lose')
                print('Your word was: ' + remainingWords[0])

        print('Thanks for playing Hangman!')```
```

答:
It looks like you don't understand how classes work or there is a piece of code not shown here. When you define a method in a class, the first argument always refers to the object on which the method operates, which is conventionally called self. Any subsequent arguments are defined how you want. Usually, you don't need to pass the first self argument because it is passed according to the object you use. Any remaining arguments are your responsibility though.

For example:

class Student:
    def __init__(self, name, age):
        # Initializer (Commonly called Constructor in other languages)
        # This is the first method that will run when you create an object and
        # it runs automatically (You don't need to call it).
        # This is where you'd initialize the state of the object, for example:
        # Create a student with name and age.

        # name and age are regular parameters of the __init__ method. We'd like
        # to save them as attributes of our student object which is represented
        # by self.
        self.name = name
        self.age = age
        # Maybe we'd like to save a list of grades too
        self.grades = []

    def add_grade(self, grade):
        # self is our object, and grade is the parameter
        self.grades.append(grade)

    def get_average(self):
        # If we don't need additional parameters, we don't have to, but self is
        # mandatory
        return sum(self.grades) / len(self.grades)

    def print_status(self):
        # Note I am calling get_average() and I don't specify self. It's determined automatically.
        print("Name:", self.name)
        print("Age:", self.age)
        print("Average:", self.get_average())

# We created the class, but we need to create some objects to use it.
s1 = Student("Dan", 15)
s2 = Student("Maya", 14)
# Note we only pass the custom parameters we specified which are `grade`
# self is determined by the object we are using (s1 or s2)
s1.add_grade(81)
s1.add_grade(86)
s2.add_grade(89)
s2.add_grade(93)
s1.print_status()
s2.print_status()
```

I hope this example helps you understand how methods work. In your code, I don't understand why you pass the methods as arguments of the play method and I don't see where you call this method or where you even create a Hangman object, so I can't help further.

Title: too many positional arguments in python

Body:
Explanation
I am currently writing a code that simulates a game of hangman, but cheats by attempting to evade the player's guesses by changing the word. The class and methods are defined in hangman.py, while play_hangman.py calls the instance of Hangman and the play method (cannot be changed per the instructions of the assignment).

Problem
In the play method, I received the following error: "
TypeError: askForWordLength() takes 1 positional argument but 2 were given "
I know that this means I am giving too many arguments into the call of the method, but I am unsure of how to change it. I have tried rewriting the 5th line of the following code multiple times to fix this error, but it does not cease:

Specific Section of Code*

    def play(self):
        MODE = 1
        openSession = 1

        while(openSession == 1):
            word_length = self.askForWordLength(self.words)
            num_guesses = self.askForNumOfGuesses()
            wordStatus = self.wordStatus(word_length)
            letters_already_guessed = []
        print()

        gameOver = 0
        while (gameOver == 0):
            if (MODE == 1):
                self.printCountOfRemainingWords(self.remainingWords)

        self.printGameStats(self.remainingWords. letters_already_guessed,
                            self.num_guesses, self.wordStatus)

        guess = self.askPlayerForGuess(letters_already_guessed)
        letters_already_guessed.append(guess)
        num_guesses -= 1

        remainingWords = self.retrieveRemainingWords(guess, self.remainingWords,
                                                     num_guesses, word_length)

        wordStatus = self.wordStatus(remainingWords[0], letters_already_guessed)
        print()

        if (guess in wordStatus):
            num_guesses += 1

        if ('-' not in wordStatus):
            game_over = 1
            print('Congratulations! You won!')
            print('Your word was: ' + wordStatus)

        if (num_guesses == 0 and game_over == 0):
            game_over = 1
            print('Haha! You Lose')
            print('Your word was: ' + remainingWords[0])

        print('Thanks for playing Hangman!')

ENTIRE CODE

hangman.py

import re
class Hangman:
    # hangman self method
    def hangman(self):
        self.hangman = Hangman()  # object of the Hangman class

    def words(self):
        with open('dictionary.txt') as file:  # opens dictionary text file
            file_lines = file.read().splitlines()  # reads and splits each line

        all_words = []  # empty list to contain all words
        valid_words = []  # empty list to contain all valid words

        for word in file_lines:  # traverses all words in the file lines
            if len(word) >= 3:  # accepts word if it has at least 3 letters
                all_words.append(word)  # appends accepted word to list

        # list of all invalid characters in python
        CHARACTERS = ["~", "`", "!", "@", "#", "$", "%", "^", "&", "*", "(",
                      ")", "-", "_", "=", "+", "[", "]", "{", "}", "|", "\","
                      "", "'", "?", "/", ">", ".", "<", ",", "", ";", ":"]

        for i in CHARACTERS:    # traverse list of invalids
            for word in all_words:
                if i not in word:   # if invalid character is not in word
                    valid_words.append(word)    # accept and append to list

        return valid_words  # return list of valid words

    def askForWordLength(self, valid_words):

        word_lengths = []   # empty list for possible word lengths
        for word in valid_words:    # traverse list of valid words
            length = word.__len__()  # record length of current word
            if (length not in word_lengths):
                word_lengths.append(length)     # accept and append to list
        word_lengths.sort()

        # inform user of possible word lengths
        print('The available word lengths are: ' + str(word_lengths[0]) + '-'
              + str(word_lengths[-1]))
        print()

        # have user choose from possible word lengths
        while(1):
            try:
                length = int(input('Please enter the word length you want: '))
                if (length in word_lengths):
                    return length
            except ValueError:
                print('Your input is invalid!. Please use a valid input!')
                print()

    def askForNumberOfGuesses(self):
        while(1):
            try:
                num_guesses = int(input('Enter number of guesses you want: '))
                if (num_guesses >= 3):
                    return num_guesses
            except ValueError:
                print('Your input is invalid!. Please use a valid input!')
                print()

    def wordStatus(self, length):
        status = '-'
        for i in range(0, length):
            status += '-'
        return

    def remainingWords(self, file_lines, length):
        words = []
        for word in file_lines:
            if (word.__len__() == length):
                words.append(word)
        return words

    def printGameStats(self, letters_guessed, status, num_guesses):
        print('Game Status: ' + str(status))
        print()
        print('Attempted Guesses' + str(letters_guessed))
        print('Remaining Guesses' + str(num_guesses))

    def askPlayerForGuess(self, letters_guessed):
        letter = str(input('Guess a letter: ')).lower()
        pattern = re.compile("^[a-z]{1}$")
        invalid_guess = letter in letters_guessed or re.match(pattern, letter) == None

        if (invalid_guess):
            while (1):
                print()
                if (re.match(pattern, letter) == None):
                    print('Invalid guess. Please enter a correct character!')
                if (letter in letters_guessed):
                    print('\nYou already guessed that letter' + letter)

                letter = str(input('Please guess a letter: '))
                valid_guess = letter not in letters_guessed and re.match(pattern, letter) != None

                if (valid_guess):
                    return letter
        return letter

    def retrieveWordStatus(self, word_family, letters_already_guessed):
        status = ''
        for letter in word_family:
            if (letter in letters_already_guessed):
                status += letter
            else:
                status += '-'
        return status

    def retrieveRemainingWords(self, guess, num_guesses, remaining_words,
                               wordStatus, guesses_num, word_length,
                               createWordFamiliesDict,
                               findHighestCountWordFamily,
                               generateListOfWords):

        word_families = createWordFamiliesDict(remaining_words, guess)
        family_return = wordStatus(word_length)
        avoid_guess = num_guesses == 0 and family_return in word_families

        if (avoid_guess):
            family_return = wordStatus(word_length)
        else:
            family_return = findHighestCountWordFamily(word_families)

        words = generateListOfWords(remaining_words, guess, family_return)
        return words

    def createWordFamiliesDict(self, remainingWords, guess):
        wordFamilies = dict()
        for word in remainingWords:
            status = ''
            for letter in word:
                if (letter == guess):
                    status += guess
                else:
                    status += '-'

            if (status not in wordFamilies):
                wordFamilies[status] = 1
            else:
                wordFamilies[status] = wordFamilies[status] + 1
        return wordFamilies

    def generateListOfWords(self, remainingWords, guess, familyToReturn):
        words = []
        for word in remainingWords:
            word_family = ''
            for letter in word:
                if (letter == guess):
                    word_family += guess
                else:
                    word_family += '-'

            if (word_family == familyToReturn):
                words.append(word)
        return words

    def findHighestCountWordFamily(self, wordFamilies):
        familyToReturn = ''
        maxCount = 0
        for word_family in wordFamilies:
            if wordFamilies[word_family] > maxCount:
                maxCount = wordFamilies[word_family]
                familyToReturn = word_family
        return familyToReturn

    def printCountOfRemainingWords(self, remainingWords):
        show_remain_words = str(input('Want to view the remaining words?: '))
        if (show_remain_words == 'yes'):
            print('Remaining words: ' + str(len(remainingWords)))
        else:
            print()

    def play(self, askForWordLength, askForNumberOfGuesses, remainingWords,
             words, wordStatus, printCountOfRemainingWords, printGameStats,
             askPlayerForGuess, retrieveRemainingWords):
        MODE = 1
        openSession = 1

        while (openSession == 1):
            word_length = askForWordLength(words)
            num_guesses = askForNumberOfGuesses()

            wordStatus = wordStatus(word_length)
            letters_already_guessed = []
            print()

            game_over = 0
            while (game_over == 0):
                if (MODE == 1):
                    printCountOfRemainingWords(remainingWords)

            printGameStats(remainingWords, letters_already_guessed,
                           num_guesses, wordStatus)

            guess = askPlayerForGuess(letters_already_guessed)
            letters_already_guessed.append(guess)
            num_guesses -= 1

            remainingWords = retrieveRemainingWords(guess, remainingWords,
                                                    num_guesses, word_length)

            wordStatus = wordStatus(remainingWords[0], letters_already_guessed)
            print()

            if (guess in wordStatus):
                num_guesses += 1

            if ('-' not in wordStatus):
                game_over = 1
                print('Congratulations! You won!')
                print('Your word was: ' + wordStatus)

            if (num_guesses == 0 and game_over == 0):
                game_over = 1
                print('Haha! You Lose')
                print('Your word was: ' + remainingWords[0])

        print('Thanks for playing Hangman!')```

Body:
It looks like you don't understand how classes work or there is a piece of code not shown here. When you define a method in a class, the first argument always refers to the object on which the method operates, which is conventionally called self. Any subsequent arguments are defined how you want. Usually, you don't need to pass the first self argument because it is passed according to the object you use. Any remaining arguments are your responsibility though.

For example:

class Student:
    def __init__(self, name, age):
        # Initializer (Commonly called Constructor in other languages)
        # This is the first method that will run when you create an object and
        # it runs automatically (You don't need to call it).
        # This is where you'd initialize the state of the object, for example:
        # Create a student with name and age.

        # name and age are regular parameters of the __init__ method. We'd like
        # to save them as attributes of our student object which is represented
        # by self.
        self.name = name
        self.age = age
        # Maybe we'd like to save a list of grades too
        self.grades = []

    def add_grade(self, grade):
        # self is our object, and grade is the parameter
        self.grades.append(grade)

    def get_average(self):
        # If we don't need additional parameters, we don't have to, but self is
        # mandatory
        return sum(self.grades) / len(self.grades)

    def print_status(self):
        # Note I am calling get_average() and I don't specify self. It's determined automatically.
        print("Name:", self.name)
        print("Age:", self.age)
        print("Average:", self.get_average())

# We created the class, but we need to create some objects to use it.
s1 = Student("Dan", 15)
s2 = Student("Maya", 14)
# Note we only pass the custom parameters we specified which are `grade`
# self is determined by the object we are using (s1 or s2)
s1.add_grade(81)
s1.add_grade(86)
s2.add_grade(89)
s2.add_grade(93)
s1.print_status()
s2.print_status()

I hope this example helps you understand how methods work. In your code, I don't understand why you pass the methods as arguments of the play method and I don't see where you call this method or where you even create a Hangman object, so I can't help further.


来源: stackexchange

问:
How to use SUM() with getMany() in TypeORM?
I'm trying to write a group by query with TypeOrm/PostgreSQL ("pg": "^8.3.3", "typeorm": "^0.2.25").

The SQL query I need to be run is:

SELECT
    ad_id,
    COUNT (impression_id) AS impressions
FROM
    Ad_impressions
GROUP BY
    ad_id
ORDER BY
    impressions
```
<p>I've read all the documentation and searched a lot online, but couldn't get it to work. This was my best try:</p>
<pre class="lang-js prettyprint-override"><code>await getConnection()
  .getRepository(Ad_impressions)
  .createQueryBuilder('Ad_impressions')
  .select([
    'Ad_impressions.ad_id',
    'COUNT(Ad_impressions.impression_id) as count',
  ])
  .groupBy("Ad_impressions.ad_id")
  .orderBy('impressions', 'DESC')
  .getMany();
</code>```

答:
use getRawMany instead of getMany.</p>
```<code>await getConnection().getRepository(Ad_impressions).createQueryBuilder('Ad_impressions').select([
'Ad_impressions.ad_id',
'COUNT(Ad_impressions.impression_id) as count',]).groupBy("Ad_impressions.ad_id").orderBy('impressions', 'DESC').getRawMany();
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to write a group by query with TypeOrm/PostgreSQL ("pg": "^8.3.3", "typeorm": "^0.2.25").

The SQL query I need to be run is:

SELECT
    ad_id,
    COUNT (impression_id) AS impressions
FROM
    Ad_impressions
GROUP BY
    ad_id
ORDER BY
    impressions

I've read all the documentation and searched a lot online, but couldn't get it to work. This was my best try:

await getConnection()
  .getRepository(Ad_impressions)
  .createQueryBuilder('Ad_impressions')
  .select([
    'Ad_impressions.ad_id',
    'COUNT(Ad_impressions.impression_id) as count',
  ])
  .groupBy("Ad_impressions.ad_id")
  .orderBy('impressions', 'DESC')
  .getMany();

Body:
use getRawMany instead of getMany.

await getConnection().getRepository(Ad_impressions).createQueryBuilder('Ad_impressions').select([
'Ad_impressions.ad_id',
'COUNT(Ad_impressions.impression_id) as count',]).groupBy("Ad_impressions.ad_id").orderBy('impressions', 'DESC').getRawMany();


问:
The app signature is different from that of the released version
I am trying to upload new apk with a keystore file and its giving this error. System says The app signature is different from that of the released version.</p>

答:
The key-store which you have used for update release version should be consistent with the released version which there is in the app gallery.

If you don't have the key-store, you have to create new one and you can resubmit the application. If you create and resubmit with the new key-store, in that case you can leave a note saying Agree to ignore key-store difference in the Notes column of the Version information page.


问:
How to get epoch time in AWS Step Function
We can refer to the current time in AWS Step functions using "$$.State.EnteredTime", But that gives the ISO format. Is there a way to get the Epoch seconds/milliseconds? I want to add the TTL value in the DynamoDB based on that.

Is this possible? Or do I have to invoke a Lambda function only for the timestamp?

答:
This requires a Lambda Invoke Task. A small set of value transformations (e.g. string interpolation, JSON parsing) are natively handled by Intrinsic Functions.  Most value transforms, however, including date manipulation, require an external task resource like Lambda.

"EpochExecutionTimeLambda": {
  "Type": "Task",
  "ResultPath": "$.epoch",
  "Resource": "arn:aws:lambda:us-east-1:...",
  "Parameters": {
    "dateTime.$": "$$.State.EnteredTime"
  }
```
<p>The lambda handler is of course trivial:</p>
<pre class="lang-js prettyprint-override"><code>exports.handler = async (event) => new Date(event.dateTime).valueOf()
</code>```

Body:
This requires a Lambda Invoke Task. A small set of value transformations (e.g. string interpolation, JSON parsing) are natively handled by Intrinsic Functions.  Most value transforms, however, including date manipulation, require an external task resource like Lambda.

"EpochExecutionTimeLambda": {
  "Type": "Task",
  "ResultPath": "$.epoch",
  "Resource": "arn:aws:lambda:us-east-1:...",
  "Parameters": {
    "dateTime.$": "$$.State.EnteredTime"
  }

The lambda handler is of course trivial:

exports.handler = async (event) => new Date(event.dateTime).valueOf()


问:
x11 - ImportError: No module named 'kivy.core.window.window_x11'
when i try to run any kivy program with python 3.5 in my kali linux os. Then i get the below error.

program:-

```<code>from kivy.app import App
from kivy.lang import Builder
from kivy.uix.relativelayout import RelativeLayout

Builder.load_string('''
<hey>:
    RelativeLayout:
        Button:
            text:"Hey"
''')

class hey(RelativeLayout):
    pass

class helloApp(App):
    def build(self):
        return hey()

if __name__=="__main__":
    helloApp().run()
</code>```

error:-

```<code>[INFO   ] [OSC         ] using <multiprocessing> for socket
[INFO   ] [Window      ] Provider: sdl2(['window_egl_rpi'] ignored)
[CRITICAL] [Window      ] Unable to find any valuable Window provider at all!
egl_rpi - ImportError: cannot import name 'bcm'
  File "/usr/lib/python3/dist-packages/kivy/core/__init__.py", line 59, in core_select_lib
    fromlist=[modulename], level=0)
  File "/usr/lib/python3/dist-packages/kivy/core/window/window_egl_rpi.py", line 12, in <module>
    from kivy.lib.vidcore_lite import bcm, egl

sdl2 - TypeError: expected bytes, str found
  File "/usr/lib/python3/dist-packages/kivy/core/__init__.py", line 67, in core_select_lib
    cls = cls()
  File "/usr/lib/python3/dist-packages/kivy/core/window/window_sdl2.py", line 138, in __init__
    super(WindowSDL, self).__init__()
  File "/usr/lib/python3/dist-packages/kivy/core/window/__init__.py", line 722, in __init__
    self.create_window()
  File "/usr/lib/python3/dist-packages/kivy/core/window/window_sdl2.py", line 237, in create_window
    self.fullscreen, resizable, state)
  File "kivy/core/window/_window_sdl2.pyx", line 94, in kivy.core.window._window_sdl2._WindowSDL2Storage.setup_window (kivy/core/window/_window_sdl2.c:2204)

x11 - ImportError: No module named 'kivy.core.window.window_x11'
  File "/usr/lib/python3/dist-packages/kivy/core/__init__.py", line 59, in core_select_lib
    fromlist=[modulename], level=0)

[CRITICAL] [App         ] Unable to get a Window, abort.
</code>```

It used to be work fine when i installed kivy in previous kali linux os but due to some reasons i installed kali again and kivy again but this time i am not able to make it work.

答:
Try installing pygame

pip install pygame
```

ContentLicense: CC BY-SA 3.0

Body:
when i try to run any kivy program with python 3.5 in my kali linux os. Then i get the below error.

program:-

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.relativelayout import RelativeLayout

Builder.load_string('''
<hey>:
    RelativeLayout:
        Button:
            text:"Hey"
''')

class hey(RelativeLayout):
    pass

class helloApp(App):
    def build(self):
        return hey()

if __name__=="__main__":
    helloApp().run()

error:-

[INFO   ] [OSC         ] using <multiprocessing> for socket
[INFO   ] [Window      ] Provider: sdl2(['window_egl_rpi'] ignored)
[CRITICAL] [Window      ] Unable to find any valuable Window provider at all!
egl_rpi - ImportError: cannot import name 'bcm'
  File "/usr/lib/python3/dist-packages/kivy/core/__init__.py", line 59, in core_select_lib
    fromlist=[modulename], level=0)
  File "/usr/lib/python3/dist-packages/kivy/core/window/window_egl_rpi.py", line 12, in <module>
    from kivy.lib.vidcore_lite import bcm, egl

sdl2 - TypeError: expected bytes, str found
  File "/usr/lib/python3/dist-packages/kivy/core/__init__.py", line 67, in core_select_lib
    cls = cls()
  File "/usr/lib/python3/dist-packages/kivy/core/window/window_sdl2.py", line 138, in __init__
    super(WindowSDL, self).__init__()
  File "/usr/lib/python3/dist-packages/kivy/core/window/__init__.py", line 722, in __init__
    self.create_window()
  File "/usr/lib/python3/dist-packages/kivy/core/window/window_sdl2.py", line 237, in create_window
    self.fullscreen, resizable, state)
  File "kivy/core/window/_window_sdl2.pyx", line 94, in kivy.core.window._window_sdl2._WindowSDL2Storage.setup_window (kivy/core/window/_window_sdl2.c:2204)

x11 - ImportError: No module named 'kivy.core.window.window_x11'
  File "/usr/lib/python3/dist-packages/kivy/core/__init__.py", line 59, in core_select_lib
    fromlist=[modulename], level=0)

[CRITICAL] [App         ] Unable to get a Window, abort.

It used to be work fine when i installed kivy in previous kali linux os but due to some reasons i installed kali again and kivy again but this time i am not able to make it work.


问:
C vs C++ - cross-platform
I have a very quick question to which I havn't found an answer for.
Are there any major platforms (Windows, MacOS, unix, linux, Android, iOS, etc....) out there that supports C but not C++?

Thanks

答: Since C is a subset of C++, you'll definitely bump into some environment that supports C but no C++. Whether such a platform may be called 'major' by any standards is another question. (There was a C compiler for the C64, but no C++ compiler to my knowledge. The C64 was absolutely a major platform :)</p>

Title: C vs C++ - cross-platform


问:
How to check if current date is between two dates in javascript
I'm trying to make a Livestream feature in my project, I have an array of programs (videos), every video has startDate and endDate. I should run every video when its time has come.</p>
```<code>const programs = [
    { video: "URL", startDate: 1644405993, endDate: 1644406032 },
    { video: "URL", startDate: 1644405993, endDate: 1644406032 },
    { video: "URL", startDate: 1644405993, endDate: 1644406032 },
    { video: "URL", startDate: 1644405993, endDate: 1644406032 }
];
</code>```

答:
try this

```<code>export const checkTime = (startDate, endDate) => {// startDate= 1644405993, endDate = 1644406032
const now = new Date()
const bookingStartDate = new Date(startDate) // use this step to convert your date if its stored in a different format
const bookingEndDate = new Date(endDate) // use this step to convert your date if its stored in a different format
return now.getTime() > bookingStartDate.getTime() && now.getTime() < bookingEndDate.getTime()
</code>```

}

Body:
I'm trying to make a Livestream feature in my project, I have an array of programs (videos), every video has startDate and endDate. I should run every video when its time has come.

const programs = [
    { video: "URL", startDate: 1644405993, endDate: 1644406032 },
    { video: "URL", startDate: 1644405993, endDate: 1644406032 },
    { video: "URL", startDate: 1644405993, endDate: 1644406032 },
    { video: "URL", startDate: 1644405993, endDate: 1644406032 }
];

Body:
try this

export const checkTime = (startDate, endDate) => {// startDate= 1644405993, endDate = 1644406032
const now = new Date()
const bookingStartDate = new Date(startDate) // use this step to convert your date if its stored in a different format
const bookingEndDate = new Date(endDate) // use this step to convert your date if its stored in a different format
return now.getTime() > bookingStartDate.getTime() && now.getTime() < bookingEndDate.getTime()

}


问:
SQL select unique ID from multiple tables
I have multiple SQL tables, for example two tables with employees from office1 and office2. Each employer has an unique ID, which I have. I do not know in office the employer works so I want to select from both tables.

note in reality I have up to 50 tables, still with a unique ID.

database name for example employers

```<code>use employers
SHOW tables;

+---------------------+
| Tables_in_employers |
+---------------------+
| office1             |
| office2             |
+---------------------+

SELECT * FROM `office1`, `office2` WHERE ID=1

Column `ID` in where clause is ambiguous
</code>```

I have seen a solution like this: (SELECT * FROM multiple tables. MySQL)

```<code>SELECT * FROM `office1`, `office2` WHERE office1.ID=1 GROUP BY
</code>```

But that statement only search in the office1 table, while I want to search both tables and only return the row where the ID matches.

Now I tend to use a for loop en go over each table (in python), but before I implement that I wanted to be sure that this can not be done (faster) in pure SQL.

答:
Use union:

```<code>SELECT ID, office
FROM (select ID, 'office' as 'office1' FROM office1
      union all
      select ID, 'office' as 'office2' FROM office2) allOffices
WHERE ID=1;
</code>```

Or create a view:

```<code>create view allOffices as
  select ID, 'office' as 'office1' from office1
  union all
  select ID, 'office' as 'office2' from office2;
</code>```

After this your can do:

```<code>SELECT ID, office
FROM allOffices WHERE ID=1
</code>```

The output will contain the column ID, and the columnd office with the name that is specified in the CREATE VIEW.

NOTE: it is possible that these queries return more than 1 row, if the ID exists in both offices.

Body:
I have multiple SQL tables, for example two tables with employees from office1 and office2. Each employer has an unique ID, which I have. I do not know in office the employer works so I want to select from both tables.

note in reality I have up to 50 tables, still with a unique ID.

database name for example employers

use employers
SHOW tables;

+---------------------+
| Tables_in_employers |
+---------------------+
| office1             |
| office2             |
+---------------------+

SELECT * FROM `office1`, `office2` WHERE ID=1

Column `ID` in where clause is ambiguous

I have seen a solution like this: (SELECT * FROM multiple tables. MySQL)

SELECT * FROM `office1`, `office2` WHERE office1.ID=1 GROUP BY

But that statement only search in the office1 table, while I want to search both tables and only return the row where the ID matches.

Now I tend to use a for loop en go over each table (in python), but before I implement that I wanted to be sure that this can not be done (faster) in pure SQL.

Body:
Use union:

SELECT ID, office
FROM (select ID, 'office' as 'office1' FROM office1
      union all
      select ID, 'office' as 'office2' FROM office2) allOffices
WHERE ID=1;

Or create a view:

create view allOffices as
  select ID, 'office' as 'office1' from office1
  union all
  select ID, 'office' as 'office2' from office2;

After this your can do:

SELECT ID, office
FROM allOffices WHERE ID=1

The output will contain the column ID, and the columnd office with the name that is specified in the CREATE VIEW.

NOTE: it is possible that these queries return more than 1 row, if the ID exists in both offices.


问:
HTML5 Canvas Font Size Based on Canvas Size
I have the canvas size set to 1/3 the window.innerHeight and window.innerWidth of the browser.

Most of the elements on the canvas are also set based on the width and height of the canvas, so that they scale down in size and are positioned based on the size of the canvas.

How do I scale font sizes based on this as well?

For example, the font size of my opening screen of a game I'm making, is 80pt. That's way too big if the browser is really small. It goes off the canvas.

答:
Another technique to draw text (or anything else) scaled, is to use the canvas transformation matrix.

The trick is to temporarily move the coordinate system (0, 0) to the text insertion point and scale around the point before drawing.

Save the drawing context

Move coordinate system to the text insertion point using context.translate()

Scale upp/down with desired scale factor using use context.scale()

Insert the text at the translation point (0, 0).

Restore the context.

Sample code that draws text with desired scale at point x, y:

```<code>function drawText(context, x, y, text, scale){
    context.save();
    context.translate(x, y)
    context.scale(scale, scale);
    context.fillText(text, 0, 0);
    context.restore();
}
</code>```

To draw text centered use

```<code>context.textAlign ="center";
context.textBaseline = "middle";
</code>```

Body:
Another technique to draw text (or anything else) scaled, is to use the canvas transformation matrix.

The trick is to temporarily move the coordinate system (0, 0) to the text insertion point and scale around the point before drawing.

Save the drawing context

Move coordinate system to the text insertion point using context.translate()

Scale upp/down with desired scale factor using use context.scale()

Insert the text at the translation point (0, 0).

Restore the context.

Sample code that draws text with desired scale at point x, y:

function drawText(context, x, y, text, scale){
    context.save();
    context.translate(x, y)
    context.scale(scale, scale);
    context.fillText(text, 0, 0);
    context.restore();
}

To draw text centered use

context.textAlign ="center";
context.textBaseline = "middle";


问:
R : How to extract the factor levels as numeric from a column and assign it to a new column using tydyverse?
Suppose I have a data frame, df

```<code>df = data.frame(name = rep(c("A", "B", "C"), each = 4))
</code>```

I want to get a new data frame with one additional column named Group, in which Group element is the numeric value of the corresponding level of name, as shown in df2.

I know case_when could do it. My issue is that my real data frame is quite complicated, there are many levels of the name column. I am too lazy to list case by case.

Is there an easier and smarter way to do it?

Thanks.

```<code>df2
   name Group
1     A     1
2     A     1
3     A     1
4     A     1
5     B     2
6     B     2
7     B     2
8     B     2
9     C     3
10    C     3
11    C     3
12    C     3
</code>```

答:
A couple other simple solutions:

library(dplyr)

df %>%
  mutate(Group = match(name, unique(name)))
#>    name Group
#> 1     A     1
#> 2     A     1
#> 3     A     1
#> 4     A     1
#> 5     B     2
#> 6     B     2
#> 7     B     2
#> 8     B     2
#> 9     C     3
#> 10    C     3
#> 11    C     3
#> 12    C     3

df %>%
  mutate(Group = cumsum(name != lag(name, default = "")))
#>    name Group
#> 1     A     1
#> 2     A     1
#> 3     A     1
#> 4     A     1
#> 5     B     2
#> 6     B     2
#> 7     B     2
#> 8     B     2
#> 9     C     3
#> 10    C     3
#> 11    C     3
#> 12    C     3
```

Body:
Suppose I have a data frame, df

df = data.frame(name = rep(c("A", "B", "C"), each = 4))

I want to get a new data frame with one additional column named Group, in which Group element is the numeric value of the corresponding level of name, as shown in df2.

I know case_when could do it. My issue is that my real data frame is quite complicated, there are many levels of the name column. I am too lazy to list case by case.

Is there an easier and smarter way to do it?

Thanks.

df2
   name Group
1     A     1
2     A     1
3     A     1
4     A     1
5     B     2
6     B     2
7     B     2
8     B     2
9     C     3
10    C     3
11    C     3
12    C     3


问:
Unable to delete all row in Data extension using ssjs
I am trying to delete rows in DE (shared DE). The code I am using is

  <title>test12</title>

```

My code (ones is complete and running) will be running as script in automation . For now i am testing it , thus i have put it cloudpages . This cloud page is also in enterprise BU and so is the Data extension from which i want to delete

I get following error :
{"message":"Object expected: DeleteData","jintException":"Jint.Native.JsException: Exception of type 'Jint.Native.JsException' was thrown.\r\n at Jint.ExecutionVisitor.Visit(MethodCall methodCall)\r\n at Jint.Expressions.MethodCall.Accept(IJintVisitor visitor)\r\n at Jint.ExecutionVisitor.Visit(MemberExpression expression)\r\n at Jint.Expressions.MemberExpression.Accept(IJintVisitor visitor)\r\n at Jint.ExecutionVisitor.Visit(VariableDeclarationStatement statement)\r\n at Jint.Expressions.VariableDeclarationStatement.Accept(IJintVisitor visitor)\r\n at Jint.ExecutionVisitor.Visit(BlockStatement statement)\r\n at Jint.Expressions.BlockStatement.Accept(IJintVisitor visitor)\r\n at Jint.ExecutionVisitor.Visit(TryStatement statement)","description":"Jint.Native.JsException: Object expected: DeleteData\r\nException of type 'Jint.Native.JsException' was thrown. - from Jint\r\n\r\n"}

any clue was is causing the issue .

答:
first please use StackExchange for more reactivity on SFMC stuff.

The parameters of DeleteData function include brackets on two last parameters.

```<code> <script runat="server">
            Platform.Load("core", "1.1.1");
            try{
                var deleteCount = DeleteData("Voucher_Notification_Threshold",["return"], [1])
            }catch(ex)
            {
                Write(Stringify(ex));
            }
</script>
</code>```

Body:
I am trying to delete rows in DE (shared DE). The code I am using is

  <title>test12</title>

My code (ones is complete and running) will be running as script in automation . For now i am testing it , thus i have put it cloudpages . This cloud page is also in enterprise BU and so is the Data extension from which i want to delete

I get following error :
{"message":"Object expected: DeleteData","jintException":"Jint.Native.JsException: Exception of type 'Jint.Native.JsException' was thrown.\r\n at Jint.ExecutionVisitor.Visit(MethodCall methodCall)\r\n at Jint.Expressions.MethodCall.Accept(IJintVisitor visitor)\r\n at Jint.ExecutionVisitor.Visit(MemberExpression expression)\r\n at Jint.Expressions.MemberExpression.Accept(IJintVisitor visitor)\r\n at Jint.ExecutionVisitor.Visit(VariableDeclarationStatement statement)\r\n at Jint.Expressions.VariableDeclarationStatement.Accept(IJintVisitor visitor)\r\n at Jint.ExecutionVisitor.Visit(BlockStatement statement)\r\n at Jint.Expressions.BlockStatement.Accept(IJintVisitor visitor)\r\n at Jint.ExecutionVisitor.Visit(TryStatement statement)","description":"Jint.Native.JsException: Object expected: DeleteData\r\nException of type 'Jint.Native.JsException' was thrown. - from Jint\r\n\r\n"}

any clue was is causing the issue .

Body:
first please use StackExchange for more reactivity on SFMC stuff.

The parameters of DeleteData function include brackets on two last parameters.

 <script runat="server">
            Platform.Load("core", "1.1.1");
            try{
                var deleteCount = DeleteData("Voucher_Notification_Threshold",["return"], [1])
            }catch(ex)
            {
                Write(Stringify(ex));
            }
</script>


问:
Why am I getting TypeError: Cannot read property '0' of undefined error in google apps script?
I am just trying to bold the first column data in the sheet.

```<code>function formatColumnHeader(){
var thisSheet = SpreadsheetApp.getActiveSheet();
var dataRange = thisSheet.getDataRange();
var dataValues = dataRange.getValues();

for(var row =1;row<dataValues.length;row++){
 dataRange[row][0].setFontWeight('bold');
}
}
</code>```

But I get TypeError: Cannot read property '0' of undefined error. What am I doing wrong here?

答:
You can try range.offset:

```<code>function formatColumnHeader(){
  const thisSheet = SpreadsheetApp.getActiveSheet(),
    dataRange = thisSheet.getDataRange();
  dataRange.offset(0, 0, dataRange.getNumRows(), 1).setFontWeight('bold');
}
</code>```

Or if you have no need for dataRange, try getRange() to get only the range that you need:

```<code>function formatColumnHeader(){
  const thisSheet = SpreadsheetApp.getActiveSheet();
  dataRange = thisSheet.getRange(1, 1, thisSheet.getLastRow()).setFontWeight('bold');
}
</code>```

Body:
I am just trying to bold the first column data in the sheet.

function formatColumnHeader(){
var thisSheet = SpreadsheetApp.getActiveSheet();
var dataRange = thisSheet.getDataRange();
var dataValues = dataRange.getValues();

for(var row =1;row<dataValues.length;row++){
 dataRange[row][0].setFontWeight('bold');
}
}

But I get TypeError: Cannot read property '0' of undefined error. What am I doing wrong here?

Body:
You can try range.offset:

function formatColumnHeader(){
  const thisSheet = SpreadsheetApp.getActiveSheet(),
    dataRange = thisSheet.getDataRange();
  dataRange.offset(0, 0, dataRange.getNumRows(), 1).setFontWeight('bold');
}

Or if you have no need for dataRange, try getRange() to get only the range that you need:

function formatColumnHeader(){
  const thisSheet = SpreadsheetApp.getActiveSheet();
  dataRange = thisSheet.getRange(1, 1, thisSheet.getLastRow()).setFontWeight('bold');
}


问:
Unix Regex (ERE) for finding a lines with 4 or more numbers
I've tried so many variations but none seem to work, I have no idea what I don't understand.

The last one I've tried is (\<[[:digit:]]+\>.*){4,}.
But it doesn't even find lines like 123 123 123 123.
The input lines can be anything (even like hello 123 my 1 name 2 is 3).

I didn't specify it, sorry, but what I meant is: line "123 a2" has 1 number, line "1 2 3 45" has 4 numbers.

答:
It seems there is some problem with quantifying the pattern in your grep command. If the first number has more than one digits, and the others contain just one, your regex works. Else, it won't, see the testing results:

#!/bin/bash
s="123 1 2 3  - works, the first number is two+ digits, the rest are one digits
1 2 3 45 - does not work, the first number is one-digit
14 2 3 4 - works
123 a2 - not output as expected as there is just one number
12 and one 1 more and 23 and 6 and some more 3546
hello 123 my 1 name 2 is 3 - output fine since the first number is three-digit and the rest are one digit"

grep -E '(\<[[:digit:]]+\>.*){4,}' <<< "$s"
```
<p>Output:</p>
```123 1 2 3  - works, the first number is two+ digits, the rest are one digits
14 2 3 4 - works
hello 123 my 1 name 2 is 3 - output fine since the first number is three-digit and the rest are one digit
```
<p>If you rewrite it without <code>{4,}</code> it works:</p>
<pre class="lang-sh prettyprint-override"><code>grep -E '\<[0-9]+\>.*\<[0-9]+\>.*\<[0-9]+\>.*\<[0-9]+\>' file
</code>```

See this online demo.

You can use this awk in any environment, too:

awk '{cnt=0; for (i=1; i<=NF; ++i) { if ($i ~ /^[0-9]+$/) { cnt++ } } }cnt>3' file
```
<p>See the online demo. <em>Details</em>:</p>
<ul>
<li><code>cnt=0</code> - set the <code>cnt</code> counter variable to <code>0</code></li>
<li><code>for (i=1; i<=NF; ++i) {...}</code> - iterate over all fields in the current record (=line)</li>
<li><code>if ($i ~ /^[0-9]+$/) { cnt++ } }</code> - if the field is made of digits increment <code>cnt</code></li>
<li><code>cnt>3</code> - if <code>cnt</code> is larger than <code>3</code>, print the found record.</li>
</ul>
<p>See the online demo:</p>
<pre class="lang-sh prettyprint-override"><code>#!/bin/bash
s="123  123  123  123
1 2 3 45
1 3 5
hello 123 my 1 name 2 is 3"

awk '{cnt=0; for (i=1; i<=NF; ++i) { if ($i ~ /^[0-9]+$/) { cnt++ } } }cnt>3' <<< "$s"
</code>```

Output:

123  123  123  123
1 2 3 45
hello 123 my 1 name 2 is 3
```

Body:
It seems there is some problem with quantifying the pattern in your grep command. If the first number has more than one digits, and the others contain just one, your regex works. Else, it won't, see the testing results:

#!/bin/bash
s="123 1 2 3  - works, the first number is two+ digits, the rest are one digits
1 2 3 45 - does not work, the first number is one-digit
14 2 3 4 - works
123 a2 - not output as expected as there is just one number
12 and one 1 more and 23 and 6 and some more 3546
hello 123 my 1 name 2 is 3 - output fine since the first number is three-digit and the rest are one digit"

grep -E '(\<[[:digit:]]+\>.*){4,}' <<< "$s"

Output:

123 1 2 3  - works, the first number is two+ digits, the rest are one digits
14 2 3 4 - works
hello 123 my 1 name 2 is 3 - output fine since the first number is three-digit and the rest are one digit

If you rewrite it without {4,} it works:

grep -E '\<[0-9]+\>.*\<[0-9]+\>.*\<[0-9]+\>.*\<[0-9]+\>' file

See this online demo.

You can use this awk in any environment, too:

awk '{cnt=0; for (i=1; i<=NF; ++i) { if ($i ~ /^[0-9]+$/) { cnt++ } } }cnt>3' file

See the online demo. Details:

cnt=0 - set the cnt counter variable to 0

for (i=1; i<=NF; ++i) {...} - iterate over all fields in the current record (=line)

if ($i ~ /^[0-9]+$/) { cnt++ } } - if the field is made of digits increment cnt

cnt>3 - if cnt is larger than 3, print the found record.

See the online demo:

#!/bin/bash
s="123  123  123  123
1 2 3 45
1 3 5
hello 123 my 1 name 2 is 3"

awk '{cnt=0; for (i=1; i<=NF; ++i) { if ($i ~ /^[0-9]+$/) { cnt++ } } }cnt>3' <<< "$s"

Output:

123  123  123  123
1 2 3 45
hello 123 my 1 name 2 is 3


问:
DecimalFormatter with a custom pattern
I'm creating a custom formatter where I want to avoid using the Locale, so having a groupingSeparator, decimalDelimiter configure the decimalFormatter with the configured values.

But when I want to modify the groupingSeparator and decimalSeparator looks like I have to define a pattern but I don't know how the price would be, I know the max that could be 9.999,99.

I'm able to change the "." and "," dynamically with my settings, but I'm facing some problems when for instance the price is 0,3 if I have the

```<code>maximumFractionDigits = 2
minimumFractionDigits = 2
</code>```

If the price is 0,3 the output should be 0,30, also if the price is 4 the output should be 4,00.

I'm using this as a pattern : #.###,##" but is giving an exception

Malformed pattern "#.###,##"

Having this pattern applyPattern("###,###") most of cases work except the 0,30 that it shows ,30 and is wrong I guess the problem is the pattern...

So the thing is the maximum number to display is :
9.999,99
And the minimum number to display is
0.00

Here's my formatter

```<code>val decimalFormat = NumberFormat.getCurrencyInstance() as DecimalFormat
        return decimalFormat.apply {
            applyPattern("####,##") <-- wondering what to put here
            isGroupingUsed = true <-- because I accept thousand price
            maximumFractionDigits = maxDecimal
            minimumFractionDigits = minDecimal
            decimalFormatSymbols = decimalFormatSymbols.apply {
                groupingSeparator = groupingSep
                decimalSeparator = decimalSep
            }
            negativePrefix = "" <-- To don't show the currency
            positivePrefix = "" <-- To don't show the currency
        }.format(amount)
</code>```

Using this applyPattern("0.#") works for the case of 0, but it doesn't works for cases of thousands even if I add the grouping separator as a "," it won't put it and print the thousand without grouping separator like
expected = 1,234
actual = 1234

答: Use "#,##0.00". The # means a digit should be displayed there except for trailing/leading zeros. The 0 means a digit is always displayed, even if it is a trailing/leading zero. The number of decimal places in the formatted string is equal to the total number of 0s after the dot, so in this example 2.

Title: DecimalFormatter with a custom pattern

Body:
I'm creating a custom formatter where I want to avoid using the Locale, so having a groupingSeparator, decimalDelimiter configure the decimalFormatter with the configured values.

But when I want to modify the groupingSeparator and decimalSeparator looks like I have to define a pattern but I don't know how the price would be, I know the max that could be 9.999,99.

I'm able to change the "." and "," dynamically with my settings, but I'm facing some problems when for instance the price is 0,3 if I have the

maximumFractionDigits = 2
minimumFractionDigits = 2

If the price is 0,3 the output should be 0,30, also if the price is 4 the output should be 4,00.

I'm using this as a pattern : #.###,##" but is giving an exception

Malformed pattern "#.###,##"

Having this pattern applyPattern("###,###") most of cases work except the 0,30 that it shows ,30 and is wrong I guess the problem is the pattern...

So the thing is the maximum number to display is :
9.999,99
And the minimum number to display is
0.00

Here's my formatter

val decimalFormat = NumberFormat.getCurrencyInstance() as DecimalFormat
        return decimalFormat.apply {
            applyPattern("####,##") <-- wondering what to put here
            isGroupingUsed = true <-- because I accept thousand price
            maximumFractionDigits = maxDecimal
            minimumFractionDigits = minDecimal
            decimalFormatSymbols = decimalFormatSymbols.apply {
                groupingSeparator = groupingSep
                decimalSeparator = decimalSep
            }
            negativePrefix = "" <-- To don't show the currency
            positivePrefix = "" <-- To don't show the currency
        }.format(amount)

Using this applyPattern("0.#") works for the case of 0, but it doesn't works for cases of thousands even if I add the grouping separator as a "," it won't put it and print the thousand without grouping separator like
expected = 1,234
actual = 1234


问:
Is there any different between search engine's cached result and live results?
I am asked by a client of mine to search within

Bing's cached results instead of live, current results

using Bing API. I am unable to comprehend this. To me a search engine always searches within the pages that it has cached (indexed) on its servers. Am I missing something?

答: He meant bingj.com which perhaps is used by Microsoft in the similar fashion in which Google shows cached pages.


问:
(Yup) how to create multiple errors using a single .test() function
EDIT: while the accepted solution worked, this worked much better in my use case

I have one function that validates that neither input field A nor input field B are empty
and with the way my form is built I have to write only one function to check both. (The actual function is much more complicated so I opted to create the example function below)

this is my test function:

```<code>function isValid(message) {
    //I don't use the message variable but I added it anyway
    return this.test("isValid", message, function (value) {
    if(!value.A) {
        return createError({path: `${this.path}.A`, message:"A is empty"});
    }
    if(!value.B) {
        return createError({path: `${this.path}.B`, message:"B is empty"});
    }
    return true;
    })
</code>```

The result of this is that when A and B are empty I return the first createError so the rest of the function is skipped and this is what the formik.errors object looks like:

```<code>{
    parent: {
        A: "A is empty"
    }
}
</code>```

How do I create an array of errors and return it instead?

I tried:

returning an array of createErrors() but I got the same result,

using createErrors with an array of paths and messages but the formik.errors looked like this:

```<code>{
    parent.A: { parent.B: "2 errors occured" }
}
</code>```

instead of the desired:

```<code>{
    parent: {
        a: "A is empty",
        b: "B is empty"
    }
}
</code>```

答:
You can use ValidationError from Yup to achieve this goal. The constructor of ValidationError accepts array of other ValidationError instances. The individual ValidationError instances are capable of holding path and error message and the parent instance will combine them.

Here's the example test function:

import { ValidationError } from 'yup'

const testFunc = (value) => {
    const keys = ['A', 'B']

    const errors = keys.map((key) => {
        if (value[key]) { return null } // Successful validation, no error

        return new ValidationError(
          `${key} is empty`,
          value[key],
          key
        )
    }).filter(Boolean)

    if (errors.length === 0) { return true }

    return new ValidationError(errors)
}
```
<p>It is also possible to do the same thing with <code>createError</code> judging by the source code.</p>
<p>You can pass a function instead of a string to <code>message</code> property of <code>createError</code> call. In this case the function would be called within <code>createError</code> => <code>ValidationError.formatError</code> here. And if this function returned an array of the properly built <code>VaildationError</code> instances we would get the same result.</p>
<p>Here's an example test function for that approach:</p>
<pre class="lang-js prettyprint-override"><code>import { ValidationError } from 'yup'

const testFunc = (value, { createError }) => {
    const keys = ['A', 'B']

    const errors = keys.map((key) => {
        if (value[key]) { return null } // Successful validation, no error

        return new ValidationError(
          `${key} is empty`,
          value[key],
          key
        )
    }).filter(Boolean)

    if (errors.length === 0) { return true }

    return createError({
      message: () => errors
    })
}
</code>```

Body:
EDIT: while the accepted solution worked, this worked much better in my use case

I have one function that validates that neither input field A nor input field B are empty
and with the way my form is built I have to write only one function to check both. (The actual function is much more complicated so I opted to create the example function below)

this is my test function:

function isValid(message) {
    //I don't use the message variable but I added it anyway
    return this.test("isValid", message, function (value) {
    if(!value.A) {
        return createError({path: `${this.path}.A`, message:"A is empty"});
    }
    if(!value.B) {
        return createError({path: `${this.path}.B`, message:"B is empty"});
    }
    return true;
    })

The result of this is that when A and B are empty I return the first createError so the rest of the function is skipped and this is what the formik.errors object looks like:

{
    parent: {
        A: "A is empty"
    }
}

How do I create an array of errors and return it instead?

I tried:

returning an array of createErrors() but I got the same result,

using createErrors with an array of paths and messages but the formik.errors looked like this:

{
    parent.A: { parent.B: "2 errors occured" }
}

instead of the desired:

{
    parent: {
        a: "A is empty",
        b: "B is empty"
    }
}

Body:
You can use ValidationError from Yup to achieve this goal. The constructor of ValidationError accepts array of other ValidationError instances. The individual ValidationError instances are capable of holding path and error message and the parent instance will combine them.

Here's the example test function:

import { ValidationError } from 'yup'

const testFunc = (value) => {
    const keys = ['A', 'B']

    const errors = keys.map((key) => {
        if (value[key]) { return null } // Successful validation, no error

        return new ValidationError(
          `${key} is empty`,
          value[key],
          key
        )
    }).filter(Boolean)

    if (errors.length === 0) { return true }

    return new ValidationError(errors)
}

It is also possible to do the same thing with createError judging by the source code.

You can pass a function instead of a string to message property of createError call. In this case the function would be called within createError => ValidationError.formatError here. And if this function returned an array of the properly built VaildationError instances we would get the same result.

Here's an example test function for that approach:

import { ValidationError } from 'yup'

const testFunc = (value, { createError }) => {
    const keys = ['A', 'B']

    const errors = keys.map((key) => {
        if (value[key]) { return null } // Successful validation, no error

        return new ValidationError(
          `${key} is empty`,
          value[key],
          key
        )
    }).filter(Boolean)

    if (errors.length === 0) { return true }

    return createError({
      message: () => errors
    })
}


问:
Fast Algorithm for partial sums on a list
I have been learning Python for 2 months now. In order to hone my programming skills, I solve problems on Codewars from time to time.

Task

Codewars kata:

Write a program that takes a list of numbers as an argument and return a list of partial sums.

My Attempt

I wrote a solution that I tested and it works:

```<code>def parts_sums(ls):
    length=len(ls)+1
    def gen():
        for elt in range(0,length):
            yield sum(ls[elt:])

    result= list(gen())
    return result
</code>```

Codewars is rejecting this solution because it's too slow for lists with thousands of numbers.

I have spent an embarrassingly huge amount of time trying to come up with a faster solution with no avail.

How can the algorithm be designed more performant?

答:
A solution with an explicit loop:

```<code>result= ls + [0]
for i in range(len(result)-1, 0, -1):
  result[i-1]= result[i] + result[i-1]
</code>```

Note that it can also be done in-place in ls.

Body:
I have been learning Python for 2 months now. In order to hone my programming skills, I solve problems on Codewars from time to time.

Task

Codewars kata:

Write a program that takes a list of numbers as an argument and return a list of partial sums.

My Attempt

I wrote a solution that I tested and it works:

def parts_sums(ls):
    length=len(ls)+1
    def gen():
        for elt in range(0,length):
            yield sum(ls[elt:])

    result= list(gen())
    return result

Codewars is rejecting this solution because it's too slow for lists with thousands of numbers.

I have spent an embarrassingly huge amount of time trying to come up with a faster solution with no avail.

How can the algorithm be designed more performant?

Body:
A solution with an explicit loop:

result= ls + [0]
for i in range(len(result)-1, 0, -1):
  result[i-1]= result[i] + result[i-1]

Note that it can also be done in-place in ls.


问:
searching length of sting in arg[]
I'm trying to get string length from char argv array but I don't know how to check this.

I'm writing 3 words to console for example: red blue yellow.
Then I want to write out "yellow" but I don't know how to do that.
I tried to save the words in a file but I don't have backspaces in the file this looks that:
redblueyellow

```<code>#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main(int argc,char* argv[]) {
    string temp;
    fstream save;
    string tab[argc];
    for(int i=1; i<argc; i++) {
        if(argv[i]==' ') {
            tab[argv]=tab[i];
        }
    }
    return 0;
}
</code>```

答:
The line

```<code>string tab[argc];
</code>```

is not valid ISO C++, because the length of the array must be a compile-time constant. Some compilers may support variable-length arrays as an extension, though.

However, it is possible to convert the C-style argv strings to a std::vector of std::string. See this question for further information:

Convert command line argument to string

In your code, the line

```<code>if(argv[i]==' ') {
</code>```

does not make sense, as you are comparing a pointer to a string with a character literal.

If you call your program like this

myprogramname red blue yellow
```
<p>then the following will apply:</p>
<ul>
<li><code>argc</code> will have the value <code>4</code></li>
<li><code>argv[0]</code> will point to a string containing <code>myprogramname</code></li>
<li><code>argv[1]</code> will point to a string containing <code>red</code></li>
<li><code>argv[2]</code> will point to a string containing <code>blue</code></li>
<li><code>argv[3]</code> will point to a string containing <code>yellow</code></li>
<li><code>argv[4]</code> will have the value <code>NULL</code></li>
</ul>
<p>Therefore, if you want to print <code>yellow</code>, you can simply write</p>
```std::cout << argv[3] << '\n';
```
<p>If you want to print the length of the string <code>yellow</code>, you can simply write</p>
```std::cout << std::strlen( argv[3] ) << '\n';
```
<p>Note that you must <code>#include <cstring></code> in order to use <code>std::strlen</code>.</p>
<p>Alternatively, instead of using <code>std::strlen</code>, you can first convert <code>argv[3]</code> to a <code>std::string</code>, before obtaining its length:</p>
```std::string str{ argv[3] };
std::cout << str.length() << '\n';
```

If you want to write to a file, such as to the std::fstream with the name save in your program, then you can replace std::cout with save in the code above. However, you will have to open the file first, before using it. Also, you may want to consider using std::ofstream instead of std::fstream, because you seem to only want to use the file for writing, not reading.

Title: searching length of sting in arg[]

Body:
I'm trying to get string length from char argv array but I don't know how to check this.

I'm writing 3 words to console for example: red blue yellow.
Then I want to write out "yellow" but I don't know how to do that.
I tried to save the words in a file but I don't have backspaces in the file this looks that:
redblueyellow

#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main(int argc,char* argv[]) {
    string temp;
    fstream save;
    string tab[argc];
    for(int i=1; i<argc; i++) {
        if(argv[i]==' ') {
            tab[argv]=tab[i];
        }
    }
    return 0;
}

Body:
The line

string tab[argc];

is not valid ISO C++, because the length of the array must be a compile-time constant. Some compilers may support variable-length arrays as an extension, though.

However, it is possible to convert the C-style argv strings to a std::vector of std::string. See this question for further information:

Convert command line argument to string

In your code, the line

if(argv[i]==' ') {

does not make sense, as you are comparing a pointer to a string with a character literal.

If you call your program like this

myprogramname red blue yellow

then the following will apply:

argc will have the value 4

argv[0] will point to a string containing myprogramname

argv[1] will point to a string containing red

argv[2] will point to a string containing blue

argv[3] will point to a string containing yellow

argv[4] will have the value NULL

Therefore, if you want to print yellow, you can simply write

std::cout << argv[3] << '\n';

If you want to print the length of the string yellow, you can simply write

std::cout << std::strlen( argv[3] ) << '\n';

Note that you must #include <cstring> in order to use std::strlen.

Alternatively, instead of using std::strlen, you can first convert argv[3] to a std::string, before obtaining its length:

std::string str{ argv[3] };
std::cout << str.length() << '\n';

If you want to write to a file, such as to the std::fstream with the name save in your program, then you can replace std::cout with save in the code above. However, you will have to open the file first, before using it. Also, you may want to consider using std::ofstream instead of std::fstream, because you seem to only want to use the file for writing, not reading.


问:
how to display country flags in custom react input phone in react?
recently I implemented a custom react input phone but I can't display country flags in the options and in the selected country.
actually, I cant use the PhoneInput directly because I need to extract the country and send its label to the server (like: 'US').
if do you have any idea for displaying flags in the custom inputs or extracting selected country labels in the default PhoneInput, please answer.

thanks

this is my code lines:

```<code>import Input, {
  getCountries,
  getCountryCallingCode,
} from "react-phone-number-input/input";
import en from "react-phone-number-input/locale/en.json";
import "react-phone-number-input/style.css";

const RegisterForm = () => {
  const [onFocuseInput, setOnFocuseInput] = useState("");
  const [phoneNumber, setPhoneNumber] = useState();
  const [country, setCountry] = useState();

const CountrySelect = ({ value, onChange, labels, ...rest }) => (
    <select
      {...rest}
      value={value}
      onChange={(event) => {
        onChange(event.target.value || undefined);
      }}
    >
      <option value="">country</option>
      {getCountries().map((country) => (
        <option key={country} value={country}>
          {labels[country]} +{getCountryCallingCode(country)}
        </option>
      ))}
    </select>
  );

 <div className="mb-6 flex">
          <CountrySelect
            className={`border-b-2 bg-none outline-none w-1/4 text-xs ${
              onFocuseInput === "country"
                ? "border-blue-700 "
                : "border-gray-300"
            }`}
            labels={en}
            value={country}
            onChange={setCountry}
            name="countrySelect"
            onFocus={() => setOnFocuseInput("country")}
          />
          <Input
            className={`${
              onFocuseInput === "phoneNumber"
                ? "focusedInput w-full"
                : "registerInput w-full"
            }`}
            placeholder="phoneNumber"
            dir="ltr"
            country={country}
            value={phoneNumber}
            onChange={setPhoneNumber}
            name="phoneNumber"
            onFocus={() => setOnFocuseInput("phoneNumber")}
            required
          />
        </div>
        {loading ? (
          <div className="flex justify-center items-center my-5 bg-red-600 p-4 rounded-full">
            <div
              className="spinner-border animate-spin inline-block w-8 h-8 border-4 border-blue-700 border-t-white rounded-full"
              role="status"
            ></div>
          </div>
  );
};

export default RegisterForm;
</code>```

答:
You can parse the value entered in the input field and get out the country code. You can use libphonenumber-js for it.</p>
```<code>import React, { useState } from "react";
import Input, {parsePhoneNumber} from "react-phone-number-input";
import "react-phone-number-input/style.css";

const RegisterForm = () => {
  const [onFocuseInput, setOnFocuseInput] = useState("");
  const [phoneNumber, setPhoneNumber] = useState("");
  const [country, setCountry] = useState("");

  const handleChange = (value) => {
    let p = "";
    let c = "";
    const parsedValue = parsePhoneNumber(value ? value : "", 'US');
    if (parsedValue) {
      p = parsedValue.nationalNumber;
      c = parsedValue.countryCallingCode;
    }
    setPhoneNumber(p);
    setCountry(c);
  };

  return (
    <div>
      <div className="mb-6 flex">
        <Input
          className={`${
            onFocuseInput === "phoneNumber"
              ? "focusedInput w-full"
              : "registerInput w-full"
          }`}
          placeholder="phoneNumber"
          dir="ltr"
          defaultCountry="US"
          limitMaxLength
          onChange={handleChange}
          name="phoneNumber"
          onFocus={() => setOnFocuseInput("phoneNumber")}
          required
        />
      </div>
    </div>
  );
};

export default RegisterForm;
</code>```

Body:
recently I implemented a custom react input phone but I can't display country flags in the options and in the selected country.
actually, I cant use the PhoneInput directly because I need to extract the country and send its label to the server (like: 'US').
if do you have any idea for displaying flags in the custom inputs or extracting selected country labels in the default PhoneInput, please answer.

thanks

this is my code lines:

import Input, {
  getCountries,
  getCountryCallingCode,
} from "react-phone-number-input/input";
import en from "react-phone-number-input/locale/en.json";
import "react-phone-number-input/style.css";

const RegisterForm = () => {
  const [onFocuseInput, setOnFocuseInput] = useState("");
  const [phoneNumber, setPhoneNumber] = useState();
  const [country, setCountry] = useState();

const CountrySelect = ({ value, onChange, labels, ...rest }) => (
    <select
      {...rest}
      value={value}
      onChange={(event) => {
        onChange(event.target.value || undefined);
      }}
    >
      <option value="">country</option>
      {getCountries().map((country) => (
        <option key={country} value={country}>
          {labels[country]} +{getCountryCallingCode(country)}
        </option>
      ))}
    </select>
  );

          <CountrySelect
            className={`border-b-2 bg-none outline-none w-1/4 text-xs ${
              onFocuseInput === "country"
                ? "border-blue-700 "
                : "border-gray-300"
            }`}
            labels={en}
            value={country}
            onChange={setCountry}
            name="countrySelect"
            onFocus={() => setOnFocuseInput("country")}
          />
          <Input
            className={`${
              onFocuseInput === "phoneNumber"
                ? "focusedInput w-full"
                : "registerInput w-full"
            }`}
            placeholder="phoneNumber"
            dir="ltr"
            country={country}
            value={phoneNumber}
            onChange={setPhoneNumber}
            name="phoneNumber"
            onFocus={() => setOnFocuseInput("phoneNumber")}
            required
          />

        {loading ? (

  );
};

export default RegisterForm;

Body:
You can parse the value entered in the input field and get out the country code. You can use libphonenumber-js for it.

import React, { useState } from "react";
import Input, {parsePhoneNumber} from "react-phone-number-input";
import "react-phone-number-input/style.css";

const RegisterForm = () => {
  const [onFocuseInput, setOnFocuseInput] = useState("");
  const [phoneNumber, setPhoneNumber] = useState("");
  const [country, setCountry] = useState("");

  const handleChange = (value) => {
    let p = "";
    let c = "";
    const parsedValue = parsePhoneNumber(value ? value : "", 'US');
    if (parsedValue) {
      p = parsedValue.nationalNumber;
      c = parsedValue.countryCallingCode;
    }
    setPhoneNumber(p);
    setCountry(c);
  };

  return (
    <div>
      <div className="mb-6 flex">
        <Input
          className={`${
            onFocuseInput === "phoneNumber"
              ? "focusedInput w-full"
              : "registerInput w-full"
          }`}
          placeholder="phoneNumber"
          dir="ltr"
          defaultCountry="US"
          limitMaxLength
          onChange={handleChange}
          name="phoneNumber"
          onFocus={() => setOnFocuseInput("phoneNumber")}
          required
        />
      </div>
    </div>
  );
};

export default RegisterForm;


问:
Use Import Maps and Stimulus with Rails 6
I'm currently on Rails 6.0.4 and I want to use Stimulus to build a new page. There's a lot of work still to do before upgrading to Rails 7, so I want to use importmaps and stimulus with Rails 6 if possible. But so far I haven't been able to get a stimulus controller working. I followed these steps:

1. Update the Gemfile and bundle:

```<code>gem 'importmap-rails'
gem 'stimulus-rails'
</code>```

2. Run rails importmap:install

This gave me config/importmap.rb, and app/javascript/application.js, which was pinned as "application" in the config file.

3. Rename the current application.js file

My current application.js is inside app/assets/application.js.coffee, so I renamed this to old_application.js.coffee for the time being and updated application.html.haml to the following:

```<code>= javascript_include_tag "old_application", defer: true
= javascript_importmap_tags
</code>```

This seemed to work and it gave me the following import map when I rendered the page:

```<code>{
  "imports": {
    "application": "/assets/application-920fceca960b509c1e98c9b27d167fa368d4b588ceb1be42d1667552714f94d5.js"
  }
}
</code>```

4.Run rails stimulus:install

This gave me the app/javascript/controllers folder with index.js, application.js and hello_controller.js inside.

It also updated config/importmap.rb to the following:

```<code>pin "application", preload: true
pin "@hotwired/stimulus", to: "stimulus.min.js", preload: true
pin "@hotwired/stimulus-loading", to: "stimulus-loading.js", preload: true
pin_all_from "app/javascript/controllers", under: "controllers"
</code>```

... and my app/javascript/application.js to the following:

```<code>import "controllers"
</code>```

This then gives me an error, saying that controllers/hello_controller.js has not been precompiled:

5. Update asset paths and precompiled files

We're on version 3 of sprockets, and upgrading to version 4 will also take some time, due to this issue. So instead I updated the existing initializers/assets.rb file to include the new javascript folder and files:

```<code>Rails.application.config.assets.paths << Rails.root.join('app', 'javascript', 'controllers')
Rails.application.config.assets.precompile += ['application.js', 'controllers/index.js', 'controllers/application.js', 'controllers/hello_controller.js']
</code>```

This fixed the issue and gives me the following import map on the rendered page:

```<code>{
  "imports": {
    "application": "/assets/application-920fceca960b509c1e98c9b27d167fa368d4b588ceb1be42d1667552714f94d5.js",
    "@hotwired/stimulus": "/assets/stimulus.min-c5a29ae8ade968ede2149a7e76a29d0756a87cef66959113681098e5923ba26b.js",
    "@hotwired/stimulus-loading": "/assets/stimulus-loading-6b29b7e0382bd421ac62df99b46f45072fd3962208fbf0b2522041b4d037bbd9.js",
    "controllers/hello_controller": "/assets/hello_controller-8cddac086717993eeda2cc8af3be73bc3a6ecfb07212600aeed8ce8122fffa34.js",
    "controllers": "/assets/index-7445df4dc00776a5e3496034da4bc5906891c342c89c0e6a7775b1498b8222d8.js",
    "controllers/application": "/assets/application-5703baa647baaa5a3da21d4e61aa5686824d0e0ab82c2ba11f5c963cc8414a8f.js"
  }
}
</code>```

6. Test stimulus controller with an alert

I changed hello_controller.js to show an alert when it's connected:

```<code>import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  connect() {
    alert('Hello World!')
  }
}

</code>```

But when I attach this to an element with data-controller="hello" I don't see anything, suggesting that stimulus hasn't been correctly loaded.

This is the partial for that:

```<code>.home-container{data: { controller: 'hello' }}
  %section
    .container
</code>```

Which gives me this HTML:

```<code><div class="home-container" data-controller="hello">
  <section>
    <div class="container">
    </div>
  </section>
<div>
</code>```

Can anyone suggest what I might be missing? If I start a new rails app on Rails 7 and set everything up like that, it works without a problem.

答: I was experiencing the same issue. Running rails assets:clean and rails assets:clobber solved the issue for me. Sorry, I do not remember which one did the trick, as I was applying the clueless dog approach.

Body:
I'm currently on Rails 6.0.4 and I want to use Stimulus to build a new page. There's a lot of work still to do before upgrading to Rails 7, so I want to use importmaps and stimulus with Rails 6 if possible. But so far I haven't been able to get a stimulus controller working. I followed these steps:

1. Update the Gemfile and bundle:

gem 'importmap-rails'
gem 'stimulus-rails'

2. Run rails importmap:install

This gave me config/importmap.rb, and app/javascript/application.js, which was pinned as "application" in the config file.

3. Rename the current application.js file

My current application.js is inside app/assets/application.js.coffee, so I renamed this to old_application.js.coffee for the time being and updated application.html.haml to the following:

= javascript_include_tag "old_application", defer: true
= javascript_importmap_tags

This seemed to work and it gave me the following import map when I rendered the page:

{
  "imports": {
    "application": "/assets/application-920fceca960b509c1e98c9b27d167fa368d4b588ceb1be42d1667552714f94d5.js"
  }
}

4.Run rails stimulus:install

This gave me the app/javascript/controllers folder with index.js, application.js and hello_controller.js inside.

It also updated config/importmap.rb to the following:

pin "application", preload: true
pin "@hotwired/stimulus", to: "stimulus.min.js", preload: true
pin "@hotwired/stimulus-loading", to: "stimulus-loading.js", preload: true
pin_all_from "app/javascript/controllers", under: "controllers"

... and my app/javascript/application.js to the following:

import "controllers"

This then gives me an error, saying that controllers/hello_controller.js has not been precompiled:

5. Update asset paths and precompiled files

We're on version 3 of sprockets, and upgrading to version 4 will also take some time, due to this issue. So instead I updated the existing initializers/assets.rb file to include the new javascript folder and files:

Rails.application.config.assets.paths << Rails.root.join('app', 'javascript', 'controllers')
Rails.application.config.assets.precompile += ['application.js', 'controllers/index.js', 'controllers/application.js', 'controllers/hello_controller.js']

This fixed the issue and gives me the following import map on the rendered page:

{
  "imports": {
    "application": "/assets/application-920fceca960b509c1e98c9b27d167fa368d4b588ceb1be42d1667552714f94d5.js",
    "@hotwired/stimulus": "/assets/stimulus.min-c5a29ae8ade968ede2149a7e76a29d0756a87cef66959113681098e5923ba26b.js",
    "@hotwired/stimulus-loading": "/assets/stimulus-loading-6b29b7e0382bd421ac62df99b46f45072fd3962208fbf0b2522041b4d037bbd9.js",
    "controllers/hello_controller": "/assets/hello_controller-8cddac086717993eeda2cc8af3be73bc3a6ecfb07212600aeed8ce8122fffa34.js",
    "controllers": "/assets/index-7445df4dc00776a5e3496034da4bc5906891c342c89c0e6a7775b1498b8222d8.js",
    "controllers/application": "/assets/application-5703baa647baaa5a3da21d4e61aa5686824d0e0ab82c2ba11f5c963cc8414a8f.js"
  }
}

6. Test stimulus controller with an alert

I changed hello_controller.js to show an alert when it's connected:

import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  connect() {
    alert('Hello World!')
  }
}

But when I attach this to an element with data-controller="hello" I don't see anything, suggesting that stimulus hasn't been correctly loaded.

This is the partial for that:

.home-container{data: { controller: 'hello' }}
  %section
    .container

Which gives me this HTML:

Can anyone suggest what I might be missing? If I start a new rails app on Rails 7 and set everything up like that, it works without a problem.


问:
error: 'operator[]' is not defined
I'm having a problem compiling with g++ a fragment of my library that is related with the operator[].

I have recreated the same problem with this code:

```<code>    template<class A,class B> class X {
    public:
        template<class C> X<C,B>& operator[]( const C& );
    };

    template<class A,class B,class C> class Y : public X<C,B> {
        friend X<C,B>& X<A,B>::template operator[]<C>( const C& );
    private:
        Y( X<A,B>& object , const C& index ) : X<C,B>() {};
    };

    template<class A,class B> template<class C> X<C,B>& X<A,B>::operator[]( const C& index ) {
        return *( new Y<A,B,C>( *this , index ) );
    }

    int main() {
        X<int,void> x;
        X<int,void>& y = x[2];
    }
</code>```

g++ exits with the following error:

```<code>./src/test.cpp: In instantiation of ‘Y<int, void, int>’:
./src/test.cpp:14:   instantiated from ‘X<C, B>& X<A, B>::operator[](const C&) [with C = int, A = int, B = void]’
./src/test.cpp:19:   instantiated from here
./src/test.cpp:8: error: ‘operator[]’ not defined
./src/test.cpp: In member function ‘X<C, B>& X<A, B>::operator[](const C&) [with C = int, A = int, B = void]’:
./src/test.cpp:19:   instantiated from here
./src/test.cpp:10: error: ‘Y<A, B, C>::Y(X<A, B>&, const C&) [with A = int, B = void, C = int]’ is private
./src/test.cpp:14: error: within this context
</code>```

I think that the problem is in the friend declaration of 'operator[]' in class Y, but I don't know where it is wrong. I tried searching myself, but can't find anything useful.
Can anyone help me?

Thanks, Gianni

答:
Since you did not tell what your real design goal is, it is a bit difficult to propose something good, but at least using

```<code>template<class CC> friend X<CC,B>& X<A,B>::operator[]( const CC& );
</code>```

as the friend declaration will make it compile, since that tells it to be a template.

Edit:

On a second thought, I think your code should work too, as it does not specify a specialization. Have you tried using clang to test it? It seems like a bug in gcc there...

Title: error: 'operator[]' is not defined

Body:
I'm having a problem compiling with g++ a fragment of my library that is related with the operator[].

I have recreated the same problem with this code:

    template<class A,class B> class X {
    public:
        template<class C> X<C,B>& operator[]( const C& );
    };

    template<class A,class B,class C> class Y : public X<C,B> {
        friend X<C,B>& X::template operator[]<C>( const C& );
    private:
        Y( X& object , const C& index ) : X<C,B>() {};
    };

    template<class A,class B> template<class C> X<C,B>& X::operator[]( const C& index ) {
        return *( new Y( *this , index ) );
    }

    int main() {
        X<int,void> x;
        X<int,void>& y = x[2];
    }

g++ exits with the following error:

./src/test.cpp: In instantiation of ‘Y<int, void, int>’:
./src/test.cpp:14:   instantiated from ‘X<C, B>& X::operator[](const C&) [with C = int, A = int, B = void]’
./src/test.cpp:19:   instantiated from here
./src/test.cpp:8: error: ‘operator[]’ not defined
./src/test.cpp: In member function ‘X<C, B>& X::operator[](const C&) [with C = int, A = int, B = void]’:
./src/test.cpp:19:   instantiated from here
./src/test.cpp:10: error: ‘Y::Y(X&, const C&) [with A = int, B = void, C = int]’ is private
./src/test.cpp:14: error: within this context

I think that the problem is in the friend declaration of 'operator[]' in class Y, but I don't know where it is wrong. I tried searching myself, but can't find anything useful.
Can anyone help me?

Thanks, Gianni

Body:
Since you did not tell what your real design goal is, it is a bit difficult to propose something good, but at least using

template<class CC> friend X<CC,B>& X<A,B>::operator[]( const CC& );

as the friend declaration will make it compile, since that tells it to be a template.

Edit:

On a second thought, I think your code should work too, as it does not specify a specialization. Have you tried using clang to test it? It seems like a bug in gcc there...


问:
Django channels Disconect after closing the tab
I'm new to Django channels and I'm building a simple chatroom. With this chatroom, I want to disconnect a user if he closes the browser tab and if he reopens the tab with the same link, I want to reconnect him to the same chat that he was. How can I do that?</p>

答:
in order to reconnect to the same WebSocket, you just connect again to the same URL. From the client (browser) side you can use the example JavaScript code:

```<code>webSocket = new WebSocket('ws:/localhost:8000/ws/chat/');
</code>```

The server side (the "backend", i.e., Django Channels) closes the connection when there are no clients connected.

What you probably mean is that you would like to have access to the chat history, yes? As I understand the WebSocket it is a communication protocol (in some sense similar to the HTTP). So it is used just to send the messages, not to store them. You should store the messages somewhere anyway, e.g., in the database. Then, on the "reconnect" you in fact get the messages from the database via views, or, in a different fashion, with the consumers.

Hope that helps. You would have to specify a concrete scenario for me to help you further.

Body:
in order to reconnect to the same WebSocket, you just connect again to the same URL. From the client (browser) side you can use the example JavaScript code:

webSocket = new WebSocket('ws:/localhost:8000/ws/chat/');

The server side (the "backend", i.e., Django Channels) closes the connection when there are no clients connected.

What you probably mean is that you would like to have access to the chat history, yes? As I understand the WebSocket it is a communication protocol (in some sense similar to the HTTP). So it is used just to send the messages, not to store them. You should store the messages somewhere anyway, e.g., in the database. Then, on the "reconnect" you in fact get the messages from the database via views, or, in a different fashion, with the consumers.

Hope that helps. You would have to specify a concrete scenario for me to help you further.


问:
Centering CSS grid divs with iFrame and Img
So I want to create a grid on my site that has 2 i frames at the top and 2 imgs below e.g

```<code>X X
X X
</code>```

I have managed to get some code working, but it doesn't look quite right, right now the grid is stuck to the left-hand side of the page and in mobile view it just goes off the screen and doesn't fit to a mobile version, another issue is there is a random gap between each column. E.g below.

iframe {
  border: 1px solid;
}

.plotly-charts {
  justify-content: center;
  display: grid;
  grid-template-columns: 1fr 1fr;
  padding: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="plotly-charts">
  <div class="charts">
    <iframe width="600px" height="500px" frameborder="0" scrolling="no" src="someframe"></iframe>
  </div>
  <div class="charts">
    <iframe width="600px" height="500px" frameborder="0" scrolling="no" src="someframe"></iframe>
  </div>
  <div class="charts">
    <img src="https://dummyimage.com/300x300/525eff/ffffff" alt="Word Cloud Positive" style="width:300px; height:300px;">
  </div>
  <div class="charts">
    <img src="https://dummyimage.com/300x300/525eff/ffffff" alt="Word Cloud Negative-Neutral" style="width:300px; height:300px;">
  </div>
</div></code>```

答:
Remove width/height attributes from iframe, make it flexible with CSS, also remove inline styles from you images and make it responsive.
Also, make .charts flex. In this case you can align this cells' content.

See CSS Code snippet part comments for more details.

Expand Code snippet to fullpage, to see example

.plotly-charts {
  display: grid;
  grid-template-columns: 1fr 1fr;
  /* add grid gaps (gaps between rows and columns) */
  column-gap: 1rem;
  row-gap: 1rem;
}

/* make cell flex */
.charts {
  display: flex;
  justify-content: center;
}

.charts iframe {
  width: 100%;
  /* you can add ratios to your iframe in other way */
  aspect-ratio: 6/5;
}

/* add styles to you images, make it responsive */
.charts img {
  height: auto;
  width: 100%;
}

/* added for example purposes */
.charts iframe, .charts img {
  max-width: 600px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="plotly-charts">
  <div class="charts">
    <iframe frameborder="0" scrolling="no" src="//plotly.com/~mathewsjoyy/3.embed?logo=false&link=false&autosize=true"></iframe>
  </div>
  <div class="charts">
    <iframe frameborder="0" scrolling="no" src="//plotly.com/~mathewsjoyy/1.embed?logo=false&link=false&autosize=true"></iframe>
  </div>
  <div class="charts">
    <img src="https://dummyimage.com/600x400/000/fff" alt="Word Cloud Positive">
  </div>
  <div class="charts">
    <img src="https://dummyimage.com/600x400/000/fff" alt="Word Cloud Negative-Neutral">
  </div>
</div></code>```

Body:
So I want to create a grid on my site that has 2 i frames at the top and 2 imgs below e.g

X X
X X

I have managed to get some code working, but it doesn't look quite right, right now the grid is stuck to the left-hand side of the page and in mobile view it just goes off the screen and doesn't fit to a mobile version, another issue is there is a random gap between each column. E.g below.

iframe {
  border: 1px solid;
}

.plotly-charts {
  justify-content: center;
  display: grid;
  grid-template-columns: 1fr 1fr;
  padding: 5px;
}

Body:
Remove width/height attributes from iframe, make it flexible with CSS, also remove inline styles from you images and make it responsive.
Also, make .charts flex. In this case you can align this cells' content.

See CSS Code snippet part comments for more details.

Expand Code snippet to fullpage, to see example

.plotly-charts {
  display: grid;
  grid-template-columns: 1fr 1fr;
  /* add grid gaps (gaps between rows and columns) */
  column-gap: 1rem;
  row-gap: 1rem;
}

/* make cell flex */
.charts {
  display: flex;
  justify-content: center;
}

.charts iframe {
  width: 100%;
  /* you can add ratios to your iframe in other way */
  aspect-ratio: 6/5;
}

/* add styles to you images, make it responsive */
.charts img {
  height: auto;
  width: 100%;
}

/* added for example purposes */
.charts iframe, .charts img {
  max-width: 600px;
}

<div class="plotly-charts">
  <div class="charts">
    <iframe frameborder="0" scrolling="no" src="//plotly.com/~mathewsjoyy/3.embed?logo=false&link=false&autosize=true"></iframe>
  </div>
  <div class="charts">
    <iframe frameborder="0" scrolling="no" src="//plotly.com/~mathewsjoyy/1.embed?logo=false&link=false&autosize=true"></iframe>
  </div>
  <div class="charts">
    <img src="https://dummyimage.com/600x400/000/fff" alt="Word Cloud Positive">
  </div>
  <div class="charts">
    <img src="https://dummyimage.com/600x400/000/fff" alt="Word Cloud Negative-Neutral">
  </div>
</div>


问:
Why removing create-react-app files and folders take a long while?
When I want to remove create-react-app files and folders take a long while?
It is not using much of space, like 250MB.
Also I have to say my computer removes quickly another files and folders with size of bigger than create-react-app.

I use shift + Delete.

答: React (and thus create-react-app) has a lot of little dependencies. Each with a lot of files. So, even though there isn't much space being used, it's lots of individual small files that all need to be removed. You can 'observe' this in pretty much any project using NPM/Yarn.</p>