问:
TicTacToe and Minimax
I am a young programmer that is learning python and struggling to implement an AI (using minimax) to play TicTacToe. I started watching a tutorial online, but the tutorial was on JavaScript and thus couldn't solve my problem. I also had a look at this question ( Python minimax for tictactoe ), but it did not have any answers and the implementation was considerably different from mine.

EDIT: the code you will find below is an edit suggested by one of the answers (@water_ghosts).

EDIT #2: I deleted possiblePositions, as the AI should choose a free field and not a place from the possiblePositions (that wouldn't make it that smart while implementing minimax :) )

Now the code doesn't give out any errors at all and functions properly, but one small thing: the AI always chooses the next available field. For example in situations where i am i move away from winning, instead of blocking my win option, it chooses the next free spot.

If you're wondering what that elements dict is doing there: i just wanted to make sure the programm chose the best index...

Here is my code:

```<code>class TicTacToe:
    def __init__(self):

        self.board = [" ", " ", " ", " ", " ", " ", " ", " ", " "]

        self.playerSymbol = ""
        self.playerPosition = []

        self.aiSymbol = ""
        self.aiPosition = []

        self.score = 0

        self.winner = None

        self.scoreBoard = {
            self.playerSymbol: -1,
            self.aiSymbol: 1,
            "tie": 0
        }

        self.turn = 0

        self.optimalMove = int()

    def drawBoard(self):
        print(self.board[0] + " | " + self.board[1] + " | " + self.board[2])
        print("___" + "___" + "___")
        print(self.board[3] + " | " + self.board[4] + " | " + self.board[5])
        print("___" + "___" + "___")
        print(self.board[6] + " | " + self.board[7] + " | " + self.board[8])

    def choice(self):

        answer = input("What do you want to play as? (type x or o) ")

        if answer.upper() == "X":
            self.playerSymbol = "X"
            self.aiSymbol = "O"
        else:
            self.playerSymbol = "O"
            self.aiSymbol = "X"

    def won(self):

        winningPositions = [{0, 1, 2}, {3, 4, 5}, {6, 7, 8}, {0, 4, 8}, {2, 4, 6}, {0, 3, 6}, {1, 4, 7}, {2, 5, 8}]

        for position in winningPositions:
            if position.issubset(self.playerPosition):
                self.winner = self.playerSymbol
                print("Player Wins :)")
                return True
            elif position.issubset(self.aiPosition):
                self.winner = self.aiSymbol
                print("AI wins :(")
                return True
        if self.board.count(" ") == 0:
            self.winner = "tie"
            print("Guess it's a draw")
            return True

        return False

    def findOptimalPosition(self):

        bestScore = float("-Infinity")
        elements = {}  # desperate times call for desperate measures

        for i in range(9):
            if self.board[i] == " ":
                self.board[i] = self.aiSymbol  # AI quasi made the move here
                if self.minimax(True) > bestScore:
                    bestScore = self.score
                    elements[i] = bestScore
                self.board[i] = " "
        return max(elements, key=lambda k: elements[k])

    def minimax(self, isMaximizing):

        if self.winner is not None:
            return self.scoreBoard[self.winner]

        if isMaximizing:
            bestScore = float("-Infinity")
            for i in range(9):
                if self.board[i] == " ":
                    self.board[i] = self.aiSymbol
                    bestScore = max(self.minimax(False), bestScore)
                    self.board[i] = " "
            return bestScore
        else:
            bestScore = float("Infinity")
            for i in range(9):
                if self.board[i] == " ":
                    self.board[i] = self.playerSymbol
                    bestScore = min(self.minimax(True), bestScore)
                    self.board[i] = " "
            return bestScore

    def play(self):

        self.choice()

        while not self.won():
            if self.turn % 2 == 0:
                pos = int(input("Where would you like to play? (0-8) "))
                self.playerPosition.append(pos)
                self.board[pos] = self.playerSymbol
                self.turn += 1
                self.drawBoard()
            else:
                aiTurn = self.findOptimalPosition()
                self.aiPosition.append(aiTurn)
                self.board[aiTurn] = self.aiSymbol
                self.turn += 1
                print("\n")
                print("\n")
                self.drawBoard()
        else:
            print("Thanks for playing :)")

tictactoe = TicTacToe()
tictactoe.play()

</code>```

I come from a java background and am not used to this :(
Any help would be highly appreciated

I am open to suggestions and ways to improve my code and fix this problem.
Thanks in advance and stay healthy,
Kristi

答:
I am posting this as an answer, just in case somebody in the future stumbles upon the same problem :)

the main issue i encountered (besides my bad programming style) is that i forgot to update the contents the lists playerPosition and aiPosition.
You can review the rest of the changes in the working code:

```<code>class TicTacToe:
    def __init__(self):

        self.board = [" ", " ", " ", " ", " ", " ", " ", " ", " "]

        self.playerSymbol = ""
        self.playerPosition = []

        self.aiSymbol = ""
        self.aiPosition = []

        self.winner = None

        self.scoreBoard = None

        self.turn = 0

        self.optimalMove = int()

    def drawBoard(self):
        print(self.board[0] + " | " + self.board[1] + " | " + self.board[2])
        print("___" + "___" + "___")
        print(self.board[3] + " | " + self.board[4] + " | " + self.board[5])
        print("___" + "___" + "___")
        print(self.board[6] + " | " + self.board[7] + " | " + self.board[8])

    def choice(self):

        answer = input("What do you want to play as? (type x or o) ")

        if answer.upper() == "X":
            self.playerSymbol = "X"
            self.aiSymbol = "O"
        else:
            self.playerSymbol = "O"
            self.aiSymbol = "X"

        self.scoreBoard = {
            self.playerSymbol: -1,
            self.aiSymbol: 1,
            "tie": 0
        }

    def availableMoves(self):

        moves = []
        for i in range(0, len(self.board)):
            if self.board[i] == " ":
                moves.append(i)
        return moves

    def won_print(self):
        self.won()
        if self.winner == self.aiSymbol:
            print("AI wins :(")
            exit(0)
        elif self.winner == self.playerSymbol:
            print("Player Wins :)")
            exit(0)
        elif self.winner == "tie":
            print("Guess it's a draw")
            exit(0)

    def won(self):

        winningPositions = [{0, 1, 2}, {3, 4, 5}, {6, 7, 8},
                            {0, 4, 8}, {2, 4, 6}, {0, 3, 6},
                            {1, 4, 7}, {2, 5, 8}]

        for position in winningPositions:
            if position.issubset(self.playerPosition):
                self.winner = self.playerSymbol
                return True
            elif position.issubset(self.aiPosition):
                self.winner = self.aiSymbol
                return True
        if self.board.count(" ") == 0:
            self.winner = "tie"
            return True

        self.winner = None
        return False

    def set_i_ai(self, i):
        self.aiPosition.append(i)
        self.board[i] = self.aiSymbol

    def set_clear_for_ai(self, i):
        self.aiPosition.remove(i)
        self.board[i] = " "

    def set_i_player(self, i):
        self.playerPosition.append(i)
        self.board[i] = self.playerSymbol

    def set_clear_for_player(self, i):
        self.playerPosition.remove(i)
        self.board[i] = " "

    def findOptimalPosition(self):

        bestScore = float("-Infinity")
        elements = {}  # desperate times call for desperate measures

        for i in self.availableMoves():
            self.set_i_ai(i)
            score = self.minimax(False)
            if score > bestScore:
                bestScore = score
                elements[i] = bestScore
            self.set_clear_for_ai(i)
        if bestScore == 1:
            print("you messed up larry")
        elif bestScore == 0:
            print("hm")
        else:
            print("whoops i made a prog. error")
        return max(elements, key=lambda k: elements[k])

    def minimax(self, isMaximizing):

        if self.won():
            return self.scoreBoard[self.winner]

        if isMaximizing:
            bestScore = float("-Infinity")
            for i in self.availableMoves():
                self.set_i_ai(i)
                bestScore = max(self.minimax(False), bestScore)
                self.set_clear_for_ai(i)
            return bestScore
        else:
            bestScore = float("Infinity")
            for i in self.availableMoves():
                self.set_i_player(i)
                bestScore = min(self.minimax(True), bestScore)
                self.set_clear_for_player(i)
            return bestScore

    def play(self):

        self.choice()

        while not self.won_print():
            if self.turn % 2 == 0:
                pos = int(input("Where would you like to play? (0-8) "))
                self.playerPosition.append(pos)
                self.board[pos] = self.playerSymbol
                self.turn += 1
                self.drawBoard()
            else:
                aiTurn = self.findOptimalPosition()
                self.aiPosition.append(aiTurn)
                self.board[aiTurn] = self.aiSymbol
                self.turn += 1
                print("\n")
                print("\n")
                self.drawBoard()
        else:
            print("Thanks for playing :)")

if __name__ == '__main__':
    tictactoe = TicTacToe()
    tictactoe.play()

</code>```

But as mentioned, the code may work, but there are MANY problems regarding the logic and structure, so do not straight-forward copy-paste it :))

Title: TicTacToe and Minimax

Body:
I am a young programmer that is learning python and struggling to implement an AI (using minimax) to play TicTacToe. I started watching a tutorial online, but the tutorial was on JavaScript and thus couldn't solve my problem. I also had a look at this question ( Python minimax for tictactoe ), but it did not have any answers and the implementation was considerably different from mine.

EDIT: the code you will find below is an edit suggested by one of the answers (@water_ghosts).

EDIT #2: I deleted possiblePositions, as the AI should choose a free field and not a place from the possiblePositions (that wouldn't make it that smart while implementing minimax :) )

Now the code doesn't give out any errors at all and functions properly, but one small thing: the AI always chooses the next available field. For example in situations where i am i move away from winning, instead of blocking my win option, it chooses the next free spot.

If you're wondering what that elements dict is doing there: i just wanted to make sure the programm chose the best index...

Here is my code:

class TicTacToe:
    def __init__(self):

        self.board = [" ", " ", " ", " ", " ", " ", " ", " ", " "]

        self.playerSymbol = ""
        self.playerPosition = []

        self.aiSymbol = ""
        self.aiPosition = []

        self.score = 0

        self.winner = None

        self.scoreBoard = {
            self.playerSymbol: -1,
            self.aiSymbol: 1,
            "tie": 0
        }

        self.turn = 0

        self.optimalMove = int()

    def drawBoard(self):
        print(self.board[0] + " | " + self.board[1] + " | " + self.board[2])
        print("___" + "___" + "___")
        print(self.board[3] + " | " + self.board[4] + " | " + self.board[5])
        print("___" + "___" + "___")
        print(self.board[6] + " | " + self.board[7] + " | " + self.board[8])

    def choice(self):

        answer = input("What do you want to play as? (type x or o) ")

        if answer.upper() == "X":
            self.playerSymbol = "X"
            self.aiSymbol = "O"
        else:
            self.playerSymbol = "O"
            self.aiSymbol = "X"

    def won(self):

        winningPositions = [{0, 1, 2}, {3, 4, 5}, {6, 7, 8}, {0, 4, 8}, {2, 4, 6}, {0, 3, 6}, {1, 4, 7}, {2, 5, 8}]

        for position in winningPositions:
            if position.issubset(self.playerPosition):
                self.winner = self.playerSymbol
                print("Player Wins :)")
                return True
            elif position.issubset(self.aiPosition):
                self.winner = self.aiSymbol
                print("AI wins :(")
                return True
        if self.board.count(" ") == 0:
            self.winner = "tie"
            print("Guess it's a draw")
            return True

        return False

    def findOptimalPosition(self):

        bestScore = float("-Infinity")
        elements = {}  # desperate times call for desperate measures

        for i in range(9):
            if self.board[i] == " ":
                self.board[i] = self.aiSymbol  # AI quasi made the move here
                if self.minimax(True) > bestScore:
                    bestScore = self.score
                    elements[i] = bestScore
                self.board[i] = " "
        return max(elements, key=lambda k: elements[k])

    def minimax(self, isMaximizing):

        if self.winner is not None:
            return self.scoreBoard[self.winner]

        if isMaximizing:
            bestScore = float("-Infinity")
            for i in range(9):
                if self.board[i] == " ":
                    self.board[i] = self.aiSymbol
                    bestScore = max(self.minimax(False), bestScore)
                    self.board[i] = " "
            return bestScore
        else:
            bestScore = float("Infinity")
            for i in range(9):
                if self.board[i] == " ":
                    self.board[i] = self.playerSymbol
                    bestScore = min(self.minimax(True), bestScore)
                    self.board[i] = " "
            return bestScore

    def play(self):

        self.choice()

        while not self.won():
            if self.turn % 2 == 0:
                pos = int(input("Where would you like to play? (0-8) "))
                self.playerPosition.append(pos)
                self.board[pos] = self.playerSymbol
                self.turn += 1
                self.drawBoard()
            else:
                aiTurn = self.findOptimalPosition()
                self.aiPosition.append(aiTurn)
                self.board[aiTurn] = self.aiSymbol
                self.turn += 1
                print("\n")
                print("\n")
                self.drawBoard()
        else:
            print("Thanks for playing :)")

tictactoe = TicTacToe()
tictactoe.play()

I come from a java background and am not used to this :(
Any help would be highly appreciated

I am open to suggestions and ways to improve my code and fix this problem.
Thanks in advance and stay healthy,
Kristi

Body:
I am posting this as an answer, just in case somebody in the future stumbles upon the same problem :)

the main issue i encountered (besides my bad programming style) is that i forgot to update the contents the lists playerPosition and aiPosition.
You can review the rest of the changes in the working code:

class TicTacToe:
    def __init__(self):

        self.board = [" ", " ", " ", " ", " ", " ", " ", " ", " "]

        self.playerSymbol = ""
        self.playerPosition = []

        self.aiSymbol = ""
        self.aiPosition = []

        self.winner = None

        self.scoreBoard = None

        self.turn = 0

        self.optimalMove = int()

    def drawBoard(self):
        print(self.board[0] + " | " + self.board[1] + " | " + self.board[2])
        print("___" + "___" + "___")
        print(self.board[3] + " | " + self.board[4] + " | " + self.board[5])
        print("___" + "___" + "___")
        print(self.board[6] + " | " + self.board[7] + " | " + self.board[8])

    def choice(self):

        answer = input("What do you want to play as? (type x or o) ")

        if answer.upper() == "X":
            self.playerSymbol = "X"
            self.aiSymbol = "O"
        else:
            self.playerSymbol = "O"
            self.aiSymbol = "X"

        self.scoreBoard = {
            self.playerSymbol: -1,
            self.aiSymbol: 1,
            "tie": 0
        }

    def availableMoves(self):

        moves = []
        for i in range(0, len(self.board)):
            if self.board[i] == " ":
                moves.append(i)
        return moves

    def won_print(self):
        self.won()
        if self.winner == self.aiSymbol:
            print("AI wins :(")
            exit(0)
        elif self.winner == self.playerSymbol:
            print("Player Wins :)")
            exit(0)
        elif self.winner == "tie":
            print("Guess it's a draw")
            exit(0)

    def won(self):

        winningPositions = [{0, 1, 2}, {3, 4, 5}, {6, 7, 8},
                            {0, 4, 8}, {2, 4, 6}, {0, 3, 6},
                            {1, 4, 7}, {2, 5, 8}]

        for position in winningPositions:
            if position.issubset(self.playerPosition):
                self.winner = self.playerSymbol
                return True
            elif position.issubset(self.aiPosition):
                self.winner = self.aiSymbol
                return True
        if self.board.count(" ") == 0:
            self.winner = "tie"
            return True

        self.winner = None
        return False

    def set_i_ai(self, i):
        self.aiPosition.append(i)
        self.board[i] = self.aiSymbol

    def set_clear_for_ai(self, i):
        self.aiPosition.remove(i)
        self.board[i] = " "

    def set_i_player(self, i):
        self.playerPosition.append(i)
        self.board[i] = self.playerSymbol

    def set_clear_for_player(self, i):
        self.playerPosition.remove(i)
        self.board[i] = " "

    def findOptimalPosition(self):

        bestScore = float("-Infinity")
        elements = {}  # desperate times call for desperate measures

        for i in self.availableMoves():
            self.set_i_ai(i)
            score = self.minimax(False)
            if score > bestScore:
                bestScore = score
                elements[i] = bestScore
            self.set_clear_for_ai(i)
        if bestScore == 1:
            print("you messed up larry")
        elif bestScore == 0:
            print("hm")
        else:
            print("whoops i made a prog. error")
        return max(elements, key=lambda k: elements[k])

    def minimax(self, isMaximizing):

        if self.won():
            return self.scoreBoard[self.winner]

        if isMaximizing:
            bestScore = float("-Infinity")
            for i in self.availableMoves():
                self.set_i_ai(i)
                bestScore = max(self.minimax(False), bestScore)
                self.set_clear_for_ai(i)
            return bestScore
        else:
            bestScore = float("Infinity")
            for i in self.availableMoves():
                self.set_i_player(i)
                bestScore = min(self.minimax(True), bestScore)
                self.set_clear_for_player(i)
            return bestScore

    def play(self):

        self.choice()

        while not self.won_print():
            if self.turn % 2 == 0:
                pos = int(input("Where would you like to play? (0-8) "))
                self.playerPosition.append(pos)
                self.board[pos] = self.playerSymbol
                self.turn += 1
                self.drawBoard()
            else:
                aiTurn = self.findOptimalPosition()
                self.aiPosition.append(aiTurn)
                self.board[aiTurn] = self.aiSymbol
                self.turn += 1
                print("\n")
                print("\n")
                self.drawBoard()
        else:
            print("Thanks for playing :)")

if __name__ == '__main__':
    tictactoe = TicTacToe()
    tictactoe.play()

But as mentioned, the code may work, but there are MANY problems regarding the logic and structure, so do not straight-forward copy-paste it :))


来源: stackexchange

问:
Browser read integer from binary string
I have for example here this string

```<code>'x���'
</code>```

Which you may possibly not see depending on the devide you're using. That's the number 2024000250 encoded as a 32 bit signed big endian integer, which I've generated using Node

```<code>let buffer = new Buffer(4);
b.writeInt32BE(2024000250).toString();
</code>```

I'm receiving the 4 bytes in question on the client side but I can't seem to find how to turn them back into an integer...

答:
Well I finally got around to getting this to work.

It is not quite what I started off with but I'm just gonna post this for some other lost souls.

It is worth mentioning that ibrahim's answer contains most of the necessary information but is trying to satisfy the XY problem which my question ended up being.

I just send my binary data, as binary

```<code>let buffer = new Buffer(4);
buffer.writeInt32BE(2024000250);

// websocket connection
connection.send(buffer);
</code>```

Then in the browser

```<code>// message listener
let reader = new FileReader();
reader.addEventListener('loadend', () => {
  let view = new DataView(reader.result);

  // there goes the precious data
  console.log(view.getInt32());
});
reader.readAsArrayBuffer(message.data);
</code>```

In all honesty this tickles my gag reflex. Why am I using a file reader to get some data out of a binary message? There is a good chance a better way of doing this exists, if so please add to this answer.

Other methods I found are the fetch API which is no better than the file reader in terms of hack rating and Blob.prototype.arrayBuffer which is not yet supported fully.

ContentLicense: CC BY-SA 4.0

Title: Browser read integer from binary string

Body:
I have for example here this string

'x���'

Which you may possibly not see depending on the devide you're using. That's the number 2024000250 encoded as a 32 bit signed big endian integer, which I've generated using Node

let buffer = new Buffer(4);
b.writeInt32BE(2024000250).toString();

I'm receiving the 4 bytes in question on the client side but I can't seem to find how to turn them back into an integer...

Body:
Well I finally got around to getting this to work.

It is not quite what I started off with but I'm just gonna post this for some other lost souls.

It is worth mentioning that ibrahim's answer contains most of the necessary information but is trying to satisfy the XY problem which my question ended up being.

I just send my binary data, as binary

let buffer = new Buffer(4);
buffer.writeInt32BE(2024000250);

// websocket connection
connection.send(buffer);

Then in the browser

// message listener
let reader = new FileReader();
reader.addEventListener('loadend', () => {
  let view = new DataView(reader.result);

  // there goes the precious data
  console.log(view.getInt32());
});
reader.readAsArrayBuffer(message.data);

In all honesty this tickles my gag reflex. Why am I using a file reader to get some data out of a binary message? There is a good chance a better way of doing this exists, if so please add to this answer.

Other methods I found are the fetch API which is no better than the file reader in terms of hack rating and Blob.prototype.arrayBuffer which is not yet supported fully.


问:
convenient way to convert seconds into more specific format
Is there any convenient way to convert seconds into more specific format.

For example:

I want to convert

```<code>559 seconds
</code>```

to

```<code>9 min 19 sec
</code>```

答:
gmdate can be used

```<code>echo gmdate("H:i:s", 559 );
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Is there any convenient way to convert seconds into more specific format.

For example:

I want to convert

559 seconds

to

9 min 19 sec

Body:
gmdate can be used

echo gmdate("H:i:s", 559 );


问:
Where to process data on MERN stack?
I'm building an expenses control app based on MERN Stack and I was wondering which way is the best to process data.

To be more specific, my expense data has the following model

```<code>  {
    "_id" : ObjectId("5eceb10f0b59a200a545c39b"),
    "date" : ISODate("2019-10-10T00:00:00.000Z"),
    "description" : "INTERT BILL",
    "credit" : "",
    "debit" : "-100",
    "category" : "HOME",
    "subcategory" : "INTERNET",
    "__v" : 0
  }
</code>```

If I want to group expenses by category on a specific date, what would be the best way to do it?

Processing it on mongodb, through an aggregate query or fetch all expenses on a specific date range and grouping it on node.js before sending to client?

Desired output:

```<code>{
  HOME: {
   total: '-300',
   subcategories: [
    {
      internet: { total: -100}
    },
    {
      water: { total: -200 }
    }
   ]
  }
}

</code>```

答:
You should let MongoDB to the grouping, especially if you're dealing with a big dataset. The reason for that is that you could potentially block the event-loop by long running operations. Here's an aggregation query that should help you get started:

```<code>yourModel.aggregate([
        {
            $match: {
                date: yourDateToMatch
            }
        },
        { // you need this conversion stage in order to be able to do maths with your debit field
            $addFields: {
                convertedDebit: {
                    $toDecimal: "$debit"
                }
            }
        },
        {
            $group: {
                _id: "$category",
                total: {
                    $sum: "$convertedDebit"
                },
                // add grouping options for subcategories
            }
        }

    ])
</code>```

and just return the result using node.

Title: Where to process data on MERN stack?

Body:
I'm building an expenses control app based on MERN Stack and I was wondering which way is the best to process data.

To be more specific, my expense data has the following model

  {
    "_id" : ObjectId("5eceb10f0b59a200a545c39b"),
    "date" : ISODate("2019-10-10T00:00:00.000Z"),
    "description" : "INTERT BILL",
    "credit" : "",
    "debit" : "-100",
    "category" : "HOME",
    "subcategory" : "INTERNET",
    "__v" : 0
  }

If I want to group expenses by category on a specific date, what would be the best way to do it?

Processing it on mongodb, through an aggregate query or fetch all expenses on a specific date range and grouping it on node.js before sending to client?

Desired output:

{
  HOME: {
   total: '-300',
   subcategories: [
    {
      internet: { total: -100}
    },
    {
      water: { total: -200 }
    }
   ]
  }
}

Body:
You should let MongoDB to the grouping, especially if you're dealing with a big dataset. The reason for that is that you could potentially block the event-loop by long running operations. Here's an aggregation query that should help you get started:

yourModel.aggregate([
        {
            $match: {
                date: yourDateToMatch
            }
        },
        { // you need this conversion stage in order to be able to do maths with your debit field
            $addFields: {
                convertedDebit: {
                    $toDecimal: "$debit"
                }
            }
        },
        {
            $group: {
                _id: "$category",
                total: {
                    $sum: "$convertedDebit"
                },
                // add grouping options for subcategories
            }
        }

    ])

and just return the result using node.


问:
Can i register a new website domain with firebase?
I'm working on new mobile app project and we are trying to register a new website domain for the product. But it requires a server IP address. My question is there a way to use firebase services to provide a server IP address ?</p>

答: Firebase does not provide DNS services.  Firebase Hosting will give let you attach your existing domain name to its web hosting service, but it will not give you a dedicated static IP address.</p>


问:
Error loading Jupyter Notebook Extensions
I am using a Macbook with OS Sierra, and running Python 3.6.1 and Jupyter Notebook Server 5.0.0
I installed Jupyter Notebook extensions, following the instructions as mentioned on https://github.com/ipython-contrib/jupyter_contrib_nbextensions

While the notebooks work fine on my system, I cannot view the nbextensions tab. The following is the error log I see on running jupyter notebook in terminal. I have seen some related problems posted here on SO, but they seem to be about installing specific extensions.

Further, one of the solutions seemed to be suggest pip install jupyter_nbextensions_configurator, but as can be seen from the output below, I already have the extension installed.

```<code>Requirement already satisfied: traitlets in /usr/local/lib/python3.6/site-packages (from jupyter_nbextensions_configurator)
Requirement already satisfied: tornado in /usr/local/lib/python3.6/site-packages (from jupyter_nbextensions_configurator)
</code>```

However, in the logs, you will notice that ModuleNotFoundError: No module named 'jupyter_nbextensions_configurator' is one of the error messages.

```<code>[W 08:44:49.973 NotebookApp] server_extensions is deprecated, use nbserver_extensions
[W 08:44:50.146 NotebookApp] Error loading server extension jupyter_nbextensions_configurator
    Traceback (most recent call last):
      File "/usr/local/lib/python3.6/site-packages/notebook/notebookapp.py", line 1271, in init_server_extensions
        mod = importlib.import_module(modulename)
      File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module
        return _bootstrap._gcd_import(name[level:], package, level)
      File "<frozen importlib._bootstrap>", line 978, in _gcd_import
      File "<frozen importlib._bootstrap>", line 961, in _find_and_load
      File "<frozen importlib._bootstrap>", line 948, in _find_and_load_unlocked
    ModuleNotFoundError: No module named 'jupyter_nbextensions_configurator'
[I 08:44:50.158 NotebookApp] Serving notebooks from local directory: /Users/sp
[I 08:44:50.158 NotebookApp] 0 active kernels
[I 08:44:50.158 NotebookApp] The Jupyter Notebook is running at: http://localhost:8888/?token=c777a7ab5dc6cf416c238b7b37f58d10ebea9db0743b46ae
[I 08:44:50.158 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).
[C 08:44:50.163 NotebookApp]

    Copy/paste this URL into your browser when you connect for the first time,
    to login with a token:
        http://localhost:8888/?token=c777a7ab5dc6cf416c238b7b37f58d10ebea9db0743b46ae
[I 08:44:51.633 NotebookApp] Accepting one-time-token-authenticated connection from ::1
[W 08:44:54.407 NotebookApp] 404 GET /nbextensions/nbextensions_configurator/tree_tab/main.js?v=20170511084449 (::1) 25.76ms referer=http://localhost:8888/tree
</code>```

What am I missing here? Thanks!

答:
I had the same error for a long time. Reinstalling nbconfig, changing settings, giving it extra time to load, validating installation before opening the notebook, etc. did not help.

What worked for me in the end was switching browsers!
I switched from Safari on my Mac to Chrome and things are working perfectly!
(Safari Version 13.0.2, mac OS High Sierra 10.13.6, Chrome Version 83.0.4103.61)

Body:
I am using a Macbook with OS Sierra, and running Python 3.6.1 and Jupyter Notebook Server 5.0.0
I installed Jupyter Notebook extensions, following the instructions as mentioned on https://github.com/ipython-contrib/jupyter_contrib_nbextensions

While the notebooks work fine on my system, I cannot view the nbextensions tab. The following is the error log I see on running jupyter notebook in terminal. I have seen some related problems posted here on SO, but they seem to be about installing specific extensions.

Further, one of the solutions seemed to be suggest pip install jupyter_nbextensions_configurator, but as can be seen from the output below, I already have the extension installed.

Requirement already satisfied: traitlets in /usr/local/lib/python3.6/site-packages (from jupyter_nbextensions_configurator)
Requirement already satisfied: tornado in /usr/local/lib/python3.6/site-packages (from jupyter_nbextensions_configurator)

However, in the logs, you will notice that ModuleNotFoundError: No module named 'jupyter_nbextensions_configurator' is one of the error messages.

[W 08:44:49.973 NotebookApp] server_extensions is deprecated, use nbserver_extensions
[W 08:44:50.146 NotebookApp] Error loading server extension jupyter_nbextensions_configurator
    Traceback (most recent call last):
      File "/usr/local/lib/python3.6/site-packages/notebook/notebookapp.py", line 1271, in init_server_extensions
        mod = importlib.import_module(modulename)
      File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module
        return _bootstrap._gcd_import(name[level:], package, level)
      File "<frozen importlib._bootstrap>", line 978, in _gcd_import
      File "<frozen importlib._bootstrap>", line 961, in _find_and_load
      File "<frozen importlib._bootstrap>", line 948, in _find_and_load_unlocked
    ModuleNotFoundError: No module named 'jupyter_nbextensions_configurator'
[I 08:44:50.158 NotebookApp] Serving notebooks from local directory: /Users/sp
[I 08:44:50.158 NotebookApp] 0 active kernels
[I 08:44:50.158 NotebookApp] The Jupyter Notebook is running at: http://localhost:8888/?token=c777a7ab5dc6cf416c238b7b37f58d10ebea9db0743b46ae
[I 08:44:50.158 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).
[C 08:44:50.163 NotebookApp]

    Copy/paste this URL into your browser when you connect for the first time,
    to login with a token:
        http://localhost:8888/?token=c777a7ab5dc6cf416c238b7b37f58d10ebea9db0743b46ae
[I 08:44:51.633 NotebookApp] Accepting one-time-token-authenticated connection from ::1
[W 08:44:54.407 NotebookApp] 404 GET /nbextensions/nbextensions_configurator/tree_tab/main.js?v=20170511084449 (::1) 25.76ms referer=http://localhost:8888/tree

What am I missing here? Thanks!


问:
How to press button from keyboard instead of using mouse in tkinter?
I'm new to tkinter and I'm trying to create a calculator similar to windows calculator for practicing. I have created a calculator UI using tkinter.

If I press any key from keyboard, the button should be pressed in the calculator window similar to windows calculator. I have given justify as left for l1. But it is aligned in center only. I don't know where I'm wrong. Also I need to know how to create a sliding menu in tkinter.

Any ideas will be really helpful.

Below is the code of my calculator UI.

```<code>#Importing required libraries
from tkinter import *
import math
import fractions
import tkinter.font as font
from PIL import ImageTk, Image

#Creating instance for window
win = Tk()

#Function for reset
def reset(dummy=None):
    e1.delete(0, 'end')
    e2.delete(0, 'end')

#Function for backspace
def backspace():
    x = str(e2.get())
    e2.delete(0, END)
    e2.insert(0, x[:-1])

#Function for button click
def click(number):
    x = e2.get()
    e2.delete(0, END)
    e2.insert(0, str(x) + str(number))

#Giving title to window
win.title('Calculator')
#Customizing main=window
win.geometry('330x443')
win.configure(bg='#e8e8e8')
win.resizable(0,0)

#Defining Font style
l1_font = font.Font(family='Georgia', size=15)
e1_font = font.Font(family='Helvetica', size=15)
e2_font = font.Font(family='Helvetica', size=35)
b_font = font.Font(family='Helvetica', size=15)

#Binding enter and escape to window

win.bind('<Return>')
win.bind('<Escape>', reset)

#Frame1
f1 = Frame(win, bg='#e6e6e6')
f1.pack()

#Frame1 - Label1
l1 = Label(f1, text='Calculator', justify='left', anchor='w', justify='left', bg='#e6e6e6', pady=20)
l1['font'] = l1_font
l1.pack()

#Frame2
f2 = Frame(win, bg='#e6e6e6')
f2.pack()

#Frame2 - Entry1
e1 = Entry(f2, width = 65, justify = 'right', bg='#e6e6e6', validate="key", relief=FLAT)
#e1['validatecommand'] = (e1.register(entry_validation),'%P','%d')
e1['font'] = e1_font
e1.pack()

#Frame2 - Entry2
e2 = Entry(f2, width = 65, justify = 'right', bg='#e6e6e6', validate="key", relief=FLAT)
#e2['validatecommand'] = (e2.register(entry_validation),'%P','%d')
e2['font'] = e2_font
e2.pack()

#Frame3
f3 = Frame(win, bg='#e6e6e6')
f3.pack()

#Frame3 - Buttons
button1 = Button(f3, height =3, width =10, relief=FLAT, bg='white', command=lambda: click(1))
button2 = Button(f3, height =3, width =10, relief=FLAT, bg='white', command=lambda: click(2))
button3 = Button(f3, height =3, width =10, relief=FLAT, bg='white', command=lambda: click(3))
button4 = Button(f3, height =3, width =10, relief=FLAT, bg='white', command=lambda: click(4))
button5 = Button(f3, height =3, width =10, relief=FLAT, bg='white', command=lambda: click(5))
button6 = Button(f3, height =3, width =10, relief=FLAT, bg='white', command=lambda: click(6))
button7 = Button(f3, height =3, width =10, relief=FLAT, bg='white', command=lambda: click(7))
button8 = Button(f3, height =3, width =10, relief=FLAT, bg='white', command=lambda: click(8))
button9 = Button(f3, height =3, width =10, relief=FLAT, bg='white', command=lambda: click(9))
button0 = Button(f3, height =3, width =10, relief=FLAT, bg='white', command=lambda: click(0))

button_add = Button(f3, height =3, width =10, relief=FLAT, bg='#f7f7f7', command=lambda: click('+'))
button_sub = Button(f3, height =3, width =10, relief=FLAT, bg='#f7f7f7', command=lambda: click('-'))
button_mult = Button(f3, height =3, width =10, relief=FLAT, bg='#f7f7f7', command=lambda: click('*'))
button_div = Button(f3, height =3, width =10, relief=FLAT, bg='#f7f7f7', command=lambda: click('/'))

button_dot = Button(f3, height =3, width =10, relief=FLAT, bg='white', command=lambda: click('.'))
button_enter = Button(f3, height =3, width =10, relief=FLAT, bg='#9aafed')
button_clear = Button(f3, height =3, width =10, relief=FLAT, bg='#f7f7f7', command=reset)
button_bs = Button(f3, height =3, width =10, relief=FLAT, bg='#f7f7f7', command=backspace)

button_space = Button(f3, height =3, width =10, relief=FLAT, bg='#f7f7f7', command=lambda: click(' '))
button_na2 = Button(f3, height =3, width =10, relief=FLAT, bg='white', command=reset)

#Shoving buttons into window

#Frame3 - Buttons - Row 1
button_clear.grid(row = 0, column = 0, padx=0.75, pady=0.75)
button_div.grid(row = 0, column = 1, padx=0.75, pady=0.75)
button_mult.grid(row = 0, column = 2, padx=0.75, pady=0.75)
button_bs.grid(row = 0, column = 3, padx=0.75, pady=0.75)

#Frame3 - Buttons - Row 2
button7.grid(row = 1, column = 0, padx=0.75, pady=0.75)
button8.grid(row = 1, column = 1, padx=0.75, pady=0.75)
button9.grid(row = 1, column = 2, padx=0.75, pady=0.75)
button_sub.grid(row = 1, column = 3, padx=0.75, pady=0.75)

#Frame3 - Buttons - Row 3
button4.grid(row = 2, column = 0, padx=0.75, pady=0.75)
button5.grid(row = 2, column = 1, padx=0.75, pady=0.75)
button6.grid(row = 2, column = 2, padx=0.75, pady=0.75)
button_add.grid(row = 2, column = 3, padx=0.75, pady=0.75)

#Frame3 - Buttons - Row 4
button1.grid(row = 3, column = 0, padx=0.75, pady=0.75)
button2.grid(row = 3, column = 1, padx=0.75, pady=0.75)
button3.grid(row = 3, column = 2, padx=0.75, pady=0.75)
button_space.grid(row = 3, column = 3, padx=0.75, pady=0.75)

#Frame3 - Buttons - Row 5
button_na2.grid(row = 4, column = 0, padx=0.75, pady=0.75)
button0.grid(row = 4, column = 1, padx=0.75, pady=0.75)
button_dot.grid(row = 4, column = 2, padx=0.75, pady=0.75)
button_enter.grid(row = 4, column = 3, padx=0.75, pady=0.75)

win.mainloop()
</code>```

答:
For capturing keyboard events try code below. Example taken from effbot.org

```<code>def key(event):
print("pressed", repr(event.char))

frame = Frame(root, width=100, height=100)
frame.bind("<Key>", key)
frame.focus_set()
frame.pack()
</code>```

You used justify twice. Maybe this is the problem.

```<code>l1 = Label(f1, text='Calculator', justify='left', anchor='w', justify='left', bg='#e6e6e6', pady=20)
</code>```

To create sliding menu you can try using scale widget. More info again on effbot.org

Scrollbar example effbot.org

```<code>from tkinter import *

root = Tk()

left_frame = Frame(root, height=200, width=200, background='green')
left_frame.grid(row=0, column=0)
right_frame = Frame(root, height=200, width=200)
right_frame.grid(row=0, column=1)

scrollbar = Scrollbar(right_frame)
scrollbar.pack(side=RIGHT, fill=Y)
listbox = Listbox(right_frame, yscrollcommand=scrollbar.set)
for i in range(1000):
    listbox.insert(END, str(i))
listbox.pack(side=LEFT, fill=BOTH)

scrollbar.config(command=listbox.yview)

mainloop()
</code>```

Body:
I'm new to tkinter and I'm trying to create a calculator similar to windows calculator for practicing. I have created a calculator UI using tkinter.

If I press any key from keyboard, the button should be pressed in the calculator window similar to windows calculator. I have given justify as left for l1. But it is aligned in center only. I don't know where I'm wrong. Also I need to know how to create a sliding menu in tkinter.

Any ideas will be really helpful.

Below is the code of my calculator UI.

#Importing required libraries
from tkinter import *
import math
import fractions
import tkinter.font as font
from PIL import ImageTk, Image

#Creating instance for window
win = Tk()

#Function for reset
def reset(dummy=None):
    e1.delete(0, 'end')
    e2.delete(0, 'end')

#Function for backspace
def backspace():
    x = str(e2.get())
    e2.delete(0, END)
    e2.insert(0, x[:-1])

#Function for button click
def click(number):
    x = e2.get()
    e2.delete(0, END)
    e2.insert(0, str(x) + str(number))

#Giving title to window
win.title('Calculator')
#Customizing main=window
win.geometry('330x443')
win.configure(bg='#e8e8e8')
win.resizable(0,0)

#Defining Font style
l1_font = font.Font(family='Georgia', size=15)
e1_font = font.Font(family='Helvetica', size=15)
e2_font = font.Font(family='Helvetica', size=35)
b_font = font.Font(family='Helvetica', size=15)

#Binding enter and escape to window

win.bind('<Return>')
win.bind('<Escape>', reset)

#Frame1
f1 = Frame(win, bg='#e6e6e6')
f1.pack()

#Frame1 - Label1
l1 = Label(f1, text='Calculator', justify='left', anchor='w', justify='left', bg='#e6e6e6', pady=20)
l1['font'] = l1_font
l1.pack()

#Frame2
f2 = Frame(win, bg='#e6e6e6')
f2.pack()

#Frame2 - Entry1
e1 = Entry(f2, width = 65, justify = 'right', bg='#e6e6e6', validate="key", relief=FLAT)
#e1['validatecommand'] = (e1.register(entry_validation),'%P','%d')
e1['font'] = e1_font
e1.pack()

#Frame2 - Entry2
e2 = Entry(f2, width = 65, justify = 'right', bg='#e6e6e6', validate="key", relief=FLAT)
#e2['validatecommand'] = (e2.register(entry_validation),'%P','%d')
e2['font'] = e2_font
e2.pack()

#Frame3
f3 = Frame(win, bg='#e6e6e6')
f3.pack()

#Frame3 - Buttons
button1 = Button(f3, height =3, width =10, relief=FLAT, bg='white', command=lambda: click(1))
button2 = Button(f3, height =3, width =10, relief=FLAT, bg='white', command=lambda: click(2))
button3 = Button(f3, height =3, width =10, relief=FLAT, bg='white', command=lambda: click(3))
button4 = Button(f3, height =3, width =10, relief=FLAT, bg='white', command=lambda: click(4))
button5 = Button(f3, height =3, width =10, relief=FLAT, bg='white', command=lambda: click(5))
button6 = Button(f3, height =3, width =10, relief=FLAT, bg='white', command=lambda: click(6))
button7 = Button(f3, height =3, width =10, relief=FLAT, bg='white', command=lambda: click(7))
button8 = Button(f3, height =3, width =10, relief=FLAT, bg='white', command=lambda: click(8))
button9 = Button(f3, height =3, width =10, relief=FLAT, bg='white', command=lambda: click(9))
button0 = Button(f3, height =3, width =10, relief=FLAT, bg='white', command=lambda: click(0))

button_add = Button(f3, height =3, width =10, relief=FLAT, bg='#f7f7f7', command=lambda: click('+'))
button_sub = Button(f3, height =3, width =10, relief=FLAT, bg='#f7f7f7', command=lambda: click('-'))
button_mult = Button(f3, height =3, width =10, relief=FLAT, bg='#f7f7f7', command=lambda: click('*'))
button_div = Button(f3, height =3, width =10, relief=FLAT, bg='#f7f7f7', command=lambda: click('/'))

button_dot = Button(f3, height =3, width =10, relief=FLAT, bg='white', command=lambda: click('.'))
button_enter = Button(f3, height =3, width =10, relief=FLAT, bg='#9aafed')
button_clear = Button(f3, height =3, width =10, relief=FLAT, bg='#f7f7f7', command=reset)
button_bs = Button(f3, height =3, width =10, relief=FLAT, bg='#f7f7f7', command=backspace)

button_space = Button(f3, height =3, width =10, relief=FLAT, bg='#f7f7f7', command=lambda: click(' '))
button_na2 = Button(f3, height =3, width =10, relief=FLAT, bg='white', command=reset)

#Shoving buttons into window

#Frame3 - Buttons - Row 1
button_clear.grid(row = 0, column = 0, padx=0.75, pady=0.75)
button_div.grid(row = 0, column = 1, padx=0.75, pady=0.75)
button_mult.grid(row = 0, column = 2, padx=0.75, pady=0.75)
button_bs.grid(row = 0, column = 3, padx=0.75, pady=0.75)

#Frame3 - Buttons - Row 2
button7.grid(row = 1, column = 0, padx=0.75, pady=0.75)
button8.grid(row = 1, column = 1, padx=0.75, pady=0.75)
button9.grid(row = 1, column = 2, padx=0.75, pady=0.75)
button_sub.grid(row = 1, column = 3, padx=0.75, pady=0.75)

#Frame3 - Buttons - Row 3
button4.grid(row = 2, column = 0, padx=0.75, pady=0.75)
button5.grid(row = 2, column = 1, padx=0.75, pady=0.75)
button6.grid(row = 2, column = 2, padx=0.75, pady=0.75)
button_add.grid(row = 2, column = 3, padx=0.75, pady=0.75)

#Frame3 - Buttons - Row 4
button1.grid(row = 3, column = 0, padx=0.75, pady=0.75)
button2.grid(row = 3, column = 1, padx=0.75, pady=0.75)
button3.grid(row = 3, column = 2, padx=0.75, pady=0.75)
button_space.grid(row = 3, column = 3, padx=0.75, pady=0.75)

#Frame3 - Buttons - Row 5
button_na2.grid(row = 4, column = 0, padx=0.75, pady=0.75)
button0.grid(row = 4, column = 1, padx=0.75, pady=0.75)
button_dot.grid(row = 4, column = 2, padx=0.75, pady=0.75)
button_enter.grid(row = 4, column = 3, padx=0.75, pady=0.75)

win.mainloop()

Body:
For capturing keyboard events try code below. Example taken from effbot.org

def key(event):
print("pressed", repr(event.char))

frame = Frame(root, width=100, height=100)
frame.bind("<Key>", key)
frame.focus_set()
frame.pack()

You used justify twice. Maybe this is the problem.

l1 = Label(f1, text='Calculator', justify='left', anchor='w', justify='left', bg='#e6e6e6', pady=20)

To create sliding menu you can try using scale widget. More info again on effbot.org

Scrollbar example effbot.org

from tkinter import *

root = Tk()

left_frame = Frame(root, height=200, width=200, background='green')
left_frame.grid(row=0, column=0)
right_frame = Frame(root, height=200, width=200)
right_frame.grid(row=0, column=1)

scrollbar = Scrollbar(right_frame)
scrollbar.pack(side=RIGHT, fill=Y)
listbox = Listbox(right_frame, yscrollcommand=scrollbar.set)
for i in range(1000):
    listbox.insert(END, str(i))
listbox.pack(side=LEFT, fill=BOTH)

scrollbar.config(command=listbox.yview)

mainloop()


问:
switch character in line linux
This is file that I got

```<code> 1  CAGGAAAGACAATTCCAAAATCAGTTAGAGTCCTGTTGGCGCGTGTAATACATCTCCACTTTGAAAATGAAGACAGGGGGTTACGAGTGTTATTAATGAG
 2  TGGGAATGTAAATTAGTCCAGCCACTCTGGAGAACCGTATGGAGGTTCCTCCAAAAATTACAAATAGAACTACCATATGATCCAGCAATCCCATGCTATG
 3  AGATTTCCCTGAGAAAGTCATATTTAAGCTGCCATTTGAAGACCAAGGAATCATGACTAGAGACAAGAAGAGAGAACATAGAGTGATTATGGAGAATCTT
 4  AGTATCAGTCCAGTCCTCAGTGACGGGACCCTAACTGACCTGCCCTTCTTTGGCTTAGATTGCTTAAATGGTTCTGGATGTGATGATGGTGCACCTTGCC
 5  TATATTAGAGTAGAGTCTAAAGATTAGAATGATCCACAGGTTAATATGGGCCATTATAAAGAGATTAGTGATATTAACAATNTAGTATCAACATGGAGAT
 6  TCTATTATTTCATTGGGGTTGCAAAATTGTGATTTTCTAATCATTTCACTTTTCCTATATTTATTGCCTGGAACTTTGTAAAGAAGAAATTGATCTTATT
 7  TACCCTCAGGCTTATTAGGGTTGGAAACTCCACCCTGGGAAATTTGTGGTCAGACAGGTTTTCTGCTCTGGAACACTTTTTTCTGTTGTTTAAGATTTTT
 8  GCAAGAGAATCACTTGAACCCAGGAGGCAGAGGTTGCAGTGAGCCGGGATCGCGCCACTGCACTTCAGCCTGGGTGACAGTGTGAGACTCCATCTCAAAA
 9  TCACTGGTATTAAATCCCCAAATCAGAAATTTTGGACTGATTAAAAAAATGCACCAATCAAACAACAGAATTTCACACCAGATTTTGATAGTATACTTAT
10  GTAAACTACTTGTGAATATTTTTAATTAATGGCAATGTGGTTGCTTGCATACATTTAATAACAACATGTTTTATTTTATAANGGGCCATAACTGGAGGAA
11  TTCTTTTGAACTACTGAATCTCTGAGAACACTTAACAGGGTGAAGTTCAGTATTTACTTATTATTGTGAATCTGATAGCTGAAGTGATTTTTGTACAGCA
12  TCCCAAAGTGCTGGGATGACAGGCGTGAGCCACCGCGCCCGGCCCAAAGGAATTACTTTTAACTAAGAAACCTCCCACCCACCTCCTCCAGTTGCTATAT
13  CCGATCTTCAGGTTCTAAATTATGAAGTGGTTGATGGTCCTCAATAAGTGAACCATGAAATGCTTTCTTTACCTGGTGAAAATACATGGTGGTATAATAA
</code>```

Each character in file represent nucleotide sequence, and I'm trying to switch it in complement one, and change it in reversed direction.

which

```<code>G -> C , C->G , A->U, T -> A
</code>```

sample input & output will be

```<code>input
CAAATGGG

output
CCCAUUUG
</code>```

I tried

```<code> sed -i 's/C/G/g' file | sed -i 's/G/C/g' file | sed -i 's/A/U/g' file | sed -i 's/T/A/g' file
</code>```

but dind't worㅏ

答:
If you chain your sed commands as shown it will keep remapping the letter.

You can actually do the letter mapping, without the reverse, very simply with tr which is designed to do character by character translation: tr "GCAT" "CGUA" file. tr translates each character in the first string, in turn, to the corresponding character in the second string. Then to get the reversed string, you can use rev. So in all:

```<code>cat file | tr "GCAT" "CGUA" | rev
</code>```

Or better (as @edmorton suggests), when directly from the file:

```<code>tr "GCAT" "CGUA" < file | rev
</code>```

You can avoid the redirection, as @mathguy suggests, but changing the order (since rev accepts a file argument, whereas tr does not):

```<code>rev file | tr "CATG" "GUAC"
</code>```

Example:

```<code>$ echo "CAAATGGG" | tr "CATG" "GUAC" | rev
CCCAUUUG
</code>```

Title: switch character in line linux

Body:
This is file that I got

 1  CAGGAAAGACAATTCCAAAATCAGTTAGAGTCCTGTTGGCGCGTGTAATACATCTCCACTTTGAAAATGAAGACAGGGGGTTACGAGTGTTATTAATGAG
 2  TGGGAATGTAAATTAGTCCAGCCACTCTGGAGAACCGTATGGAGGTTCCTCCAAAAATTACAAATAGAACTACCATATGATCCAGCAATCCCATGCTATG
 3  AGATTTCCCTGAGAAAGTCATATTTAAGCTGCCATTTGAAGACCAAGGAATCATGACTAGAGACAAGAAGAGAGAACATAGAGTGATTATGGAGAATCTT
 4  AGTATCAGTCCAGTCCTCAGTGACGGGACCCTAACTGACCTGCCCTTCTTTGGCTTAGATTGCTTAAATGGTTCTGGATGTGATGATGGTGCACCTTGCC
 5  TATATTAGAGTAGAGTCTAAAGATTAGAATGATCCACAGGTTAATATGGGCCATTATAAAGAGATTAGTGATATTAACAATNTAGTATCAACATGGAGAT
 6  TCTATTATTTCATTGGGGTTGCAAAATTGTGATTTTCTAATCATTTCACTTTTCCTATATTTATTGCCTGGAACTTTGTAAAGAAGAAATTGATCTTATT
 7  TACCCTCAGGCTTATTAGGGTTGGAAACTCCACCCTGGGAAATTTGTGGTCAGACAGGTTTTCTGCTCTGGAACACTTTTTTCTGTTGTTTAAGATTTTT
 8  GCAAGAGAATCACTTGAACCCAGGAGGCAGAGGTTGCAGTGAGCCGGGATCGCGCCACTGCACTTCAGCCTGGGTGACAGTGTGAGACTCCATCTCAAAA
 9  TCACTGGTATTAAATCCCCAAATCAGAAATTTTGGACTGATTAAAAAAATGCACCAATCAAACAACAGAATTTCACACCAGATTTTGATAGTATACTTAT
10  GTAAACTACTTGTGAATATTTTTAATTAATGGCAATGTGGTTGCTTGCATACATTTAATAACAACATGTTTTATTTTATAANGGGCCATAACTGGAGGAA
11  TTCTTTTGAACTACTGAATCTCTGAGAACACTTAACAGGGTGAAGTTCAGTATTTACTTATTATTGTGAATCTGATAGCTGAAGTGATTTTTGTACAGCA
12  TCCCAAAGTGCTGGGATGACAGGCGTGAGCCACCGCGCCCGGCCCAAAGGAATTACTTTTAACTAAGAAACCTCCCACCCACCTCCTCCAGTTGCTATAT
13  CCGATCTTCAGGTTCTAAATTATGAAGTGGTTGATGGTCCTCAATAAGTGAACCATGAAATGCTTTCTTTACCTGGTGAAAATACATGGTGGTATAATAA

Each character in file represent nucleotide sequence, and I'm trying to switch it in complement one, and change it in reversed direction.

which

G -> C , C->G , A->U, T -> A

sample input & output will be

input
CAAATGGG

output
CCCAUUUG

I tried

 sed -i 's/C/G/g' file | sed -i 's/G/C/g' file | sed -i 's/A/U/g' file | sed -i 's/T/A/g' file

but dind't worㅏ

Body:
If you chain your sed commands as shown it will keep remapping the letter.

You can actually do the letter mapping, without the reverse, very simply with tr which is designed to do character by character translation: tr "GCAT" "CGUA" file. tr translates each character in the first string, in turn, to the corresponding character in the second string. Then to get the reversed string, you can use rev. So in all:

cat file | tr "GCAT" "CGUA" | rev

Or better (as @edmorton suggests), when directly from the file:

tr "GCAT" "CGUA" < file | rev

You can avoid the redirection, as @mathguy suggests, but changing the order (since rev accepts a file argument, whereas tr does not):

rev file | tr "CATG" "GUAC"

Example:

$ echo "CAAATGGG" | tr "CATG" "GUAC" | rev
CCCAUUUG


问:
selenium.common.exceptions.WebDriverException: Message: Service .\geckodriver.exe unexpectedly exited. Status code was: 3221225595
I been trying to make Instapy work but struck with this error.

```<code>selenium.common.exceptions.WebDriverException: Message: Service .\geckodriver.exe unexpectedly exited. Status code was: 3221225595
</code>```

Here is some information about things I have already done;

Download latest version for GeckoDriver.

Download latest version of FireFox.

Installed Visual C++ Redistributable for Visual Studio 2015

Waiting keenly for solution :)

答:
This error message...

```<code>selenium.common.exceptions.WebDriverException: Message: Service .\geckodriver.exe unexpectedly exited. Status code was: 3221225595
</code>```

...implies that the GeckoDriver unexpectedly exited.

Status code: 3221225595

As per the documentation in Getting error Service geckodriver unexpectedly exited. Status code was: 3221225595 Status Code 3221225477 is raised in absence of VCRUNTIME140.dll.

As of now you will need to install Microsoft Visual Studio redistributable runtime on all your Windows test machines for geckodriver to work.

This issue was discussed and tracked in Bugzilla through Geckodriver windows binaries don't run anymore without having the Microsoft MSCV runtime installed.

Outro

You can find a detailed discussion in:

geckodriver requires Microsoft MSVC runtime to be installed on Windows

Body:
I been trying to make Instapy work but struck with this error.

selenium.common.exceptions.WebDriverException: Message: Service .\geckodriver.exe unexpectedly exited. Status code was: 3221225595

Here is some information about things I have already done;

Download latest version for GeckoDriver.

Download latest version of FireFox.

Installed Visual C++ Redistributable for Visual Studio 2015

Waiting keenly for solution :)

Body:
This error message...

selenium.common.exceptions.WebDriverException: Message: Service .\geckodriver.exe unexpectedly exited. Status code was: 3221225595

...implies that the GeckoDriver unexpectedly exited.

Status code: 3221225595

As per the documentation in Getting error Service geckodriver unexpectedly exited. Status code was: 3221225595 Status Code 3221225477 is raised in absence of VCRUNTIME140.dll.

As of now you will need to install Microsoft Visual Studio redistributable runtime on all your Windows test machines for geckodriver to work.

This issue was discussed and tracked in Bugzilla through Geckodriver windows binaries don't run anymore without having the Microsoft MSCV runtime installed.

Outro

You can find a detailed discussion in:

geckodriver requires Microsoft MSVC runtime to be installed on Windows


问:
Nginx config. File from disk with check
I dont understand how i can write logic : if file in folder exists then return;</p>

```<code>location ~ "/((\w{2})[\w-]+\.(png|jpg))$" {

    if(-f e:\\ThumbFull\\$2\\$1){
        alias  e:\\ThumbFull\\$2\\$1;
    }

    if(-f e:\\Image\\$2\\$1){
        alias  e:\\Image\\$2\\$1;
    }
    return 404;
}
</code>```

答:
You could set root to a common parent directory (i.e. e:/) and use try_files to check for the file in both directories.

For example:

```<code>location ~ "/((\w{2})[\w-]+\.(png|jpg))$" {
    root e:/;
    try_files /ThumbFull/$2/$1 /Image/$2/$1 =404;
}
</code>```

See this document for details.

Title: Nginx config. File from disk with check

Body:
I dont understand how i can write logic : if file in folder exists then return;

location ~ "/((\w{2})[\w-]+\.(png|jpg))$" {

    if(-f e:\\ThumbFull\\$2\\$1){
        alias  e:\\ThumbFull\\$2\\$1;
    }

    if(-f e:\\Image\\$2\\$1){
        alias  e:\\Image\\$2\\$1;
    }
    return 404;
}

Body:
You could set root to a common parent directory (i.e. e:/) and use try_files to check for the file in both directories.

For example:

location ~ "/((\w{2})[\w-]+\.(png|jpg))$" {
    root e:/;
    try_files /ThumbFull/$2/$1 /Image/$2/$1 =404;
}

See this document for details.


问:
Conversion failed with UNION
I'm using SQL Server Management Studio in order to build a query that reports issues.

Alone these queries work fine but as soon as they are added via using a union I end up with the following  error message:

Msg 245, Level 16, State 1, Line 1

  Conversion failed when converting the varchar value 'OFC' to data type smallint

I've attempted to use Cast and Convert on the w.wpage and p.ppage columns. I've attempted to use them directly on the case statements for both sub-queries which varying results but always a:

conversion failed when converting...

error.

Any help or advice would be greatly appreciated.

```<code>SELECT
    a.Article,
    a.ARTICLENAME,
    a.Offer,
    a.EBD,
    q.Excl,
    a.OfferYear,
    b.SeasonID,
    CASE
       WHEN CONCAT(catid,packnum) <> CONCAT(a.offer, a.article)
          THEN 'Add'
       WHEN a.EBD = 'B' AND q.Excl = 'BE'
          THEN 'True'
       ELSE 'Exclusive'
    END AS Action,
    CASE
       WHEN CONCAT(a.offer, a.article) = CONCAT(d.ToCat, d.article)
          THEN 'Y'
          ELSE 'N'
    END AS [On CN]
FROM
    Lago_CID_Master a
INNER JOIN
    CatalogInfo b ON (a.Offer = b.Catalog) AND (a.OfferYear = b.MailYear)
LEFT JOIN
    ChangeNoticeCopyFile d ON (a.ARTICLE = d.article)
                           AND (a.Offer = d.ToCat) AND (a.OfferYear = d.ToYear)
LEFT JOIN
    (SELECT
         c.Packnum, c.CatID, c.Excl
     FROM
         PIC704Current c
     INNER JOIN
         cataloginfo d ON (c.CatID = d.catalog) AND (c.Year = d.MailYear)
     WHERE
         d.MailYear = '2020'
         AND d.SeasonID = 'F20'
         AND d.MediaId IN ('CAT Catalog', 'SCAT Sale Catalog', 'SSTF Sale Statement Stuff', 'STUF Statement Stuffer', 'PKG Package Insert', 'SPKG Sale Pkg Insert')
         AND d.Brand = 'Seventh Avenue') q ON CONCAT(q.catid,q.packnum) = CONCAT(a.offer, a.article)
WHERE
    q.CatID IS NULL
    AND (CASE WHEN Retail < '1' THEN 'Yes' ELSE 'No' END) = 'No'
    AND b.MailYear = '2020'
    AND b.SeasonID = 'F20'
    AND b.MediaId = 'Cat Catalog'
    AND b.Brand = 'Seventh Avenue'

--Pages
UNION

SELECT DISTINCT
    a.PackNum, a.Description, a.CatID,
    c.SeasonID, a.Page as MFPage, w.WPage, p.Ppage,
    CASE
       WHEN a.page <> w.wpage
          THEN 'Update Page'
          ELSE ''
    END AS action,
    CASE
       WHEN CONCAT(a.CatID, a.PackNum) = CONCAT(d.offer, d.article)
          THEN 'Y'
          ELSE 'N'
    END AS [On CN]
FROM
    pic704current a
INNER JOIN
    Lago_CID_Master b ON (a.CatID = b.Offer)
                      AND (a.year = b.OfferYear) AND (a.PackNum = b.ARTICLE)
JOIN
    CatalogInfo c ON (a.catid = c.catalog) AND (a.year = c.mailyear)
FULL OUTER JOIN
    ChangeNoticeChanges d ON (b.ARTICLE = d.article)
                          AND (a.CatID = d.offer) AND (a.Year = d.offeryear)
LEFT JOIN
    --Working Page
    (SELECT
         e.packnum, e.catid,
         CASE
            WHEN CAST(f.wpfrom AS int) >= 7000 THEN 'EOC'
            WHEN CAST(f.wpfrom AS int) BETWEEN 700 AND 800
                 AND f.spreadname LIKE '%CHECK%' THEN 'CHK'
            WHEN f.spreadname LIKE '%ORDER FORM%'
                 OR f.spreadname LIKE '%CTOB%' THEN 'COF'
            WHEN f.spreadname LIKE '%OFC%' THEN 'OFC'
            WHEN f.spreadname LIKE '%EXOBC%' THEN 'WR' +
                 CASE WHEN SUBSTRING(f.spreadname, CHARINDEX(e.catid, f.spreadname) + 2, 1) = ' '
                           OR SUBSTRING(f.spreadname, CHARINDEX(f.offer, f.spreadname) + 2, 1) = '' THEN '1'
                           ELSE SUBSTRING(f.spreadname, CHARINDEX(f.offer, f.spreadname) + 2, 1)
                 END
            WHEN f.spreadname LIKE '%IBC%' THEN 'IB' +
                 CASE WHEN substring(f.spreadname,charindex(f.offer, f.spreadname)+2,1) = ' ' or substring(f.spreadname,charindex(f.offer, f.spreadname)+2,1) = '' then '1'
ELSE substring(spreadname,charindex(f.offer, f.spreadname)+2,1) End
WHEN Cast(f.wpfrom as int) = 2 then 'IF' + case when charindex(f.offer, f.spreadname) = 0  then '1' when substring(f.spreadname,charindex(f.offer, f.spreadname)+2,1) = '' then '1'
ELSE substring(f.spreadname,charindex(f.offer, f.spreadname)+2,1) End
WHEN f.spreadname like '%OBC%' then 'OB' +  case when substring(f.spreadname,charindex(f.offer, f.spreadname)+2,1) = ' ' or substring(f.spreadname,charindex(f.offer, f.spreadname)+2,1) = '' then '1'
ELSE substring(f.spreadname,charindex(f.offer, f.spreadname)+2,1) End
ELSE right('00' + f.wpfrom,3) END AS WPage

FROM pic704current e INNER JOIN Lago_CID_Master f ON (e.CatID = f.Offer) and (e.year = f.OfferYear) and (e.PackNum = f.ARTICLE)
JOIN CatalogInfo g on (e.catid = g.catalog) and (e.year = g.mailyear)

WHERE
e.year = '2020'
and g.SeasonID = 'F20'
and g.brand = 'Seventh Avenue'
and g.MediaId in('CAT Catalog','SCAT Sale Catalog','SSTF Sale Statement Stuff','STUF Statement Stuffer','PKG Package Insert','SPKG Sale Pkg Insert')) w
ON CONCAT(a.catid,a.packnum) = CONCAT(w.CatID, w.PackNum)

LEFT JOIN

--Paginated Page
(SELECT I.packnum, I.catid
,CASE WHEN Cast(J.PPFROM as int) >=7000 then 'EOC'
WHEN Cast(J.PPFROM as int) between 700 and 800 and J.spreadname like '%CHECK%' then 'CHK'
WHEN J.spreadname like '%ORDER FORM%'  or J.spreadname like '%CTOB%' then 'COF'
WHEN J.spreadname like '%OFC%' then 'OFC'
WHEN J.spreadname like '%EXOBC%' then 'WR' +  case when substring(J.spreadname,charindex(I.catid, J.spreadname)+2,1) = ' ' or substring(J.spreadname,charindex(J.offer, J.spreadname)+2,1) = '' then '1'
ELSE substring(J.spreadname,charindex(J.offer, J.spreadname)+2,1) End
WHEN J.spreadname like '%IBC%' then 'IB' + case when substring(J.spreadname,charindex(J.offer, J.spreadname)+2,1) = ' ' or substring(J.spreadname,charindex(J.offer, J.spreadname)+2,1) = '' then '1'
ELSE substring(spreadname,charindex(J.offer, J.spreadname)+2,1) End
WHEN Cast(J.PPFROM as int) = 2 then 'IF' + case when charindex(J.offer, J.spreadname) = 0  then '1' when substring(J.spreadname,charindex(J.offer, J.spreadname)+2,1) = '' then '1'
ELSE substring(J.spreadname,charindex(J.offer, J.spreadname)+2,1) End
WHEN J.spreadname like '%OBC%' then 'OB' +  case when substring(J.spreadname,charindex(J.offer, J.spreadname)+2,1) = ' ' or substring(J.spreadname,charindex(J.offer, J.spreadname)+2,1) = '' then '1'
ELSE substring(J.spreadname,charindex(J.offer, J.spreadname)+2,1) End
ELSE right('00' + J.PPFROM,3) END AS PPage

FROM pic704current I INNER JOIN Lago_CID_Master J ON (I.CatID = J.Offer) and (I.year = J.OfferYear) and (I.PackNum = J.ARTICLE)
JOIN CatalogInfo K on (I.catid = K.catalog) and (I.year = K.mailyear)

WHERE
I.year = '2020'
and K.SeasonID = 'F20'
and K.brand = 'Seventh Avenue'
and K.MediaId in('CAT Catalog','SCAT Sale Catalog','SSTF Sale Statement Stuff','STUF Statement Stuffer','PKG Package Insert','SPKG Sale Pkg Insert'))P
ON CONCAT(a.catid,a.packnum) = CONCAT(p.CatID, p.PackNum)

WHERE
(CASE WHEN wpage <> a.page and ppage = '000' then 'true' else 'false' end) = 'true'
and
(CASE WHEN ppage > '0' and ppage <> a.page then 'true' else 'false' end) = 'true'
and a.year = '2020'
and c.SeasonID = 'F20'
and c.brand = 'Seventh Avenue'
and c.MediaId in('CAT Catalog','SCAT Sale Catalog','SSTF Sale Statement Stuff','STUF Statement Stuffer','PKG Package Insert','SPKG Sale Pkg Insert')

ORDER BY Action
</code>```

答:
Since your problem starts by adding the union operator it seems that the datatypes in your columns do not match up. The string 'OFC' cannot be converted into an integer so that will always fail. Looking at the descriptions of your columns i would hazard a guess that PackNum is an integer and Article is a string.

To find the offending column what you could do is run the query's independently with an 'INTO #temp' statement just before the FROM part. And then check the data type of the the two temporary tables you have created. I bet that you will find an int in one and a string in the other.

Then according to your requirements ammend the query or cast the integer column as a varchar.

Title: Conversion failed with UNION

Body:
I'm using SQL Server Management Studio in order to build a query that reports issues.

Alone these queries work fine but as soon as they are added via using a union I end up with the following  error message:

Msg 245, Level 16, State 1, Line 1

  Conversion failed when converting the varchar value 'OFC' to data type smallint

I've attempted to use Cast and Convert on the w.wpage and p.ppage columns. I've attempted to use them directly on the case statements for both sub-queries which varying results but always a:

conversion failed when converting...

error.

Any help or advice would be greatly appreciated.

SELECT
    a.Article,
    a.ARTICLENAME,
    a.Offer,
    a.EBD,
    q.Excl,
    a.OfferYear,
    b.SeasonID,
    CASE
       WHEN CONCAT(catid,packnum) <> CONCAT(a.offer, a.article)
          THEN 'Add'
       WHEN a.EBD = 'B' AND q.Excl = 'BE'
          THEN 'True'
       ELSE 'Exclusive'
    END AS Action,
    CASE
       WHEN CONCAT(a.offer, a.article) = CONCAT(d.ToCat, d.article)
          THEN 'Y'
          ELSE 'N'
    END AS [On CN]
FROM
    Lago_CID_Master a
INNER JOIN
    CatalogInfo b ON (a.Offer = b.Catalog) AND (a.OfferYear = b.MailYear)
LEFT JOIN
    ChangeNoticeCopyFile d ON (a.ARTICLE = d.article)
                           AND (a.Offer = d.ToCat) AND (a.OfferYear = d.ToYear)
LEFT JOIN
    (SELECT
         c.Packnum, c.CatID, c.Excl
     FROM
         PIC704Current c
     INNER JOIN
         cataloginfo d ON (c.CatID = d.catalog) AND (c.Year = d.MailYear)
     WHERE
         d.MailYear = '2020'
         AND d.SeasonID = 'F20'
         AND d.MediaId IN ('CAT Catalog', 'SCAT Sale Catalog', 'SSTF Sale Statement Stuff', 'STUF Statement Stuffer', 'PKG Package Insert', 'SPKG Sale Pkg Insert')
         AND d.Brand = 'Seventh Avenue') q ON CONCAT(q.catid,q.packnum) = CONCAT(a.offer, a.article)
WHERE
    q.CatID IS NULL
    AND (CASE WHEN Retail < '1' THEN 'Yes' ELSE 'No' END) = 'No'
    AND b.MailYear = '2020'
    AND b.SeasonID = 'F20'
    AND b.MediaId = 'Cat Catalog'
    AND b.Brand = 'Seventh Avenue'

--Pages
UNION

SELECT DISTINCT
    a.PackNum, a.Description, a.CatID,
    c.SeasonID, a.Page as MFPage, w.WPage, p.Ppage,
    CASE
       WHEN a.page <> w.wpage
          THEN 'Update Page'
          ELSE ''
    END AS action,
    CASE
       WHEN CONCAT(a.CatID, a.PackNum) = CONCAT(d.offer, d.article)
          THEN 'Y'
          ELSE 'N'
    END AS [On CN]
FROM
    pic704current a
INNER JOIN
    Lago_CID_Master b ON (a.CatID = b.Offer)
                      AND (a.year = b.OfferYear) AND (a.PackNum = b.ARTICLE)
JOIN
    CatalogInfo c ON (a.catid = c.catalog) AND (a.year = c.mailyear)
FULL OUTER JOIN
    ChangeNoticeChanges d ON (b.ARTICLE = d.article)
                          AND (a.CatID = d.offer) AND (a.Year = d.offeryear)
LEFT JOIN
    --Working Page
    (SELECT
         e.packnum, e.catid,
         CASE
            WHEN CAST(f.wpfrom AS int) >= 7000 THEN 'EOC'
            WHEN CAST(f.wpfrom AS int) BETWEEN 700 AND 800
                 AND f.spreadname LIKE '%CHECK%' THEN 'CHK'
            WHEN f.spreadname LIKE '%ORDER FORM%'
                 OR f.spreadname LIKE '%CTOB%' THEN 'COF'
            WHEN f.spreadname LIKE '%OFC%' THEN 'OFC'
            WHEN f.spreadname LIKE '%EXOBC%' THEN 'WR' +
                 CASE WHEN SUBSTRING(f.spreadname, CHARINDEX(e.catid, f.spreadname) + 2, 1) = ' '
                           OR SUBSTRING(f.spreadname, CHARINDEX(f.offer, f.spreadname) + 2, 1) = '' THEN '1'
                           ELSE SUBSTRING(f.spreadname, CHARINDEX(f.offer, f.spreadname) + 2, 1)
                 END
            WHEN f.spreadname LIKE '%IBC%' THEN 'IB' +
                 CASE WHEN substring(f.spreadname,charindex(f.offer, f.spreadname)+2,1) = ' ' or substring(f.spreadname,charindex(f.offer, f.spreadname)+2,1) = '' then '1'
ELSE substring(spreadname,charindex(f.offer, f.spreadname)+2,1) End
WHEN Cast(f.wpfrom as int) = 2 then 'IF' + case when charindex(f.offer, f.spreadname) = 0  then '1' when substring(f.spreadname,charindex(f.offer, f.spreadname)+2,1) = '' then '1'
ELSE substring(f.spreadname,charindex(f.offer, f.spreadname)+2,1) End
WHEN f.spreadname like '%OBC%' then 'OB' +  case when substring(f.spreadname,charindex(f.offer, f.spreadname)+2,1) = ' ' or substring(f.spreadname,charindex(f.offer, f.spreadname)+2,1) = '' then '1'
ELSE substring(f.spreadname,charindex(f.offer, f.spreadname)+2,1) End
ELSE right('00' + f.wpfrom,3) END AS WPage

FROM pic704current e INNER JOIN Lago_CID_Master f ON (e.CatID = f.Offer) and (e.year = f.OfferYear) and (e.PackNum = f.ARTICLE)
JOIN CatalogInfo g on (e.catid = g.catalog) and (e.year = g.mailyear)

WHERE
e.year = '2020'
and g.SeasonID = 'F20'
and g.brand = 'Seventh Avenue'
and g.MediaId in('CAT Catalog','SCAT Sale Catalog','SSTF Sale Statement Stuff','STUF Statement Stuffer','PKG Package Insert','SPKG Sale Pkg Insert')) w
ON CONCAT(a.catid,a.packnum) = CONCAT(w.CatID, w.PackNum)

LEFT JOIN

--Paginated Page
(SELECT I.packnum, I.catid
,CASE WHEN Cast(J.PPFROM as int) >=7000 then 'EOC'
WHEN Cast(J.PPFROM as int) between 700 and 800 and J.spreadname like '%CHECK%' then 'CHK'
WHEN J.spreadname like '%ORDER FORM%'  or J.spreadname like '%CTOB%' then 'COF'
WHEN J.spreadname like '%OFC%' then 'OFC'
WHEN J.spreadname like '%EXOBC%' then 'WR' +  case when substring(J.spreadname,charindex(I.catid, J.spreadname)+2,1) = ' ' or substring(J.spreadname,charindex(J.offer, J.spreadname)+2,1) = '' then '1'
ELSE substring(J.spreadname,charindex(J.offer, J.spreadname)+2,1) End
WHEN J.spreadname like '%IBC%' then 'IB' + case when substring(J.spreadname,charindex(J.offer, J.spreadname)+2,1) = ' ' or substring(J.spreadname,charindex(J.offer, J.spreadname)+2,1) = '' then '1'
ELSE substring(spreadname,charindex(J.offer, J.spreadname)+2,1) End
WHEN Cast(J.PPFROM as int) = 2 then 'IF' + case when charindex(J.offer, J.spreadname) = 0  then '1' when substring(J.spreadname,charindex(J.offer, J.spreadname)+2,1) = '' then '1'
ELSE substring(J.spreadname,charindex(J.offer, J.spreadname)+2,1) End
WHEN J.spreadname like '%OBC%' then 'OB' +  case when substring(J.spreadname,charindex(J.offer, J.spreadname)+2,1) = ' ' or substring(J.spreadname,charindex(J.offer, J.spreadname)+2,1) = '' then '1'
ELSE substring(J.spreadname,charindex(J.offer, J.spreadname)+2,1) End
ELSE right('00' + J.PPFROM,3) END AS PPage

FROM pic704current I INNER JOIN Lago_CID_Master J ON (I.CatID = J.Offer) and (I.year = J.OfferYear) and (I.PackNum = J.ARTICLE)
JOIN CatalogInfo K on (I.catid = K.catalog) and (I.year = K.mailyear)

WHERE
I.year = '2020'
and K.SeasonID = 'F20'
and K.brand = 'Seventh Avenue'
and K.MediaId in('CAT Catalog','SCAT Sale Catalog','SSTF Sale Statement Stuff','STUF Statement Stuffer','PKG Package Insert','SPKG Sale Pkg Insert'))P
ON CONCAT(a.catid,a.packnum) = CONCAT(p.CatID, p.PackNum)

WHERE
(CASE WHEN wpage <> a.page and ppage = '000' then 'true' else 'false' end) = 'true'
and
(CASE WHEN ppage > '0' and ppage <> a.page then 'true' else 'false' end) = 'true'
and a.year = '2020'
and c.SeasonID = 'F20'
and c.brand = 'Seventh Avenue'
and c.MediaId in('CAT Catalog','SCAT Sale Catalog','SSTF Sale Statement Stuff','STUF Statement Stuffer','PKG Package Insert','SPKG Sale Pkg Insert')

ORDER BY Action


问:
How to visually consume/create .diff .patch files in OS X?
Sorry, I'm just not finding anything that can do this!  For example I get a big fat .diff of 30 files.. sure, I can use patch and apply that to my source baseline.  But, I'd hope to be able to take that .diff and my source tree and interactively view those changes to review the diff and optionally merge in or ignore sections.

答: Check out opendiff which is part of Mac OS X Developer Tools (XCode).  It won't work exactly how you want (directly on .diff files), but you can make a temp copy of your source tree, apply your diffs, then run opendiff to compare visually.  You can then selectively merge and choose which version of each change to include.


问:
Android LiveData: How to do an ArrayList<LiveData<RetrofitObject>>?
I am creating an app with MVVM architecture and I ran into an issue of getting a list of LiveData to show in the View.

In my ViewModel I have a getAll() function that retrieves a list of strings from the database using Room. From there, I get the strings and call my Retrofit function to send each string individually to a web-server that returns an object. Here is where my issue occurs.

From the MVVM tutorials I see online, they usually have the LiveData> style but in this since I am getting each object individually, it becomes List> but I don't think this is the correct way of doing it because in my View I would need to do a ForEach loop to observe each LiveData object in the list.

I have tried other work arounds but it doesn't seem to work. Is there a better way of doing this?

DAO

```<code>@Query("SELECT * FROM table")
    fun getAll(): LiveData<List<String>>
</code>```

Repository

```<code>fun getAll(): LiveData<List<String>> {
        return dao.getAll()
    }

fun getRetrofitObject(s: String): LiveData<RetrofitObject> {
        api = jsonApi.getRetrofitObjectInfo(s, API_KEY)
        val retrofitObject: MutableLiveData<RetrofitObject> = MutableLiveData()
        api.enqueue(object : Callback<RetrofitObject> {
            override fun onFailure(call: Call<RetrofitObject>?, t: Throwable?) {
                Log.d("TEST", "Code: " + t.toString())
            }

            override fun onResponse(call: Call<RetrofitObject>?, response: Response<RetrofitObject>?) {
                if (response!!.isSuccessful) {
                    retrofitObject.value = response.body()
                }
            }
        })
        return retrofitObject
    }
</code>```

MainActivityViewModel (ViewModel)

```<code>var objectList ArrayList<LiveData<retrofitObject>> = ArrayList()

// This is getting objects using Retrofit
fun getRetrofitObject(s: String): LiveData<retrofitObject> {
        return repo.getRetrofitObject(s)
    }

// This is getting all the strings from the internal database
fun getAll(): ArrayList<LiveData<retroFitObject>> {
        repo.getAll().value?.forEach {it ->
            objectList.add(getRetrofitObject(it)) //How else would I be able to do this?
        }
        return objectList
    }
</code>```

MainActivity (View)

```<code>override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mainActivityViewModel.getAll().forEach {
                        it.observe(this, Observer {it ->
                            mainActivityViewModel.objectList.add(it) //Here is part of the issue since I don't want to use a forloop in the View

                        })
                    }
                    adapter.objectList = mainActivityViewModel.objectList
                    recyclerView.adapter = adapter
}

</code>```

Thanks, let me know if there is anything else needed or confusion!

答:
By looking at the above code you are trying to fetch a list of item for each table row from server and  and trying to update the result to your recycler view. Your logic is little confusing..
So on your activity .. first init your adapter and recyclerview

Then call your viewmodel function to get all values inside table and make a loop to call your network thread fuction in background and store the values in a live data object.

Just observe this livedata in your activity/fragment and just pass the list to adapter and notify it.by doing this,whenever your livedata got a change your recyclerview also reflect the items

The problem with your code is, you are called a retrofit network function with enque option and its a background thread process.so, code wont wait for the network completion. And it will return the retrofitObject data.but it has not got the data yet.so this will make error.

Body:
I am creating an app with MVVM architecture and I ran into an issue of getting a list of LiveData to show in the View.

In my ViewModel I have a getAll() function that retrieves a list of strings from the database using Room. From there, I get the strings and call my Retrofit function to send each string individually to a web-server that returns an object. Here is where my issue occurs.

From the MVVM tutorials I see online, they usually have the LiveData> style but in this since I am getting each object individually, it becomes List> but I don't think this is the correct way of doing it because in my View I would need to do a ForEach loop to observe each LiveData object in the list.

I have tried other work arounds but it doesn't seem to work. Is there a better way of doing this?

DAO

@Query("SELECT * FROM table")
    fun getAll(): LiveData<List<String>>

Repository

fun getAll(): LiveData<List<String>> {
        return dao.getAll()
    }

fun getRetrofitObject(s: String): LiveData<RetrofitObject> {
        api = jsonApi.getRetrofitObjectInfo(s, API_KEY)
        val retrofitObject: MutableLiveData<RetrofitObject> = MutableLiveData()
        api.enqueue(object : Callback<RetrofitObject> {
            override fun onFailure(call: Call<RetrofitObject>?, t: Throwable?) {
                Log.d("TEST", "Code: " + t.toString())
            }

            override fun onResponse(call: Call<RetrofitObject>?, response: Response<RetrofitObject>?) {
                if (response!!.isSuccessful) {
                    retrofitObject.value = response.body()
                }
            }
        })
        return retrofitObject
    }

MainActivityViewModel (ViewModel)

var objectList ArrayList<LiveData<retrofitObject>> = ArrayList()

// This is getting objects using Retrofit
fun getRetrofitObject(s: String): LiveData<retrofitObject> {
        return repo.getRetrofitObject(s)
    }

// This is getting all the strings from the internal database
fun getAll(): ArrayList<LiveData<retroFitObject>> {
        repo.getAll().value?.forEach {it ->
            objectList.add(getRetrofitObject(it)) //How else would I be able to do this?
        }
        return objectList
    }

MainActivity (View)

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mainActivityViewModel.getAll().forEach {
                        it.observe(this, Observer {it ->
                            mainActivityViewModel.objectList.add(it) //Here is part of the issue since I don't want to use a forloop in the View

                        })
                    }
                    adapter.objectList = mainActivityViewModel.objectList
                    recyclerView.adapter = adapter
}

Thanks, let me know if there is anything else needed or confusion!


问:
Add A Class To An Input Using PHP
I have been working on a form that uses PHP form validation. I also have a class in my CSS file that should be added to each of the invalid inputs. You can view a JSFiddle here. The class I am trying to add is only visible when the input is returned invalid. The class name is .invalid which you can find in the CSS. Thanks in advance, and any help is appreciated.

答:
Let's assume there are two inputs and as you want to validate via PHP the validation process will be after submitting the form as

HTML

```<code><input type="text" title="First Name" aria-placeholder="First Name" id="name" required />
<input type="text" title="Last Name" aria-placeholder="Last Name" id="name" required />
</code>```

PHP

```<code>for($i = 0;$i < sizeof($_POST);$i++){
if($_POST[$i] == null || $POST[$i] == ""){
echo "Please insert :".$_POST[$i];
 }
}
</code>```

Note: PHP will validate the form after the form has been submitted for the validation before the submission you will need use javascript.

Title: Add A Class To An Input Using PHP

Body:
Let's assume there are two inputs and as you want to validate via PHP the validation process will be after submitting the form as

HTML

<input type="text" title="First Name" aria-placeholder="First Name" id="name" required />
<input type="text" title="Last Name" aria-placeholder="Last Name" id="name" required />

PHP

for($i = 0;$i < sizeof($_POST);$i++){
if($_POST[$i] == null || $POST[$i] == ""){
echo "Please insert :".$_POST[$i];
 }
}

Note: PHP will validate the form after the form has been submitted for the validation before the submission you will need use javascript.


问:
ClimaCell API json casting to POJO
I created an application that takes weather data from the ClimaCell API and then displays it on the page. Below I will show how it looks. Firstly Postman gives such results after sending the query:

```<code>[
   {
      "temp":[
         {
            "observation_time":"2020-05-30T03:00:00Z",
            "min":{
               "value":13.49,
               "units":"C"
            }
         },
         {
            "observation_time":"2020-05-29T14:00:00Z",
            "max":{
               "value":28.15,
               "units":"C"
            }
         }
      ],
      "precipitation":[
         {
            "observation_time":"2020-05-29T07:00:00Z",
            "max":{
               "value":0,
               "units":"mm/hr"
            }
         }
      ],
      "feels_like":[
         {
            "observation_time":"2020-05-30T03:00:00Z",
            "min":{
               "value":13.49,
               "units":"C"
            }
         },
         {
            "observation_time":"2020-05-29T14:00:00Z",
            "max":{
               "value":26.8,
               "units":"C"
            }
         }
      ],
      "humidity":[
         {
            "observation_time":"2020-05-29T13:00:00Z",
            "min":{
               "value":18.1,
               "units":"%"
            }
         },
         {
            "observation_time":"2020-05-30T03:00:00Z",
            "max":{
               "value":80.4,
               "units":"%"
            }
         }
      ],
      "baro_pressure":[
         {
            "observation_time":"2020-05-29T15:00:00Z",
            "min":{
               "value":998.21,
               "units":"hPa"
            }
         },
         {
            "observation_time":"2020-05-29T07:00:00Z",
            "max":{
               "value":1001.36,
               "units":"hPa"
            }
         }
      ],
      "wind_speed":[
         {
            "observation_time":"2020-05-29T09:00:00Z",
            "min":{
               "value":3.1,
               "units":"m/s"
            }
         },
         {
            "observation_time":"2020-05-29T16:00:00Z",
            "max":{
               "value":8.98,
               "units":"m/s"
            }
         }
      ],
      "visibility":[
         {
            "observation_time":"2020-05-29T08:00:00Z",
            "min":{
               "value":24.13,
               "units":"km"
            }
         },
         {
            "observation_time":"2020-05-29T15:00:00Z",
            "max":{
               "value":24.14,
               "units":"km"
            }
         }
      ],
      "observation_time":{
         "value":"2020-05-29"
      },
      "lat":30,
      "lon":30
   }
]

</code>```

Then I created POJO for this json, which looks like this:

```<code>public class ClimaCell {
 @SerializedName("temp")
 @Expose
 private List<Values> temp = new ArrayList<>();

 @SerializedName("precipitation")
 @Expose
 private List<Values> precipitation = new ArrayList<>();

 @SerializedName("feels_like")
 @Expose
 private List<Values> feelsLike = new ArrayList<>();

 @SerializedName("humidity")
 @Expose
 private List<Values> humidity = new ArrayList<>();

 @SerializedName("baro_pressure")
 @Expose
 private List<Values> baroPressure = new ArrayList<>();

 @SerializedName("wind_speed")
 @Expose
 private List<Values> windSpeed = new ArrayList<>();

 @SerializedName("visibility")
 @Expose
 private List<Values> visibility = new ArrayList<>();

 @SerializedName("observation_time")
 @Expose
 private List<ObservationTime> observationTime = new ArrayList<>();

 @SerializedName("lat")
 @Expose
 private Double lat;

 @SerializedName("lon")
 @Expose
 private Double lon;
}

public class Values {
 @SerializedName("observation_time")
 @Expose
 private String observationTime;

 private LinkedHashMap<String, LinkedHashMap<String, String>> storage;

 @Override
 public String toString() {
    return new ToStringBuilder(this).append("observationTime", observationTime).append("storage",
                                                                             storage).toString();
 }
}

public class ObservationTime {
 @SerializedName("value")
 @Expose
 private String value;

 @Override
 public String toString() {
    return new ToStringBuilder(this).append("value", value).toString();
 }
}
</code>```

All classes with

```<code> @Getter
 @Setter
 @NoArgsConstructor
 @AllArgsConstructor
</code>```

After executing this code:

```<code>    Object quote = restTemplate.getForObject(url, Object.class);
    var list = (List<ClimaCell>) quote;

    System.out.println(list.get(0).getTemp().get(0).getStorage().get("min").get("value"));
</code>```

The variable list & quote looks like this

```<code>list = {ArrayList@7179}  size = 1
 0 = {LinkedHashMap@7947}  size = 10
  "temp" -> {ArrayList@7955}  size = 2
   key = "temp"
   value = {ArrayList@7955}  size = 2
    0 = {LinkedHashMap@7957}  size = 2
     "observation_time" -> "2020-05-30T03:00:00Z"
      key = "observation_time"
      value = "2020-05-30T03:00:00Z"
     "min" -> {LinkedHashMap@7970}  size = 2
      key = "min"
      value = {LinkedHashMap@7970}  size = 2
    1 = {LinkedHashMap@7981}  size = 2
     "observation_time" -> "2020-05-29T13:00:00Z"
      key = "observation_time"
      value = "2020-05-29T13:00:00Z"
     "max" -> {LinkedHashMap@7994}  size = 2
      key = "max"
      value = {LinkedHashMap@7994}  size = 2
  "precipitation" -> {ArrayList@8009}  size = 1
   key = "precipitation"
   value = {ArrayList@8009}  size = 1
    0 = {LinkedHashMap@8011}  size = 2
     "observation_time" -> "2020-05-29T23:00:00Z"
      key = "observation_time"
      value = "2020-05-29T23:00:00Z"
     "max" -> {LinkedHashMap@8023}  size = 2
      key = "max"
      value = {LinkedHashMap@8023}  size = 2
       "value" -> {Double@8065} 0.0625
       "units" -> "mm/hr"
  "feels_like" -> {ArrayList@8068}  size = 2 //it looks like the above
  "humidity" -> {ArrayList@8070}  size = 2  //same
  "baro_pressure" -> {ArrayList@8072}  size = 2  //...
  "wind_speed" -> {ArrayList@8074}  size = 2
  "visibility" -> {ArrayList@8076}  size = 2
  "observation_time" -> {LinkedHashMap@8077}  size = 1
   key = "observation_time"
   value = {LinkedHashMap@8077}  size = 1
    "value" -> "2020-05-29"
  "lat" -> {Double@8050} 52.237049 //until this
  "lon" -> {Double@8079} 21.017532
</code>```

and console returns such an error

```<code>java.lang.ClassCastException: class java.util.LinkedHashMap cannot be cast to class
    com.weathernow.web.model.ClimaCell (java.util.LinkedHashMap is in module java.base of loader
    'bootstrap'; com.weathernow.web.model.ClimaCell is in unnamed module of loader 'app')
         at com.weathernow.web.Service.ClimaCellService.getDailyForecast(ClimaCellService.java:42) ~
    [classes/:na]
         at
       com.weathernow.web.Controller.HomeController.getHomePageWithForecast(HomeController.java:21) ~
    [classes/:na]
</code>```

Could anyone help me with this? I've tried in many ways to cast this list on the ClimaCell class, but it never works :(

答:
Finally I solved this problem. Firstly, you need to create a good POJO (it was a hard case for someone doing it for the first time - this may be helpful), then I used gson to cast JSON into my own class

```<code>String quote = restTemplate.getForObject(url, String.class);

Gson gson = new Gson();
List<ClimaCell> pojo = gson.fromJson(quote, new TypeToken<List<ClimaCell>>() {}.getType());
</code>```

And that's all :)

Title: ClimaCell API json casting to POJO

Body:
I created an application that takes weather data from the ClimaCell API and then displays it on the page. Below I will show how it looks. Firstly Postman gives such results after sending the query:

[
   {
      "temp":[
         {
            "observation_time":"2020-05-30T03:00:00Z",
            "min":{
               "value":13.49,
               "units":"C"
            }
         },
         {
            "observation_time":"2020-05-29T14:00:00Z",
            "max":{
               "value":28.15,
               "units":"C"
            }
         }
      ],
      "precipitation":[
         {
            "observation_time":"2020-05-29T07:00:00Z",
            "max":{
               "value":0,
               "units":"mm/hr"
            }
         }
      ],
      "feels_like":[
         {
            "observation_time":"2020-05-30T03:00:00Z",
            "min":{
               "value":13.49,
               "units":"C"
            }
         },
         {
            "observation_time":"2020-05-29T14:00:00Z",
            "max":{
               "value":26.8,
               "units":"C"
            }
         }
      ],
      "humidity":[
         {
            "observation_time":"2020-05-29T13:00:00Z",
            "min":{
               "value":18.1,
               "units":"%"
            }
         },
         {
            "observation_time":"2020-05-30T03:00:00Z",
            "max":{
               "value":80.4,
               "units":"%"
            }
         }
      ],
      "baro_pressure":[
         {
            "observation_time":"2020-05-29T15:00:00Z",
            "min":{
               "value":998.21,
               "units":"hPa"
            }
         },
         {
            "observation_time":"2020-05-29T07:00:00Z",
            "max":{
               "value":1001.36,
               "units":"hPa"
            }
         }
      ],
      "wind_speed":[
         {
            "observation_time":"2020-05-29T09:00:00Z",
            "min":{
               "value":3.1,
               "units":"m/s"
            }
         },
         {
            "observation_time":"2020-05-29T16:00:00Z",
            "max":{
               "value":8.98,
               "units":"m/s"
            }
         }
      ],
      "visibility":[
         {
            "observation_time":"2020-05-29T08:00:00Z",
            "min":{
               "value":24.13,
               "units":"km"
            }
         },
         {
            "observation_time":"2020-05-29T15:00:00Z",
            "max":{
               "value":24.14,
               "units":"km"
            }
         }
      ],
      "observation_time":{
         "value":"2020-05-29"
      },
      "lat":30,
      "lon":30
   }
]

Then I created POJO for this json, which looks like this:

public class ClimaCell {
 @SerializedName("temp")
 @Expose
 private List<Values> temp = new ArrayList<>();

 @SerializedName("precipitation")
 @Expose
 private List<Values> precipitation = new ArrayList<>();

 @SerializedName("feels_like")
 @Expose
 private List<Values> feelsLike = new ArrayList<>();

 @SerializedName("humidity")
 @Expose
 private List<Values> humidity = new ArrayList<>();

 @SerializedName("baro_pressure")
 @Expose
 private List<Values> baroPressure = new ArrayList<>();

 @SerializedName("wind_speed")
 @Expose
 private List<Values> windSpeed = new ArrayList<>();

 @SerializedName("visibility")
 @Expose
 private List<Values> visibility = new ArrayList<>();

 @SerializedName("observation_time")
 @Expose
 private List<ObservationTime> observationTime = new ArrayList<>();

 @SerializedName("lat")
 @Expose
 private Double lat;

 @SerializedName("lon")
 @Expose
 private Double lon;
}

public class Values {
 @SerializedName("observation_time")
 @Expose
 private String observationTime;

 private LinkedHashMap<String, LinkedHashMap<String, String>> storage;

 @Override
 public String toString() {
    return new ToStringBuilder(this).append("observationTime", observationTime).append("storage",
                                                                             storage).toString();
 }
}

public class ObservationTime {
 @SerializedName("value")
 @Expose
 private String value;

 @Override
 public String toString() {
    return new ToStringBuilder(this).append("value", value).toString();
 }
}

All classes with

 @Getter
 @Setter
 @NoArgsConstructor
 @AllArgsConstructor

After executing this code:

    Object quote = restTemplate.getForObject(url, Object.class);
    var list = (List<ClimaCell>) quote;

    System.out.println(list.get(0).getTemp().get(0).getStorage().get("min").get("value"));

The variable list & quote looks like this

list = {ArrayList@7179}  size = 1
 0 = {LinkedHashMap@7947}  size = 10
  "temp" -> {ArrayList@7955}  size = 2
   key = "temp"
   value = {ArrayList@7955}  size = 2
    0 = {LinkedHashMap@7957}  size = 2
     "observation_time" -> "2020-05-30T03:00:00Z"
      key = "observation_time"
      value = "2020-05-30T03:00:00Z"
     "min" -> {LinkedHashMap@7970}  size = 2
      key = "min"
      value = {LinkedHashMap@7970}  size = 2
    1 = {LinkedHashMap@7981}  size = 2
     "observation_time" -> "2020-05-29T13:00:00Z"
      key = "observation_time"
      value = "2020-05-29T13:00:00Z"
     "max" -> {LinkedHashMap@7994}  size = 2
      key = "max"
      value = {LinkedHashMap@7994}  size = 2
  "precipitation" -> {ArrayList@8009}  size = 1
   key = "precipitation"
   value = {ArrayList@8009}  size = 1
    0 = {LinkedHashMap@8011}  size = 2
     "observation_time" -> "2020-05-29T23:00:00Z"
      key = "observation_time"
      value = "2020-05-29T23:00:00Z"
     "max" -> {LinkedHashMap@8023}  size = 2
      key = "max"
      value = {LinkedHashMap@8023}  size = 2
       "value" -> {Double@8065} 0.0625
       "units" -> "mm/hr"
  "feels_like" -> {ArrayList@8068}  size = 2 //it looks like the above
  "humidity" -> {ArrayList@8070}  size = 2  //same
  "baro_pressure" -> {ArrayList@8072}  size = 2  //...
  "wind_speed" -> {ArrayList@8074}  size = 2
  "visibility" -> {ArrayList@8076}  size = 2
  "observation_time" -> {LinkedHashMap@8077}  size = 1
   key = "observation_time"
   value = {LinkedHashMap@8077}  size = 1
    "value" -> "2020-05-29"
  "lat" -> {Double@8050} 52.237049 //until this
  "lon" -> {Double@8079} 21.017532

and console returns such an error

java.lang.ClassCastException: class java.util.LinkedHashMap cannot be cast to class
    com.weathernow.web.model.ClimaCell (java.util.LinkedHashMap is in module java.base of loader
    'bootstrap'; com.weathernow.web.model.ClimaCell is in unnamed module of loader 'app')
         at com.weathernow.web.Service.ClimaCellService.getDailyForecast(ClimaCellService.java:42) ~
    [classes/:na]
         at
       com.weathernow.web.Controller.HomeController.getHomePageWithForecast(HomeController.java:21) ~
    [classes/:na]

Could anyone help me with this? I've tried in many ways to cast this list on the ClimaCell class, but it never works :(

Body:
Finally I solved this problem. Firstly, you need to create a good POJO (it was a hard case for someone doing it for the first time - this may be helpful), then I used gson to cast JSON into my own class

String quote = restTemplate.getForObject(url, String.class);

Gson gson = new Gson();
List<ClimaCell> pojo = gson.fromJson(quote, new TypeToken<List<ClimaCell>>() {}.getType());

And that's all :)


问:
How can my Discord Bot disconnect from the Voicechannel
I'm trying to make a simple Discord Bot(wirtten in Python 3) that just connects and disconnects after a command. The Connect command works fine but my Discconect command doesnt work. Here is the code snippet with both commands: </p>

```<code>async def join(message):
    channel = message.message.author.voice.channel
    await channel.connect()

@client.command(pass_context = True)
async def leave(message):
    channel = message.message.author.voice.channel
    await channel.disconnect()```
</code>```

答:
Try replacing your leave function by :

@commands.command()
    async def leave(ctx):
        channel = ctx.message.author.voice.channel
        voice = get(self.bot.voice_clients, guild=ctx.guild)
        if voice and voice.is_connected():
            await ctx.send(f'Disconnecting from channel **{channel}**')
            await voice.disconnect()
        else:
            await ctx.send("I'm not connected in any channel")
```

Body:
I'm trying to make a simple Discord Bot(wirtten in Python 3) that just connects and disconnects after a command. The Connect command works fine but my Discconect command doesnt work. Here is the code snippet with both commands:

async def join(message):
    channel = message.message.author.voice.channel
    await channel.connect()

@client.command(pass_context = True)
async def leave(message):
    channel = message.message.author.voice.channel
    await channel.disconnect()```


问:
Website link shows Apache HTTP Server Documentation
My website directory /manual shows Apache HTTP Server Version 2.2 Documentation page i have removed this directory from my FTP but still o a, getting this.

I am using Linux Centos bellow is my manual.conf file configuration

There is a manual.conf which shows bellow configurations

```<code>#
# This configuration file allows the manual to be accessed at
# http://localhost/manual/
#
AliasMatch ^/manual(?:/(?:de|en|fr|ja|ko|ru))?(/.*)?$ "/var/www/manual$1"

<Directory "/var/www/manual">
    Options Indexes
    AllowOverride None
    Order allow,deny
    Allow from all
</Directory>
</code>```

答:
In fedora</p>

```<code>dnf remove httpd-manual.noarch
service httpd restart
</code>```

Body:
My website directory /manual shows Apache HTTP Server Version 2.2 Documentation page i have removed this directory from my FTP but still o a, getting this.

I am using Linux Centos bellow is my manual.conf file configuration

There is a manual.conf which shows bellow configurations

#
# This configuration file allows the manual to be accessed at
# http://localhost/manual/
#
AliasMatch ^/manual(?:/(?:de|en|fr|ja|ko|ru))?(/.*)?$ "/var/www/manual$1"

<Directory "/var/www/manual">
    Options Indexes
    AllowOverride None
    Order allow,deny
    Allow from all
</Directory>

Body:
In fedora

dnf remove httpd-manual.noarch
service httpd restart